body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p><a href="https://github.com/puneet222/MyMoney" rel="nofollow noreferrer">Github repo</a></p> <p>I've attempted a backend assignment in Go from geektrust <a href="https://www.geektrust.in/coding-problem/backend/mymoney" rel="nofollow noreferrer">Assignment Link</a>. I'm not sure the code that I have written is idiomatic in the go way. I need some feedback on this code based on its extensibility, proper use of data structures. How can this code be more improved?</p> <p>Main build function of the project.</p> <pre><code>package main import ( &quot;fmt&quot; &quot;geektrust/commander&quot; &quot;geektrust/portfolio&quot; &quot;io/ioutil&quot; &quot;os&quot; &quot;time&quot; ) func main() { args := os.Args[1:] inputFile := &quot;input.txt&quot; if len(args) &gt; 0 { inputFile = args[0] } // read input file data, err := ioutil.ReadFile(inputFile) if err != nil { fmt.Println(&quot;Error while reading file&quot;, err) } // generate commands from input file commands := commander.GenerateCommands(data) // generate portfolio from commands startYear := time.Now().Year() _ = portfolio.BuildPortfolio(commands, startYear) } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-06T06:47:56.000", "Id": "520868", "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>I suggest avoid running the commands/build code if you received an error when reading the file. In the case of an error, I would prefer to not let the program continue. Below I used the <code>else</code> block, but you could also use <code>os.Exit(0)</code> to quit after an error (just beware that way doesn't run any defers).</p>\n<p>Additionally, remove the blank identifier at <code>_ = portfolio...</code>.</p>\n<pre><code>func main() {\n args := os.Args[1:]\n inputFile := &quot;input.txt&quot;\n if len(args) &gt; 0 {\n inputFile = args[0]\n }\n // read input file\n data, err := ioutil.ReadFile(inputFile)\n if err == nil {\n // generate commands from input file\n commands := commander.GenerateCommands(data)\n // generate portfolio from commands\n startYear := time.Now().Year()\n portfolio.BuildPortfolio(commands, startYear)\n } else {\n fmt.Println(&quot;Error while reading file&quot;, err)\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-05T17:32:31.527", "Id": "263784", "ParentId": "263102", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-16T11:05:44.860", "Id": "263102", "Score": "-1", "Tags": [ "go" ], "Title": "How to make this code's design better?" }
263102
<p>I needed some help with Flex. I am trying to achieve something like <a href="https://imgur.com/wpZ2P9F" rel="nofollow noreferrer">this</a> using flex but I cant seem to align all the items to the left for both. The code I provided below works just fine, but I'm sure there has to be a better way to do it but nothing seems to be working for me.</p> <p>Here is a <a href="https://codepen.io/emonhoque/pen/ZEewWra" rel="nofollow noreferrer">CodePen Link</a> for anyone who would like to help me.</p> <pre><code>&lt;div class=&quot;sidebar&quot;&gt; &lt;nav class=&quot;sidebar-nav&quot;&gt; &lt;div class=&quot;sidebar-nav-line&quot;&gt; &lt;div class=&quot;sidebar-nav-text&quot;&gt; &lt;p&gt;Home&lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;sidebar-nav-icon&quot;&gt; &lt;img class=&quot;sidebar-nav-icon-img&quot; src=&quot;assets/img/sidebar-icons/home.png&quot; alt=&quot;Home-Icon&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;sidebar-nav-line&quot;&gt; &lt;div class=&quot;sidebar-nav-text&quot;&gt; &lt;p&gt;About Me&lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;sidebar-nav-icon&quot;&gt; &lt;img class=&quot;sidebar-nav-icon-img&quot; src=&quot;assets/img/sidebar-icons/about_me.png&quot; alt=&quot;About-Me-Icon&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;sidebar-nav-line&quot;&gt; &lt;div class=&quot;sidebar-nav-text&quot;&gt; &lt;p&gt;Projects&lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;sidebar-nav-icon&quot;&gt; &lt;img class=&quot;sidebar-nav-icon-img&quot; src=&quot;assets/img/sidebar-icons/projects.png&quot; alt=&quot;Projects-Icon&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;sidebar-nav-line&quot;&gt; &lt;div class=&quot;sidebar-nav-text&quot;&gt; &lt;p&gt;Resume&lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;sidebar-nav-icon&quot;&gt; &lt;img class=&quot;sidebar-nav-icon-img&quot; src=&quot;assets/img/sidebar-icons/resume.png&quot; alt=&quot;Resume-Icon&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;sidebar-nav-line&quot;&gt; &lt;div class=&quot;sidebar-nav-text&quot;&gt; &lt;p&gt;Contact&lt;/p&gt; &lt;/div&gt; &lt;div class=&quot;sidebar-nav-icon&quot;&gt; &lt;img class=&quot;sidebar-nav-icon-img&quot; src=&quot;assets/img/sidebar-icons/contact.png&quot; alt=&quot;Contact-Icon&quot;&gt; &lt;/div&gt; &lt;/div&gt; &lt;/nav&gt; &lt;/div&gt; </code></pre> <p>CSS</p> <pre><code>.sidebar { background-color: #2C2C2C; width: 255px; height: 100vh; } .sidebar-nav { text-align: center; } .sidebar-nav-line { display: flex; flex-direction: row; justify-content: flex-end; } .sidebar-nav-text{ margin-right: 15px; align-self: center; color: #dec29b98; text-transform: uppercase; font-size: 20px; } .sidebar-nav-icon { margin-right: 32px; align-self: center; } .sidebar-nav-icon-img { width: 30px; height: 30px; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-16T15:54:10.440", "Id": "519412", "Score": "0", "body": "Welcome to Code Review! The description is confusing because it states \"_but I cant seem to align all the items to the left for both._\" then goes on to state: \"_The code I provided below works just fine_...\" Does this work to the best of your knowledge?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T00:26:51.510", "Id": "519434", "Score": "0", "body": "It does work, I just wanted to know if there is a better way to do it. For now, i have stuck to using padding or margins to achieve what i am trying." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T06:56:07.437", "Id": "519808", "Score": "0", "body": "Use Flex and flex-direction just like div, I will post the example using Flex and direction." } ]
[ { "body": "<p>I played a little with css and ended up with this. I don't know if it's really what you wanted, but maybe it can help you get some new ideas.</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-css lang-css prettyprint-override\"><code>*{margin: 0;font-family: \"Poppins\", sans-serif;}\nhtml{background-color:#1c1c20;}\n.col{\n display:grid;\n width:200px;\n background-color:#2c2c2c;\n height:100vh;\n}\n.menu{\n width:95%;\n padding-top:10%;\n}\n.box{\n text-align:right;\n color:#dec29b98;\n padding:5px;\n}\n.box &gt; div{\nmargin-right:10px;\ndisplay:inline-block;\nvertical-align: middle;\ncursor:pointer;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"col\"&gt;\n &lt;div class=\"menu\"&gt;\n \n &lt;div class=\"box\"&gt;\n &lt;div&gt;LINK 1&lt;/div&gt;\n &lt;div&gt;&lt;img src=\"https://i.stack.imgur.com/T5uTa.png\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n \n &lt;div class=\"box\"&gt;\n &lt;div&gt;LINK 2&lt;/div&gt;\n &lt;div&gt;&lt;img src=\"https://i.stack.imgur.com/T5uTa.png\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n \n &lt;div class=\"box\"&gt;\n &lt;div&gt;LINK 3&lt;/div&gt;\n &lt;div&gt;&lt;img src=\"https://i.stack.imgur.com/T5uTa.png\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n \n &lt;/div&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T00:28:49.083", "Id": "519435", "Score": "1", "body": "I just tried it out and it works for me too! I just wanted to know if there's a better way to achieve it and this certainly seems better. I appreciate your help!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T05:50:35.583", "Id": "519447", "Score": "1", "body": "@EmonHoque Remember to not only check answers, but also upvote answers you find useful. It gives the answerer a confidence boost seeing those imaginary numbers tick up ^^" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-16T21:42:26.747", "Id": "263124", "ParentId": "263105", "Score": "2" } } ]
{ "AcceptedAnswerId": "263124", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-16T13:29:00.600", "Id": "263105", "Score": "2", "Tags": [ "html", "css" ], "Title": "Using CSS, surely there is a better way to write this Flex code?" }
263105
<p>I am creating my first business application. Unfortunately, I do not have anyone experienced in .NET or c# to review my code, and this is my first time not only using SQL, but also creating code in a professional environment. As such, I would appreciate some form of criticism / review of my User class which, so far, uses SQL the most. The code is working as intended.</p> <p>The idea for this User class is to populate and store data from the Users table in our database into a User object that can be instantiated at multiple spots in the application (which is a WinForms APP). This class is also part of an effort to keep business logic separate from UI logic.</p> <p><strong>One Note:</strong> The UserSeriatim is used as a form of optimistic concurrency control. If the UserSeriatim in the database is greater than the UserSeriatim stored in memory, then someone else has updated the record while you were making edits, and your updates will be discarded.</p> <p><strong>Another Note:</strong> I will be implementing a way to encrypt the database connection string, but right now it is not encrypted. Of course, I have removed all sensitive information from my code.</p> <p><strong>User.cs</strong></p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using RGABusinessLogic using System.Data; using System.Data.SqlClient; using System.Diagnostics; namespace RGABusinessLogic { /// &lt;summary&gt; /// Class representing a User /// &lt;/summary&gt; public class User { /// &lt;summary&gt; /// UserID of the user. /// &lt;/summary&gt; /// &lt;remarks&gt;Does not update&lt;/remarks&gt; public int UserID { get; private set; } /// &lt;summary&gt; /// The user's username /// &lt;/summary&gt; public string Username { get; set; } /// &lt;summary&gt; /// The user's password in hashed form /// &lt;/summary&gt; public string PassHash { get; set; } /// &lt;summary&gt; /// The user's security role /// &lt;/summary&gt; public int RoleID { get; set; } /// &lt;summary&gt; /// The user's window's user name /// &lt;/summary&gt; public string WindowsUserName { get; set; } /// &lt;summary&gt; /// The user's first name /// &lt;/summary&gt; public string FirstName { get; set; } /// &lt;summary&gt; /// The user's last name /// &lt;/summary&gt; public string LastName { get; set; } /// &lt;summary&gt; /// The user's middle name /// &lt;/summary&gt; public string MiddleName { get; set; } /// &lt;summary&gt; /// The user's email /// &lt;/summary&gt; public string Email { get; set; } /// &lt;summary&gt; /// The user's mobile phone number /// &lt;/summary&gt; public string MobilePhone { get; set; } /// &lt;summary&gt; /// The user's active status. 1 is active, 0 is inactive /// &lt;/summary&gt; public bool Status { get; set; } /// &lt;summary&gt; /// The windows user name of the user who created this user /// &lt;/summary&gt; /// &lt;remarks&gt;Does not update&lt;/remarks&gt; public string CreateBy { get; private set; } /// &lt;summary&gt; /// The date this user was created /// &lt;/summary&gt; /// &lt;remarks&gt;Does not update&lt;/remarks&gt; public DateTime CreateDate { get; private set; } /// &lt;summary&gt; /// The windows user name of the user who last modified this user /// &lt;/summary&gt; public string ModifyBy { get; private set; } /// &lt;summary&gt; /// The date this user was last modified /// &lt;/summary&gt; public DateTime ModifyDate { get; private set; } /// &lt;summary&gt; /// The seriatim for the user /// &lt;/summary&gt; public int UserSeriatim { get; private set; } /// &lt;summary&gt; /// Whether or not this user is a new user /// &lt;/summary&gt; private bool _newUser; /// &lt;summary&gt; /// Whether or not this user is being modified /// &lt;/summary&gt; private bool _modifyUser; /// &lt;summary&gt; /// Creates a new instance of a user /// &lt;/summary&gt; /// &lt;param name=&quot;newUser&quot;&gt;Whether or not this user is a new user&lt;/param&gt; /// &lt;param name=&quot;modifyUser&quot;&gt;Whether or not this user is being modified&lt;/param&gt; /// &lt;param name=&quot;userRecord&quot;&gt;The data used to populate the current user if the user is not null&lt;/param&gt; public User(bool newUser, bool modifyUser, DataRow userRecord = null) { _newUser = newUser; _modifyUser = modifyUser; if (_newUser) { SetCreateProperties(); } else if (userRecord != null) { PopulateUserProperties(userRecord, _modifyUser); } } /// &lt;summary&gt; /// Sets the CreatedBy and CreateDate properties for a new user /// &lt;/summary&gt; private void SetCreateProperties() { CreateBy = CurrentUser.WindowsUserName; CreateDate = DateTime.Now; UserSeriatim = 0; } /// &lt;summary&gt; /// Populates all user properties using the given data row, and then sets the ModifiedBy and Modify Date properties /// &lt;/summary&gt; /// &lt;remarks&gt; /// The given data row must have field names that match the field names in the method. If this is to ever change, this method will need an update. /// &lt;/remarks&gt; /// &lt;param name=&quot;row&quot;&gt;The data row used to populate this object's properties&lt;/param&gt; private void PopulateUserProperties(DataRow row, bool modify) { try { UserID = ConvertFromDB&lt;int&gt;(row[&quot;UserID&quot;]); Username = ConvertFromDB&lt;string&gt;(row[&quot;UserName&quot;]); PassHash = ConvertFromDB&lt;string&gt;(row[&quot;PassHash&quot;]); RoleID = ConvertFromDB&lt;int&gt;(row[&quot;RoleID&quot;]); WindowsUserName = ConvertFromDB&lt;string&gt;(row[&quot;WindowsUserName&quot;]); FirstName = ConvertFromDB&lt;string&gt;(row[&quot;FirstName&quot;]); LastName = ConvertFromDB&lt;string&gt;(row[&quot;LastName&quot;]); MiddleName = ConvertFromDB&lt;string&gt;(row[&quot;MiddleName&quot;]); MobilePhone = ConvertFromDB&lt;string&gt;(row[&quot;MobilePhone&quot;]); Email = ConvertFromDB&lt;string&gt;(row[&quot;Email&quot;]); Status = ConvertFromDB&lt;bool&gt;(row[&quot;Status&quot;]); CreateBy = ConvertFromDB&lt;string&gt;(row[&quot;CreateBy&quot;]); CreateDate = ConvertFromDB&lt;DateTime&gt;(row[&quot;CreateDate&quot;]); UserSeriatim = ConvertFromDB&lt;int&gt;(row[&quot;UserSeriatim&quot;]); if (modify) { ModifyBy = CurrentUser.WindowsUserName; ModifyDate = DateTime.Now; } else { ModifyBy = ConvertFromDB&lt;string&gt;(row[&quot;ModifyBy&quot;]); ModifyDate = ConvertFromDB&lt;DateTime&gt;(row[&quot;ModifyDate&quot;]); } } catch(Exception e) { Debug.WriteLine(e.ToString()); //This also seems like a good opportunity to display an error to the end user. return; } } /// &lt;summary&gt; /// Updates the user's record in the database /// &lt;/summary&gt; /// &lt;returns&gt;True if record was successfully updated&lt;/returns&gt; public bool UpdateUserRecord(out string errorString) { //TODO: Encryption on database username and database password string connectionString = @&quot;You're not allowed to see this connection string!&quot;; var sqlCommand = new SqlCommand(); var commandString = &quot;UPDATE Users SET &quot; + &quot;Username = @Username, &quot; + &quot;RoleID = @SecurityRole, &quot; + &quot;WindowsUserName = @WindowsUsername, &quot; + &quot;FirstName = @FirstName, &quot; + &quot;LastName = @LastName, &quot; + &quot;MiddleName = @MiddleName, &quot; + &quot;Email = @Email, &quot; + &quot;MobilePhone = @MobilePhone, &quot; + &quot;Status = @Status, &quot; + &quot;ModifyBy = @ModifyBy, &quot; + &quot;ModifyDate = @ModifyDate, &quot; + &quot;UserSeriatim = @UserSeriatim &quot; + &quot;WHERE UserID = @UserID&quot;; sqlCommand.CommandText = commandString; sqlCommand.Parameters.AddWithValue(&quot;Username&quot;, Username); //sqlCommand.Parameters.AddWithValue(&quot;SecurityRole&quot;, (int)SecurityRole); sqlCommand.Parameters.AddWithValue(&quot;SecurityRole&quot;, RoleID); sqlCommand.Parameters.AddWithValue(&quot;WindowsUserName&quot;, WindowsUserName); sqlCommand.Parameters.AddWithValue(&quot;FirstName&quot;, FirstName); sqlCommand.Parameters.AddWithValue(&quot;LastName&quot;, LastName); sqlCommand.Parameters.AddWithValue(&quot;MiddleName&quot;, MiddleName); sqlCommand.Parameters.AddWithValue(&quot;Email&quot;, Email); sqlCommand.Parameters.AddWithValue(&quot;MobilePhone&quot;, MobilePhone); sqlCommand.Parameters.AddWithValue(&quot;Status&quot;, Status); sqlCommand.Parameters.AddWithValue(&quot;ModifyBy&quot;, ModifyBy); sqlCommand.Parameters.AddWithValue(&quot;ModifyDate&quot;, ModifyDate); sqlCommand.Parameters.AddWithValue(&quot;UserID&quot;, UserID); sqlCommand.Parameters.AddWithValue(&quot;UserSeriatim&quot;, UserSeriatim + 1); if (!CheckUserSeriatim(connectionString, out string modifyBy)) { errorString = $&quot;Could not Update: Record was updated by {modifyBy}&quot;; return false; } errorString = null; return RunSqlNonQuery(connectionString, sqlCommand); } /// &lt;summary&gt; /// Updates the user's password in the database /// &lt;/summary&gt; /// &lt;returns&gt;True if record was successfully updated&lt;/returns&gt; public bool UpdatePassHash(out string errorString) { string connectionString = @&quot;You're not allowed to see this connection string!&quot;; var sqlCommand = new SqlCommand(); var commandString = &quot;UPDATE Users SET PassHash = @PassHash WHERE UserID = @UserID&quot;; sqlCommand.CommandText = commandString; sqlCommand.Parameters.AddWithValue(&quot;PassHash&quot;, PassHash); sqlCommand.Parameters.AddWithValue(&quot;UserID&quot;, UserID); if (!CheckUserSeriatim(connectionString, out string modifyBy)) { errorString = $&quot;Could not Update: Record was updated by {modifyBy}&quot;; return false; } errorString = null; return RunSqlNonQuery(connectionString, sqlCommand); } /// &lt;summary&gt; /// Adds the user's record to the database /// &lt;/summary&gt; /// &lt;returns&gt;True if record was successfully added&lt;/returns&gt; public bool AddUserRecord() { //TODO: Encryption on database username and database password string connectionString = @&quot;You're not allowed to see this connection string!&quot;; //Would I want to create a private static variable to hold the connection string? ModifyBy = CreateBy; ModifyDate = CreateDate; var sqlCommand = new SqlCommand(); string commandString = $&quot;INSERT INTO Users &quot; + $&quot;(UserSeriatim, UserName, PassHash, RoleID, &quot; + $&quot;WindowsUserName, LastName, FirstName, &quot; + $&quot;MiddleName, Email, MobilePhone, &quot; + $&quot;Status, CreateBy, &quot; + $&quot;CreateDate, ModifyBy, ModifyDate) &quot; + $&quot;VALUES (@UserSeriatim, @Username, @PassHash, @SecurityRole, &quot; + $&quot;@WindowsUserName, @LastName, @FirstName, &quot; + $&quot;@MiddleName, @Email, @MobilePhone, @Status, &quot; + $&quot;@CreateBy, @CreateDate, @ModifyBy, @ModifyDate);&quot;; sqlCommand.CommandText = commandString; sqlCommand.Parameters.AddWithValue(&quot;UserSeriatim&quot;, UserSeriatim); sqlCommand.Parameters.AddWithValue(&quot;Username&quot;, Username); sqlCommand.Parameters.AddWithValue(&quot;PassHash&quot;, PassHash); //sqlCommand.Parameters.AddWithValue(&quot;SecurityRole&quot;, (int)SecurityRole); sqlCommand.Parameters.AddWithValue(&quot;SecurityRole&quot;, RoleID); sqlCommand.Parameters.AddWithValue(&quot;WindowsUserName&quot;, WindowsUserName); sqlCommand.Parameters.AddWithValue(&quot;LastName&quot;, LastName); sqlCommand.Parameters.AddWithValue(&quot;FirstName&quot;, FirstName); sqlCommand.Parameters.AddWithValue(&quot;MiddleName&quot;, MiddleName); sqlCommand.Parameters.AddWithValue(&quot;Email&quot;, Email); sqlCommand.Parameters.AddWithValue(&quot;MobilePhone&quot;, MobilePhone); sqlCommand.Parameters.AddWithValue(&quot;Status&quot;, Status); sqlCommand.Parameters.AddWithValue(&quot;CreateBy&quot;, CreateBy); sqlCommand.Parameters.AddWithValue(&quot;CreateDate&quot;, CreateDate); sqlCommand.Parameters.AddWithValue(&quot;ModifyBy&quot;, ModifyBy); sqlCommand.Parameters.AddWithValue(&quot;ModifyDate&quot;, ModifyDate); return RunSqlNonQuery(connectionString, sqlCommand); } /// &lt;summary&gt; /// Tries to execute a sql non query. /// &lt;/summary&gt; /// &lt;param name=&quot;connectionString&quot;&gt;Connection string to the database&lt;/param&gt; /// &lt;param name=&quot;commandString&quot;&gt;Sql command to execute&lt;/param&gt; /// &lt;returns&gt;True if the execution was successful&lt;/returns&gt; private bool RunSqlNonQuery(string connectionString, SqlCommand command) { SqlConnection connection = null; try { connection = new SqlConnection(connectionString); connection.Open(); command.Connection = connection; command.ExecuteNonQuery(); } catch (SqlException e) { connection.Close(); Debug.WriteLine(e.ToString()); return false; } connection.Close(); return true; } /// &lt;summary&gt; /// Checks the current UserSeriatim in the database against this object's UserSeriatim, and returns if the check passes. /// &lt;/summary&gt; /// &lt;param name=&quot;connectionString&quot;&gt;Connection string to the database&lt;/param&gt; /// &lt;returns&gt;True if the user seriatim is not greater than the current user seriatim&lt;/returns&gt; private bool CheckUserSeriatim(string connectionString, out string modifiedBy) { SqlConnection connection = null; try { connection = new SqlConnection(connectionString); connection.Open(); var commandString = &quot;SELECT UserSeriatim, ModifyBy FROM Users WHERE UserID = @UserID&quot;; SqlCommand command = new SqlCommand(commandString, connection); command.Parameters.AddWithValue(&quot;UserID&quot;, UserID); SqlDataAdapter dataAdapter = new SqlDataAdapter(command); DataTable table = new DataTable(); dataAdapter.Fill(table); if (ConvertFromDB&lt;int&gt;(table.Rows[0][&quot;UserSeriatim&quot;]) &gt; UserSeriatim) { modifiedBy = ConvertFromDB&lt;string&gt;(table.Rows[0][&quot;ModifyBy&quot;]); return false; } connection.Close(); modifiedBy = null; return true; } catch (SqlException e) { connection.Close(); Debug.WriteLine(e.ToString()); modifiedBy = null; return false; } } /// &lt;summary&gt; /// Sets the user's status to inactive /// &lt;/summary&gt; public void DeactiveateUser() { Status = false; } /// &lt;summary&gt; /// Sets the user's status to active /// &lt;/summary&gt; public void ActivateUser() { Status = true; } /// &lt;summary&gt; /// Converts an objects database value to a c# value /// &lt;/summary&gt; /// &lt;typeparam name=&quot;T&quot;&gt;Type to covert to&lt;/typeparam&gt; /// &lt;param name=&quot;obj&quot;&gt;Object to convert&lt;/param&gt; /// &lt;returns&gt;Converted Object&lt;/returns&gt; private T ConvertFromDB&lt;T&gt;(object obj) { if (obj == null || obj == DBNull.Value) { return default(T); } else { return (T)obj; } } } } </code></pre> <p>Just incase it is important to context, here are a couple examples of where a User instance is used...</p> <p><strong>CreateUser() in CreateUserControl.cs Winforms user control</strong></p> <pre><code>/// &lt;summary&gt; /// Creates a new user and displays a message box /// &lt;/summary&gt; private void CreateUser() { _newUser.Username = usernameTextEdit.Text; _newUser.PassHash = StringHasher.ComputeSHA256Hash(passwordTextEdit.Text); _newUser.FirstName = firstNameTextEdit.Text; _newUser.LastName = usernameTextEdit.Text; _newUser.MiddleName = middleNameTextEdit.Text; _newUser.Email = emailTextEdit.Text; _newUser.MobilePhone = mobilePhoneTextEdit.Text; _newUser.WindowsUserName = windowsUserNameTextEdit.Text; _newUser.Status = statusCheckBox.Checked; try { _newUser.AddUserRecord(); MessageBox.Show($&quot;Created User: {_newUser.Username}&quot;); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } </code></pre> <p><strong>UpdateUser() in EditUserControl.cs Winforms User control</strong></p> <pre><code>/// &lt;summary&gt; /// Updates the current user and displays a message box /// &lt;/summary&gt; private void UpdateUser() { _user.Username = usernameTextEdit.Text; _user.FirstName = firstNameTextEdit.Text; _user.LastName = lastNameTextEdit.Text; _user.MiddleName = middleNameTextEdit.Text; _user.Email = emailTextEdit.Text; _user.MobilePhone = mobilePhoneTextEdit.Text; _user.WindowsUserName = windowsUserNameTextEdit.Text; _user.Status = statusCheckBox.Checked; try { if (_user.UpdateUserRecord(out string errorString)) { MessageBox.Show($&quot;Updated User: {_user.Username}&quot;); } else { MessageBox.Show(errorString); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T06:31:15.747", "Id": "519452", "Score": "2", "body": "1. Use [Dapper](https://dapper-tutorial.net/). 2. [Properly handle IDisposable objects](https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/using-objects)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T06:34:14.457", "Id": "519455", "Score": "0", "body": "Is there any particular reason why did you implement your data access with ADO.NET?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T13:09:28.967", "Id": "519492", "Score": "0", "body": "@PeterCsala It seemed straight forward to implement into the code, and it is free. All it takes is a \"using system.Data.SqlClient;\" Is there a good reason not to use ADO.NET?\n\nAs I mentioned in the post, this is my first time working with SQL, so it is all a learning experience for me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T13:15:37.467", "Id": "519494", "Score": "1", "body": "ADO.NET is kinda low level compared to any modern ORM systems. That's why is it more flexible and you can get better performance. On the other hand it is tedious. Most the ORMs provide a lot of utilities out of the box. You just have to configure it and you can change tracking, object validation, migration, scaffolding, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T19:22:59.450", "Id": "519528", "Score": "0", "body": "Dapper is often just as fast as ADO.NET: https://stackoverflow.com/a/47796179/648075 ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T19:44:45.020", "Id": "519531", "Score": "0", "body": "I looked at a couple of ORMs and \"micro ORMs\", and have decided since I'm not too worried about speed, I will be re writing my code to use Entity Framework. I though the generation of data model classes was pretty neat!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T22:04:22.953", "Id": "519546", "Score": "1", "body": "aside from using ORM, you didn't validate user inputs, you just take the inputs as is and reassign them into the model. You should implement the proper validations for each property (username, email ..etc.) before you save it to the database." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T07:51:11.963", "Id": "519666", "Score": "0", "body": "Remove namespaces which are not in use.\nApply validation for each property.\nCreate seperate class file for models.\nYour Business Logic should not interact with database. There should be seperate Layer for data access.\nYou can go for more object oriented approach. Currently you are creating database connection object in each method.\nMethods like RunSqlNonQuery, ConvertFromDB can be moved to comon class as other classes saving/retrieving data from database can reuse this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-06T14:36:36.063", "Id": "520903", "Score": "0", "body": "I'd also convert data-related operations to be async. also, instead of \"dataAdapter.Fill(table)\", I'd use reader instead, for example, using (var r = command.ExecuteReader(System.Data.CommandBehavior.SequentialAccess)) {table.Load(r); }" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-16T14:48:15.460", "Id": "263110", "Score": "1", "Tags": [ "c#", "object-oriented", ".net" ], "Title": "C# User class using SqlServer Database" }
263110
<p>I am trying to translate book: Game Physics Engine Development by Ian Millington to DirectXMath and faced with the code wich transform inertia tensor. Is it right to convert code from book like that: from book:</p> <pre><code>static inline void _transformInertiaTensor(glm::mat3 &amp;iitWorld, const glm::quat &amp;q, const glm::mat3 &amp;iitBody, const glm::mat4 &amp;rotmat) { float t4 = rotmat[0][0] * iitBody[0][0] + rotmat[0][1] * iitBody[1][0] + rotmat[0][2] * iitBody[2][0]; float t9 = rotmat[0][0] * iitBody[0][1] + rotmat[0][1] * iitBody[1][1] + rotmat[0][2] * iitBody[2][1]; float t14 = rotmat[0][0] * iitBody[0][2] + rotmat[0][1] * iitBody[1][2] + rotmat[0][2] * iitBody[2][2]; float t28 = rotmat[1][0] * iitBody[0][0] + rotmat[1][1] * iitBody[1][0] + rotmat[1][2] * iitBody[2][0]; float t33 = rotmat[1][0] * iitBody[0][1] + rotmat[1][1] * iitBody[1][1] + rotmat[1][2] * iitBody[2][1]; float t38 = rotmat[1][0] * iitBody[0][2] + rotmat[1][1] * iitBody[1][2] + rotmat[1][2] * iitBody[2][2]; float t52 = rotmat[2][0] * iitBody[0][0] + rotmat[2][1] * iitBody[1][0] + rotmat[2][2] * iitBody[2][0]; float t57 = rotmat[2][0] * iitBody[0][1] + rotmat[2][1] * iitBody[1][1] + rotmat[2][2] * iitBody[2][1]; float t62 = rotmat[2][0] * iitBody[0][2] + rotmat[2][1] * iitBody[1][2] + rotmat[2][2] * iitBody[2][2]; iitWorld[0][0] = t4 * rotmat[0][0] + t9 * rotmat[0][1] + t14 * rotmat[0][2]; iitWorld[0][1] = t4 * rotmat[1][0] + t9 * rotmat[1][1] + t14 * rotmat[1][2]; iitWorld[0][2] = t4 * rotmat[2][0] + t9 * rotmat[2][1] + t14 * rotmat[2][2]; iitWorld[1][0] = t28 * rotmat[0][0] + t33 * rotmat[0][1] + t38 * rotmat[0][2]; iitWorld[1][1] = t28 * rotmat[1][0] + t33 * rotmat[1][1] + t38 * rotmat[1][2]; iitWorld[1][2] = t28 * rotmat[2][0] + t33 * rotmat[2][1] + t38 * rotmat[2][2]; iitWorld[2][0] = t52 * rotmat[0][0] + t57 * rotmat[0][1] + t62 * rotmat[0][2]; iitWorld[2][1] = t52 * rotmat[1][0] + t57 * rotmat[1][1] + t62 * rotmat[1][2]; iitWorld[2][2] = t52 * rotmat[2][0] + t57 * rotmat[2][1] + t62 * rotmat[2][2]; } </code></pre> <p>to my DirectX code:</p> <pre><code>XMVECTOR orientation = XMQuaternionNormalize(XMLoadFloat4(&amp;m_orientation)); XMMATRIX orientationMatrix = XMMatrixRotationQuaternion(orientation); XMMATRIX inverseInertiaTensor = XMLoadFloat4x4(&amp;m_inverse_inertia_tensor); XMMATRIX inverseInertiaTensorInWorldSpace = XMMatrixMultiply(orientationMatrix, inverseInertiaTensor); XMMATRIX inverseInertiaTensorWorld = XMMatrixMultiply(inverseInertiaTensorInLocalSpace, XMMatrixTranspose(orientationMatrix)); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-16T16:19:25.050", "Id": "519414", "Score": "0", "body": "Have you tested your code? Does it appear to work?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-16T18:55:43.540", "Id": "519424", "Score": "1", "body": "By tests it seems that this code is fine. But I am afraid that the result is incorrect due to incorrect representation of the matrices(row major or column major and the sequence of multiplication)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-16T15:49:59.903", "Id": "263111", "Score": "0", "Tags": [ "c++", "matrix", "mathematics", "physics" ], "Title": "Transform inertia tensor" }
263111
<p>I have the following implementation for the <code>__lt__</code>. Could you please check if it's okay to compare objects like that?</p> <pre><code>class Record(NamedTuple): video_id: str uuid: Optional[UUID] mac: Optional[str] s3_bucket: str s3_key: str reference_date: date @staticmethod def _lt(a: Any, b: Any) -&gt; bool: if a and b: return a &lt; b if a is None and b: return True return False def __lt__(self, other: &quot;Record&quot;) -&gt; Union[bool, Type[&quot;NotImplementedType&quot;]]: if not isinstance(other, Record): return NotImplemented for field in self._fields: self_ = getattr(self, field) other_ = getattr(other, field) if self_ == other_: continue return self._lt(self_, other_) return False </code></pre>
[]
[ { "body": "<p>This code is dangerous:</p>\n<pre class=\"lang-py prettyprint-override\"><code> if a and b:\n return a &lt; b\n if a is None and b:\n return True\n return False\n</code></pre>\n<p>Consider <code>a = -1</code> and <code>b = 0</code>. <code>a and b</code> is <code>False</code> because <code>b</code> is falsey, so <code>a &lt; b</code> is never computed.</p>\n<p>Since <code>a is None</code> is false, we skip to <code>return False</code>, yielding a surprising result for <code>Record._lt(-1, 0)</code></p>\n<p>You should explicitly test <code>a is not None and b is not None</code> instead of <code>a and b</code>.</p>\n<p>Based on your typing, it currently doesn’t look like you’d pass in an <code>int</code> or a <code>float</code>, but if the class changes in the future, or is used as the model for another similar class, the unexpected behaviour might arise.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T08:29:03.263", "Id": "519467", "Score": "0", "body": "what do you think about using @dataclass(order=True) instead of custom __lt__ method?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T19:21:49.073", "Id": "519830", "Score": "0", "body": "A `@dataclass` is mutable (assuming `frozen=True` is not specified), where as tuples, including `NamedTuple`, are immutable. Without knowing more about the class and it's intended usages, it is hard to give a definitive answer. I like both `@dataclass` and `NamedTuple`, but they are different animals used for different things." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T05:29:19.150", "Id": "263132", "ParentId": "263112", "Score": "8" } }, { "body": "<ol>\n<li>No code is always more correct than yes code. <code>NamedTuple</code> has comparison.</li>\n</ol>\n<p>Unless one has a good reason to <a href=\"https://en.wikipedia.org/wiki/Principle_of_least_astonishment\" rel=\"nofollow noreferrer\">surprise the user</a> with other than the perfectly good built-in behavior, in which case they would document that reason clearly, this is far from OK.</p>\n<ol start=\"2\">\n<li>You <em>may</em> want to use a <a href=\"https://rmcomplexity.com/article/2021/01/04/everything-you-need-to-know-about-dataclasses.html#data-classes-that-we-can-compare-and-order\" rel=\"nofollow noreferrer\"><code>dataclass</code></a> instead, which supports type annotations better:</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>from dataclasses import dataclass\n\n@dataclass(order=True)\nclass Record:\n video_id: str\n uuid: Optional[UUID]\n mac: Optional[str]\n s3_bucket: str\n s3_key: str\n reference_date: date\n</code></pre>\n<p>-- EDIT --</p>\n<p>It's always good to describe the intent in code, by means of a (unit-) test script.</p>\n<p>An example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>assert Record(&quot;myvid&quot;, None, None) &lt; Record(&quot;yourvid&quot;, None, None)\nassert Record(&quot;id&quot;, s3_key=&quot;a/b/c&quot;) &lt; Record(&quot;id&quot;, s3_key=&quot;a/b/x&quot;)\ntry:\n Record(&quot;id&quot;) &lt; Record(None)\nelse:\n raise AssertionError(&quot;should have raised&quot;)\n...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T08:28:11.307", "Id": "519466", "Score": "0", "body": "Does default comparison works the same as mine?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T08:46:59.850", "Id": "519468", "Score": "0", "body": "for example, how to compare int and None?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T08:50:33.797", "Id": "519469", "Score": "0", "body": "I advise to write a simple test script to clarify your intent. I'll edit a hint to that in my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T09:32:30.617", "Id": "519471", "Score": "0", "body": "so it's necessary to write a custom comparator because the exception will be thrown and we don't know what to return true or false" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T10:00:12.093", "Id": "519472", "Score": "0", "body": "Wait - do you _need_ to have a 'NotImplemented' as result (as in `if compare(a, b) == NotImplemented`)?\n\nThen don't hijack the `__lt__`, but define a dedicated function for this. Else users will definitely be surprised by this unexpected behavior.\n\nIf you _need_ the `a<b` to raise, you're good to go with the default implementation." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T06:08:15.480", "Id": "263133", "ParentId": "263112", "Score": "4" } } ]
{ "AcceptedAnswerId": "263132", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-16T15:53:44.697", "Id": "263112", "Score": "7", "Tags": [ "python", "python-3.x" ], "Title": "Named tuple with less-than operator" }
263112
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/263071/231235">Two dimensional bicubic interpolation implementation in Matlab</a>. While I am working on neural network designing, I want to compare the effects between using padding and using linear / non-linear interpolation on several outputs of convolution layers in the hidden layers. Due to bicubic interpolation is not contained in the <code>Method</code> options of <a href="https://www.mathworks.com/help/images/ref/nnet.cnn.layer.resize2dlayer.html" rel="nofollow noreferrer">resize2dLayer</a> and <a href="https://www.mathworks.com/help/images/ref/dlresize.html" rel="nofollow noreferrer">dlresize</a>, I am attempting to migrate the two dimensional bicubic interpolation algorithm into <a href="https://www.mathworks.com/help/deeplearning/ug/train-network-using-model-function.html" rel="nofollow noreferrer">Model Function</a>. In other words, a bicubic interpolating resize operation is able to be performed in backwards propagation process.</p> <p><strong>The experimental implementation</strong></p> <ul> <li><p><code>dlBicubicInterpolation</code> function implementation:</p> <pre><code>function [output] = dlBicubicInterpolation(dlArray ,newSize) Ndim = size(size(dlArray), 2); if Ndim == 2 output = BicubicInterpolation(dlArray, newSize); return; end if Ndim == 3 output = dlarray(zeros([newSize size(dlArray, 3)]), dims(dlArray)); for i = 1:ize(dlArray, 3) output(:, :, i) = BicubicInterpolation(dlArray(:, :, i), newSize); end return; end if Ndim == 4 output = dlarray(zeros([newSize size(dlArray, 3) size(dlArray, 4)]), dims(dlArray)); for i = 1:size(dlArray, 3) for j = 1:size(dlArray, 4) output(:, :, i, j) = BicubicInterpolation(dlArray(:, :, i, j), newSize); end end return; end error(&quot;Unsupported case!&quot;); end </code></pre> </li> <li><p>The other used functions:</p> <pre><code>function [output] = BicubicInterpolation(input, newSize) originSize = size(input); newSizeX = newSize(1); newSizeY = newSize(2); inputDims = dims(input); output = dlarray(zeros(size(input)), inputDims(1:2)); ratiox = originSize(1) / newSizeX; ratioy = originSize(2) / newSizeY; for y = 0:newSizeY - 1 for x = 0:newSizeX - 1 xMappingToOrigin = x * ratiox; yMappingToOrigin = y * ratioy; xMappingToOriginFloor = floor(xMappingToOrigin); yMappingToOriginFloor = floor(yMappingToOrigin); xMappingToOriginFrac = xMappingToOrigin - xMappingToOriginFloor; yMappingToOriginFrac = yMappingToOrigin - yMappingToOriginFloor; ndata = zeros(4, 4); for ndatay = -1:2 for ndatax = -1:2 ndata(ndatax + 2, ndatay + 2) = input( ... clip(xMappingToOriginFloor + ndatax, 0, originSize(1) - 1) + 1, ... clip(yMappingToOriginFloor + ndatay, 0, originSize(2) - 1) + 1); end end output(x + 1, y + 1) = BicubicPolate(ndata, xMappingToOriginFrac, yMappingToOriginFrac); end end end function [output] = clip(input, lowerbound, upperbound) if (input &gt; upperbound) output = upperbound; return; end if (input &lt; lowerbound) output = lowerbound; return; end output = input; end function [output] = BicubicPolate(ndata, fracx, fracy) x1 = CubicPolate( ndata(1,1), ndata(2,1), ndata(3,1), ndata(4,1), fracx ); x2 = CubicPolate( ndata(1,2), ndata(2,2), ndata(3,2), ndata(4,2), fracx ); x3 = CubicPolate( ndata(1,3), ndata(2,3), ndata(3,3), ndata(4,3), fracx ); x4 = CubicPolate( ndata(1,4), ndata(2,4), ndata(3,4), ndata(4,4), fracx ); output = CubicPolate( x1, x2, x3, x4, fracy ); end function [output] = CubicPolate(v0, v1, v2, v3, fracy ) A = (v3-v2)-(v0-v1); B = (v0-v1)-A; C = v2-v0; D = v1; output = D + fracy * (C + fracy * (B + fracy * A)); end </code></pre> </li> </ul> <p><strong>The full testing code</strong></p> <p>With referring to the example in the webpage <a href="https://www.mathworks.com/help/deeplearning/ug/train-network-using-model-function.html" rel="nofollow noreferrer">Train Network Using Model Function</a>, the line <code>dlY = dlconv(dlX,weights,bias,'Padding','same');</code> in the first convolution layer has been modified into <code>dlY = dlconv(dlX,weights,bias);</code> and then <code>dlBicubicInterpolation</code> function is used for performing resize operation <code>dlY = dlBicubicInterpolation(dlY, [28 28]);</code> for testing purpose.</p> <pre><code>%% Load Training Data [XTrain,YTrain,anglesTrain] = digitTrain4DArrayData; dsXTrain = arrayDatastore(XTrain,'IterationDimension',4); dsYTrain = arrayDatastore(YTrain); dsAnglesTrain = arrayDatastore(anglesTrain); dsTrain = combine(dsXTrain,dsYTrain,dsAnglesTrain); classNames = categories(YTrain); numClasses = numel(classNames); numResponses = size(anglesTrain,2); numObservations = numel(YTrain); %% % View some images from the training data. idx = randperm(numObservations,64); I = imtile(XTrain(:,:,:,idx)); figure imshow(I) %% Define Deep Learning Model % Define the following network that predicts both labels and angles of rotation. %% % Define and Initialize Model Parameters and State filterSize = [5 5]; numChannels = 1; numFilters = 16; sz = [filterSize numChannels numFilters]; numOut = prod(filterSize) * numFilters; numIn = prod(filterSize) * numFilters; parameters.conv1.Weights = initializeGlorot(sz,numOut,numIn); parameters.conv1.Bias = initializeZeros([numFilters 1]); %% % Initialize the parameters and state for the first batch normalization layer. parameters.batchnorm1.Offset = initializeZeros([numFilters 1]); parameters.batchnorm1.Scale = initializeOnes([numFilters 1]); state.batchnorm1.TrainedMean = zeros(numFilters,1,'single'); state.batchnorm1.TrainedVariance = ones(numFilters,1,'single'); %% % Initialize the parameters for the second convolutional layer. filterSize = [3 3]; numChannels = 16; numFilters = 32; sz = [filterSize numChannels numFilters]; numOut = prod(filterSize) * numFilters; numIn = prod(filterSize) * numFilters; parameters.conv2.Weights = initializeGlorot(sz,numOut,numIn); parameters.conv2.Bias = initializeZeros([numFilters 1]); %% % Initialize the parameters and state for the second batch normalization layer. parameters.batchnorm2.Offset = initializeZeros([numFilters 1]); parameters.batchnorm2.Scale = initializeOnes([numFilters 1]); state.batchnorm2.TrainedMean = zeros(numFilters,1,'single'); state.batchnorm2.TrainedVariance = ones(numFilters,1,'single'); %% % Initialize the parameters for the third convolutional layer. filterSize = [3 3]; numChannels = 32; numFilters = 32; sz = [filterSize numChannels numFilters]; numOut = prod(filterSize) * numFilters; numIn = prod(filterSize) * numFilters; parameters.conv3.Weights = initializeGlorot(sz,numOut,numIn); parameters.conv3.Bias = initializeZeros([numFilters 1]); %% % Initialize the parameters and state for the third batch normalization layer. parameters.batchnorm3.Offset = initializeZeros([numFilters 1]); parameters.batchnorm3.Scale = initializeOnes([numFilters 1]); state.batchnorm3.TrainedMean = zeros(numFilters,1,'single'); state.batchnorm3.TrainedVariance = ones(numFilters,1,'single'); %% % Initialize the parameters for the convolutional layer in the skip connection. filterSize = [1 1]; numChannels = 16; numFilters = 32; sz = [filterSize numChannels numFilters]; numOut = prod(filterSize) * numFilters; numIn = prod(filterSize) * numFilters; parameters.convSkip.Weights = initializeGlorot(sz,numOut,numIn); parameters.convSkip.Bias = initializeZeros([numFilters 1]); %% % Initialize the parameters and state for the batch normalization layer in the % skip connection. parameters.batchnormSkip.Offset = initializeZeros([numFilters 1]); parameters.batchnormSkip.Scale = initializeOnes([numFilters 1]); state.batchnormSkip.TrainedMean = zeros([numFilters 1],'single'); state.batchnormSkip.TrainedVariance = ones([numFilters 1],'single'); %% % Initialize the parameters for the fully connected layer corresponding to the % classification output. sz = [numClasses 6272]; numOut = numClasses; numIn = 6272; parameters.fc1.Weights = initializeGlorot(sz,numOut,numIn); parameters.fc1.Bias = initializeZeros([numClasses 1]); %% % Initialize the parameters for the fully connected layer corresponding to the % regression output. sz = [numResponses 6272]; numOut = numResponses; numIn = 6272; parameters.fc2.Weights = initializeGlorot(sz,numOut,numIn); parameters.fc2.Bias = initializeZeros([numResponses 1]); %% % View the struct of the parameters. parameters %% % View the parameters for the &quot;conv1&quot; operation. parameters.conv1 %% % View the struct of the state. state %% state.batchnorm1 numEpochs = 20; miniBatchSize = 128; %% plots = &quot;training-progress&quot;; %% Train Model mbq = minibatchqueue(dsTrain,... 'MiniBatchSize',miniBatchSize,... 'MiniBatchFcn', @preprocessMiniBatch,... 'MiniBatchFormat',{'SSCB','',''}); %% % Initialize parameters for Adam. trailingAvg = []; trailingAvgSq = []; %% % Initialize the training progress plot. if plots == &quot;training-progress&quot; figure lineLossTrain = animatedline('Color',[0.85 0.325 0.098]); ylim([0 inf]) xlabel(&quot;Iteration&quot;) ylabel(&quot;Loss&quot;) grid on end %% % Train the model. iteration = 0; start = tic; % Loop over epochs. for epoch = 1:numEpochs % Shuffle data. shuffle(mbq) % Loop over mini-batches while hasdata(mbq) iteration = iteration + 1; [dlX,dlY1,dlY2] = next(mbq); % Evaluate the model gradients, state, and loss using dlfeval and the % modelGradients function. [gradients,state,loss] = dlfeval(@modelGradients, parameters, dlX, dlY1, dlY2, state); % Update the network parameters using the Adam optimizer. [parameters,trailingAvg,trailingAvgSq] = adamupdate(parameters,gradients, ... trailingAvg,trailingAvgSq,iteration); % Display the training progress. if plots == &quot;training-progress&quot; D = duration(0,0,toc(start),'Format','hh:mm:ss'); addpoints(lineLossTrain,iteration,double(gather(extractdata(loss)))) title(&quot;Epoch: &quot; + epoch + &quot;, Elapsed: &quot; + string(D)) drawnow end end end %% Test Model [XTest,YTest,anglesTest] = digitTest4DArrayData; dsXTest = arrayDatastore(XTest,'IterationDimension',4); dsYTest = arrayDatastore(YTest); dsAnglesTest = arrayDatastore(anglesTest); dsTest = combine(dsXTest,dsYTest,dsAnglesTest); mbqTest = minibatchqueue(dsTest,... 'MiniBatchSize',miniBatchSize,... 'MiniBatchFcn', @preprocessMiniBatch,... 'MiniBatchFormat',{'SSCB','',''}); %% doTraining = false; classesPredictions = []; anglesPredictions = []; classCorr = []; angleDiff = []; % Loop over mini-batches. while hasdata(mbqTest) % Read mini-batch of data. [dlXTest,dlY1Test,dlY2Test] = next(mbqTest); % Make predictions using the predict function. [dlY1Pred,dlY2Pred] = model(parameters,dlXTest,doTraining,state); % Determine predicted classes. Y1PredBatch = onehotdecode(dlY1Pred,classNames,1); classesPredictions = [classesPredictions Y1PredBatch]; % Dermine predicted angles Y2PredBatch = extractdata(dlY2Pred); anglesPredictions = [anglesPredictions Y2PredBatch]; % Compare predicted and true classes Y1Test = onehotdecode(dlY1Test,classNames,1); classCorr = [classCorr Y1PredBatch == Y1Test]; % Compare predicted and true angles angleDiffBatch = Y2PredBatch - dlY2Test; angleDiff = [angleDiff extractdata(gather(angleDiffBatch))]; end %% accuracy = mean(classCorr) %% angleRMSE = sqrt(mean(angleDiff.^2)) %% idx = randperm(size(XTest,4),9); figure for i = 1:9 subplot(3,3,i) I = XTest(:,:,:,idx(i)); imshow(I) hold on sz = size(I,1); offset = sz/2; thetaPred = anglesPredictions(idx(i)); plot(offset*[1-tand(thetaPred) 1+tand(thetaPred)],[sz 0],'r--') thetaValidation = anglesTest(idx(i)); plot(offset*[1-tand(thetaValidation) 1+tand(thetaValidation)],[sz 0],'g--') hold off label = string(classesPredictions(idx(i))); title(&quot;Label: &quot; + label) end %% Model Function function [dlY1,dlY2,state] = model(parameters,dlX,doTraining,state) % Convolution weights = parameters.conv1.Weights; bias = parameters.conv1.Bias; dlY = dlconv(dlX,weights,bias); dlY = dlBicubicInterpolation(dlY, [28 28]); % Batch normalization, ReLU offset = parameters.batchnorm1.Offset; scale = parameters.batchnorm1.Scale; trainedMean = state.batchnorm1.TrainedMean; trainedVariance = state.batchnorm1.TrainedVariance; if doTraining [dlY,trainedMean,trainedVariance] = batchnorm(dlY,offset,scale,trainedMean,trainedVariance); % Update state state.batchnorm1.TrainedMean = trainedMean; state.batchnorm1.TrainedVariance = trainedVariance; else dlY = batchnorm(dlY,offset,scale,trainedMean,trainedVariance); end dlY = relu(dlY); % Convolution, batch normalization (Skip connection) weights = parameters.convSkip.Weights; bias = parameters.convSkip.Bias; dlYSkip = dlconv(dlY,weights,bias,'Stride',2); offset = parameters.batchnormSkip.Offset; scale = parameters.batchnormSkip.Scale; trainedMean = state.batchnormSkip.TrainedMean; trainedVariance = state.batchnormSkip.TrainedVariance; if doTraining [dlYSkip,trainedMean,trainedVariance] = batchnorm(dlYSkip,offset,scale,trainedMean,trainedVariance); % Update state state.batchnormSkip.TrainedMean = trainedMean; state.batchnormSkip.TrainedVariance = trainedVariance; else dlYSkip = batchnorm(dlYSkip,offset,scale,trainedMean,trainedVariance); end % Convolution weights = parameters.conv2.Weights; bias = parameters.conv2.Bias; dlY = dlconv(dlY,weights,bias,'Padding','same','Stride',2); % Batch normalization, ReLU offset = parameters.batchnorm2.Offset; scale = parameters.batchnorm2.Scale; trainedMean = state.batchnorm2.TrainedMean; trainedVariance = state.batchnorm2.TrainedVariance; if doTraining [dlY,trainedMean,trainedVariance] = batchnorm(dlY,offset,scale,trainedMean,trainedVariance); % Update state state.batchnorm2.TrainedMean = trainedMean; state.batchnorm2.TrainedVariance = trainedVariance; else dlY = batchnorm(dlY,offset,scale,trainedMean,trainedVariance); end dlY = relu(dlY); % Convolution weights = parameters.conv3.Weights; bias = parameters.conv3.Bias; dlY = dlconv(dlY,weights,bias,'Padding','same'); % Batch normalization offset = parameters.batchnorm3.Offset; scale = parameters.batchnorm3.Scale; trainedMean = state.batchnorm3.TrainedMean; trainedVariance = state.batchnorm3.TrainedVariance; if doTraining [dlY,trainedMean,trainedVariance] = batchnorm(dlY,offset,scale,trainedMean,trainedVariance); % Update state state.batchnorm3.TrainedMean = trainedMean; state.batchnorm3.TrainedVariance = trainedVariance; else dlY = batchnorm(dlY,offset,scale,trainedMean,trainedVariance); end dlY = dlYSkip + dlY; dlY = relu(dlY); weights = parameters.fc1.Weights; bias = parameters.fc1.Bias; dlY1 = fullyconnect(dlY,weights,bias); dlY1 = softmax(dlY1); weights = parameters.fc2.Weights; bias = parameters.fc2.Bias; dlY2 = fullyconnect(dlY,weights,bias); end %% Model Gradients Function function [gradients,state,loss] = modelGradients(parameters,dlX,T1,T2,state) doTraining = true; [dlY1,dlY2,state] = model(parameters,dlX,doTraining,state); lossLabels = crossentropy(dlY1,T1); lossAngles = mse(dlY2,T2); loss = lossLabels + 0.1*lossAngles; gradients = dlgradient(loss,parameters); end %% Mini-Batch Preprocessing Function function [X,Y,angle] = preprocessMiniBatch(XCell,YCell,angleCell) X = cat(4,XCell{:}); Y = cat(2,YCell{:}); angle = cat(2,angleCell{:}); Y = onehotencode(Y,1); end %% function [output] = dlBicubicInterpolation(dlArray ,newSize) Ndim = size(size(dlArray), 2); if Ndim == 2 output = BicubicInterpolation(dlArray, newSize); return; end if Ndim == 3 output = dlarray(zeros([newSize size(dlArray, 3)]), dims(dlArray)); for i = 1:ize(dlArray, 3) output(:, :, i) = BicubicInterpolation(dlArray(:, :, i), newSize); end return; end if Ndim == 4 output = dlarray(zeros([newSize size(dlArray, 3) size(dlArray, 4)]), dims(dlArray)); for i = 1:size(dlArray, 3) for j = 1:size(dlArray, 4) output(:, :, i, j) = BicubicInterpolation(dlArray(:, :, i, j), newSize); end end return; end error(&quot;Unsupported case!&quot;); end function [output] = BicubicInterpolation(input, newSize) originSize = size(input); newSizeX = newSize(1); newSizeY = newSize(2); inputDims = dims(input); output = dlarray(zeros(size(input)), inputDims(1:2)); ratiox = originSize(1) / newSizeX; ratioy = originSize(2) / newSizeY; for y = 0:newSizeY - 1 for x = 0:newSizeX - 1 xMappingToOrigin = x * ratiox; yMappingToOrigin = y * ratioy; xMappingToOriginFloor = floor(xMappingToOrigin); yMappingToOriginFloor = floor(yMappingToOrigin); xMappingToOriginFrac = xMappingToOrigin - xMappingToOriginFloor; yMappingToOriginFrac = yMappingToOrigin - yMappingToOriginFloor; ndata = zeros(4, 4); for ndatay = -1:2 for ndatax = -1:2 ndata(ndatax + 2, ndatay + 2) = input( ... clip(xMappingToOriginFloor + ndatax, 0, originSize(1) - 1) + 1, ... clip(yMappingToOriginFloor + ndatay, 0, originSize(2) - 1) + 1); end end output(x + 1, y + 1) = BicubicPolate(ndata, xMappingToOriginFrac, yMappingToOriginFrac); end end end function [output] = clip(input, lowerbound, upperbound) if (input &gt; upperbound) output = upperbound; return; end if (input &lt; lowerbound) output = lowerbound; return; end output = input; end function [output] = BicubicPolate(ndata, fracx, fracy) x1 = CubicPolate( ndata(1,1), ndata(2,1), ndata(3,1), ndata(4,1), fracx ); x2 = CubicPolate( ndata(1,2), ndata(2,2), ndata(3,2), ndata(4,2), fracx ); x3 = CubicPolate( ndata(1,3), ndata(2,3), ndata(3,3), ndata(4,3), fracx ); x4 = CubicPolate( ndata(1,4), ndata(2,4), ndata(3,4), ndata(4,4), fracx ); output = CubicPolate( x1, x2, x3, x4, fracy ); end function [output] = CubicPolate(v0, v1, v2, v3, fracy ) A = (v3-v2)-(v0-v1); B = (v0-v1)-A; C = v2-v0; D = v1; output = D + fracy * (C + fracy * (B + fracy * A)); end </code></pre> <p><strong>Test Platform Information</strong></p> <p>Matlab version: '9.10.0.1684407 (R2021a) Update 3'</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/263071/231235">Two dimensional bicubic interpolation implementation in Matlab</a>.</p> </li> <li><p>What changes has been made in the code since last question?</p> <p>I am attempting to migrate the two dimensional bicubic interpolation algorithm into <a href="https://www.mathworks.com/help/deeplearning/ug/train-network-using-model-function.html" rel="nofollow noreferrer">Model Function</a> in this post.</p> </li> <li><p>Why a new review is being asked for?</p> <p>If there is any possible improvement, please let me know.</p> </li> </ul> <p><strong>Reference</strong></p> <ul> <li><a href="https://www.mathworks.com/help/deeplearning/ug/list-of-functions-with-dlarray-support.html" rel="nofollow noreferrer">List of Functions with dlarray Support</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-16T16:47:23.423", "Id": "263113", "Score": "0", "Tags": [ "performance", "algorithm", "image", "numerical-methods", "matlab" ], "Title": "Two dimensional bicubic interpolation implementation for dlarray in Matlab" }
263113
<p>I am creating a command in my discord bot to send an announcement to every server it is in, and this is the only way i could think of doing it, but i know there is a more efficient way of doing it.</p> <p>Can anyone help me in improving this code, as it stand ATM it works 100% (well i have testing in a local controlled environment in about 20 server and it works)</p> <p>I’m looking for more efficient way to build the message before sending and even a better format of the code.</p> <p>Any help would be greatly appreciated.</p> <pre><code>// ----------------- // Global variables // ----------------- // Codebeat:disable[LOC,ABC,BLOCK_NESTING,ARITY] /* eslint-disable consistent-return */ /* eslint-disable no-use-before-define */ /* eslint-disable no-unused-vars */ const sendMessage = require(&quot;../../core/command.send&quot;); const auth = require(&quot;../../core/auth&quot;); const time = { &quot;long&quot;: 30000, &quot;short&quot;: 5000 }; // -------------------- // Announce to servers // -------------------- async function announcement (data) { data.announcement = { &quot;heading&quot;: null, &quot;message&quot;: null, &quot;title&quot;: null }; // Announcment started - Collect Title. const filter = (m) =&gt; m.author.id === data.message.author.id; data.message.delete({&quot;timeout&quot;: time.short}).catch((err) =&gt; console.log( &quot;Command Message Deleted Error, command.send.js = &quot;, err )); await data.message.channel.send(`Please enter Anouncment Title.`).then(() =&gt; { data.message.channel.awaitMessages(filter, { &quot;errors&quot;: [&quot;time&quot;], &quot;max&quot;: 1, &quot;time&quot;: 30000 }). then((message) =&gt; { data.announcement.title = message.first(); body(data); }). catch((collected) =&gt; { data.message.channel.send(`No Title Provided - Command Timed out - Title ${collected}`); }); }); async function body (data) { await data.message.channel.send(`Please Enter message you wish to send.`).then(() =&gt; { data.message.channel.awaitMessages(filter, { &quot;errors&quot;: [&quot;time&quot;], &quot;max&quot;: 1, &quot;time&quot;: 30000 }). then((message) =&gt; { data.announcement.message = message.first(); embedOption(data); }). catch((collected) =&gt; { data.message.channel.send(`No Message Provided - Command Timed out - Message ${collected}`); }); }); } async function embedOption (data) { await data.message.channel.send(`Would you like to send as a Embed or Normal Message`).then(() =&gt; { data.message.channel.awaitMessages(filter, { &quot;errors&quot;: [&quot;time&quot;], &quot;max&quot;: 1, &quot;time&quot;: 30000 }). then((message) =&gt; { let responce = null; let responceLower = null; responce = message.first(); responceLower = responce.content.toLowerCase(); if (responceLower === &quot;embed&quot; || responceLower === &quot;e&quot;) { reviewEmbed(data); } else if (responceLower === &quot;normal&quot; || responceLower === &quot;n&quot;) { reviewNormal(data); } else { data.message.channel.send(`Command Terminated: Invalid Response`); } }). catch((collected) =&gt; { data.message.channel.send(`No Responce Provided - Command Timed out - Embed Option ${collected}`); }); }); } async function reviewNormal (data) { await data.message.channel.send(`Please Review the message, Do you want to send.? \`YES\` / \`NO\``).then(() =&gt; { data.message.channel.send(`This is a Message from the RITA Dev Team\n\n${data.announcement.title}\n${data.announcement.message}`); data.message.channel.awaitMessages(filter, { &quot;errors&quot;: [&quot;time&quot;], &quot;max&quot;: 1, &quot;time&quot;: 30000 }).then((message) =&gt; { let responce = null; let responceLower = null; responce = message.first(); responceLower = responce.content.toLowerCase(); if (responceLower === &quot;yes&quot; || responceLower === &quot;y&quot;) { data.message.channel.send(`Announcment has been sent!`).then((msg) =&gt; { msg.delete({&quot;timeout&quot;: time.long}).catch((err) =&gt; console.log( &quot;Bot Message Deleted Error, command.send.js = &quot;, err )); }); let i = 0; data.message.client.guilds.cache.forEach((guild) =&gt; { i += 1; if (guild.id &amp;&amp; guild.systemChannel &amp;&amp; guild.systemChannel.permissionsFor(guild.me).has(&quot;SEND_MESSAGES&quot;)) { console.log(`Normal Message ${i} Sent to guild ${guild.id} - ${guild.name}`); return guild.systemChannel.send(`This is a Message from the RITA Dev Team\n\n${data.announcement.title}\n${data.announcement.message}`); } }); clean(data); } else if (responceLower === &quot;no&quot; || responceLower === &quot;n&quot;) { data.message.channel.send(`Command Terminated`); clean(data); } else { data.message.channel.send(`Command Terminated: Invalid Response`); clean(data); } }). catch((collected) =&gt; { data.message.channel.send(`No Responce Provided - Command Timed out - Review Normal ${collected}`); clean(data); }); }); } async function reviewEmbed (data) { await data.message.channel.send(`Please Review the message, Do you want to send.? \`YES\` / \`NO\``).then(() =&gt; { data.message.channel.send({&quot;embed&quot;: { &quot;color&quot;: 9514728, &quot;description&quot;: `${data.announcement.message}`, &quot;footer&quot;: { &quot;text&quot;: &quot;This is a Message from the RITA Dev Team\nRITA is developed by the RITA Bot Project&quot; }, &quot;title&quot;: `${data.announcement.title}` }}); data.message.channel.awaitMessages(filter, { &quot;errors&quot;: [&quot;time&quot;], &quot;max&quot;: 1, &quot;time&quot;: 30000 }).then((message) =&gt; { let responce = null; let responceLower = null; responce = message.first(); responceLower = responce.content.toLowerCase(); if (responceLower === &quot;yes&quot; || responceLower === &quot;y&quot;) { data.message.channel.send(`Announcment has been sent!`).then((msg) =&gt; { msg.delete({&quot;timeout&quot;: time.long}).catch((err) =&gt; console.log( &quot;Bot Message Deleted Error, command.send.js = &quot;, err )); }); let i = 0; data.message.client.guilds.cache.forEach((guild) =&gt; { i += 1; if (guild.id &amp;&amp; guild.systemChannel &amp;&amp; guild.systemChannel.permissionsFor(guild.me).has(&quot;SEND_MESSAGES&quot;)) { console.log(`Embed Message ${i} Sent to guild ${guild.id} - ${guild.name}`); return guild.systemChannel.send({&quot;embed&quot;: { &quot;color&quot;: 9514728, &quot;description&quot;: `${data.announcement.message}`, &quot;footer&quot;: { &quot;text&quot;: &quot;This is a Message from the RITA Dev Team\nRITA is developed by the RITA Bot Project&quot; }, &quot;title&quot;: `${data.announcement.title}` }}); } }); clean(data); } else if (responceLower === &quot;no&quot; || responceLower === &quot;n&quot;) { data.message.channel.send(`Command Terminated`); clean(data); } else { data.message.channel.send(`Command Terminated: Invalid Response`); clean(data); } }). catch((collected) =&gt; { data.message.channel.send(`No Responce Provided - Command Timed out - Review Embed ${collected}`); clean(data); }); }); } } function clean (data) { const messageManager = data.channel.messages; messageManager.fetch({&quot;limit&quot;: 9}).then((messages) =&gt; { // `messages` is a Collection of Message objects messages.forEach((message) =&gt; { message.delete(); }); }); } module.exports = function run (data) { // ----------------------------------- // Error if settings param is missing // ----------------------------------- if (!auth.devID.includes(data.message.author.id)) { data.text = &quot;:cop: This Command is for bot developers only.\n&quot;; return sendMessage(data); } // ---------------- // Execute setting // ---------------- return announcement(data); }; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-16T17:37:56.197", "Id": "263115", "Score": "1", "Tags": [ "javascript", "performance", "discord" ], "Title": "More Efficent Code for Announcment Command in Discord.js" }
263115
<p>I've only just started learning javascript and decided to try and make a simple app where individual countries can be selected, highlighting them, and the name appearing in the top corner.</p> <p>The code works, but there as a novice I'm sure its far from the best way to do it! One thing I feel isn't the best is using a global var for country selection (<code>window.selected</code>).</p> <p>The main app MyMap.jsx:</p> <pre><code>import React, { Component } from 'react'; import L from &quot;leaflet&quot; import {MapContainer, GeoJSON, useMap, useMapEvent } from &quot;react-leaflet&quot;; import mapData from './../data/countries.json'; import 'leaflet/dist/leaflet.css'; // Set default value for no selection window.selected = '&lt;/b&gt;&lt;i&gt;Click a country&lt;/i&gt;&lt;b&gt;' // Custom Components let info = L.control(); info.onAdd = function (map) { this.div = L.DomUtil.create('div', 'info'); this.div.innerHTML = '&lt;h4&gt;Current Selection&lt;/h4&gt;&lt;i&gt;Click a country&lt;/i&gt;&lt;br /&gt;'; return this.div; }; info.update = function (props) { this.div.innerHTML = '&lt;h4&gt;Current Selection&lt;/h4&gt;&lt;b&gt;'+props+'&lt;/b&gt;&lt;br /&gt;'; }; function InfoBox() { // Add to the map const map = useMap() info.addTo(map); // Update text to display selected country useMapEvent('click', () =&gt; { info.update(window.selected) }) return null } function TileLayer() { const map = useMap(); const mapboxAccessToken = TOKEN_HERE; // Set default values for the map React.useEffect(() =&gt; { new L.TileLayer( &quot;https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/{z}/{x}/{y}?access_token=&quot; + mapboxAccessToken, { tileSize: 512, zoomOffset: -1 } ).addTo(map); }, [map]); return null; } // Create Map class MyMap extends Component { state = {selectedCountry: null} geoStyle = { stroke: false, fillOpacity: 0 }; // Highlight the selected country highlightCountry = (e) =&gt; { if (this.state.selectedCountry ) { this.state.selectedCountry.setStyle(this.geoStyle); } info.update(this.state.selectedCountry) this.setState({ selectedCountry: e.target }); window.selected = e.target.feature.properties.ADMIN var layer = e.target; layer.setStyle({ stroke: true, weight: 3, color: '#666', dashArray: '', fillOpacity: 0.7 }); layer.bringToFront(); } onEachCountry = (country, layer) =&gt; { layer.on({ click: this.highlightCountry }); } render() { return ( &lt;div&gt; &lt;h1 style={{textAlign: &quot;center&quot;}}&gt;My Map&lt;/h1&gt; &lt;MapContainer style={{height: &quot;80vh&quot;}} zoom={2} center={[30, 0]}&gt; &lt;GeoJSON style={this.geoStyle} data={mapData.features} onEachFeature={this.onEachCountry} /&gt; &lt;TileLayer /&gt; &lt;InfoBox /&gt; &lt;/MapContainer&gt; &lt;/div&gt; ) } } export default MyMap; </code></pre> <p>and the css:</p> <pre><code>.info { padding: 6px 8px; font: 14px/16px Arial, Helvetica, sans-serif; background: white; background: rgba(255, 255, 255, 0.8); box-shadow: 0 0 15px rgba(0, 0, 0, 0.2); border-radius: 5px; } .info h4 { margin: 0 0 5px; color: #777; } .MapContainer { width: 100%; height: 100vh; } </code></pre> <p>The HTML is the generic react html doc from create-react-app.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-16T17:41:56.803", "Id": "263116", "Score": "2", "Tags": [ "css", "react.js", "jsx", "user-interface", "leaflet" ], "Title": "Create a map where countries can be selected using react-leaflet" }
263116
<p>I am trying to implement a small programming language, in Nim, as a way of improving my (close to non-existent) programming skills. The programming language is intended to have IF-GOTO, variables, and the ability to read from stdin. First, I wrote the VM, this thing:</p> <pre><code>import strutils #Nim module for string handling proc parseFile(filename: string): seq[string] = var rawcode = readFile(filename) var code = rawcode.split(&quot;\n&quot;) return code #Parses file into seq of 1-line strings proc main(mem: var seq[int]) = var code = parseFile(readLine(stdin)) #Gets filename from stdin, reads it, parses it, and assigns it to code. var codeptr = 0; #Points to line of code currently being processed while codeptr &lt; len(code): var currins = code[codeptr].split(&quot; &quot;) #current line of code being processed if currins[0] == &quot;store&quot;: var IP2213 = currins[1].parseInt() mem[IP2213] = currins[2].parseInt() #Store stuff in mem. if currins[0] == &quot;addstore&quot;: var IP = currins[1].parseInt() mem[IP] = mem[IP] + currins[2].parseInt() #mem[address] += a new number elif currins[0] == &quot;substore&quot;: var IP1 = currins[1].parseInt() mem[IP1] = mem[IP1] - currins[2].parseInt() #mem[address] -= a new number elif currins[0] == &quot;add&quot;: var IP2 = currins[1].parseInt() var IP3 = currins[2].parseInt() var IP4 = currins[3].parseInt() mem[IP4] = mem[IP2] + mem[IP3] #adds two numbers in traditional register machine way. elif currins[0] == &quot;sub&quot;: var IP5 = currins[1].parseInt() var IP6 = currins[2].parseInt() var IP7 = currins[3].parseInt() mem[IP7] = mem[IP5] - mem[IP6] #subs two numbers in traditional register machine way. elif currins[0] == &quot;mul&quot;: var IP8 = currins[1].parseInt() var IP9 = currins[2].parseInt() var IP10 = currins[3].parseInt() mem[IP10] = mem[IP8] * mem[IP9] #muls two numbers in traditional register machine way. elif currins[0] == &quot;div&quot;: var IP11 = currins[1].parseInt() var IP12 = currins[2].parseInt() var IP13 = currins[3].parseInt() mem[IP13] = int(mem[IP11] / mem[IP12]) #divs two numbers in traditional register machine way. elif currins[0] == &quot;swap&quot;: var IP20 = currins[1].parseInt() var IP21 = currins[2].parseInt() var temp = mem[IP21] mem[IP21] = mem[IP20] mem[IP20] = temp #swaps the values of two mem locations elif currins[0] == &quot;cp&quot;: var IP22 = currins[1].parseInt() var IP23 = currins[2].parseInt() mem[IP23] = mem[IP22] #copies the value of one location unto another elif currins[0] == &quot;inp&quot;: var IP223 = currins[1].parseInt() mem[IP223] = readLine(stdin).parseInt() #take one int of input and place it mem. elif currins[0] == &quot;finp&quot;: var IP223 = currins[1].parseInt() mem[IP223] = ord(readLine(stdin)[0]) #take one char of input and place it mem. elif currins[0] == &quot;jmpifnot&quot;: var IP30 = currins[1].parseInt() var IP31 = currins[2] var IP32 = currins[3].parseInt() var IP33 = currins[4] var IP34 = currins[5].parseInt() if IP31 == &quot;=&quot;: if mem[IP30] != mem[IP32]: if IP33 == &quot;-&quot;: codeptr -= IP34 elif IP33 == &quot;+&quot;: codeptr += IP34 elif IP31 == &quot;!&quot;: if mem[IP30] == mem[IP32]: if IP33 == &quot;-&quot;: codeptr -= IP34 elif IP33 == &quot;+&quot;: codeptr += IP34 #if statement. Jumps forward or backward if == or != elif currins[0] == &quot;fecho&quot;: var IP217 = currins[1].parseInt() echo chr(mem[IP217]) #echos char at mem elif currins[0] == &quot;echo&quot;: var IP37 = currins[1].parseInt() echo mem[IP37] #echos int at mem inc(codeptr) var mem = newSeq[int](10000); #makes mem array main(mem) #runs it </code></pre> <p>Then I wrote another script that uses a dictionary to have variables, and be slightly more readable.</p> <pre><code>import strutils, tables, strformat #Imports Nim modules needed. proc parseFile(filename: string): seq[string] = var rawcode = readFile(filename) var code = rawcode.split(&quot;\n&quot;) return code #Splits file into seq of lines var f = open(&quot;c.txt&quot;, fmWrite) #file to write the code for the VM to. var vartable = initTable[string, int]() #Table to hold the variables and the mem locations they represent. var code = parseFile(readLine(stdin)) #Gets the seq of lines needed. var codeptr = 0 #Code line pointer var avail = 0 #Available mem locations to assign variables to. var truereal: string proc main() = while codeptr &lt; len(code): #Main loop var cur: seq[string] #Current line to process cur = code[codeptr].split(&quot; &quot;) for i in 0..20: cur.add(&quot; &quot;) if cur[0] == &quot;var&quot;: vartable[cur[1]] = avail avail = avail + 1 #For var declaration elif cur[1] == &quot;=&quot;: if not haskey(vartable, cur[0]): vartable[cur[0]] = avail avail = avail + 1 f.write(fmt&quot;store {vartable[cur[0]]} {cur[2].parseInt()}&quot;, &quot;\n&quot;) #Assigns value to var elif cur[2] == &quot;+&quot;: if not haskey(vartable, cur[0]): vartable[cur[0]] = avail avail = avail + 1 f.write(fmt&quot;add {vartable[cur[1]]} {vartable[cur[3]]} {vartable[cur[0]]}&quot;, &quot;\n&quot;) #Adds to variables together and puts the result into a third one elif cur[2] == &quot;-&quot;: if not haskey(vartable, cur[0]): vartable[cur[0]] = avail avail = avail + 1 f.write(fmt&quot;sub {vartable[cur[1]]} {vartable[cur[3]]} {vartable[cur[0]]}&quot;, &quot;\n&quot;) #Subtracts two variables from each other and puts the result into a third one elif cur[2] == &quot;*&quot;: if not haskey(vartable, cur[0]): vartable[cur[0]] = avail avail = avail + 1 f.write(fmt&quot;mul {vartable[cur[1]]} {vartable[cur[3]]} {vartable[cur[0]]}&quot;, &quot;\n&quot;) #Multiplies two variables by each other and puts the result into a third one elif cur[2] == &quot;/&quot;: if not haskey(vartable, cur[0]): vartable[cur[0]] = avail avail = avail + 1 f.write(fmt&quot;div {vartable[cur[1]]} {vartable[cur[3]]} {vartable[cur[0]]}&quot;, &quot;\n&quot;) #Divides two variables by each other and puts the result into a third one elif cur[0] == &quot;echonum&quot;: f.write(fmt&quot;echo {vartable[cur[1]]}&quot;, &quot;\n&quot;) #Echos the int value of a var elif cur[0] == &quot;echochar&quot;: f.write(fmt&quot;fecho {vartable[cur[1]]}&quot;, &quot;\n&quot;) #Echos the char value of a var elif cur[0] == &quot;input&quot;: f.write(fmt&quot;inp {vartable[cur[1]]}&quot;, &quot;\n&quot;) #Takes one int of input elif cur[0] == &quot;inputchar&quot;: f.write(fmt&quot;finp {vartable[cur[1]]}&quot;, &quot;\n&quot;) #takes one char of input elif cur[0] == &quot;if&quot;: var list: string var curl = codeptr var jto = cur[4].parseInt() + curl var li: int while curl &lt; jto: list = &quot; &quot; &amp; list &amp; code[curl] &amp; &quot; &quot; curl = curl + 1 for i in list.split(&quot; &quot;): if i == &quot;if&quot;: li = li + 1 elif i == &quot;+&quot;: li = li + 1 elif i == &quot;-&quot;: li = li + 1 elif i == &quot;*&quot;: li = li + 1 elif i == &quot;/&quot;: li = li + 1 elif i == &quot;goto&quot;: li = li + 1 elif i == &quot;echonum&quot;: li = li + 1 elif i == &quot;=&quot;: li = li + 1 elif i == &quot;echochar&quot;: li = li + 1 elif i == &quot;input&quot;: li = li + 1 elif i == &quot;inputchar&quot;: li = li + 1 f.write(fmt&quot;jmpifnot {vartable[cur[1]]} {cur[2]} {vartable[cur[3]]} + {li}&quot;, &quot;\n&quot;) #Jumps some lines forward if the condition is not true. An if statement of sorts. elif cur[0] == &quot;goto&quot;: var list: string var curl = codeptr var jto = curl - cur[4].parseInt() var li: int while curl &gt; jto: list = &quot; &quot; &amp; list &amp; code[jto] &amp; &quot; &quot; jto = jto + 1 for i in list.split(&quot; &quot;): if i == &quot;if&quot;: li = li + 1 elif i == &quot;+&quot;: li = li + 1 elif i == &quot;-&quot;: li = li + 1 elif i == &quot;*&quot;: li = li + 1 elif i == &quot;/&quot;: li = li + 1 elif i == &quot;goto&quot;: li = li + 1 elif i == &quot;echonum&quot;: li = li + 1 elif i == &quot;=&quot;: li = li + 1 elif i == &quot;echochar&quot;: li = li + 1 elif i == &quot;input&quot;: li = li + 1 elif i == &quot;inputchar&quot;: li = li + 1 if cur[2] == &quot;=&quot;: truereal = &quot;!&quot; elif cur[2] == &quot;!&quot;: truereal = &quot;=&quot; f.write(fmt&quot;jmpifnot {vartable[cur[1]]} {truereal} {vartable[cur[3]]} - {li}&quot;, &quot;\n&quot;) #Jumps some lines backward if the condition is true. An goto statement of sorts. codeptr = codeptr + 1 main() </code></pre> <p>Small example program:</p> <pre><code>var B var C var Q input B input C input Q echonum B echonum C echonum Q </code></pre> <p>Which should print the 3 numbers you enter.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T09:35:06.560", "Id": "519567", "Score": "0", "body": "Is this the right version of the code? I'm just getting `Error: undeclared identifier: 'branched'` when trying to run the first snippet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T06:12:16.163", "Id": "519664", "Score": "0", "body": "Sorry! I was trying something stupid and left the code in." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-16T20:00:51.513", "Id": "263120", "Score": "2", "Tags": [ "performance", "beginner", "interpreter", "virtual-machine", "nim" ], "Title": "Small language, compiles to register VM bytecode" }
263120
<p>I have the following class</p> <pre><code>class Dob: def __init__(self): self.welcome_text = &quot;&quot; #Computes DOB def calc_dob(self): pass #Get User Input def get_input(self, msg): pass def __repr__(self): print(self.welcome_text) total_days = self.calc_dob() return str(total_days) </code></pre> <p>And calls it like this:</p> <pre><code>if __name__ == &quot;__main__&quot;: print(Dob()) </code></pre> <p>Initially I thought this is OK but importing it into PyCharm IDE, it shows warning that methods <em>calc_dob</em> and <em>get_input</em> could be static.</p> <p>Following the IDE's suggestion, it moves the methods outside of the class.</p> <p>All that is left is the <em>__repr__</em> method .That makes me think something is wrong with the Class above.</p> <p>Is the code OK, and I should just rather mark the methods with <em>@staticmethod</em> annotation? <strong>or</strong> my idea isn't Object Oriented and how can I make it Object Oriented.</p> <p>Any help will be appreciated please.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-16T21:33:19.173", "Id": "519430", "Score": "0", "body": "The reason why pycharm \"complains\" is because `self` is not used in the methods `calc_dob` or `get_input`. Once you fill out these functions it will be Ok! I would also recommend writing the class as `DayOfBirth` following [Pep8](https://www.python.org/dev/peps/pep-0008/)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T09:32:43.340", "Id": "519722", "Score": "0", "body": "Please note that on Code Review, we review code that does what it's supposed to do. Your code seems like it's missing 3/4 of its intended features, so it's too early in the process to get a proper review. Please take a look at the [help/on-topic]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T09:46:03.530", "Id": "519723", "Score": "0", "body": "Felt bad, and it's all about same bad energy around Stack Exchange. Everything that's required to test in Isolation the Above class is right there and redundant stuffs removed for brevity. The question is about and tagged Object Oriented analysis, so it's about the design being proper and object oriented or not. Just Someone from some part of the world who couldn't be of help just come from nowhere and feels the best is to Close leaving some silly comments. Horrible!!!!" } ]
[ { "body": "<p>The design of the above class is wrong and I can see now. A <strong>birthday</strong> Object should hold date and relevant data as Instance Variables, and it shouldn't be responsible for printing to the console.</p>\n<p>I/O should be done when calling the class. And as we have a Date Object already in the standard library, a function would do.</p>\n<p>It's bad coming from a Java background where everything has to go inside a Class, didn't think twice before constructing one when a mere <em>package level function</em> will do.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T08:12:14.833", "Id": "263137", "ParentId": "263121", "Score": "0" } } ]
{ "AcceptedAnswerId": "263137", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-16T20:26:47.780", "Id": "263121", "Score": "-1", "Tags": [ "python-3.x", "object-oriented", "design-patterns" ], "Title": "Proper way to Implement a Birthday Class in Object Oriented Python" }
263121
<p>I'm struggling to solve this Kata. My code works but I can't pass because it's timing out. I have googled it and even tried other people's code but still doesn't pass.</p> <p>Any suggestion on how can I make a faster solution?</p> <p><strong>The Kata:</strong> <a href="https://www.codewars.com/kata/54eb33e5bc1a25440d000891/train/python" rel="nofollow noreferrer">https://www.codewars.com/kata/54eb33e5bc1a25440d000891/train/python</a></p> <blockquote> <p>My little sister came back home from school with the following task: given a squared sheet of paper she has to cut it in pieces which, when assembled, give squares the sides of which form an increasing sequence of numbers. At the beginning it was lot of fun but little by little we were tired of seeing the pile of torn paper. So we decided to write a program that could help us and protects trees.</p> <p>Task</p> <p>Given a positive integral number n, return a strictly increasing sequence (list/array/string depending on the language) of numbers, so that the sum of the squares is equal to n².</p> <p>If there are multiple solutions (and there will be), return as far as possible the result with the largest possible values:</p> <p>Examples</p> <p>decompose(11) must return [1,2,4,10]. Note that there are actually two ways to decompose 11²: 11² = 121 = 1 + 4 + 16 + 100 = 1² + 2² + 4² + 10² but don't return [2,6,9], since 9 is smaller than 10.</p> <p>For decompose(50) don't return [1, 1, 4, 9, 49] but [1, 3, 5, 8, 49] since [1, 1, 4, 9, 49] doesn't form a strictly increasing sequence.</p> <p>Note: Neither <code>[n]</code> nor <code>[1,1,1,…,1]</code> are valid solutions. If no valid solution exists, return nil, null, Nothing, None (depending on the language) or &quot;[]&quot; (C) ,{} (C++), [] (Swift, Go).</p> <p>The function &quot;decompose&quot; will take a positive integer n and return the decomposition of N = n² as:</p> <ul> <li><code>[x1 ... xk]</code> or</li> <li><code>&quot;x1 ... xk&quot;</code> or</li> <li><code>Just [x1 ... xk]</code> or</li> <li><code>Some [x1 ... xk]</code> or</li> <li><code>{x1 ... xk}</code> or</li> <li><code>&quot;[x1,x2, ... ,xk]&quot;</code></li> </ul> <p>depending on the language (see &quot;Sample tests&quot;)</p> <p>decompose 50 returns &quot;1,3,5,8,49&quot;<br /> decompose 4 returns &quot;Nothing&quot;</p> </blockquote> <blockquote> <p>Hint: Very often xk will be n-1.</p> </blockquote> <p><strong>My code:</strong></p> <pre class="lang-py prettyprint-override"><code>def decompose(n): count = 1 lst = [] tot = n ** 2 while tot &gt; 0: if n - count == 0: return None elif (n - count) ** 2 &lt;= tot: tot -= (n - count) ** 2 lst.append(n - count) count += 1 else: count += 1 return sorted(lst) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T01:18:38.920", "Id": "519436", "Score": "0", "body": "I doubt it works. Better try **stackoverflow.com**. For every count you have to add either `(n - count)` or skip it. In the first case you could recursively call to see whether there is a solution, and then that is the best solution. Also count is not limited, for every else." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T01:54:11.340", "Id": "519437", "Score": "0", "body": "I have posted on StackOverflow and other users told me to post it here. The code works, I have tested with different values, the problem is when it is tested with big numbers, and it takes a long time to run (starts to get slow with 7 digits). The way that I´m using the 'while' isn´t in a recursively? I´m new to coding and I still get confused with some terms. I appreciate your help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T04:50:43.233", "Id": "519444", "Score": "0", "body": "[Do some math](https://en.wikipedia.org/wiki/Lagrange%27s_four-square_theorem)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T07:10:42.337", "Id": "519456", "Score": "0", "body": "I've just tried the posted code, and `decompose(50)` returns `None`. What testing have you done?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T10:32:47.037", "Id": "519476", "Score": "0", "body": "@vnp the theorem you linked isn't applicable because of the side conditions in the problem. E.g. strictly increasing sequence (same number can't occur twice) and select the solution that has the largest possible numbers when multiple solutions exist. The linked theorem says you can write all natural numbers as the sum of four squares, not that it's not possible to have more or fewer squares too. There are in fact several solutions." } ]
[ { "body": "<p>Just have a java at hand.</p>\n<p>Your function:</p>\n<pre><code>List&lt;Integer&gt; decompose(int n) {\n int count = 1;\n List&lt;Integer&gt; lst = new ArrayList&lt;&gt;();\n int tot = n * n;\n while (tot &gt; 0) {\n if (n - count == 0) {\n return Collections.emptyList();\n } else if ((n - count) * (n - count) &lt;= tot) {\n tot -= (n - count) * (n - count);\n lst.add(n - count);\n count++;\n } else {\n count++;\n }\n }\n Collections.sort(lst);\n return lst;\n}\n</code></pre>\n<p>My function as I think you intended:</p>\n<pre><code>List&lt;Integer&gt; decompose2(int n) {\n return decompose2Rec(n - 1, n * n);\n}\n\nList&lt;Integer&gt; decompose2Rec(int i, int tot) {\n if (tot == 0) {\n return new ArrayList&lt;&gt;();\n }\n if (i &lt;= 0 || tot &lt; 0) {\n return null;\n }\n List&lt;Integer&gt; sublist = decompose2Rec(i - 1, tot - i*i);\n if (sublist != null) {\n sublist.add(i);\n return sublist;\n }\n return decompose2Rec(i - 1, tot);\n}\n</code></pre>\n<p>Test code:</p>\n<pre><code> for (int n = 11; n &lt; 15; ++n) {\n System.out.printf(&quot;%3d -&gt; %s%n -&gt; %s%n&quot;, n, decompose(n), decompose2(n));\n }\n</code></pre>\n<p>Result, the first line your function:</p>\n<pre><code> 11 -&gt; [1, 2, 4, 10]\n -&gt; [1, 2, 4, 10]\n 12 -&gt; []\n -&gt; [1, 2, 3, 7, 9]\n 13 -&gt; [5, 12]\n -&gt; [5, 12]\n 14 -&gt; []\n -&gt; [4, 6, 12]\n\n150 -&gt; [1, 3, 17, 149]\n -&gt; [1, 3, 17, 149]\n151 -&gt; []\n -&gt; [3, 6, 16, 150]\n152 -&gt; [1, 2, 3, 17, 151]\n -&gt; [1, 2, 3, 17, 151]\n153 -&gt; [4, 17, 152]\n -&gt; [4, 17, 152]\n154 -&gt; []\n -&gt; [1, 3, 4, 5, 16, 153]\n</code></pre>\n<p>The reason is, that if <code>n - count</code> is not in the result list, you still subtract it when possible.</p>\n<p>This is typically a situation for <strong>recursion</strong>, anticipating the result of a smaller problem:</p>\n<ul>\n<li>start with candidates from n-1 downto 1.</li>\n<li>every candidate is either added or not</li>\n<li>if added and a result for the rest is found, add and return with final result</li>\n<li>otherwise try lesser candidates</li>\n</ul>\n<p><strong>Speed improvement</strong> can be done by considering the <em>square root of <code>tot</code></em> as next candidate if that is smaller than <code>n - count - 1</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T03:04:40.727", "Id": "263129", "ParentId": "263125", "Score": "2" } }, { "body": "<p>As <a href=\"/a/263129/75307\">Joop's answer</a> says, it makes sense to do this kind of search using recursion. That gives a natural means of backtracking when one line of search doesn't work out.</p>\n<p>If we consider candidates in order from largest to smallest, we naturally know the correct order - just prepend each successful element to the list, as it will be smaller than all the previously-added ones.</p>\n<p>I split the problem into two functions. The first is a recursive function to find the distinct squares no larger than <code>c</code> which sum to <code>n</code>. The second is a function which calls that with the arguments <code>n²</code> and <code>n - 1</code>:</p>\n<pre><code>def helper(n, c):\n &quot;&quot;&quot;\n Find a set of distinct numbers, each no greater than C, whose\n squares sum to N.\n\n Returns as a list, in numerical order.\n\n If no such set exists, return None.\n &quot;&quot;&quot;\n\ndef decompose(n):\n return helper(n * n, n - 1)\n</code></pre>\n<p>Then to fill in the body of <code>helper</code>, I did the recursive step first. Assume that <code>c</code> is in the list; then we need to find the numbers smaller than <code>c</code> whose squares sum to <code>n - c²</code>:</p>\n<pre><code> return helper(n - c * c, c - 1) + [c]\n</code></pre>\n<p>If that doesn't find a solution, then the recursive call will return <code>None</code> and we can detect that by catching the exception that <code>None + [c]</code> will throw:</p>\n<pre><code> try:\n return helper(n - c * c, c - 1) + [c]\n except TypeError:\n # the recursive call returned None, so try the next smaller\n # candidate instead\n return helper(n, c - 1)\n</code></pre>\n<p>Now we need to ensure that the recursion terminates:</p>\n<pre><code> if n == 0:\n # found an exact sum\n return []\n</code></pre>\n<pre><code> if c == 0:\n # ran out of candidates\n return None\n</code></pre>\n<p>And ensure that we don't waste time exploring solutions where <code>n - c²</code> goes negative:</p>\n<pre><code> if n &lt; c * c:\n c = int(math.sqrt(n))\n</code></pre>\n<p>Putting it all together:</p>\n<pre><code>import math\n\ndef helper(n, c):\n &quot;&quot;&quot;\n Find a set of distinct numbers, each no greater than C, whose\n squares sum to N.\n\n Returns as a list, in numerical order.\n\n If no such set exists, return None.\n &quot;&quot;&quot;\n if n == 0:\n return []\n if n &lt; c * c:\n c = int(math.sqrt(n))\n if c == 0:\n return None\n try:\n return helper(n - c * c, c - 1) + [c]\n except TypeError:\n # the recursive call returned None, so try the next smaller\n # candidate instead\n return helper(n, c - 1)\n\ndef decompose(n):\n return helper(n * n, n - 1)\n\nif __name__ == &quot;__main__&quot;:\n print(decompose(11))\n print(decompose(50))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T10:25:28.517", "Id": "519475", "Score": "0", "body": "Great answer! Did not know you dabbled with the snake ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T16:29:37.420", "Id": "519515", "Score": "1", "body": "@N3buchadnezzar just a dabbler, I'm afraid. But thank you! :-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T10:08:17.650", "Id": "263138", "ParentId": "263125", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-16T23:49:36.793", "Id": "263125", "Score": "2", "Tags": [ "python", "performance", "programming-challenge", "time-limit-exceeded" ], "Title": "return the sum of the squares that is equal to n²" }
263125
<p>I got lot of suggestions for optimizing my neural network last post I made, now I wanted to post updated version of it were I got rid of most of performance eaters, now I would really appriciate <strong>neural network side help</strong>, because last post I only got c++ side stuff, program is working as excpected, but <strong>relu network dies way to quickly</strong> in network with 2 inputs, so maybe my math is incorrect somewhere in updateWeights(). (or calculateErrors())</p> <p>Neural Network Class:</p> <pre><code>#pragma once #include &lt;vector&gt; #include &lt;numeric&gt; #include &lt;iostream&gt; #include &lt;functional&gt; #include &lt;cmath&gt; #include &lt;iterator&gt; namespace ActivationFunctions { struct relu { float operator()(float input) const noexcept { return input * (input &gt;= 0); } struct deriv_t { float operator()(float input) const noexcept { return input &gt;= 0; } } derivative; }; struct lrelu { float operator()(float input) const noexcept { return (input &lt; 0) * (-derivative.a * input) + (input &gt;= 0) * input; } struct deriv_t { float a = 0.01f; float operator()(float input) const noexcept { return (input &gt;= 0 ? 1 : a); } } derivative; }; struct sigmoid { float operator()(float input) const noexcept { return 1.0f / (1.0f + std::expf(-input)); } struct deriv_t { float operator()(float input) const noexcept { float s = 1.0f / (1.0f + std::expf(-input)); return s * (1.0f - s); } } derivative; }; struct tanh { float operator()(float input) const noexcept { return std::tanhf(input); } struct deriv_t { float operator()(float input) const noexcept { float t = std::tanhf(input); return 1.0f - t * t; } } derivative; }; struct step { float operator()(float input) const noexcept { return (input &lt;= 0 ? -1 : 1); } struct deriv_t { float operator()(float input) const noexcept { return 1; } } derivative; }; struct none { float operator()(float input) const noexcept { return input; } struct deriv_t { float operator()(float input) const noexcept { return 1; } } derivative; }; }; template&lt;typename Activation = ActivationFunctions::relu&gt; class NeuralNetwork { using layer = std::vector&lt;float&gt;; using neuron_layers = std::vector&lt;layer&gt;; using batch = neuron_layers; using neuron_weights = std::vector&lt;neuron_layers&gt;; using size_type = size_t; public: float learningRate = 0.1f; float weightRandRange = 0.1f; public: NeuralNetwork(const std::vector&lt;size_type&gt;&amp; topology) { //Resize layers to how many layers network will have size_type layers = topology.size() - 1; m_neuron_layers.resize(layers); m_unactivated_neuron_layers.resize(layers); m_neuron_layer_errors.resize(layers); for (size_type i = 0; i &lt; layers; ++i) { m_neuron_layers[i].resize(topology[i + 1]); m_unactivated_neuron_layers[i].resize(topology[i + 1]); m_neuron_layer_errors[i].resize(topology[i + 1]); } srand(time(NULL)); //Initialize weights and resize them according to last layer m_neuron_weights.resize(layers); for (size_type i = 0; i &lt; layers; ++i) { m_neuron_weights[i].resize(topology[i + 1]); for (size_type j = 0; j &lt; topology[i + 1]; ++j) { size_type lastLayerOutputSize = topology[i]; m_neuron_weights[i][j].resize(lastLayerOutputSize + 1); m_neuron_weights[i][j].back() = 0; for (size_type k = 0; k &lt; lastLayerOutputSize; ++k) { m_neuron_weights[i][j][k] = initWeightRandom(); } } } } void forward(const float* inputs) { std::copy(inputs, inputs + m_inputs.size(), m_inputs.data()); //Forwarding input layer according to network inputs //Multiplying weights over inputs for each input neuron using inner_product and adding bias (specified as last parameter of inner_product) for (size_type i = 0; i &lt; m_neuron_layers[0].size(); ++i) { m_neuron_layers[0][i] = m_unactivated_neuron_layers[0][i] = std::inner_product(inputs, inputs + m_inputs.size(), m_neuron_weights[0][i].data(), m_neuron_weights[0][i].back()); } //Forwarding other layer according to last layer's outputs in the same way for (size_type i = 1; i &lt; m_neuron_layers.size(); ++i) { for (size_type j = 0; j &lt; m_neuron_layers[i].size(); ++j) { m_neuron_layers[i][j] = m_unactivated_neuron_layers[i][j] = std::inner_product(m_neuron_layers[i - 1].begin(), m_neuron_layers[i - 1].end(), m_neuron_weights[i][j].begin(), m_neuron_weights[i][j].back()); } } //Applying activation function to neurons for (size_type i = 0; i &lt; m_neuron_layers.size() - 1; ++i) { for (size_type j = 0; j &lt; m_neuron_layers[i].size(); ++j) { m_neuron_layers[i][j] = m_activation(m_neuron_layers[i][j]); } } } void backpropagate(const float* targets) { calculateErrors(targets); updateWeights(); } void calculateErrors(const float* targets) { for (size_type i = 0; i &lt; m_neuron_layers.back().size(); ++i) { m_neuron_layer_errors.back()[i] = targets[i] - m_neuron_layers.back()[i]; } //Than using calculated output errors calculate hidden errors //We iterate over all the layers(except output layer) and then iterate over all the neurons in current layer //And then we wanna do: errors[i] = errors[i + 1] * weights[i].transpose() (&quot;i&quot; is layer index) //errors[i] and errors[i + 1] is a vector and weights[i] is a matrix //aligned as [inputs][neurons] (I think) so if we transpose that it will be [neurons][weights] //so we can translate errors[i] = errors[i + 1] * weights[i + 1].transpose(); (WARN: weights[i + 1] might be incorrect it might be weights[i]) //to errors[i][j] += errors[i + 1][k] * weights[i + 1][k][j] (&quot;j&quot; is neuron index in current layer)(&quot;k&quot; is neuron index in next layer) for (long i = m_neuron_layers.size() - 2; i &gt;= 0; --i) { for (size_type j = 0; j &lt; m_neuron_layers[i].size(); ++j) { m_neuron_layer_errors[i][j] = 0; for (size_type k = 0; k &lt; m_neuron_layers[i + 1].size(); ++k) { m_neuron_layer_errors[i][j] += m_neuron_layer_errors[i + 1][k] * m_neuron_weights[i + 1][k][j]; } } } } void updateWeights() { //Input Weights for (size_type j = 0; j &lt; m_neuron_layers[0].size(); ++j) { for (size_type k = 0; k &lt; m_inputs.size(); ++k) { m_neuron_weights[0][j][k] += learningRate * m_neuron_layer_errors[0][j] * m_activation.derivative(m_unactivated_neuron_layers[0][j]) * m_inputs[k]; } } //Weights for (size_type i = 1; i &lt; m_neuron_layers.size(); ++i) { for (size_type j = 0; j &lt; m_neuron_layers[i].size(); ++j) { for (size_type k = 0; k &lt; m_neuron_layers[i - 1].size(); ++k) { m_neuron_weights[i][j][k] += learningRate * m_neuron_layer_errors[i][j] * m_activation.derivative(m_unactivated_neuron_layers[i][j]) * m_neuron_layers[i - 1][k]; } } } //Bias for (size_type i = 0; i &lt; m_neuron_layers.size(); ++i) { for (size_type j = 0; j &lt; m_neuron_layers[i].size(); ++j) { m_neuron_weights[i][j].back() += learningRate * m_neuron_layer_errors[i][j] * m_activation.derivative(m_unactivated_neuron_layers[i][j]); } } } void train(const batch inputs, const batch targets) { for (size_type i = 0; i &lt; inputs.size(); ++i) { forward(inputs[i].data()); backpropagate(targets[i].data()); } } void train(const batch inputs, const batch targets, batch&amp; predictions) { predictions.clear(); predictions.resize(inputs.size()); for (size_type i = 0; i &lt; inputs.size(); ++i) { forward(inputs[i].data()); backpropagate(targets[i].data()); predictions[i] = m_neuron_layers.back(); } } public: //&lt;UTILITIES&gt;// const float* getOutput() const { return m_neuron_layers.back().data(); } void reset() { m_neuron_layers.clear(); m_neuron_layer_errors.clear(); m_unactivated_neuron_layers.clear(); for (size_type i = 0; i &lt; m_neuron_weights.size(); ++i) { for (size_type j = 0; j &lt; m_neuron_weights.size(); ++j) { for (size_type k = 0; k &lt; m_neuron_weights.size(); ++k) { m_neuron_weights[i][j][k] = initWeightRandom(); } } } } float mse() const { float error = 0; for (const auto&amp; x : m_neuron_layer_errors.back()) error += x * x; return std::sqrt(error / m_neuron_layers.back().size()); } private: float initWeightRandom() const { return (float(rand()) / RAND_MAX * 2 - 1) * float(weightRandRange); } public: //&lt;DEBUG&gt;// friend std::ostream&amp; operator &lt;&lt; (std::ostream&amp; os, const NeuralNetwork&amp; net) { os &lt;&lt; &quot;Error: &quot; &lt;&lt; net.mse(); return os; } void print() { std::ostream_iterator&lt;float&gt; carr(std::cout, &quot; | &quot;); std::cout &lt;&lt; &quot;Network = \n{\n&quot;; for (size_type i = 0; i &lt; m_neuron_layers.size(); ++i) { std::cout &lt;&lt; (&quot; Layer[&quot; + std::to_string(i) + &quot;] = \n {\n&quot;); for (size_type j = 0; j &lt; m_neuron_layers[i].size(); ++j) { std::cout &lt;&lt; (&quot; Neuron[&quot; + std::to_string(j) + &quot;] = \n {\n&quot;); std::cout &lt;&lt; (&quot; Weights = [ | &quot;); std::copy(m_neuron_weights[i][j].begin(), m_neuron_weights[i][j].end() - 1, carr); std::cout &lt;&lt; &quot;];\n&quot;; std::cout &lt;&lt; (&quot; Bias = &quot; + std::to_string(m_neuron_weights[i][j].back())) + &quot;;\n&quot;; std::cout &lt;&lt; (&quot; Unactivated_Output = &quot; + std::to_string(m_unactivated_neuron_layers[i][j])) + &quot;;\n&quot;; std::cout &lt;&lt; (&quot; Output = &quot; + std::to_string(m_neuron_layers[i][j]) + &quot;;\n&quot;); std::cout &lt;&lt; (&quot; Error = &quot; + std::to_string(m_neuron_layer_errors[i][j])) + &quot;;\n&quot;; std::cout &lt;&lt; &quot; };\n&quot;; } std::cout &lt;&lt; &quot; }\n&quot;; } std::cout &lt;&lt; &quot;\n Outputs = [ | &quot;; std::copy(m_neuron_layers.back().data(), m_neuron_layers.back().data() + m_neuron_layers.back().size(), carr); std::cout &lt;&lt; &quot;];\n&quot;; std::cout &lt;&lt; &quot;}&quot; &lt;&lt; std::endl; } private: layer m_inputs; neuron_layers m_neuron_layers; neuron_layers m_unactivated_neuron_layers; neuron_layers m_neuron_layer_errors; neuron_weights m_neuron_weights; const Activation m_activation = {}; }; </code></pre>
[]
[ { "body": "<h1>Write only one statement per line</h1>\n<p>For some reason you decided to make all the activation functions and their derivatives one-liners. This results in some very long lines, requiring sideways scrolling. I recommend you just use one statement per line.</p>\n<h1>Make constants <code>static constexpr</code></h1>\n<p>The constants <code>a</code> (in <code>lrelu::deriv_t</code>), as well as <code>learningRate</code> and <code>weightRandRange</code> are never changed in the code you showed here. If they are really constant, prefer to make them <code>static constexpr</code>.</p>\n<h1>Use <code>size_type</code> consistently</h1>\n<p>You are still using <code>long</code> in one place as an index into <code>m_neuron_layers</code>. This should be <code>size_type</code> as well. This can be done by changing the loop from:</p>\n<pre><code>for (long i = m_neuron_layers.size() - 2; i &gt;= 0; --i)\n</code></pre>\n<p>Which unfortunately depends on <code>i</code> going negative, to:</p>\n<pre><code>for (size_type i = m_neuron_layers.size() - 1; i-- &gt; 0;)\n</code></pre>\n<p>However, I would remove <code>size_type</code> completely and just use <code>std::size_t</code> everywhere. The reason is that <code>size_type</code> is only used internally, and it should never be anything but <code>std::size_t</code>.</p>\n<h1>Naming things</h1>\n<p>Use a consistent naming scheme. Your main class name uses <a href=\"https://en.wikipedia.org/wiki/Pascal_case\" rel=\"nofollow noreferrer\">PascalCase</a>, but the types you define with <code>using</code> inside that class are all in <a href=\"https://en.wikipedia.org/wiki/Snake_case\" rel=\"nofollow noreferrer\">snake_case</a>. Futhermore, there's <code>size_type</code> which has the suffix <code>_type</code>, but the other types don't. I recommend that you keep things as consistent as possible; either use PascalCase for all types you define, or use the <code>_type</code> suffix for all type aliases you define.</p>\n<h1>Input/output types</h1>\n<p>Some functions, like <code>forward()</code>, take raw pointers to <code>float</code> as input, others, like <code>train()</code>, take <code>std::vectors</code> as input, by value even! The first is rather unsafe, as it doesn't pass the size of the buffer of <code>float</code>s, the latter is very inefficient, since it is making unnecessary copies.</p>\n<p>Prefer passing inputs as <code>const</code> <em>references</em> to STL container types. (If you want to be really fancy and you can use C++20, you could make those functions take <a href=\"https://en.cppreference.com/w/cpp/ranges/input_range\" rel=\"nofollow noreferrer\"><code>std::ranges::input_range</code></a>s.) Add <code>assert()</code> statements to verify that the passed input has the expected size, to catch programming errors.</p>\n<p>For <code>getOutput()</code>, you can return a <code>const</code> reference to <code>m_neuron_layers.back()</code>.</p>\n<h1>Avoid unnecessary copies</h1>\n<p>Apart from the unnecessary copies mentioned in the above section, you more explicitly make a copy of the input given to <code>forward()</code>. The input values are reused by <code>updateWeights()</code>, but why couldn't you just pass the same pointer/reference to <code>inputs</code> to <code>updateWeights()</code>? That would allow you to remove the member variable <code>m_inputs</code>, and avoid having to make a copy.</p>\n<h1>Potential to use more STL algorithms</h1>\n<p>You are already using STL algorithms in <code>std::forward()</code>, but there are many places where you could use them. On the other hand, plain <code>for</code>-loops can sometimes be more readable, so I would not hold this against you.</p>\n<h1>Use C++'s random number generators</h1>\n<p>Don't use <code>srand()</code> and <code>rand()</code>, those are C functions, and they are not particularly good for random number generation. Prefer using <a href=\"https://en.cppreference.com/w/cpp/numeric/random\" rel=\"nofollow noreferrer\">C++11's random number generation</a> functionality. In particular, you should be able to replace <code>initWeightRandom()</code> with a member variable of type <a href=\"https://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution\" rel=\"nofollow noreferrer\"><code>std::uniform_real_distribution</code></a>.</p>\n<h1>Unnecessary call to <code>clear()</code></h1>\n<p>In <code>train()</code>, you are going to overwrite all the elements of <code>predictions</code> anyway, so the call to <code>clear()</code> is superfluous, and will unnecessarily cause the array to be filled with zeroes due to the call to <code>resize()</code> right afterwards. Remove the call to <code>clear()</code> and just keep the <code>resize()</code>.</p>\n<h1>Printing results</h1>\n<p>It's weird to see <code>operator&lt;&lt;</code> just print the root mean square error, but having a function <code>print()</code> that prints the whole state of the neural network. I would expect them to do the same thing. If the user of this class just wants to print the error value, then they can just do that themselves, the difference in typing between <code>std::cout &lt;&lt; net</code> and <code>std::cout &lt;&lt; net.mse()</code> is minimal.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T14:39:41.760", "Id": "519601", "Score": "0", "body": "thanks, some mentions:\n I name all the things weirdly like that (it's just my style). \nlong/int was necessary in that for loop. rand() works well mostly so why not, but still fixed it, learning rate is not static constexpr, user should be able to change that (so I prefer it to be just public member), others were fixed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T14:54:43.590", "Id": "519605", "Score": "0", "body": "Well, if there is consistency in your weirdness it's fine I guess :) The `long` is avoidable, I've updated the answer to show how." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T09:57:03.010", "Id": "263182", "ParentId": "263126", "Score": "2" } }, { "body": "<p>All your output statements are of the form:<br />\n<code>std::cout &lt;&lt; (&quot; Layer[&quot; + std::to_string(i) + &quot;] = \\n {\\n&quot;);</code><br />\nthat is very weird. Why are you using <code>to_string</code> and concatenating the strings for the output, rather than just using <code>&lt;&lt;</code> normally?</p>\n<p>That is: <code>cout &lt;&lt; &quot; Layer[&quot; &lt;&lt; i &lt;&lt; &quot;] = \\n {\\n&quot;;</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T14:32:24.557", "Id": "519599", "Score": "0", "body": "you are right, fixed it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T14:30:24.737", "Id": "263189", "ParentId": "263126", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T00:42:38.193", "Id": "263126", "Score": "2", "Tags": [ "c++", "performance", "machine-learning", "neural-network" ], "Title": "Updated version of my first neural network in c++" }
263126
<p>The <a href="https://i.stack.imgur.com/ElBNM.png" rel="nofollow noreferrer">exercise</a> is asking to make wider stripes similar to the previous exercise. I've included the exercise and code from it along with code that I've been messing with to get the desired result.</p> <p>I know it can be done easily with loops, but the point of the exercise is to use what has been already introduced in the book. <a href="http://www.facom.ufu.br/%7Emarcelo/PF/pictures_racket.pdf" rel="nofollow noreferrer">http://www.facom.ufu.br/~marcelo/PF/pictures_racket.pdf</a></p> <p>I need a way to implement a series expression (5n+4) in order to get the result I desire.</p> <p>I'm starting to think there isn't a way without looping or using if statements ect... (trying to use conditionals only is the goal here) I think what I have will suffice, but I know it's not right and the book will show a better way later on I assume.</p> <p>I would like some feedback on the first exercise if there was a way to improve it and some critiquing on the wide-stripe logic as well.</p> <p>The exercise or code isn't complete, but you can see where I'm going with it if you run the code. I'm missing a cleaner way to write it, but it hasn't struck me yet.</p> <pre><code>(require picturing-programs) ; builds an image black to red from left to right (see above lines 282-305) (define (always-zero x y) ; x a number ; y a number 0 ) (define WIDTH 150) (define HEIGHT 100) ; make-stripes : number number -&gt; Image ; Takes in a width and height to create a shape ; with even and odd numbered stripes (define (red-stripe x y) (cond [(= (modulo (* y y) 2) 0) 255] [else 0])) (define (blue-stripe x y) (cond[(= (modulo (* y y) 3) 1) 255] [else 0])) (define (make-stripes width height) (build3-image width height red-stripe always-zero blue-stripe)) ; another-make-stripe-function (define (add5 y) (+ y 5)) (define (red-stripe2 x y) (cond [(even? (add5 y)) 255] [else 0])) (define (blue-stripe2 x y) (cond[(odd? (- 150 y)) 255] [else 0])) (define (make-wide-stripes width height) (build3-image width height red-stripe2 always-zero blue-stripe2)) (build3-image 150 100 red-stripe2 always-zero blue-stripe2) (define red (color 255 0 0 255)) (define blue (color 0 0 255 255)) (define total-rows (/ HEIGHT 5)) ;20 (define (row y) (+ y 5)) ; (define (0-4? n) (and (&gt;= n 0) (&lt;= n 4))) (define (5-9? n) (and (&gt;= n 5) (&lt;= n 9))) (define (10-14? n) (and (&gt;= n 10) (&lt;= n 14))) (define (15-19? n) (and (&gt;= n 15) (&lt;= n 19))) (define (20-24? n) (and (&gt;= n 20) (&lt;= n 24))) (define (25-29? n) (and (&gt;= n 25) (&lt;= n 29))) (define (blue-or-red x y) (cond [(0-4? y) blue] [(5-9? y) red] [(10-14? y) blue] [(15-19? y) red] [(20-24? y) blue] [(25-29? y) red] [else blue])) (define (random-br-picture width height) (build-image width height blue-or-red)) (build-image 150 100 blue-or-red) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T12:04:44.823", "Id": "519574", "Score": "0", "body": "`total-rows` is invalid since `HEIGHT` isn't defined anywhere. Also `always-zero` is missing in this snippet, making it not runnable. If you wanna be nice to readers consider adding `(require picturing-programs)` at the top too, maybe `#lang racket` too, so it's a fully self-contained example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T12:53:06.470", "Id": "519576", "Score": "0", "body": "@ferada okay fixed and added. I think I should brush up on recursive practices in order to grasp what needs to be done? And I don't know how I can implement total-rows in the program yet, but I know there need to be 20 rows for this height. I want to write it for any number though." } ]
[ { "body": "<p>To answer that first, you don't need anything complicated, just observe\nthat the pattern is binary, on and off, and compare that with\nhow odd and even numbers are following the same pattern, then apply that\nand scale by the strip width.</p>\n<p>Once you see that, you can define it in multiple ways, one would be\nsomething like this:</p>\n<pre><code>(define (blue-or-red x y)\n (cond [(odd? (quotient y 5)) red]\n [else blue]))\n</code></pre>\n<p>Or you can of course use the <code>modulo</code> check again, basically defining your own <code>odd?</code> (or <code>even?</code>) predicate that way.</p>\n<p>Note that <code>cond</code> is equivalent to an <code>if</code> here, you could write this as\nwell:</p>\n<pre><code>(define (blue-or-red x y)\n (if (odd? (quotient y 5)) red blue))\n</code></pre>\n<hr />\n<p>You wrote that you want things to make sense with any kind of image\nsize: Simply ensure that everywhere you're referring to 150 or 100 you\ninstead use the proper variables, <code>WIDTH</code> and <code>HEIGHT</code> and you should be\nall set. In general using uppercase like that is unusual for variable\nnames though. Also you'd normally probably make these parameters to a custom function too, so that they're not globally defined (e.g. <code>(define (make-my-bitmap width height) ...)</code> and then pass them through).</p>\n<hr />\n<p>While defining them as separate predicates is unnecessary, the number\ncomparisons can also be simplified:</p>\n<pre><code>(&lt;= 15 n 19)\n</code></pre>\n<p>This works because <code>&lt;=</code> accepts one or more arguments and does what\nyou'd expect it to.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T14:35:55.063", "Id": "263190", "ParentId": "263127", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T01:37:11.227", "Id": "263127", "Score": "3", "Tags": [ "racket" ], "Title": "Wide-stripes function in Racket" }
263127
<p>I'm don't know much about javascript, but and slowly learning through using other people's code. The below code I'm using is quite repetitive, with the only variance being the ID names. I feel like someone will know (and hopefully show) me how to do this show/hide function better.</p> <pre><code>$('#C7-Drawer-Shelf-Combo').on('change', function () { if (this.value) { $(&quot;.under-drawer-bench&quot;).show(); } else { $(&quot;.under-drawer-bench&quot;).hide(); } }); $('#T7-Drawer-Shelf-Combo').on('change', function () { if (this.value) { $(&quot;.under-drawer-bench&quot;).show(); } else { $(&quot;.under-drawer-bench&quot;).hide(); } }); $('#C11-Drawer-Shelf-Combo').on('change', function () { if (this.value) { $(&quot;.under-drawer-bench&quot;).show(); } else { $(&quot;.under-drawer-bench&quot;).hide(); } }); $('#T11-Drawer-Shelf-Combo').on('change', function () { if (this.value) { $(&quot;.under-drawer-bench&quot;).show(); } else { $(&quot;.under-drawer-bench&quot;).hide(); } }); $('#14X-Drawer-Shelf-Combo').on('change', function () { if (this.value) { $(&quot;.under-drawer-bench&quot;).show(); } else { $(&quot;.under-drawer-bench&quot;).hide(); } }); $('#17X-Drawer-Shelf-Combo').on('change', function () { if (this.value) { $(&quot;.under-drawer-bench&quot;).show(); } else { $(&quot;.under-drawer-bench&quot;).hide(); } }); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T14:42:40.467", "Id": "519508", "Score": "1", "body": "Are you sure this is correct? It seems strange that all event handlers would toggle the same element(s). Can you add the HTML that belongs to this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T16:40:46.220", "Id": "519517", "Score": "0", "body": "@RoToRa that is a good point! We won't know until the OP replies/updates the post but my hunch is the HTML is similar to the HTML in the fiddle linked in [their other post from the day before](https://codereview.stackexchange.com/q/263060/120114) just with added class names on the elements with ids like `*-Under-Drawer-Bench`." } ]
[ { "body": "<p>You can change the selector to select all items at once.</p>\n<p>First option: select all ids comma separated:</p>\n<pre><code>$('#C7-Drawer-Shelf-Combo,#T7-Drawer-Shelf-Combo,#C11-Drawer-Shelf-Combo').on('change', function () {\n if (this.value) {\n $(&quot;.under-drawer-bench&quot;).show();\n } else {\n $(&quot;.under-drawer-bench&quot;).hide();\n }\n});\n</code></pre>\n<p>Second option (prefered): use a css class. Add a specific css class to all those items, and use this class in the selector:</p>\n<pre><code>&lt;select id=&quot;#C7-Drawer-Shelf-Combo&quot; class=&quot;custom-class&quot;&gt;....&lt;/select&gt;\n&lt;select id=&quot;#T7-Drawer-Shelf-Combo&quot; class=&quot;custom-class&quot;&gt;....&lt;/select&gt;\n&lt;select id=&quot;#C11-Drawer-Shelf-Combo&quot; class=&quot;custom-class&quot;&gt;....&lt;/select&gt;\n\n$('.custom-class').on('change', function () {\n if (this.value) {\n $(&quot;.under-drawer-bench&quot;).show();\n } else {\n $(&quot;.under-drawer-bench&quot;).hide();\n }\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-06T00:22:22.933", "Id": "520856", "Score": "0", "body": "Thank you, I ended up using your first option, with a little edit - I used the ID phrase that @aloisdg wrote \"[id$='-Drawer-Shelf-Combo']\" to save having to type all IDs out." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T07:37:48.403", "Id": "263134", "ParentId": "263128", "Score": "5" } }, { "body": "<p>You can target all element ending with <code>[id$='-Drawer-Shelf-Combo']</code>. Use <a href=\"https://api.jquery.com/toggle/\" rel=\"nofollow noreferrer\"><code>toggle</code></a> to show/hide.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>$(&quot;[id$='-Drawer-Shelf-Combo']&quot;).on('change', function () {\n $(&quot;.under-drawer-bench&quot;).toggle();\n});\n</code></pre>\n<p>Withtout the HTML/CSS I cant test it though.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-06T00:28:18.280", "Id": "520857", "Score": "0", "body": "Thanks for your comment, I needed to keep it as show/hide instead of toggle as I didn't want it to toggle off in case if the user changes their mind and selects a different dropdown option, but I used your ID phrase as that saved me having to type all the IDs out (see comment on answer)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T07:39:38.157", "Id": "263135", "ParentId": "263128", "Score": "1" } } ]
{ "AcceptedAnswerId": "263134", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T01:46:21.090", "Id": "263128", "Score": "3", "Tags": [ "javascript", "beginner", "jquery" ], "Title": "Show/hide for multiple IDs" }
263128
<p>I manage a fleet of IoT devices.</p> <p>As for now, GitHub announced that the username-password authentication would be deprecative soon, so I have to change the password on each device to the GitHub access token. I store the new token at AWS secrets manager. And those are the scripts to extract the new token and implement it on the device.</p> <p>update_github_token.py</p> <pre><code>from get_aws_secret_manager import get_secret import subprocess SECRET_NAME = 'prod/GitHub/Token' GITHUB_TOKEN_KEY = 'droneGitHubToken' GITHUB_USER_NAME = 'danAairlines' GITHUB_REPO_OWNER = 'Aairlinesfox' def get_github_tokken(): github_secret_dict = get_secret(SECRET_NAME) return github_secret_dict[GITHUB_TOKEN_KEY] def build_token_github_url(): github_token = get_github_tokken() return f'https://{GITHUB_USER_NAME}:{github_token}@github.com/{GITHUB_REPO_OWNER}/drone.git' def update_drone_github_url(): github_url = build_token_github_url() subprocess.run(f'sudo git remote set-url origin {github_url}', shell=True, check=True) if __name__ == '__main__': update_drone_github_url() </code></pre> <p>The second module is AWS script, as appears on their website. I just modified the get_secret function by adding args. And at the end of the file, I added:</p> <pre><code>secret = json.loads(get_secret_value_response['SecretString']) return secret </code></pre> <p>get_aws_secret_manager.py</p> <pre><code># If you need more information about configurations or implementing the sample code, visit the AWS docs: # https://aws.amazon.com/developers/getting-started/python/ import boto3 import base64 from botocore.exceptions import ClientError import json def get_secret(aws_secret_name: str, aws_region_name: str = &quot;eu-central-1&quot;): secret_name = aws_secret_name region_name = aws_region_name # Create a Secrets Manager client session = boto3.session.Session() client = session.client( service_name='secretsmanager', region_name=region_name ) # In this sample we only handle the specific exceptions for the 'GetSecretValue' API. # See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html # We rethrow the exception by default. try: get_secret_value_response = client.get_secret_value( SecretId=secret_name ) except ClientError as e: if e.response['Error']['Code'] == 'DecryptionFailureException': # Secrets Manager can't decrypt the protected secret text using the provided KMS key. # Deal with the exception here, and/or rethrow at your discretion. raise e elif e.response['Error']['Code'] == 'InternalServiceErrorException': # An error occurred on the server side. # Deal with the exception here, and/or rethrow at your discretion. raise e elif e.response['Error']['Code'] == 'InvalidParameterException': # You provided an invalid value for a parameter. # Deal with the exception here, and/or rethrow at your discretion. raise e elif e.response['Error']['Code'] == 'InvalidRequestException': # You provided a parameter value that is not valid for the current state of the resource. # Deal with the exception here, and/or rethrow at your discretion. raise e elif e.response['Error']['Code'] == 'ResourceNotFoundException': # We can't find the resource that you asked for. # Deal with the exception here, and/or rethrow at your discretion. raise e else: # Decrypts secret using the associated KMS CMK. # Depending on whether the secret is a string or binary, one of these fields will be populated. if 'SecretString' in get_secret_value_response: secret = json.loads(get_secret_value_response['SecretString']) return secret else: decoded_binary_secret = base64.b64decode(get_secret_value_response['SecretBinary'])``` </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T07:46:34.637", "Id": "263136", "Score": "1", "Tags": [ "python", "python-3.x", "programming-challenge" ], "Title": "Python script to replace GitHub password with tokens" }
263136
<p>I made a small adaptive function that sorts vector:</p> <pre class="lang-cpp prettyprint-override"><code>template&lt;class T&gt; vector&lt;T&gt; BubbleSort(vector&lt;T&gt; arr, bool (*compare)(T, T)) { const int arraySize = arr.size(); //Size of vector. Is it ok to leave it const? //int i = 1 - to be able to swap with previous(i-1) element for (int i = 1; i &lt; arraySize; i++) { if (compare(arr[i], arr[i - 1])) { //Swap 2 elements. Is swap() better? T helper = arr[i]; arr[i] = arr[i - 1]; arr[i - 1] = helper; if (i != 1) i -= 2; //Because in the next cycle i will be ++ } } return arr; } </code></pre> <p>It can be a little confusing, so I wrote some comments...<br> I also tested it with <code>sort()</code> function, which actually a way more faster. I've tested it on 10000 numbers.</p> <p>First, <code>for</code> was like <code>for (int i = 0; i &lt; arr.size(); i++)</code>. And time of sort was ~5 seconds. When I changed <code>arr.size()</code> to variable, it is now ~4.5 seconds.</p> <p>...while <code>sort()</code> takes only ~0.04 seconds...</p> <p>I know <code>sort()</code> may use another sorting algorithm, but could you please show how <code>BubbleSort()</code> function can be more faster?</p> <h2>Edit</h2> <p>Here is part of the code I tested this function:</p> <pre class="lang-cpp prettyprint-override"><code>vector&lt;int&gt; arr; ifstream dataset(&quot;Numbers.txt&quot;); int n; while (dataset &gt;&gt; n) arr.push_back(n); //Here comes the test: clock_t start = clock(); arr = sortfunctions::BubbleSort&lt;int&gt;(arr, [](int a, int b) { return a &lt; b; }); clock_t end = clock(); </code></pre> <p>I checked the result(<code>arr</code>) before and after. It is actually sorted. And if you will look at this result in the console, you can see a visual pattern by the way.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T13:22:47.350", "Id": "519495", "Score": "2", "body": "This is some strange variation of bubble sort, if it is bubble sort at al. Bubble sort is when the biggest element \"floats\" to the top, then the second \"floats\" under it and so on. So, you need two loops: i from 1 to n-1 (including), j from 1 to n-i (including), so [j] and [j-1] gets swapped if needed. In this one you're stepping back when swap occurs - so elements are \"drawn\" sometimes. I'm not sure if you'll have a reasonable number of comparisons here.\n\nIf you need performance - you should use the best algorithm available. That's basics. No use of optimizing bad algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T13:28:32.393", "Id": "519497", "Score": "1", "body": "If you are interested in optimizing your searches, I suggest you take a look at [quicksort](https://en.wikipedia.org/wiki/Quicksort), [merge sort](https://en.wikipedia.org/wiki/Merge_sort) and [heapsort](https://en.wikipedia.org/wiki/Heapsort), and maybe a hybrid, such as [introsort](https://en.wikipedia.org/wiki/Introsort)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T13:59:19.853", "Id": "519499", "Score": "1", "body": "Invoking the C++20 CPO `std:::swap(a, b)` is in general more performant and non-throwing due to specialization. You can still use the two-step `using std::swap; swap(a, b);` which earlier versions needed for the same advantages. Or even `std::iter_swap(&a, &b);`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T14:40:35.647", "Id": "519507", "Score": "3", "body": "This is an insertion sort: you have a sorted sublist that starts at size 1, and you repeatedly take the next non-sorted element and sort it into its place in the sublist until the entire list is sorted. The main \"quirk\" making this different from a textbook insertion sort is that you don't keep track of the length of the sorted sublist, so you have to find it again after each insertion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T14:57:22.580", "Id": "519510", "Score": "3", "body": "Thanks @trentcl - this is https://en.wikipedia.org/wiki/Gnome_sort\nEven changing to bubble sort will speed it up." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T14:08:54.223", "Id": "519585", "Score": "0", "body": "@Deduplicator are you missing \"`ranges:`\" in your CPO comment? I've never heard of the `:::` syntax." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T14:45:49.507", "Id": "519603", "Score": "0", "body": "@JDługosz Triple-colon is the new and improved DWIM, don't cha know?" } ]
[ { "body": "<p>You understand that making the code faster means reducing the value of k1 in the complexity of <code>k1*n²</code> while using a different algorithm would change that to <code>k2*n*log(n)</code>. But understanding that...</p>\n<p><code>template&lt;class T&gt; vector&lt;T&gt; BubbleSort(vector&lt;T&gt; arr, bool (*compare)(T, T)) {</code><br />\nOne speed difference between <code>std::sort</code> and the C library's sort is that the former takes the comparison operation as a <em>functor</em> typed by a template argument.\nPassing a function-calling-object rather than a pointer to a regular function allows the compiler to <em>inline</em> the call. Generally, compilers won't follow pointers to functions, even when it's clear to the human reader that the specific function is known at the time of that specific call. But passing a functor makes the choice of function part of the type system, and the compiler naturally inlines that.\nMany function calls to a trivial compare operation will be a lot of overhead.</p>\n<p>So, take the comparison operation in the same way that the standard library takes code parameters in <code>sort</code> and any of the standard algorithms, <em>not</em> as a C-style plain pointer to function.</p>\n<p>This should be the largest contributor.</p>\n<hr />\n<p>In the same signature, I see you are passing <code>arr</code> by value, and then returning a copy of that. The compiler will use the <code>move</code> constructor for the <code>return</code> which will eliminate copying of the dynamically allocated memory.\nBut you are, by design, copying the array and sorting that copy. The <code>std::sort</code> sorts in-place so does not copy the whole thing.</p>\n<hr />\n<p><code>const int arraySize = arr.size(); //Size of vector. Is it ok to leave it const?</code><br />\nWell, does the size change?</p>\n<p><code>//Swap 2 elements. Is swap() better?</code><br />\nYes! Does it make a difference in your actual benchmark? Well, you never showed the test code so I don't know what type <code>T</code> is. Are they expensive to construct and destruct? Are they very large and thus expensive to copy the bytes around? You are not using <code>move</code> semantics and you are causing a duplicate to exist for a while, and a <code>swap</code> for some type could be optimized to not do any of that. For a <code>string</code> (that's not using SSO in both instances) you will find <code>swap</code> to be <em>much</em> faster, for example.</p>\n<hr />\n<p>Your code is using subscripts and a <code>vector</code>, probably porting textbook code that sorts an array. But in C++ we like to use <em>iterators</em> and write a template that works for any kind of sequential container, not just <code>vector</code>. The <code>std::sort</code> can also be called with a subrange of elements in a vector, no problem; you see it's much more versatile.\nThat doesn't affect the performance though. Subscripting a <code>vector</code> is fast.</p>\n<hr />\n<p>Are you benchmarking an optimized build? I'm surprised that saving <code>.size()</code> made that much of a difference!</p>\n<h1>Does it actually work?</h1>\n<p>I only see one loop, making one pass and bubbling the elements up by one position. It doesn't <strong>repeat</strong> that pass <em>n</em> times or until no exchanges were needed.</p>\n<p>This makes your slow performance rather confusing... if it's just making one pass through the array, it should be instantaneous for only 10000 numbers.</p>\n<p><strong>Update:</strong> As <a href=\"https://codereview.stackexchange.com/users/243687/pavlo-slavynskyy\">Pavlo Slavynskyy</a>\npointed out in a comment, your code is actually <a href=\"https://en.wikipedia.org/wiki/Gnome_sort\" rel=\"nofollow noreferrer\">Gnome Sort</a> or <em>stupid sort</em>.</p>\n<blockquote>\n<p>The gnome sort is a sorting algorithm which is similar to insertion sort in that it works with one item at a time but gets the item to the proper place by a series of swaps, similar to a bubble sort. It is conceptually simple, <strong>requiring no nested loops</strong>. The average running time is O(n²) but tends towards O(n) if the list is initially almost sorted.</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T16:40:52.923", "Id": "519518", "Score": "1", "body": "Regarding `.size()` - if element type (T) is allowed to alias the size variable (or in vector case the \"begin and \"end\" pointer variables which are used to calculate size), then a loop that has \".size()\" in the header will re-load the size on every iteration (instead of keeping it in a register), because compiler needs to produce correct code for the event of that size being overwritten. Example: https://godbolt.org/z/deofze8va" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T16:44:57.973", "Id": "519519", "Score": "1", "body": "Do you have a reference that `return arr;` and `return std::move(arr)` are different? I understand that the copy-elision doesn't apply, but surprised that returning a local copy isn't allowed to treat it as an rvalue. In [my test](https://gcc.godbolt.org/z/qWWWzf5se), the resultant code is identical, and the only difference is that the `std::move()` version causes a GCC warning about the redundant move operation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T13:54:20.147", "Id": "519581", "Score": "1", "body": "@TobySpeight I see that return _does_ automatically move from parameters. I must have been confusing it with something else (NRVO?) or the CPPCON presentation I remember watching might be slightly different from the final standard." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T14:49:12.270", "Id": "519604", "Score": "1", "body": "Learn something new every day. Never heard of \"Gnome\" sort before. Bit cruel calling it stupid sort when it has a best case of `n` and a very low k value. I like it. Obviously bad for large data sets but should be good for small sets (where the n^2 has not overwhelmed the k value)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T15:22:18.143", "Id": "519608", "Score": "0", "body": "It's _stupid_ because it forgets where it left off. Introducing a variable would turn it into an _insertion sort_. Swapping and comparing every element is only better than doing a binary search and bulk copying of the elements to be moved when the number of elements to move is about 5, for such simple numeric type elements." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T14:53:35.203", "Id": "263147", "ParentId": "263140", "Score": "3" } } ]
{ "AcceptedAnswerId": "263147", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T11:37:20.500", "Id": "263140", "Score": "1", "Tags": [ "c++", "performance", "sorting", "vectors" ], "Title": "C++ vector bubble sort in my edition" }
263140
<p>I started reading a book about python two days ago and today I wrote my first code. It's supposed to be a rock, paper, scissors game and from the tests I've done so far it works quite well.</p> <p>However since I'm new I had to google a lot stuff and I'm 100% sure that there are a lot of things I could have done better, especially regarding the amount of elif-statements that I needed in order to cover every possible outcome.</p> <p>Any advice is appreciated!</p> <pre><code>#Imports the random module import random #Prints the introduction to the game print(&quot;Welcome! This program allows you to play the famous game: Rock, paper, scissors! \n&quot;) #Asks the user for input a = input(&quot;Now it's your time to choose, what will you take? Rock, paper or scissors? &quot;) #Repeats the users choice for aesthetic reasons print (&quot;You chose&quot;, a, &quot;!&quot;) #Turns the users input into a lowercase word for an easier use later on a = a.lower() #Creates a list of choices for the computer to &quot;choose&quot; from game_list = [&quot;Rock&quot;, &quot;Paper&quot;, &quot;Scissors&quot;] #Lets the computer choose a random option b = random.choice(game_list) #Shows the user which option the computer choose print(&quot;The computer chose&quot;, b, &quot;!&quot;) #Turns the computers choice into a lowercase word for an easier use later on b = b.lower() #All the possible outcomes and conditions the computer has to check if a == &quot;rock&quot; and b == &quot;rock&quot;: print(&quot;It's a draw!&quot;) elif a == &quot;rock&quot; and b == &quot;paper&quot;: print(&quot;You lost!&quot;) elif a == &quot;rock&quot; and b == &quot;scissors&quot;: print(&quot;You won!&quot;) elif a == &quot;paper&quot; and b == &quot;rock&quot;: print(&quot;You won!&quot;) elif a == &quot;paper&quot; and b == &quot;paper&quot;: print(&quot;It's a draw!&quot;) elif a == &quot;paper&quot; and b == &quot;scissors&quot;: print(&quot;You lost!&quot;) elif a == &quot;scissors&quot; and b == &quot;rock&quot;: print(&quot;You lost!&quot;) elif a == &quot;scissors&quot; and b == &quot;paper&quot;: print(&quot;You won!&quot;) elif a == &quot;rock&quot; and b == &quot;scissors&quot;: print(&quot;It's a draw!&quot;) else: print(&quot;Something went wrong.&quot;) print(&quot;Have you typed in your choice correctly?&quot;) #The computer says goodbye print(&quot;Thank you for playing, I hope you had fun!&quot;) </code></pre> <p>I'll also add my &quot;worksheet&quot; or whatever you want to call it. I've seen a video on Youtube of a guy saying that it's important to first think about what the program has to do, before you start coding.</p> <p>So here is what I wrote before I started and what I wrote after I was done (corrections) and after I had to add more things that I didn't think of before:</p> <ol> <li>The program introduces the game to the player.</li> <li>The program has to ask the player for input (Rock, paper or scissors).</li> <li>It has to save the input as a variable to use it later on.</li> <li>The program itself has to choose an option by itself (randomly).</li> <li>The program needs to create conditions for outcomes for every possible combination of decisions the player and the computer can make.</li> <li>The program has to test the human input and computer choice under the conditions.</li> <li>The computer has to tell the player what the outcome is (output).</li> <li>The computer should say goodbye.</li> </ol> <p>Corrections:</p> <ol> <li>I had to import the random module first.</li> <li>I decided that it looks better if the program repeats the user input.</li> <li>I decided that it was smarter to turn the user input into an lowercase word, so that the program wouldn't run into trouble later on (during the conditions).</li> <li>Creating a list made the random choice easier.</li> <li>I decided that it looks better if the program outputs the computer choice.</li> <li>Lowercase word again.</li> </ol> <p>Advice here is appreciated too, especially regarding my way of writing down what the program has to do.</p>
[]
[ { "body": "<p><strong>Organize code in commented paragraphs or small sections</strong>. It's good that you\nare being methodical in your approach and that you have embraced code comments.\nHowever, every good thing can be taken to unhelpful extremes. A\ncomment-per-line or a comment-per-step is probably too much. Comments do not\nhelp much if they merely duplicate what's already clear from the code. They\nwork much better as organizational devices, as mechanisms to provide a\nhigh-level summary of the code's purpose and main points, or to clarify tricky details. Think of comments the way you might think of subheadings in an long\nemail message (organizational) or as ways to elaborate on complex portions of\nthe code (explanatory). Since nothing in this program is very complex\nalgorithmically, your comments can be mostly organizational.</p>\n<p><strong>Normalize your internal data</strong>. Your code needs a list of the choices. Store\nthem either lowercase or uppercase -- whichever makes computation easier. If\nyou need them capitalized differently for presentation to the user, Python has\nmany ways to do that easily. The idea is to standardize your data so that the\ncode logic is simpler.</p>\n<p><strong>Use data structures to eliminate repetition</strong>. Your code has a big <code>if-else</code>\nstructure than can be reduced to a simple dict-lookup. This game has a small\nnumber of cases to handle: put them in a dict that maps every pair of choices\nto the correct outcome.</p>\n<p><strong>Aim for variable names that communicate well</strong>. Naming is never easy, but\nit is important for writing clear, easy-to-read, easy-to-maintain code.\nYour current names strike me as too abstract (<code>a</code> and <code>b</code>) and less specific\nand direct than they could be (<code>game_list</code>).</p>\n<p><strong>Favor less chatty messages</strong>. This is a bit of a stylistic point, but most\nhumans don't want to slog through long messages from their computer overlords.\nAlso, code is easier to maintain and edit if your messages are concise. Get to\nthe point in as few words as possible.</p>\n<p><strong>Validate user input</strong>. Rather than having a mystery outcome (<em>something\nwent wrong</em>), just tell the user they goofed up.</p>\n<p><strong>Why limit the fun</strong>? Wrap a <code>while True</code> loop around your code and let the\nuser play as long as they like.</p>\n<pre class=\"lang-python prettyprint-override\"><code>import random\n\n# Set up the choices and outcomes.\n\nCHOICES = ['rock', 'paper', 'scissors']\n\nDRAW = 'Draw.'\nWON = 'You won!'\nLOST = 'You lost!'\n\nOUTCOMES = {\n ('rock', 'rock'): DRAW,\n ('rock', 'paper'): LOST,\n ('rock', 'scissors'): WON,\n ('paper', 'rock'): WON,\n ('paper', 'paper'): DRAW,\n ('paper', 'scissors'): LOST,\n ('scissors', 'rock'): LOST,\n ('scissors', 'paper'): WON,\n ('scissors', 'scissors'): DRAW,\n}\n\n# Play game.\n\nwhile True:\n # Get human choice and validate.\n human = input('Rock, paper, or scissors? ').lower().strip()\n if not human:\n break\n elif human not in CHOICES:\n print(&quot;Invalid choice.&quot;)\n continue\n\n # Computer choice.\n computer = random.choice(CHOICES)\n print(f&quot;The computer chose {computer}.&quot;)\n\n # Game outcome.\n print(OUTCOMES[human, computer])\n\n</code></pre>\n<p><strong>Future improvements you might consider</strong>. Keep track of wins and losses. Let\nthe user freely abbreviate their choice (eg, entering just <code>r</code> for <code>rock</code>, etc).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T19:57:22.403", "Id": "519532", "Score": "0", "body": "Oh wow. So simple. Very nice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T00:16:47.440", "Id": "519551", "Score": "0", "body": "I saw this and couldn't resist eliminating the manually defined `OUTCOMES` array. I'm not sure it's the neatest style, but I'd offer the following:\n`ENDGAMES = ['Draw.', 'You lost!', 'You won!']`\n`OUTCOMES = {(first, second): ENDGAMES[(second_i-first_i) % len(CHOICES)] for first_i, first in enumerate(CHOICES) for second_i, second in enumerate(CHOICES)}`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T00:35:27.657", "Id": "519552", "Score": "1", "body": "@yoniLavi Yes, I was briefly tempted as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T06:45:37.757", "Id": "519561", "Score": "1", "body": "Wow, thank you a lot! I'll need some time to understand the code you wrote, but it's incredible that you can create the same game with less code while also adding stuff to the game itself. I wrote down every advice you gave me and I'll try to apply it in my next project that I'll post in a few hours. :) Thanks again!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T17:39:12.433", "Id": "263158", "ParentId": "263150", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T15:17:21.553", "Id": "263150", "Score": "4", "Tags": [ "python", "beginner", "rock-paper-scissors" ], "Title": "Rock, paper and scissors" }
263150
<p>As part of my testing, I have to connect to Unix server using putty and execute few unix jobs.</p> <p>Feature file Steps for test scenario:</p> <pre><code>Scenario Outline: Job execution in Unix Given I logged into unix server When I navigate to job directory &quot;&lt;job_directory_path&gt;&quot; and submit the job &quot;&lt;job&gt;&quot; Then I validate job run status code And close the session Examples: data@jobs.xlsx:jobs | | | | | snapshot of excelsheet jobs.xlsx |jobdirectorypath|jobname| |/com/home/joblist|QAWAS12| |/com/home/joblist|QAWAS13| </code></pre> <p>Step definition file</p> <pre><code>@Given(&quot;^I logged into unix server$&quot;) public void i_logged_into_unix_server() throws Throwable { try{ Unixcon ucon = new Unixcon.getInstance(); uc.con_to_unix(); System.out.println(&quot;connected&quot;); }catch(Exception e){ e.printStackTrace(); } } @When(&quot;^I navigate to job directory \&quot;([^\&quot;]*)\&quot; and submit the job \&quot;([^\&quot;]*)\&quot;$&quot;) public void i_navigate_to_job_directory_something_and_submit_the_job_something(String jobdirectorypath, String jobname) throws Throwable { try{ Unixcon ucon = new Unixcon.getInstance(); uc.execute_job(jobdirectorypath, jobname); System.out.println(&quot;job executed:&quot;+jobname); }catch(Exception e){ e.printStackTrace(); } } @Then(&quot;^I validate job run status code$&quot;) public void i_validate_job_run_status_code() throws Throwable { try{ Unixcon ucon = new Unixcon.getInstance(); String status_code = String.valueOf(ucon.ch.getExitStatus()); if(status_code == 0){ System.out.println(&quot;Passed&quot;); write_to_excel(&quot;status&quot;,status_code,&quot;Passed&quot;); }else{ System.out.println(&quot;Failed&quot;); write_to_excel(&quot;status&quot;,status_code,&quot;Failed&quot;); }catch(Exception e){ e.printStackTrace(); } } @And(&quot;^close the session$&quot;) public void close_the_session() throws Throwable { try{ Unixcon ucon = new Unixcon.getInstance(); ucon.close_session(); System.out.println(&quot;closed&quot;); }catch(Exception e){ e.printStackTrace(); } } </code></pre> <p>Unixcon.JAVA</p> <pre><code>public class Unixcon{ public JSch jsch =null; public Session session = nulll; public Channel ch =null; String host = TestProperty.getProperty(&quot;HOSTNAME&quot;); String username = TestProperty.getProperty(&quot;USERNAME&quot;); String password = TestProperty.getProperty(&quot;PASSWORD&quot;); int port = TestProperty.getProperty(&quot;PORT&quot;); private static Unixcon ucon; public static Unixcon getInstatnce(){ if(ucon==null){ ucon = new Unixcon(); } return ucon; } private Unixcon(){ super(); } public void con_to_unix(){ try{ jsch = new JSch(); session = jsch.getSession(username,host,port); session.setpassword(password); Properties p = new Properties(); p.put(&quot;StrictHostKeyChecking&quot;, &quot;no&quot;); session.setconfig(p); session.connect(); }catch(Exception e) { e.printStackTrace(); } } public void execute_job(String jobdirectorypath, String jobname){ try{ ch = session.OpenChannel(&quot;exec&quot;); ((ChannelExec) ch).setCommand(&quot;cd&quot; + jobdirectorypath +&quot; &amp;&amp; ./&quot; + jobname); ch.connect(); InputStrem in = ch.getInputStream(); BufferedReader r = new BufferedReader(new InputStreamReader(in)); String l = &quot;&quot;; while((l=r.readLine()) != null){ System.out.println(l); } }catch(Exception e){ e.printStachTrace(); } } public void close_session() { try{ if(session != null) { ch.disconnect(); session.disconnect(); }catch(Exception e){ e.printStachTrace(); } } } </code></pre> <p>Is my implementation approch correct? Please provide your suggestions for code improvement.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T12:59:41.897", "Id": "519865", "Score": "1", "body": "Methods initialise variables called \"ucon\" then attempt method calls on \"uc\". If the OP won't present compiled and tested code, why should we review it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-27T20:28:46.333", "Id": "520248", "Score": "1", "body": "@dariosicily [Only the OP is allowed to edit the code in the question.](https://codereview.meta.stackexchange.com/q/762) As such I have rolled back your edit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-28T05:33:54.933", "Id": "520263", "Score": "0", "body": "@Peilonrayz Thank you for your help and explanation." } ]
[ { "body": "<blockquote>\n<p>Is my implementation approch correct?</p>\n</blockquote>\n<p>You mean, your implementation of <code>Unixcon.JAVA</code> ? Then if it works as expected it may be correct but I doubt because there are some typos and invalid syntax in your code:</p>\n<h2>Strange errors</h2>\n<p><em>(that looks like you have not done your homework)</em></p>\n<ul>\n<li><p>The test do a <code>new Unixcon.getInstance()</code>. Which is invalid because</p>\n<ol>\n<li>The constructor is private, so you cannot create any instance outside of the class.</li>\n<li>There are no parentheses in your constructor</li>\n</ol>\n<p>-&gt; If you want to call a static method, you should do <code>Unixcon.getInstance()</code></p>\n</li>\n<li><p>The test use <code>getInstance()</code> while your class declare <code>getInstatnce()</code></p>\n<p>-&gt; Align your names, compile and test your code before posting it.</p>\n</li>\n<li><p>Missing brackets, the <code>if</code> in <code>close_session</code> has an unbalanced bracket.</p>\n</li>\n</ul>\n<p>Anyway, there are some possible improvements:</p>\n<h2>Singleton</h2>\n<ul>\n<li>Your <code>Unixcon</code> is a singleton this means that you cannot run two processes in parallel without running in troubles.</li>\n<li>Your singleton may not be unique; there are many articles explaining how to get one unique instance.</li>\n</ul>\n<h2>Naming</h2>\n<ul>\n<li>Java use <em>lowerCamelCase</em> for methods names. Rename to <code>conToUnix</code>, <code>executeJob</code>, etc...</li>\n</ul>\n<h2>OO Design</h2>\n<ul>\n<li><p>Use encapsulation to hide the implementation details. Don't expose <code>Channel ch</code> but provide an accessor to <code>getExitStatus()</code></p>\n</li>\n<li><p>Pass the <code>TestProperty</code> so that you can easily connect to another host or use another means to get those values.</p>\n</li>\n</ul>\n<p>That's a personal opinion, but what about having a non singleton connection object that return a <code>JobExecution</code> when you run a job ?</p>\n<pre><code>/* Allow many instances and use an ssh style connection string \n * to clarify your code. But keep another constructor that takes\n * all parameters independently.\n *\n * The UnixConnection implements AutoCloseable for a simpler code\n */ \ntry(UnixConnection connection = new UnixConnection(&quot;user@hostname:port&quot;, password)) { \n JobExecution result = connection.execute(&quot;jobname&quot;, inDirectory);\n /* isSuccessful is a simple test on the exit status, but clarify \n * the intention much more than `== 0`. \n * Alternatively you may want to throw a `JobExceutionError` \n * instead of playing with a status. */\n if ( result.isSuccessful() ) {\n result.getJobName();\n result.getStatus();\n result.getOutputStream(); // Or a String or an Collection/Stream/Iterable&lt;String&gt;\n }\n} \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T19:53:55.097", "Id": "263293", "ParentId": "263152", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T15:40:15.203", "Id": "263152", "Score": "0", "Tags": [ "java", "selenium", "unix", "automation", "cucumber" ], "Title": "Unix batch job execution from BDD automation framework" }
263152
<p>I have some performance critical inter-thread messaging code in C++. Multiple producers, one or more consumers.</p> <p>Profiling dozens of iterations of this messaging code over several years of development, I'm usually fighting mutex contention. If not a direct mutex on a std::queue, then a heap mutex on the data pointed to by the pointers in whatever concurrent_queue I'm using. If I use big (~256 byte) structs to hold data to the consumers to avoid or minimise heap usage, I end up often memcopy bound from move assignment.</p> <p>As an attempt to solve all my problems at once, I've written an allocation free, lock free, MPMC ring buffer. Object are produced and consumed without being even moved. <strong>No mutexes. No allocations. No memcopies. Only atomic operations.</strong></p> <p>I've written some simple tests, and implemented it in the performance critical code. Seems to work, and seems to offer a decent performance improvement in the case my boss cares about. I doubt this is as good as I can get it.</p> <p>I haven't torture tested it. I haven't tested on non MS compilers. I figure this code is hard enough that I should really ask for pointers before getting too deep in.</p> <p>I am interested in any feedback anyone has.</p> <p>Extremely trivialised use case example:</p> <pre><code> // buffer contains 1 &lt;&lt; 8 (256) std::strings RingBuffer&lt;std::string, 8&gt; buffer; // Producer example { auto producer = buffer.TryProduce(); if (!producer) {... handle if we produce too quickly ...} producer-&gt;clear(); // We re-use any existing capacity, so there may be a string here. producer-&gt;push_back('A'); producer-&gt;push_back(.... lots more typically....); // Production completes by the destruction of the producer object. // As soon as this destructor runs, the std::string can be consumed. } // Consumer example { auto consumer = buffer.TryConsume(); if (!consumer) {... handle buffer underrun - ie no instructions in the queue ...} if (!consumer-&gt;empty() &amp;&amp; (*consumer)[0] == 'A') { // Do something with this instruction that's prefixed with &quot;A&quot;. // It's safe to read from any other memory in &quot;*consumer&quot; for as long as we have it // in scope. } // When consumer is destroyed, that memory is made available for producers // to write to. } </code></pre> <p>Main header file:</p> <pre><code>#pragma once /////////////////////////////////////////////////////////////////////////////// // // Implements an allocation free (after initial construction), lock-free, // parallel, multi-producer, multi-consumer ring buffer. Any data // type T is supported, so long as it's default constructible. // // The type doesn't even need to be movable / copyable, as the TryProduce // and TryConsume methods do not force the values to be copied or moved, // although that is a likely enough case that the TryPushBack and TryPopFront // helpers are included. Values are typically consumed from the same address // they're produced in. // // Items added to the end of the buffer and guaranteed to be popped out in // order, or, more strictly, consumption is guaranteed to commence in the // same order that production commenced. // // Eg (single consumer): // // T 1: |---Produce A--------| |---Produce B--------| // T 2: |--Produce C -----| |----produce D------| // T 3: idle.................|Consume A|Consume C|.|Consume D|Consume B| // // Or (multiple consumers): // T 3: idle.................|Consume A|............|Consume D| // T 4: idle..................|Consume C|.............|Consume B| // // LGPL - (c) Ashley.Harris@Maptek.com.au. // /////////////////////////////////////////////////////////////////////////////// #include &lt;atomic&gt; #include &lt;memory&gt; namespace rb { template&lt;class T, uint8_t BitsForItemCount&gt; class RingBuffer { public: static_assert(std::is_default_constructible_v&lt;T&gt;); static_assert(BitsForItemCount &gt; 0); static constexpr uint32_t ItemCount = 1 &lt;&lt; BitsForItemCount; enum class State : uint8_t; struct Consumer; struct Producer; RingBuffer(); // Will attempt to read from the buffer. If the buffer was empty, the // Consumer will return false in boolean context. While the Consumer is in // scope it is guaranteed that the memory your reading will remain // untouched and will not be re-used by any producers. Consumer TryConsume(); // Will attempt to reserve a spot in the buffer for you, and if it // succeeded, you can take your time populating it (eg with a complex // assignment move operation) in safety knowing that no reader will access // it until the Producer goes out of scope. // // If no space in the buffer was available, the producer will // return false in a boolean context. // // There is no way to cancel production once this method has been called, // if this is an issue for you A) Don't call it until you know for sure or // B) set up a no-op value of T that your consumers will safely skip over. // // If you try to cancel by letting an exception escape (e.g. your move // assignment operator throws), that is very bad, as the T may be left in // an invalid state and then submitted to a consumer. This results in an // assertion failure in debug if attempted. Producer TryProduce(); // ------------------ // Simple helpers - it's quite common to want to use this buffer with a // type that implements fast move: // Moves Item into the write pointer of the ring buffer, if it'll fit. // Returns whether the move occurred. bool TryPushBack(T&amp;&amp; Item); // Moves an item from the front of the buffer to ItemDestination, if there // is one to read. Returns whether the move occurred. bool TryPopFront(T&amp; ItemDestination); enum class State : uint8_t { Empty, Populating, Queued, Reading }; private: static constexpr uint32_t ItemDiv = (uint64_t(uint32_t(-1)) + 1) / ItemCount; static_assert( (ItemDiv &amp; (ItemDiv - 1)) == 0, &quot;ItemDiv should always be a power of 2. Otherwise won't wrap correctly.&quot;); struct Consumer { explicit operator bool() const { return myValue; } auto&amp; Get() const { return *myValue; } auto&amp; Get() { return *myValue; } operator const T&amp;() const { return Get(); } operator T&amp;() { return Get(); } T&amp; operator*() { return Get(); } const T&amp; operator*() const { return Get(); } T* operator-&gt;() { return &amp;Get(); } const T* operator-&gt;() const { return &amp;Get(); } Consumer(const Consumer&amp; DontCopy) = delete; Consumer(Consumer&amp;&amp; Move); Consumer&amp; operator=(const Consumer&amp; DontCopy) = delete; Consumer&amp; operator=(Consumer&amp;&amp; Move); void Release(); ~Consumer() { Release(); } Consumer() = default; Consumer(T* Data, std::atomic_uint8_t* State) : myValue(Data), myState(State){}; private: T* myValue = nullptr; std::atomic_uint8_t* myState = nullptr; }; struct Producer { explicit operator bool() const { return myValue; } auto&amp; Get() const { return *myValue; } auto&amp; Get() { return *myValue; } operator const T&amp;() const { return Get(); } operator T&amp;() { return Get(); } T&amp; operator*() { return Get(); } const T&amp; operator*() const { return Get(); } T* operator-&gt;() { return &amp;Get(); } const T* operator-&gt;() const { return &amp;Get(); } Producer(const Producer&amp; DontCopy) = delete; Producer(Producer&amp;&amp; Move); Producer&amp; operator=(const Producer&amp; DontCopy) = delete; Producer&amp; operator=(Producer&amp;&amp; Move); void Release(); ~Producer(); Producer() = default; Producer(T* Data, std::atomic_uint8_t* State) : myValue(Data), myState(State){}; private: T* myValue = nullptr; std::atomic_uint8_t* myState = nullptr; }; std::unique_ptr&lt;T[]&gt; myData; std::unique_ptr&lt;std::atomic_uint8_t[]&gt; myStates; std::atomic_uint32_t myNextRead = 0; std::atomic_uint32_t myNextWrite = 0; }; } </code></pre> <p>Template implementations file:</p> <pre><code>template&lt;class T, uint8_t BC&gt; RingBuffer&lt;T, BC&gt;::RingBuffer() : myData(std::make_unique&lt;T[]&gt;(ItemCount)), myStates(std::make_unique&lt;std::atomic_uint8_t[]&gt;(ItemCount)), myNextRead(0), myNextWrite(0) { } template&lt;class T, uint8_t BC&gt; typename RingBuffer&lt;T, BC&gt;::Consumer RingBuffer&lt;T, BC&gt;::TryConsume() { uint8_t timeout = 1; while (timeout++) { auto toRead = myNextRead.load(std::memory_order_acquire); auto toWrite = myNextWrite.load(std::memory_order_acquire); if (toRead == toWrite) { // Buffer is empty. return Consumer(nullptr, nullptr); } auto readPtr = myData.get() + (toRead / ItemDiv); auto statePtr = myStates.get() + (toRead / ItemDiv); auto oldState = uint8_t(State::Queued); if (statePtr-&gt;compare_exchange_strong( oldState, uint8_t(State::Reading), std::memory_order_release)) { // We've marked it as reading successfully. // Advance the read pointer for the next read. We do it by a large // power of two so that it wraps around at the size of the buffer - // otherwise we end up having to do a compare exchange if the counter // is at end. myNextRead.fetch_add(ItemDiv, std::memory_order_release); return Consumer(readPtr, statePtr); } // We were unable to mark the item for &quot;reading&quot; from &quot;queued&quot;, that // means it was: // - still being populated by a writer. // - given to another consumer on a different thread and the // myNextRead value was incremented by the other thread. // // Loop back around and try again a few hundred times - otherwise // we fail. } return Consumer(nullptr, nullptr); } template&lt;class T, uint8_t BC&gt; typename RingBuffer&lt;T, BC&gt;::Producer RingBuffer&lt;T, BC&gt;::TryProduce() { uint8_t timeout = 1; while (timeout++) { auto toRead = myNextRead.load(std::memory_order_acquire); auto toWrite = myNextWrite.load(std::memory_order_acquire); if (toRead == toWrite + ItemDiv) { // Buffer is full. return Producer(nullptr, nullptr); } auto writePtr = myData.get() + (toWrite / ItemDiv); auto statePtr = myStates.get() + (toWrite / ItemDiv); auto oldState = uint8_t(State::Empty); if (statePtr-&gt;compare_exchange_strong( oldState, uint8_t(State::Populating), std::memory_order_release)) { // We've marked it as populating successfully. // Advance the write pointer for the next write. We do it by a a // large power of two so that it wraps around at the size of the // buffer - otherwise we end up having to do a compare exchange if // the counter is at end. myNextWrite.fetch_add(ItemDiv, std::memory_order_release); return Producer(writePtr, statePtr); } // We were unable to mark the item for &quot;writing&quot; from &quot;empty&quot;, that // means it was: // - still being read by a reader. // - given to another producer on a different thread and the toWrite // value is about to increment. // // Loop back around and try again a few hundred times - otherwise // we fail. } return Producer(nullptr, nullptr); } // Moves Item into the write pointer of the ring buffer, if it'll fit. // Returns whether the move occurred. template&lt;class T, uint8_t BitsForItemCount&gt; inline bool RingBuffer&lt;T, BitsForItemCount&gt;::TryPushBack(T&amp;&amp; Item) { auto producer = TryProduce(); if (!producer) return false; producer.Get() = std::move(Item); return true; } // Moves an item from the front of the buffer to ItemDestination, if there // is one to read. Returns whether the move occurred. template&lt;class T, uint8_t BitsForItemCount&gt; inline bool RingBuffer&lt;T, BitsForItemCount&gt;::TryPopFront(T&amp; ItemDestination) { auto consumer = TryConsume(); if (!consumer) return false; ItemDestination = std::move(consumer.Get()); return true; } template&lt;class T, uint8_t BitsForItemCount&gt; typename RingBuffer&lt;T, BitsForItemCount&gt;::Producer::Producer&amp; RingBuffer&lt;T, BitsForItemCount&gt;::Producer::operator=(Producer&amp;&amp; Move) { Release(); myValue = Move.myValue; myState = Move.myState; Move.myValue = nullptr; Move.myState = nullptr; return *this; } template&lt;class T, uint8_t BitsForItemCount&gt; inline RingBuffer&lt;T, BitsForItemCount&gt;::Producer::Producer(Producer&amp;&amp; Move) { myValue = Move.myValue; myState = Move.myState; Move.myValue = nullptr; Move.myState = nullptr; } template&lt;class T, uint8_t BitsForItemCount&gt; inline void RingBuffer&lt;T, BitsForItemCount&gt;::Producer::Release() { if (myValue) { myState-&gt;store(uint8_t(State::Queued), std::memory_order_release); myValue = nullptr; } } template&lt;class T, uint8_t BitsForItemCount&gt; inline RingBuffer&lt;T, BitsForItemCount&gt;::Producer::~Producer() { if (dbgN::IsDebugFull() &amp;&amp; myValue &amp;&amp; std::uncaught_exception()) { ASSERTF_UNREACHABLE(R&quot;( Exception thrown during a buffer locked for production. Did a move constructor throw? Why would you do that? This will result in partial data being transmitted into the buffer and sent to consumers, which will probably cause issues. (no - we can't rewind the buffer, other producers may of already started on the next element and we can't break ordering guarentees) Don't use exceptions to leave the scope! if you really love exceptions and can't do without them for this tiny region of performance sensitive code - Catch, write a no-op to the buffer that your consumers will skip over safely, Release(), and then rethrow)&quot;); } Release(); } template&lt;class T, uint8_t BitsForItemCount&gt; inline RingBuffer&lt;T, BitsForItemCount&gt;::Consumer::Consumer(Consumer&amp;&amp; Move) { myValue = Move.myValue; myState = Move.myState; Move.myValue = nullptr; Move.myState = nullptr; } template&lt;class T, uint8_t BitsForItemCount&gt; typename RingBuffer&lt;T, BitsForItemCount&gt;::Consumer&amp; RingBuffer&lt;T, BitsForItemCount&gt;::Consumer::operator=(Consumer&amp;&amp; Move) { Release(); myValue = Move.myValue; myState = Move.myState; Move.myValue = nullptr; Move.myState = nullptr; } template&lt;class T, uint8_t BitsForItemCount&gt; inline void RingBuffer&lt;T, BitsForItemCount&gt;::Consumer::Release() { if (myValue) { myState-&gt;store(uint8_t(State::Empty), std::memory_order_release); myValue = nullptr; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T21:29:13.640", "Id": "519540", "Score": "0", "body": "Is this possible: Thread 0: TryConsume => load toRead/toWrite => check empty (not empty) => context switch (right before state compare exchange). In the meantime Thread 1: TryConsume => load toRead/toWrite => advance read ptr => Release. Nothing more to read. Now we get back to Thread 0 and it tries to read already read area and advances \"myNextRead\" somewhere beyond written area." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T21:55:49.927", "Id": "519643", "Score": "2", "body": "related: [Lock-free Progress Guarantees](https://stackoverflow.com/q/45907210) analyzes the MPMC queue from liblfds, which uses sequence numbers in each bucket to avoid having both readers reader the current write-index, and vice versa. (i.e. reduces contention between \"hot\" parts for both sides.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T09:51:18.873", "Id": "519724", "Score": "0", "body": "I don't see how this is lock-free is any better than a mutex version. The heaviest operations that mutexes have are memory fencing - `acquire` and `release` fences. The operations themselves don't take much time bit they require cache data to be reloaded/committed which will slow down whatever code uses the class. What's the advantage over mutexes?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T12:04:23.557", "Id": "519729", "Score": "0", "body": "MPMC are the most difficult queues to get to work properly. Is there any chance you could rework the system to use multiple MPSC instead?" } ]
[ { "body": "<blockquote>\n<pre><code> template&lt;class T, uint8_t BitsForItemCount&gt; class RingBuffer\n</code></pre>\n</blockquote>\n<p>This is missing</p>\n<pre><code>#include &lt;cstdint&gt;\nusing std::uint8_t\n</code></pre>\n<p>That said, I really dislike headers that populate the global namespace, so I would prefer to see <code>std::uint8_t</code> (and its friends) written in full. Is there a reason we need an <em>exactly</em> 8-bit type, or would <code>std::uint_fast8_t</code> be a better choice?</p>\n<blockquote>\n<pre><code>uint8_t timeout = 1;\nwhile (timeout++)\n</code></pre>\n</blockquote>\n<p>This looks like a <code>for</code> loop. I would prefer a countdown, or perhaps a count up to a constant, rather than leaning on the type overflow to end the loop - explicit is better than implicit.</p>\n<p>I had a quick look over the rest, and didn't see anything that jumped out at me, except the many cast of <code>State</code> variables - perhaps suggesting that plain <code>enum : std::uint8_t</code> may be easier than <code>enum class</code> for that type.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T20:03:50.930", "Id": "263161", "ParentId": "263157", "Score": "9" } }, { "body": "<p>I'm mostly going to play advocate for the devil here.</p>\n<h1>Lock-free doesn't mean fast</h1>\n<p>There is a rather persistent misconception that lock-free algorithms are faster than locking algorithms. However, that may not be true. Modern mutex implementations are extemely fast in the uncontended case, and when there is a lot of contention they use a system call that lets the kernel wait for the mutex to become unlocked. A system call definitely has a lot of overhead, but your solution is to spin 255 times. <a href=\"https://stackoverflow.com/questions/2538070/atomic-operation-cost\">Atomic operations are not free</a>, so in the contended case with many threads trying to get access, this might waste a lot of CPU time.</p>\n<p>You really should try to prove your theory that a lock-free implementation is faster than one using mutexes by running benchmarks.</p>\n<h1>Add <code>Produce()</code> and <code>Consume()</code> functions</h1>\n<p>If the ringbuffer is contended, you spin up to 255 times retrying the operation before giving up, and then you just pass the problem to the caller. The caller does not want to deal with this stuff, and will invariably do something suboptimal, like calling <code>std::this_thread::yield()</code> or <code>std::this_thread::sleep_for(some_random_timeout)</code>. Basically, it will either wait too short, wasting more CPU cycles, or will wait too long causing the CPU to be underutilized. Do try to solve this problem, and then implement the solution in <code>class RingBuffer</code>.</p>\n<p>Possible solutions are spinning indefinitely but using some kind of exponential backoff (this might even be done without wasting CPU cycles if your processor supports something like the <a href=\"https://lwn.net/Articles/790920/\" rel=\"noreferrer\">umwait instruction</a>), or using a condition variable to wait after spinning some number of times. There have been lots of efforts over time to find the most optimal way to lock, see for example this LWN article about <a href=\"https://lwn.net/Articles/531254/\" rel=\"noreferrer\">ticket spinlocks</a>.</p>\n<h1>About <code>State::Populating</code></h1>\n<p>Your design allows a producer to reserve an entry in the ringbuffer, then fill it in at leisure, and then have the guarantee that it can immediately transition that entry to <code>State::Queued</code>. That's perhaps nice for the producers, but not so nice for the consumers. Consider that we have two producers, A and B, and A called <code>TryProduce()</code> first. Now there are two entries in the ringbuffer in state <code>State::Populating</code>. But now suppose that B finishes populating its entry much faster than A. The consumers unfortunately cannot do anything with B's entry, they have to wait for A to finish populating before they can progress. This means that throughput is now limited by the producer that populates its entries the slowest. If you have many producers and the time needed to populate varies a lot, it might end up being slower than just having the producers allocate memory, and have the ringbuffer just store <code>std::unique_ptr&lt;T&gt;</code>s.</p>\n<p>There are alternatives; instead of allocating each entry, you could have each producer have a pre-allocated array in which it populates entries. You could take this even further, and have a per-producer ringbuffer, and make <code>TryConsumer()</code> transparently try to pick an element from a producer with a non-empty buffer.</p>\n<h1>Use <code>if</code> with init-statements</h1>\n<p>You can make some code more concise by moving variables initialization into <a href=\"https://en.cppreference.com/w/cpp/language/if\" rel=\"noreferrer\"><code>if</code></a>-statements, for example:</p>\n<pre><code>if (auto consumer = TryConsume(); consumer) {\n ItemDestination = std::move(consumer.Get());\n return true;\n} else {\n return false;\n}\n</code></pre>\n<h1>Pass size of ringbuffer as <code>std::size_t</code></h1>\n<p>Instead of passing <code>uint8_t BitsForItemCount</code>, just use <code>std::size_t ItemCount</code> as the size parameter. This matches the way <code>std::array</code> works, as well as many other fixed-size containers from third-party libraries. You already have a <code>static_assert</code> that will prevent non-POT sizes to be used.</p>\n<p>Regardless, also add a <code>static_assert</code> to limit <code>ItemCount</code> to <span class=\"math-container\">\\$2^{32}\\$</span>, since <code>myNextRead</code> and <code>myNextWrite</code> are only 32 bits.</p>\n<h1>Naming things</h1>\n<p>The names <code>Consumer</code> and <code>Producer</code> are badly chosen; those classes represent &quot;items&quot; or &quot;elements&quot; of the ringbuffer. So perhaps <code>ConsumeItem</code> and <code>ProduceItem</code> would be better, or maybe <code>Consumable</code>/<code>Producable</code> (although the latter sounds weird as well).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T22:01:24.180", "Id": "519644", "Score": "1", "body": "`umonitor` / `umwait` can halt the clock, but that still means they're not getting used for another thread. That's \"not wasting CPU cycles\" only in the sense of being a bit more hyperthreading-friendly than polling in a `pause` or `tpause` loop. And you can get woken up on a store to that line by another core, I think. But if the queue empties, you might well want to tell the OS about it so it can schedule something else, or go into a deeper sleep. Depends on your use-case, whether you expect a producer to always be enqueuing something very soon." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T23:03:16.630", "Id": "519646", "Score": "0", "body": "@PeterCordes It's true that it doesn't let another thread run, perhaps I should have said that it doesn't waste as much *energy*. Also, not reading the memory in a tight loop might also reduce bus traffic (whether that's actual memory access or cache coherency traffic). I didn't think about `umonitor`, that might actually be the thing you want to use here. Unfortunately, it's not something you can rely on if you want to write portable code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T00:08:25.357", "Id": "519652", "Score": "1", "body": "The normal spin-wait strategy is to try read-only until you see something interesting, then try to CAS and see if you win the race. With `pause` between tries, that's 100 cycles on Skylake and later (up from 5 in Broadwell for the reasons you mention: hyperthread contention and reduce wasted reads). Using increasing numbers of pauses between actual tries can also help (backoff), but checking read-only can hit in cache if no other core has written the line since you last checked." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T00:09:40.717", "Id": "519653", "Score": "1", "body": "umonitor + umwait can optimize that further to sleep until a modification to the line, but you wouldn't build your algo around it. For correctness purposes, I don't think it enables anything you couldn't do with normal spin-wait loops that used `pause`. Just maybe saves power and helps wake-up latency. And BTW, `umwait` only works if you've used `umonitor` to configure it, as Intel's insn ref manual says: https://www.felixcloutier.com/x86/umwait" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T16:15:54.507", "Id": "519686", "Score": "0", "body": "weird as it sounds, I've experienced locks being significantly more expensive on Windows than Linux, where spinning was faster in Windows and locks were faster in Linux" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T15:04:13.030", "Id": "519750", "Score": "0", "body": "@hanshenrik: Possibly you were using a Windows lock that was more \"heavy weight\" (e.g. always invoked the kernel even in the uncontended case, like [Preshing discusses for a Windows \"Mutex\" back in 2012](https://preshing.com/20111124/always-use-a-lightweight-mutex/)?), or the Linux lock implementation chose to spin internally in a way that was good for your user-case. Or yeah, also possible that Linux is just better (at least for your workload), by enough that doing your own spinning was worse." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T22:12:26.187", "Id": "263167", "ParentId": "263157", "Score": "16" } }, { "body": "<h1>Not lock-free</h1>\n<p>You've replaced locks with busy-waiting, but that doesn't make the algorithm lock-free. In <code>TryConsume</code>, the first consumer to win the race for the to-be-read item is then responsible for advancing the read pointer. Your other consumers wait for this advancement in a busy-loop -- making no progress.</p>\n<p>In order for the algorithm to be lock-free, other consumers would either have to steal the item from the first consumer, or declare the item already consumed and consume the next one.</p>\n<h1>ABA problem</h1>\n<p>It is possible for multiple consumers to capture the same value of the read pointer and contend for the same item. The idea of &quot;locking&quot; the item by atomically setting its state to <code>Reading</code> after capturing the read pointer doesn't work unfortunately: the item can transition from Queued to Reading to Empty to Populating and back to Queued, all before the first consumer gets to attempt the Queued-&gt;Reading transition. At which point it succeeds and returns an item out-of-order.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T22:12:05.243", "Id": "519645", "Score": "2", "body": "See [Lock-free Progress Guarantees](https://stackoverflow.com/q/45907210) - even a well-designed fixed-size circular buffer queues is only lock-free when they don't fill or empty. That doesn't mean they can't be efficient in the normal case. But it sounds like this particular queue is far worse than that, with unnecessary serialization. (liblfds's MPMC queue also uses a sequence number to track state of each entry, avoiding the ABA problem as well. And yes, once one reader has claimed a read slot, the next reader claims the next slot, potentially finished before the earlier read)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T21:31:57.587", "Id": "263202", "ParentId": "263157", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T17:10:07.410", "Id": "263157", "Score": "20", "Tags": [ "c++", "multithreading", "c++20", "lock-free", "atomic" ], "Title": "C++ lock-free, MPMC Ring buffer in C++20" }
263157
<p>This is a challenge I completed at CodeSignal.</p> <p>You are given an array of desired filenames in the order of their creation. Since two files cannot have equal names, the one which comes later will have an addition to its name in a form of <code>(k)</code>, where <code>k</code> is the smallest positive integer such that the obtained name is not used yet.</p> <p>Return an array of names that will be given to the files.</p> <p>Example</p> <p>For <code>names = [&quot;doc&quot;, &quot;doc&quot;, &quot;image&quot;, &quot;doc(1)&quot;, &quot;doc&quot;]</code>, the output should be <code>fileNaming(names) = [&quot;doc&quot;, &quot;doc(1)&quot;, &quot;image&quot;, &quot;doc(1)(1)&quot;, &quot;doc(2)&quot;]</code>.</p> <pre><code>function fileNaming(names) { arr = [] for (let i = 0; i &lt; names.length; i++) { if (!arr.includes(names[i])) { arr.push(names[i]) } else { for (let j=1; ; j++) { const str = `${names[i]}(${j})` if (!arr.includes(str)) { arr.push(str) break } } } } return arr } </code></pre> <p>The code passed all tests at CodeSignal.</p>
[]
[ { "body": "<p>Seems to be some edge cases to take care of here, so good job on that :)</p>\n<ul>\n<li>You could use a Set instead of an array since you're doing lots of checking the whole array for if an item exists. It would also hammer in the fact that the result should be a unique list of names</li>\n<li>First <code>for</code> loop could be replaced with <code>for...of</code> or <code>forEach()</code> to avoid the index variable.</li>\n<li>Readability could be improved by renaming <code>arr</code> =&gt; <code>newNames</code>, <code>str</code> =&gt; <code>candidateName</code>, <code>fileNaming</code> =&gt; <code>deduplicateFileNames</code>, or something like that. All in all it was pretty readable though.</li>\n<li>Missing <code>const</code> before <code>arr</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T19:14:38.900", "Id": "263160", "ParentId": "263159", "Score": "3" } }, { "body": "<p>There are some good points in the answer by Magnus Jeffs Tovslid already.</p>\n<p>Additionally:</p>\n<ul>\n<li><p>it is wise to include semi-colons unless you are intimately familiar with the rules of <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#automatic_semicolon_insertion\" rel=\"nofollow noreferrer\">Automatic semicolon insertion</a> or are using a tool like Babel</p>\n</li>\n<li><p>the nested <code>for</code> loop could be re-written as a <code>while</code> loop that increments the counter and breaks when it finds a string that isn't in the output array already. With this approach the call to push the new name is outside the loop, and there is no need to manually call <code>break</code>.</p>\n<pre><code>let str = `${names[i]}(1)`, j = 1;\nwhile (arr.includes(str)) {\n str = `${names[i]}(${++j})`; \n}\narr.push(str);\n</code></pre>\n<p>And that could be simplified to a <code>for</code> loop- this would allow the counter variable to be scoped to the loop:</p>\n<pre><code>let str = `${names[i]}(1)`; \nfor (let j = 1; arr.includes(str); str = `${names[i]}(${++j})`) ; //intentional no-op\narr.push(str);\n</code></pre>\n</li>\n<li><p>A functional approach with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce\" rel=\"nofollow noreferrer\"><code>names.reduce()</code></a> could simplify the code for readability, though be aware performance would be affected because of the extra functions being called for each iteration. The example below uses a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\">Set</a> and the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\">spread syntax <code>...</code></a> to put the values in the Set into an array.</p>\n</li>\n</ul>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function fileNaming(names) {\n return [...names.reduce((set, name) =&gt; {\n if (!set.has(name)) {\n set.add(name);\n } else {\n let str = `${name}(1)`;\n for (let j = 1; set.has(str); str = `${name}(${++j})`); //intentional no\n set.add(str);\n }\n return set;\n }, new Set())];\n}\nconst names = [\"doc\", \"doc\", \"image\", \"doc(1)\", \"doc\"];\nconsole.log('output: ', fileNaming(names));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T22:49:05.937", "Id": "263168", "ParentId": "263159", "Score": "3" } } ]
{ "AcceptedAnswerId": "263160", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T18:04:26.223", "Id": "263159", "Score": "4", "Tags": [ "javascript", "array", "ecmascript-6" ], "Title": "File naming (two files cannot have equal names)" }
263159
<p>I have two arrays, <code>arr_of_frequencies</code> and <code>float_array</code>, of the same length — around 500-800k values each. I have to get that down to somewhere between 200 and 300k values per array. Below is the code I've been using so far. It works but it will take around 15 seconds to run, which is about 14 seconds too long.</p> <pre><code>function get_freq_for_each_sweep_value() { if (frequency_span &gt; 3000000000) { while (float_array.length &gt; 300000) { for(var a = 0; a &lt; float_array.length; a++){ float_array.splice(a, 3); arr_of_frequencies.splice(a, 3); }; } } else { while (float_array.length &gt; 300000) { for(var a = 3-1; a &lt; float_array.length; a += 3){ float_array.splice(a, 2); arr_of_frequencies.splice(a, 2); }; } } return arr_of_frequencies; return float_array; }; </code></pre> <p>What I'm trying to do is take my original array and then cut out a certain amount of values. If there are 500k values, then I want to cut 3 out of every 4, so that array [1,2,3,4,5,6,7,8,9] is now only [1,5,9].</p> <p>These arrays have to be passed along to a graphing API in Python that will plot the points, but will only plot up to 300k points at the most. Depending on the inputs (frequency_span) determines how many values there are. The higher the span, the more values there will be. The code I have above is working right now, but it is not working well. Any ways to improve the time, or a better approach to my problem, would be appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T00:01:39.253", "Id": "519650", "Score": "0", "body": "is this a pro-audio app?" } ]
[ { "body": "<p>I would avoid splicing an array. If I remember correctly, changing the size of an array has implications under the hood. It's probably better if you created a new array of new values, if you have memory to spare.</p>\n<p>You can create a custom function that asynchronously iterates and operates through your array instead of a while loop. That way, while it's potentially slower, at least you won't block other operations in your code.</p>\n<p>If you're mostly dealing with numbers, you might want to check out <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays\" rel=\"nofollow noreferrer\">Typed Arrays</a>. They're potentially faster since you're just working with numbers and don't have the extra overhead of regular arrays.</p>\n<p>You might also consider using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators\" rel=\"nofollow noreferrer\">iterators</a>. The general gist of this is that you don't necessarily to represent a sequence of things as something concrete (e.g. an array). You can represent it with an array-like object which can fetch the items lazily/on-the-fly/allows you to write the fetching behavior.</p>\n<p>Or consider using <a href=\"https://nodejs.dev/learn/nodejs-streams\" rel=\"nofollow noreferrer\">streams</a> if the platform you're running on supports it (e.g. node). Set up a pipeline of transformations, and then stream your data through it. There are modules that simplify streams usage, might want to check those out instead of the built-in API.</p>\n<p>If you can, you could also split the work across threads. JavaScript runs on one thread by default. If you can split it out the work to separate workers, that would maximize the use of your processor.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T20:59:16.810", "Id": "263163", "ParentId": "263162", "Score": "1" } }, { "body": "<h2>Avoid <code>Array.splice</code></h2>\n<p>Your code is not clear because you have two returns. Only the first return will return a value the second return is ignored.</p>\n<p>As you are using splice you are ignoring the returns and depending on the fact that the arrays are being reduced in place.</p>\n<p>To get better performance you need to avoid using splice.</p>\n<p>300,000 values should not take much more than 1/2 a second on even the most basic device. (assuming they are just floats).</p>\n<h2>Example</h2>\n<p>The example function does one array at a time and returns a new array if the size is reduced. The max complexity is the <span class=\"math-container\">\\$O(n)\\$</span> where <span class=\"math-container\">\\$n\\$</span> is the size of the result array.</p>\n<p>If you must shorten the existing array in place, this function can also be used, just pass the input array twice as in the second example call.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function reduceArraySize(size, inArray, resultArray = []) {\n if (inArray.length &lt; size) { return inArray }\n const spacing = inArray.length / size;\n var i = -1;\n while (++i &lt; size) {\n resultArray[i] = inArray[Math.round(i * spacing)];\n }\n resultArray.length = size; //if the result is same array shorten it\n return resultArray;\n}\nconst testData = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];\n\nconsole.log(\"Reduce to new array\");\nconsole.log(reduceArraySize(10, testData) + \"\")\nconsole.log(\" \");\nconsole.log(\"Reduce in place\");\nconsole.log(reduceArraySize(15, testData, testData) + \"\");</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Performance</h2>\n<p>The next example creates an array with 30million floats and compares the time to reduce that array to 300,000 items. First it create a new array, and then it does the same in play.</p>\n<p>Reducing the array in place is about 4 times faster as there is no need to allocate new memory for the copy.</p>\n<p>Run snippet (on low end devices it may take a moment or to to build the test array). When its ready Follow instructions (click page)</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function reduceArraySize(size, inArray, resultArray = []) {\n if (inArray.length &lt; size) { return inArray }\n const spacing = inArray.length / size;\n var i = -1;\n while (++i &lt; size) {\n resultArray[i] = inArray[Math.round(i * spacing)];\n }\n resultArray.length = size; //if the result is same array shorten it\n return resultArray;\n}\n\nconst setOf = (size, cb, a = [], i = 0) =&gt; {while (i &lt; size) { a[i] = cb(i++) } return a};\nconst testData = setOf(30_000_000, i =&gt; i);\n\ninfo.textContent =\"Ready click page to reduce \" + testData.length + \" item array to 300,000 items\";\naddEventListener(\"click\", () =&gt; {\n var time1, time2, now = performance.now();\n reduceArraySize(300000, testData);\n time1 = performance.now() - now;\n now = performance.now();\n reduceArraySize(300000, testData, testData);\n time2 = performance.now() - now;\n info.innerHTML = \"Reduce 30,000,000 to 300,000 items.&lt;br&gt;\" +\n \"To new array in \" + (time1 | 0) + \"ms&lt;br&gt;\"+\n \"In place in \" + (time2 | 0) + \"ms&lt;br&gt;\";\n}, {once: true});\n \n \n </code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"info\"&gt;Creating data&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Even faster?</h2>\n<p>There are quicker ways of reducing the array however that will depend on the content (range and type of values in the array).</p>\n<p>If all values can be Floats (32 bit floating point, JS Numbers are Doubles 64 bit floating point) then you could get the GPU to do the work for you (from fractions of a second to a few ms)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T13:43:53.107", "Id": "519579", "Score": "0", "body": "I like your solution a lot, I just implemented it, using the second version of shortening it in place. The only problem I'm having is that, let's say I ask for 250k values total in the array, and there are 900k in it, the 250k spots will be taken up by values in positions 0-600k, would shortening the size of the array each time move it along quicker? To reset size minus a few extra places each time" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T15:00:02.820", "Id": "519606", "Score": "0", "body": "For example, my arrays run from 20 to 50. Spots 0-300k in the array are taken up by the values between 20 and 40, and the values in 50 are left off completely" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T11:31:09.643", "Id": "263185", "ParentId": "263162", "Score": "4" } } ]
{ "AcceptedAnswerId": "263185", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T20:18:23.510", "Id": "263162", "Score": "2", "Tags": [ "javascript", "array", "time-limit-exceeded" ], "Title": "Keeping only every nth element in an array in JavaScript" }
263162
<p>This python program analyzes movie data by finding the average budget of films in a data set - it also identifies films that exceed the average budget calculated.</p> <p>I need advice on my code in terms of (architecture, risks, opportunities, design) so that I can learn how I can code better &amp; grow my skills.</p> <pre><code># List of movies and their budgets movies = [ ('Avengers: Endgame', 400000000), ('Pirates of the Caribbean: On Stranger Tides', 379000000), ('Avengers: Age of Ultron', 365000000), ('Star Wars: Ep. VII: The Force Awakens', 306000000), ('Avengers: Infinity War', 300000000) ] # Allows user to input how many movies they want to add to the list add_new_movie = int(input('How many movies do you want to add? ')) # Takes the name and budget of the movie the user entered and add the movie to the list for _ in range(add_new_movie): name = input('Enter movie name: ') budget = input('Enter movie budget: ') new_movie = (name, int(budget)) movies.append(new_movie) # List representing over budget movies and counter to keep track of the total budget of all the movies in the list over_budget_movies = [] total_budget = 0 # Adds together the budget of each movie for movie in movies: total_budget += movie[1] # Calculates the average cost of all movies in the list average_budget = int(total_budget / len(movies)) # If the movie budget is over the average budget, how much the movies are over budget will be calculated and added to the over budget list for movie in movies: if movie[1] &gt; average_budget: over_budget_movies.append(movie) over_average_cost = movie[1] - average_budget print( f&quot;{movie[0]} was ${movie[1]:,}: ${over_average_cost:,} over average.&quot;) print() # Prints how many movies were over the average budget print( f&quot;There were {len(over_budget_movies)} movies with budgets that were over average.&quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T09:25:34.547", "Id": "519566", "Score": "2", "body": "This is entirely irrelevant to your specific question, but in terms of data analysis, [Hollywood accounting](https://en.wikipedia.org/wiki/Hollywood_accounting) is a good example of [garbage in, garbage out](https://en.wikipedia.org/wiki/Garbage_in,_garbage_out)." } ]
[ { "body": "<p><strong>Data entry without persistence does not make sense in most contexts</strong>. If a\nhuman has to type the data, save it somewhere. It could be a JSON file, CSV\nfile, database, whatever you would like to try. This kind of approach -- where\nthe data lives separately from the code -- has many benefits. It's a good\nvehicle for learning as well, so give it a shot.</p>\n<p><strong>Data entry and reporting are different tasks</strong>. Sometimes you want to add new\ndata to the system. Sometimes you want to analyze that data, get reports, etc.\nIn its simplest form, that might call for a program with 3 functions: a <code>main()</code>\nfunction where the user decides what to do (add data or get a report), and then\none function for each task.</p>\n<p><strong>Use meaningful data objects rather than generic collections</strong>. Currently, you\nrepresent a movie as a 2-tuple. But that's not very declarative: for example,\nyour code has to use <code>movie[1]</code> rather than <code>movie.budget</code>. Modern Python makes\nit super easy to create simple data objects (eg, namedtuple, dataclass, or\nattrs-based classes).</p>\n<p><strong>Avoid mixing computation and printing, if feasible</strong>. It's a good practice to\nseparate computation and anything that has &quot;side effects&quot;. Printing is the most\ncommon example of a side effect. This is a huge topic in computer science, and\nyou can learn more about it as you go forward. But when you're learning, just\ntry to get in the habit of keeping different things separate: for example,\ndon't print over-budget movies while you are creating a list of them.</p>\n<p>Here's an illustration of those ideas (ignoring data entry):</p>\n<pre><code>from collections import namedtuple\n\n# Meaningful data objects.\n\nMovie = namedtuple('Movie', 'title budget')\n\nmovies = [\n Movie('Avengers: Endgame', 400000000),\n Movie('Pirates of the Caribbean: On Stranger Tides', 379000000),\n Movie('Avengers: Age of Ultron', 365000000),\n Movie('Star Wars: Ep. VII: The Force Awakens', 306000000),\n Movie('Avengers: Infinity War', 300000000)\n]\n\n# Computation.\n\ntotal_budget = sum(m.budget for m in movies)\naverage_budget = int(total_budget / len(movies))\nover_budget_movies = [m for m in movies if m.budget &gt; average_budget]\n\n# Printing.\n\nprint(f'Number of overbudget movies: {len(over_budget_movies)}')\nfor m in over_budget_movies:\n diff = m.budget - average_budget\n print(f'{m.title} was ${m.budget}: ${diff} over average.')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T06:01:55.060", "Id": "519560", "Score": "0", "body": "You could also use `total_budget // len(movies)` (floor division, which is identical to casting to an integer for positive numbers). A better version would actually be to round to the nearest whole number (e.g. 3.75 -> 4 instead of 3)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T23:40:27.433", "Id": "263169", "ParentId": "263164", "Score": "9" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T21:02:37.470", "Id": "263164", "Score": "6", "Tags": [ "python", "python-3.x" ], "Title": "Analyzing average movie budgets using Python 3" }
263164
<p>To give a short contextual description: It is a poker game. I plan to add &quot;cards&quot; and a &quot;pot&quot;-object later on and then learn event-driven programming so that I can add a GUI. Essentially the player's placement in the game-objects &quot;player&quot; variable determines their seat.</p> <p>My main questions are in regards to the placement of methods and the data of each object. Do you guys see any sort of future issues with e.g. betting being a player method, and not a round method? Or, that there is no round-method for turning players in-active other than end-round that turns all players inactive?</p> <p>Other than that, pretty much any feedback is welcome, as long as it is backed up with a reasonable explanation of course. I am just trying to learn as many tricks as possible and &quot;future-thinking&quot;.</p> <p>Code:</p> <pre><code>import random import copy import importlib def limit(num, minimum=1, maximum=255): &quot;&quot;&quot;Limits input 'num' between minimum and maximum values. Default minimum value is 1 and maximum value is 255.&quot;&quot;&quot; return max(min(num, maximum), minimum) #A player class - contains name, amount of cash and active-states class player: def __init__(self,name,initMoney): self.cash = initMoney self.chipsInPlay = 0 #How much has this player betted? self.name = name #Data Related To Active-States self.activeGame = 1 #Does it exist at all? Reasons for non-existance: No cash, no chips and no possibility of re-joining self.activeRound = 1 #Does it exist in this round? Reasons for 0: No cash, no chips, folding self.activeTurn = 0 #Is it active this turn? Reasons for 0: Another player is active #If the player has no money and no stake in the pot, they're out of the game def checkIfOut(self): if self.cash == 0 and self.chipsInPlay == 0: self.activeRound = 0 self.activeTurn = 0 self.activeGame = 0 #Checks if the player has enough money to bet the blind and bets - doesn't check activeTurn - Doesn't change: chipsInPlay,activeTurn def blindMoneyBet(self,blind): if blind&lt;self.cash or blind == self.cash: self.cash = self.cash - blind print(f&quot;\nPlayer: {self.name} just bet the blind of {blind}$\nCurrent balance: {self.cash}$\nCurrent money in pot: {self.chipsInPlay}$\n&quot;) return else: print(&quot;blind()-Player: Imagine an all-in function here&quot;) #Checks if the player has enough to bet and bets money for the player, the money goes into the pot #Checks: If allActiveStates = 1 - Changes: activeTurn = 0*,chipsInPlay = +bet - *: unless endTurn = 0 def regularMoneyBet(self,moneyChange,min =0,endTurn = 1): if self.activeGame == 1 and self.activeRound == 1 and self.activeTurn == 1: betLimit = limit(moneyChange,min,self.cash) if moneyChange == betLimit: #He cannot bet more, than he has self.cash = self.cash - moneyChange self.chipsInPlay = self.chipsInPlay + moneyChange print(f&quot;\nPlayer: {self.name} just bet {moneyChange}$\nCurrent balance: {self.cash}$\nCurrent money in pot: {self.chipsInPlay}$\n&quot;) if endTurn == 1: self.activeTurn = 0 elif moneyChange != betLimit: print(f&quot;{self.name} tried to bet: {moneyChange}$, while he only has: {self.cash}$&quot;) elif self.activeGame != 0 or self.activeRound != 0 or self.activeTurn != 0: print(f&quot;Player: {self.name} is not active in the following ways:\nGame: {self.activeGame}\nRound: {self.activeRound}\nTurn: {self.activeTurn}&quot;) #Turns activeRound = 0 def fold(self): self.activeRound = 0 print(f&quot;{self.name} just folded&quot;) def __str__(self): return f&quot;\nName: {self.name} \nCash left: {self.cash}\nMoney in pot: {self.chipsInPlay}\nGame active = {self.activeGame}\nRound active = {self.activeRound}\nTurn active = {self.activeTurn}&quot; #Contains previous turns class gameRound: def __init__(self,players,startingPlayer = 0,bigBlind = 0, smallBlind = 0, tableSize = 5): #Data related to players in the round self.startingPlayer = startingPlayer #Given by the game object at initialization (Object) self.roundPlayers = players #Players who're still in play in the round (list with player objects) self.playersActiveRound = len(players) #Amount of players in the game (integer) #Data related to turns self.turns = [] self.lastTurnType = 0 #For keeping tack of possible actions (Integer) self.latestBet = 0 #The last bet, that was made in this round - To decide how much to raise or check (integer) self.turnNumber = 0 #For keeping track of which turn number, this is (integer) #Data related to who is active this turn self.activeThisTurn = 0 #Which player is active (object) self.activeThisTurnNumber = 0 #What number in the list of active players is the current active player (integer) self.playersActiveTurn = 0 #How many players have self.activeTurn = 1 - used for debugging (integer) #Data related to initial setup self.bigBlind = bigBlind #The bet that the first activeThisTurn has to bet (integer) self.smallBlind = smallBlind #The bet that roundPlayers[activeThisTurnNumber -1] has to bet i.e Player to the left of BBL. (integer) self.saveTurn() #Saves the initial player data at turn X (list with player objects) self.tableSize = tableSize #Debug methods below #Finds how many players are active - integer, not the actual player objects def findPlayersActiveTurn(self): g = 0 for x in self.roundPlayers: if x.activeTurn == 1: g += g self.playersActiveTurn = g #Sets the person who is active this turn, and sets the previous active player as inactive (turn) def setActiveTurn(self,playerName): #Startingplayer, which is the optional argument in the game object, which is passed down into playerName is by default 0 if type(self.activeThisTurn) == player: self.activeThisTurn.activeTurn = 0 if playerName == 0: #If no name is given x = self.roundPlayers[random.randint(0, self.playersActiveRound - 1)] self.activeThisTurn = x self.findActiveNumber() x.activeTurn = 1 elif playerName != 0: #If a name is given for x in self.roundPlayers: if x.name == playerName: x.activeTurn = 1 self.activeThisTurn = x #Saves the current player data as a nested list in the self.turns list def saveTurn(self): z = [] #For storing playerdata for x in self.roundPlayers: y = copy.copy(x) #Makes a copy of the player objects z.append(y) self.turns.append(0) #Adds a new index self.turns[self.turnNumber] = z #Turns this index into z #Finds the current active player's number in the turn order def findActiveNumber(self): g= -1 #List indexes start at 0 for x in self.roundPlayers: g = g +1 if x == self.activeThisTurn: self.activeThisTurnNumber = g #Make a debug such that, if there are more actives this turn, it will say so #Selects the closest roundActive player to the right of the current activeTurnPlayer as the next activeTurn. def nextActive(self): self.findActiveNumber() y = (self.activeThisTurnNumber+1)%len(self.roundPlayers) #Goes one player to the right, modulo so it restarts at 0 if y +1 is out of bounds for x in range(y,len(self.roundPlayers)): #x in [y;self.playersActiveRound[ h = x%len(self.roundPlayers) self.roundPlayers[h].checkIfOut() if self.roundPlayers[h].activeRound == 1 and self.roundPlayers[h] != self.activeThisTurn: #First activeRound player to the right of this current active player self.roundPlayers[h].activeTurn = 1 self.activeThisTurn = self.roundPlayers[h] return() #Ends it else: print(f&quot;\nNo other active players than {self.activeThisTurn.name}&quot;) #Removes inactive players from the round list def removeInactiveRound(self): listOfActivePlayers = [] for x in self.roundPlayers: x.checkIfOut() if x.activeRound == 1 and x.activeGame == 1: listOfActivePlayers.append(x) self.playersActiveRound = len(listOfActivePlayers) self.roundPlayers = listOfActivePlayers #Increments the turn by 1, changes the activeTurn player, removes inactive players and saves the player data to the turnlist def endTurn(self): self.turnNumber = self.turnNumber + 1 self.nextActive() self.removeInactiveRound() self.saveTurn() def startingTurn(self): self.setActiveTurn(self.startingPlayer) #Starting player is provided by the game-object whenever a round is initialized self.activeThisTurn.blindMoneyBet(self.bigBlind) #Blind instead of moneybet, as there are no restrictions in terms of active status print(self.activeThisTurnNumber) self.roundPlayers[self.activeThisTurnNumber-1].blindMoneyBet(self.smallBlind) #This works because -1 = highest number, so if 0 -1 = -1 = highest index in the list class game: def __init__(self,initPlayers,startingPlayer = 0,bigBlind = 25, smallBlind = 10): self.players = initPlayers self.updateValuesPlayersSum() self.playersCash = self.sumList[0] #How Much Money The Players Have excl. In Pot self.playersActiveGame = self.sumList[1] #How Many Players Are Active In The Game (int) self.chipsInPlay = self.sumList[2] #The Current Pot Size self.bigBlind = bigBlind self.smallBlind = smallBlind self.startingPlayer = startingPlayer #The initial starting player for this or the next round self.startRound() #Creates a gameRound object, chooses the initial starting player and makes the players bet BBL and SBL self.currentRound #Sums up the amount of cash held by all players and returns a float def cashPlayersSum(self,players): sum = 0 for x in players: sum = x.cash + sum return sum #Sums the amount of active players and returns an integer def playersActiveGameSum(self,players): sum = 0 for x in players: sum = x.activeGame + sum return sum #Sums the chips in play AKA the Pot and returns number def chipsInPlayPlayersSum(self,players): sum = 0 for x in players: sum = x.chipsInPlay + sum return sum # Sums up all sum-values and adds them to a list def valuesPlayersSum(self,players): totalSum = [] totalCash = self.cashPlayersSum(players) totalActivesGame = self.playersActiveGameSum(players) totalChipsInPlay = self.chipsInPlayPlayersSum(players) totalSum.append(totalCash) totalSum.append(totalActivesGame) totalSum.append(totalChipsInPlay) return totalSum #Updates the game's player-based sums def updateValuesPlayersSum(self): totalSum = self.valuesPlayersSum(self.players) self.sumList = totalSum self.playersCash = self.sumList[0] self.totalActivesGame = self.sumList[1] self.chipsInPlay = self.sumList[2] #Sets a person to be active in the round, and makes the first active player bet, and the player left to him on the list bet. def startRound(self): self.currentRound = gameRound(self.players,self.startingPlayer,self.bigBlind,self.smallBlind) def gameEndTurn(self): self.currentRound.endTurn() #Needs a function that continously allows for each active player to choose an action, unless all - 1 have folded, all have checked, or all have called the bet enough times to end round def __str__(self): return f&quot;\nPlayers in game : {str(self.players)} \nActive players: {str(self.playersActiveGame)} \nPot size: {str(self.chipsInPlay)} \nCash on hand: {str(self.playersCash)} &quot; def testNoob(): player0 = player(&quot;player0&quot;,125) player1 = player(&quot;player1&quot;,125) player2 = player(&quot;player2&quot;,125) players = [player0,player1,player2] aGame = game(players) return aGame </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T20:14:34.530", "Id": "519638", "Score": "1", "body": "The first program that I ever tried to write was an OO poker game. I remember gatting stuck trying to implement a truly random shuffle() method. There were plenty online, but I was overly proud and wanted to do it on my own. I was stuck for a few weeks then had a eureka moment working on something completely different. That is the first time I ever solved a problem that had me stumped. I'm feeling some crazy nostalgia right now. Can't help but smile. Sry for droning on : )" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T20:14:46.847", "Id": "519639", "Score": "1", "body": "As a tip: write it in a way that lets you reuse. You can write `card game` and then sort of extend that. That way, if you want to make solitaire later, you're already halfway there. The first half could be an incredibly useful template for thousands of programs. Oh yea, and start workin on that shuffle method! The earlier the better! XD" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T20:36:10.440", "Id": "519640", "Score": "2", "body": "Adding to my earlier comments, as you are using python, you should write `card game` as a module, and `include` said module at the top of this one. This will give you the reuse effect that I mentioned above. There are many methods, such as deal() and shuffle() and many properties, like Card and Hand(which would be a list of Cards), that are common to just about every card game. Extract them into said module. Python has excellent modularity, imo. Furthermore, this use case will let you use it to your advantage in a big way." } ]
[ { "body": "<p>Welcome to CodeExchange. Here are some ways in which your code can be improved:</p>\n<h1>Code Style</h1>\n<h2>Naming conventions</h2>\n<p>Please, use <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> naming conventions. For example, all classes names have to start with an Uppercase letter:</p>\n<pre class=\"lang-py prettyprint-override\"><code>game -&gt; Game\nplayer -&gt; Player\n</code></pre>\n<p>In general, it seems like you follow them :)</p>\n<h2>Long lines</h2>\n<p>Do not write lines that are too long. It makes them hard to read. For example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>return f&quot;\\nPlayers in game : {str(self.players)} \\nActive players: {str(self.playersActiveGame)} \\nPot size: {str(self.chipsInPlay)} \\nCash on hand: {str(self.playersCash)} &quot;\n</code></pre>\n<p>Is more readable as:</p>\n<pre class=\"lang-py prettyprint-override\"><code># By the way, there is no need to start the string representation of a class\n# with an empty line. If what you want is to have an empty line before \n# the actual class string representation, that should be the caller's responsibility\nreturn f&quot;Players in game : {str(self.players)}\\n&quot;\n + f&quot;Active players: {str(self.playersActiveGame)}\\n&quot;\n + f&quot;Pot size: {str(self.chipsInPlay)}\\n&quot;\n + f&quot;Cash on hand: {str(self.playersCash)}&quot;\n</code></pre>\n<p>Particularly, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> recommends making lines no longer than 80 characters. Some argue that is not enough (specially if you like to give you variables long meaningful names), but it is already a hint. For example , the line:</p>\n<pre class=\"lang-py prettyprint-override\"><code>return f&quot;\\nName: {self.name} \\nCash left: {self.cash}\\nMoney in pot: {self.chipsInPlay}\\nGame active = {self.activeGame}\\nRound active = {self.activeRound}\\nTurn active = {self.activeTurn}&quot;\n</code></pre>\n<p>along with its indentation, is 202 characters long. Most people will not be able to fit such a long line on their screen (not to say it is not easy to read).</p>\n<p>This same thing applies to comments. Its a really good practise to comment you code. However, if you plan on having long comments, write them above the statements, instead of next to them. For example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>self.setActiveTurn(self.startingPlayer) #Starting player is provided by the game-object whenever a round is initialized\n</code></pre>\n<p>Is more readable as such:</p>\n<pre class=\"lang-py prettyprint-override\"><code># Starting player is provided by the game-object whenever a round is \n# initialized\nself.setActiveTurn(self.startingPlayer)\n</code></pre>\n<h2>Consistent style</h2>\n<p>Be consistent in your code style.</p>\n<p>For example, sometimes you leave spaces between operators and sometimes you don't:</p>\n<pre class=\"lang-py prettyprint-override\"><code># Asignments\ng= -1 #List indexes start at 0\ng = g +1\nself.turnNumber = self.turnNumber + 1\nsum = x.chipsInPlay + sum\ny = (self.activeThisTurnNumber+1)%len(self.roundPlayers)\n...\n# Functions/methods\ndef limit(num, minimum=1, maximum=255):\ndef __init__(self,name,initMoney):\ndef regularMoneyBet(self,moneyChange,min =0,endTurn = 1):\n</code></pre>\n<p>Moreover, following <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> recommendations, you should always (there are a few exceptions) leave a space between the operators and variables, as well after commas. So the previous statements/declarations would be better written as:</p>\n<pre class=\"lang-py prettyprint-override\"><code># Asignments\ng = -1 #List indexes start at 0\ng = g + 1\nself.turnNumber = self.turnNumber + 1\nsum = x.chipsInPlay + sum\ny = (self.activeThisTurnNumber + 1) % len(self.roundPlayers)\n...\n# Functions/methods\ndef limit(num, minimum=1, maximum=255):\ndef __init__(self, name, initMoney):\ndef regularMoneyBet(self, moneyChange, min=0, endTurn=1):\n</code></pre>\n<h2>Docstrings</h2>\n<p>Its a really good practise to document you methods/functions. Just use <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings</a> so that your comments can be used to produce documentation.</p>\n<p>For example, if you documment a function like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code># This is my documentation\ndef myFunction():\n pass\n</code></pre>\n<p>Then, you cannot access the documentation if its not by reading the code:</p>\n<pre><code>&gt;&gt;&gt; help(myFunction)\nHelp on function myFunction in module __main__:\n\nmyFunction()\n\n</code></pre>\n<p>However, if you document it as this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def myFunction():\n '''This is my documentation'''\n pass\n</code></pre>\n<p>Then:</p>\n<pre><code>&gt;&gt;&gt; help()\nHelp on function myFunction in module __main__:\n\nmyFunction()\n This is my documentation\n\n</code></pre>\n<p>You can find more on docstrings <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">here</a>.</p>\n<h1>Design</h1>\n<p>Now, regarding code design, here are a few tips:</p>\n<h2>Native types are there for a reason!</h2>\n<h3>Bools</h3>\n<p><code>Player.activeGame</code> is always used as a variable with two states: 0 or 1. That is exactly what <code>bool</code>s are for:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Player:\n def __init__(self,name,initMoney):\n ...\n\n self.activeGame = True\n self.activeRound = True\n self.activeTurn = False\n</code></pre>\n<p>Going one step ahead, its a better idea to name boolean values using verbs:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Player:\n def __init__(self,name,initMoney):\n ...\n\n # Some names that might be more meaningful\n self.isInGame = True\n self.isPlayingCurrentRound = True\n self.isTheirTurn = False\n</code></pre>\n<p>Now you can change you conditions, such as:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if self.activeGame == 1 and self.activeRound == 1 and self.activeTurn == 1\n ...\n</code></pre>\n<p>to simply:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if self.isInGame and self.isPlayingCurrentRound and self.isTheirTurn:\n ...\n</code></pre>\n<p>If you then wonder, for example, how you could get the total number of players in game, there are always solutions to problems. For example:</p>\n<pre class=\"lang-py prettyprint-override\"><code># Instead of this\ndef playersActiveGameSum(self, players):\n sum = 0\n for x in players:\n sum = x.activeGame + sum\n return sum\n\n# You could use a more idiomatic expression\n def playersActiveGameSum(self, players):\n return sum([1 for player in players if player.isInGame])\n</code></pre>\n<h3>Dicts</h3>\n<p>If you plan on having seemingly different data returned in a function, such as here:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def valuesPlayersSum(self, players):\n totalSum = []\n totalCash = self.cashPlayersSum(players)\n totalActivesGame = self.playersActiveGameSum(players)\n totalChipsInPlay = self.chipsInPlayPlayersSum(players)\n\n totalSum.append(totalCash)\n totalSum.append(totalActivesGame)\n totalSum.append(totalChipsInPlay)\n\n return totalSum\n</code></pre>\n<p>You could use a dict, so that accessing the returned values has more semantics:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def valuesPlayersSum(self, players):\n playerStatistics = {}\n\n playerStatistics['totalCash'] = self.cashPlayersSum(players)\n playerStatistics['totalActivesGame'] = self.playersActiveGameSum(players)\n playerStatistics['totalChipsInPlay'] = self.chipsInPlayPlayersSum(players)\n\n return totalSum\n</code></pre>\n<p>This way, you would access the returned value's data as such:</p>\n<pre class=\"lang-py prettyprint-override\"><code>statistics = self.valuesPlayersSum(players)\nprint(f'Total cash: {statistics['totalCash']}')\nprint(f'Total active players: {statistics['totalActivesGame']}')\nprint(f'Total chips in play: {statistics['totalChipsInPlay']}')\n</code></pre>\n<p>Even better, make use of the shipped-by-default <code>namedtuple</code> in the <code>collections</code> module:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import namedtuple\nPlayerStatistics = namedtuple('PlayerStatistics', \n ['totalCash', 'totalActivesGame', 'totalChipsInPlay'])\n\n...\n\ndef valuesPlayersSum(self, players):\n totalCash = self.cashPlayersSum(players)\n totalActivesGame = self.playersActiveGameSum(players)\n totalChipsInPlay = self.chipsInPlayPlayersSum(players)\n\n return PlayerStatistics(totalCash, totalActivesGame, totalChipsInPlay)\n\n...\n\nstatistics = self.valuesPlayersSum(players)\nprint(f'Total cash: {statistics.totalCash}')\nprint(f'Total active players: {statistics.totalActivesGame}')\nprint(f'Total chips in play: {statistics.totalChipsInPlay}')\n</code></pre>\n<h2>Duplicated code</h2>\n<p>Try to follow the DRY (Dont Repeat Yourself) principle. Specially, if you are going to be doing the same exact thing twice one after the other.</p>\n<p>For example, in <code>Game</code>'s constructor, you are doing the following asignments:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def __init__(self,initPlayers,startingPlayer = 0,bigBlind = 25, smallBlind = 10):\n ...\n self.updateValuesPlayersSum()\n self.playersCash = self.sumList[0] # &lt;- Here\n self.playersActiveGame = self.sumList[1] # &lt;- Here\n self.chipsInPlay = self.sumList[2] # &lt;- Here\n ...\n</code></pre>\n<p>When you have already done them within <code>Game#updateValuesPlayersSum</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def updateValuesPlayersSum(self):\n totalSum = self.valuesPlayersSum(self.players)\n\n self.sumList = totalSum\n self.playersCash = self.sumList[0] # &lt;- Here\n self.totalActivesGame = self.sumList[1] # &lt;- Here\n self.chipsInPlay = self.sumList[2] # &lt;- Here\n</code></pre>\n<h1>Other comments</h1>\n<p>When submiting a program like this to be reviewed, it is easier if you provide executable code. That way, we can see the way you intend it to be run.</p>\n<p>The code you have provided, if executed, does nothing other than initializing variables.</p>\n<p>I guess this is already some feedback to begin with. If you wish to update your code, and provide some executable code in another question, I could probably review more of the design :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T16:27:13.313", "Id": "520046", "Score": "0", "body": "Hello m-alorda,\n\nFirst off, thank you very much for using so much of your time to write such a detailed reccomendation/advice.\n\nSecondly, I do plan on building upon this. Just had to make sure, that the fundament didn't have any serious design errors or the like, such that it became a problem later on in the proccess.\n\nI will get back to you, once I have more :)\n\nAlso, thank you very much for the PEP-link. I didn't even know that, that was a thing, but it is exactly what I was looking for." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T18:33:30.623", "Id": "263198", "ParentId": "263166", "Score": "2" } }, { "body": "<p>There's a bunch. In no particular order,</p>\n<ul>\n<li>Consider including PEP484 type hints. For <code>limit()</code>, you can use a generic type parameter to enforce that the input and output are numbers, and the input and output number type (float, int, etc.) match.</li>\n<li><code>class Player</code>, title-case.</li>\n<li><code>init_money</code> and so on, lower_snake_case, for all of your variables and method names.</li>\n<li>Prefixing parameters with <code>init_</code> is not helpful.</li>\n<li><code>active_game</code> etc. should be <code>bool</code> and not <code>int</code>. Checking them should look like <code>if self.active_game</code>, not <code>if self.active_game == 1</code></li>\n<li><code>blind&lt;self.cash or blind == self.cash</code> should just be <code>blind &lt;= self.cash</code></li>\n<li>There are a few like this, but <code>self.cash = self.cash - blind</code> should be <code>self.cash -= blind</code></li>\n<li>Your convention of <code>nnnn$</code> is odd, and at least in North-American culture is more commonly <code>$nnn</code>. The more general thing to do is not add the currency symbol at all, and call into <code>locale.currency()</code> instead.</li>\n<li>Inline <code>foo: #some comment</code> should be <code>foo: # some comment</code></li>\n<li>You seem to be assigning <code>0</code> to indicate that an object reference, i.e. <code>startingPlayer</code>, is &quot;empty&quot;. This should be replaced with <code>None</code> and assigned the <code>Optional</code> type hint.</li>\n<li><code>start_round()</code> should not be called from <code>__init__</code>. The core game logic should be executed in its own method; <code>__init__</code> is only for initialization. Furthering that point: <code>updateValuesPlayersSum</code> is setting new variables that do not appear in <code>__init__</code>, which is ungood.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T19:16:54.673", "Id": "263199", "ParentId": "263166", "Score": "2" } } ]
{ "AcceptedAnswerId": "263198", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T21:55:58.887", "Id": "263166", "Score": "2", "Tags": [ "python", "game" ], "Title": "Object-oriented poker game" }
263166
<p>I made a FizzBuzz program in arm64; I print out the values in hex instead of decimal. This was the first arm64 program I made and I'm looking for advice on how I can improve it.</p> <p>The code to print out the registers was taken from the textbook: <em>Programming with 64-Bit ARM Assembly Language: Single Board Computer Development for Raspberry Pi and Mobile Devices</em> by Stephen Smith.</p> <pre><code>// // FizzBuzz // .global _start // // x0-x2 &amp; x8 - linux shit // x3 - loop counter // x4 - variable // x5 - dividend // x6 - divisor _start: mov x3, #100 // instantiate x3 loop: subs x4, x3, #101 // subtract x3 by 101 mvn x4, x4 // multiply x4 by -1 (bug: x4 is getting set to 0) add x4, x4, #1 // if x4 % 15 == 0 then goto divby15 // r = j - qk (took this divisibility checker from number theory) mov x6, #15 udiv x5, x4, x6 msub x5, x5, x6, x4 cmp x5, #0 b.eq divby15 // if x4 % 3 == 0 then goto divby3 mov x6, #3 udiv x5, x4, x6 msub x5, x5, x6, x4 cmp x5, #0 b.eq divby3 // if x4 % 5 == 0 then goto divby5 mov x6, #5 udiv x5, x4, x6 msub x5, x5, x6, x4 cmp x5, #0 b.eq divby5 // print x // // Prints the register value // // Registers: // x1 - byte address // w5 - loop index // w6 - current character // x7 - register to print // x8 - linux shit // mov x7, x4 ldr x1, =hexstr add x1, x1, #3 mov w5, #2 loop2: and w6, w7, #0xF cmp w6, #10 b.ge letter add w6, w6, #'0' b cont letter: add w6, w6, #('A'-10) cont: strb w6, [x1] sub x1, x1, #1 lsr x7, x4, #4 subs w5, w5, #1 b.ne loop2 mov x0, #1 ldr x1, =hexstr mov x2, #6 mov x8, #64 svc 0 ///////////////////////////////////////////// ///////////////////////////////////////////// ///////////////////////////////////////////// // repeat if x3 isn't equal to 0 inc: sub x3, x3, #1 cmp x3, #0 b.ne loop b end divby3: mov x0, #1 ldr x1, =fizz mov x2, #5 mov x8, #64 svc 0 b inc divby5: mov x0, #1 ldr x1, =buzz mov x2, #5 mov x8, #64 svc 0 b inc divby15: mov x0, #1 ldr x1, =fizzbuzz mov x2, #9 mov x8, #64 svc 0 b inc end: mov x0, #0 mov x8, #93 svc 0 .data fizz: .ascii &quot;fizz\n&quot; buzz: .ascii &quot;buzz\n&quot; fizzbuzz: .ascii &quot;fizzbuzz\n&quot; hexstr: .ascii &quot;0xFF\n&quot; </code></pre>
[]
[ { "body": "<p>Using trial division with <code>udiv</code> isn't the best algorithm for FizzBuzz. It's easier to maintain a pair of counters; one counts up to 3 and resets, and the other to 5. We can combine this into a single counter (up to 15) if we like.</p>\n<p>The range is very limited - when we reach 255, it seems we reset back to 0. That limitation should be documented!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T07:26:26.820", "Id": "263179", "ParentId": "263170", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T00:27:28.287", "Id": "263170", "Score": "2", "Tags": [ "beginner", "assembly", "fizzbuzz", "arm" ], "Title": "FizzBuzz in arm64" }
263170
<p>In this python program, I built a ticketing system with functionality such as keeping track of tickets sold and error handling in case there are any invalid inputs.</p> <p>I need advice on my code in terms of (architecture, risks, opportunities, design) so that I can learn how I can code better &amp; grow my skills.</p> <pre><code>TICKET_PRICE = 10 SERVICE_CHARGE = 2 tickets_remaining = 100 def calculate_price(ticket_amount): return (ticket_amount * TICKET_PRICE) + SERVICE_CHARGE while tickets_remaining &gt;= 1: print('There are {} tickets remaining'.format(tickets_remaining)) # Capture the user's name and assign it to a new variable name = input('What is your name?: ') # Ask how many tickets they would like and calculate the price ticket_amount = input( '{}, How many tickets would you like?: '.format(name)) # Expect a ValueError to happen and handle it appropriately try: ticket_amount = int(ticket_amount) # Raise a ValueError if the request is more tickets than there are available if ticket_amount &gt; tickets_remaining: raise ValueError( 'Sorry, there are only {} tickets remaining.'.format(tickets_remaining)) except ValueError as err: print('Sorry, invalid input {}'.format(err)) else: price = calculate_price(ticket_amount) print('Your total is ${} for {} tickets'.format(price, ticket_amount)) # Prompt the user if they want to proceed Y/N proceed = input( 'Would you like to proceed with your purchase? yes/no: ') if proceed.lower() == 'yes': # TODO: Gather credit card information and process it print('Sold!') tickets_remaining -= ticket_amount else: print('Thank you {}, hope to see you again soon.'.format(name)) # Notify the user when the tickets are sold out print('Sorry, the tickets are sold out.') </code></pre> <p>‘’’</p>
[]
[ { "body": "<ol>\n<li><p>Overall, your code looks pretty clean and well explained;</p>\n</li>\n<li><p>When you want to get a 'yes' or 'no' from the user I advise you to just check the character you need the user to type so that you disregard typos or excesses. So instead of <code>if proceed.lower() == 'yes'</code> I usually use <code>if 'y' in proceed.lower()</code>;</p>\n</li>\n<li><p>You used the Python-3.x tag, so I believe you are using the latest version of Python, so I would consider using f-Strings. With that, I would make the following changes:</p>\n</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>TICKET_PRICE = 10\nSERVICE_CHARGE = 2\n\ntickets_remaining = 100\n\n\ndef calculate_price(ticket_amount):\n return (ticket_amount * TICKET_PRICE) + SERVICE_CHARGE\n\n\nwhile tickets_remaining &gt;= 1:\n print(f'There are {tickets_remaining} tickets remaining')\n\n # Capture the user's name and assign it to a new variable\n name = input('What is your name?: ')\n\n # Ask how many tickets they would like and calculate the price\n ticket_amount = input(f'{name}, How many tickets would you like?: ')\n # Expect a ValueError to happen and handle it appropriately\n try:\n ticket_amount = int(ticket_amount)\n # Raise a ValueError if the request is more tickets than there are available\n if ticket_amount &gt; tickets_remaining:\n raise ValueError(f'Sorry, there are only {tickets_remaining} tickets remaining.')\n except ValueError as err:\n print(f'Sorry, invalid input {err}')\n else:\n price = calculate_price(ticket_amount)\n print(f'Your total is ${price} for {ticket_amount} tickets')\n\n # Prompt the user if they want to proceed Y/N\n proceed = input('Would you like to proceed with your purchase? yes/no: ')\n if 'y' in proceed.lower():\n\n # TODO: Gather credit card information and process it\n\n print('Sold!')\n tickets_remaining -= ticket_amount\n else:\n print(f'Thank you {name}, hope to see you again soon.')\n\n# Notify the user when the tickets are sold out\nprint('Sorry, the tickets are sold out.')\n\n</code></pre>\n<p>As I told you, overall your code is pretty clean and I didn't see much to change, but I hope I somehow helped.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T01:58:56.573", "Id": "263173", "ParentId": "263171", "Score": "3" } }, { "body": "<p>Just some quick remarks:</p>\n<ul>\n<li>it's good that effort has been put into <strong>comments</strong>, but the code is so obvious that the comments do not tell us anything new. So I would instead write a more general docstring on top of the script to explain some of the business logic for example, that may not be obvious if you only see the code but lack the context</li>\n<li>&quot;yes&quot; should probably be the default answer, so just typing enter should be equivalent to <kbd>Y</kbd></li>\n<li>there should be some <strong>persistence</strong>, especially if you will be taking credit card payments - which seems to be a stated purpose. I guess you will be using some database to store data ?</li>\n<li>Journalization/book-keeping: I strongly recommend that you use the <a href=\"https://docs.python.org/3/howto/logging.html\" rel=\"nofollow noreferrer\">Python logger module</a>, and then you can start doing stuff like: <code>logger.info(f'Recording sale of {ticket_amount} for {price} tickets to {name}')</code> to write events to a <strong>log file</strong> on disk (but also to other destinations such as the console if you wish). NB: the entries will be timestamped in the log file if you include the timestamp in your log formater.</li>\n<li>there should be more <strong>validation of user input</strong>, for instance purchasing a <strong>negative</strong> number of tickets will not trigger an exception, but cause logic errors. A simple <strong>regular expression</strong> like <code>^[0-9]+$</code> would suffice to validate the input. Then you can ditch the <code>except ValueError</code> part.</li>\n<li>also, a quality application should have some global <strong>exception handling</strong>. So I recommend to wrap your script in a try/catch block to handle exceptions that are not explicitly addressed in other parts of your code. And of course, log the stack trace to the log file (<code>logger.error('the stack trace details...')</code>). This is even more important for <strong>unattended</strong> programs, or when the program is going to be used by somebody else, and you won't be in front of the screen right when a problem occurs. It's hard to debug when you don't have a trace and have to rely on confused explanations from an end user. If on the other hand they can send you a log file, everything usually becomes clear.</li>\n</ul>\n<p>PS: maybe it's just me but I find ticket_amount to be slightly confusing as a variable name - amount could be understood as the sum of money paid, so I might use something like ticket_quantity instead. And I would rename price to total_price to make it clear it's not the unit ticket price but the final amount paid by customer. Likewise, I would rename name to customer_name because the variable name is too generic. In other languages &quot;name&quot; would be a <strong>reserved keyword</strong>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T21:50:47.917", "Id": "263203", "ParentId": "263171", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T00:43:18.017", "Id": "263171", "Score": "3", "Tags": [ "python", "python-3.x" ], "Title": "Ticketing program using Python 3" }
263171
<p>I'm getting the highest value and its respective from a dictionary and printing it out for the user.</p> <p>Even though it's working, I'm wondering if I'm doing it in the cleanest way. Here it is:</p> <pre class="lang-py prettyprint-override"><code>People = {'Harry': 20, 'Ron': 19, 'Hermione': 21, 'Hagrid': 54} print(max(People, key=People.get), max(People.values())) # Result: Hagrid 54 </code></pre> <p>What would you do differently from this?</p>
[]
[ { "body": "<blockquote>\n<p>What would you do differently from this?</p>\n</blockquote>\n<ul>\n<li><p><a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"noreferrer\">PEP 8</a>: Variable names should be lowercase. <code>People</code> -&gt; <code>people</code>.</p>\n</li>\n<li><p>As @FMc suggested in the comment, better to separate computation and printing. It is easier to understand and change.</p>\n</li>\n<li><p>An alternative (that I find more readable) is to use a lambda in the <code>max</code> function and unpack the tuple afterward:</p>\n<pre><code>people = {'Harry': 20, 'Ron': 19, 'Hermione': 21, 'Hagrid': 54}\nentry = max(people.items(), key=lambda x: x[1])\nprint(*entry)\n# Result: Hagrid 54\n</code></pre>\n<p>Or unpacking directly:</p>\n<pre><code>key, value = max(people.items(), key=lambda x: x[1])\nprint(key, value)\n# Result: Hagrid 54\n</code></pre>\n</li>\n</ul>\n<hr />\n<h2>Edit:</h2>\n<p>Using <a href=\"https://docs.python.org/3/library/operator.html#operator.itemgetter\" rel=\"noreferrer\">operator.itemgetter</a>, as suggested in the comments:</p>\n<pre><code>import operator\n\npeople = {'Harry': 20, 'Ron': 19, 'Hermione': 21, 'Hagrid': 54}\nkey, value = max(people.items(), key=operator.itemgetter(1))\nprint(key, value)\n# Result: Hagrid 54\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T07:14:18.197", "Id": "519564", "Score": "2", "body": "More readable - and likely more efficient, since we only invoke `max()` once here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T16:02:07.847", "Id": "519609", "Score": "2", "body": "I knew `sort` had a `key` parameter, but didn't know `max` had it too. Learn something new every day." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T04:39:26.887", "Id": "263177", "ParentId": "263172", "Score": "20" } }, { "body": "<p>I don't know what your value represents, so I will assume age.</p>\n<p>Since you already have an implementation ready, which is good enough.\nI think just wrapping the code in a function would increase the readability of your code.\nThis way you're providing a descriptive API for the functionality.\nYou can then reuse this in multiple places and change the implementation however you want.</p>\n<p>Then the implementation becomes an &quot;implementation detail&quot; and has nothing to do with the cleanest way.\nSo you will not have to figure out what <code>max</code> in <code>print(max)</code> does, each time you read the code.\nRegardless of how good you can make <code>max</code> look, a function will always be more readable.\nAs when you read the code, you read it like:</p>\n<blockquote>\n<p>entry is max from people with key of entry [1]. Oh ok, you get the entry is the entry with the max value, whatever that means</p>\n</blockquote>\n<pre><code>print(oldestPerson(People))\n</code></pre>\n<p>How you implement the <code>oldestPerson()</code> doesn't really matter and you will be able to refactor it however you want later.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T23:39:27.937", "Id": "519648", "Score": "2", "body": "@Peilonrayz, your edit greatly enriched the answer. Thank you very much for this and the clarifications." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T08:12:34.190", "Id": "263180", "ParentId": "263172", "Score": "8" } }, { "body": "<p>There are many, many different ways to do this. If I had to pick a favourite for legibility, it would be to apply a single <code>max</code> to a generator that reverses the key and value (<code>max_gen</code>, below). If you need to squeeze out every last microsecond of performance, writing your own loop is faster. Whatever you do, don't call <code>max</code> twice.</p>\n<h2>Side-by-side</h2>\n<pre><code>from functools import partial\nfrom operator import itemgetter\nfrom random import shuffle\nfrom timeit import timeit\nfrom typing import Dict, Tuple\nfrom uuid import uuid4\n\nAgeDict = Dict[\n str, # name\n int, # age, years\n]\nAgeTuple = Tuple[str, int]\n\n\ndef max_getter(people: AgeDict) -&gt; AgeTuple:\n return max(people.items(), key=itemgetter(1))\n\n\ndef max_lambda(people: AgeDict) -&gt; AgeTuple:\n return max(people.items(), key=lambda kv: kv[1])\n\n\ndef max_value(people: AgeDict) -&gt; AgeTuple:\n max_v = max(people.values())\n max_k = next(k for k,v in people.items() if v==max_v)\n return max_k, max_v\n\n\ndef max_gen(people: AgeDict) -&gt; AgeTuple:\n # My favourite for legibility\n age, name = max((age, name) for name, age in people.items())\n return name, age\n\n\ndef max_loop(people: AgeDict) -&gt; AgeTuple:\n items_iter = iter(people.items())\n max_name, max_age = next(items_iter)\n for name, age in items_iter:\n if max_age &lt; age:\n max_age = age\n max_name = name\n return max_name, max_age\n\n\ndef max_invert(people: AgeDict) -&gt; AgeTuple:\n inverted = {v: k for k, v in people.items()}\n max_age = max(inverted.keys())\n return inverted[max_age], max_age\n\n\nMETHODS = (\n max_loop,\n max_value,\n max_getter,\n max_gen,\n max_lambda,\n max_invert,\n)\n\n\ndef test():\n d = {'a': 3, 'b': 1, 'c': 4, 'd': 2}\n for method in METHODS:\n assert method(d) == ('c', 4)\n\n\ndef time():\n n = 10_000\n ages = list(range(n))\n shuffle(ages)\n people = {uuid4(): age for age in ages}\n reps = 200\n\n for method in METHODS:\n print(f'{method.__name__:16}', end=' ')\n f = partial(method, people)\n t = timeit(f, number=reps) / reps\n print(f'{t*1e6:&gt;4.0f} us')\n\n\nif __name__ == '__main__':\n test()\n time()\n</code></pre>\n<h2>Output</h2>\n<pre><code>max_loop 388 us\nmax_value 458 us\nmax_getter 571 us\nmax_gen 976 us\nmax_lambda 976 us\nmax_invert 961 us\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T14:30:07.120", "Id": "263412", "ParentId": "263172", "Score": "5" } } ]
{ "AcceptedAnswerId": "263177", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T01:07:14.113", "Id": "263172", "Score": "9", "Tags": [ "python", "hash-map" ], "Title": "The cleanest way to print the max value and its key from a dictionary" }
263172
<p>I'm new in React and state hooks.I'm trying to make a website about creating booklist and save it to local storage. Also uploading image to cloudinary. My problem is ; when i trying to save cloudinary image url to the localstorage, it saves previous url. I think i have a problem about useState,useEffect hooks but i couldnt figure it. Below is my code.</p> <p>LocalStorage.js</p> <pre><code>import React, { useState, useEffect } from 'react' import BookList from '../../components/BookList' import CreateBook from '../../components/CreateBook' const getLocalStorage = () =&gt; { let list = localStorage.getItem('liste') if (list) { return JSON.parse(localStorage.getItem('liste')) } else { return [] } } const LocalStorage = () =&gt; { //state hooks const [list, setList] = useState(getLocalStorage) const [bookName, setBookName] = useState('') const [writerName, setWriterName] = useState('') const [pageNumber, setPageNumber] = useState('') const [info, setInfo] = useState('') const [image, setImage] = useState('') const [uploadUrl, setUploadUrl] = useState('') let id //Function for submit button const handleSubmit = async (e) =&gt; { e.preventDefault() // conditions for fill the blanks if (!bookName || !writerName || !pageNumber || !image) { setInfo('Please fill the blanks') } else { try { const data = new FormData() data.append('file', image) data.append('upload_preset', 'book-list-project') data.append('cloud_name', 'book-list') let response = await fetch( 'https://api.cloudinary.com/v1_1/book-list/image/upload', { method: 'POST', body: data, } ) let result = await response.json() setUploadUrl(result.url) id = new Date().getTime().toString() const newBook = { id: id, bookName: bookName, writerName: writerName, pageNumber: pageNumber, uploadUrl: uploadUrl, } setList([...list, newBook]) setBookName('') setWriterName('') setPageNumber('') setInfo('Book created') setImage('') } catch (error) { console.log(error) } } } //Function for remove specific book from local storage const removeSpecificBook = (id) =&gt; { setList(list.filter((book) =&gt; book.id !== id)) } // Function for clear all books from local storage const removeAllBooks = () =&gt; { setList([]) } useEffect(() =&gt; { localStorage.setItem('liste', JSON.stringify(list)) }, [list]) return ( &lt;div&gt; &lt;CreateBook bookName={bookName} writerName={writerName} pageNumber={pageNumber} handleSubmit={handleSubmit} info={info} setBookName={setBookName} setWriterName={setWriterName} setPageNumber={setPageNumber} setImage={setImage} /&gt; &lt;BookList items={list} removeSpecificBook={removeSpecificBook} removeAllBooks={removeAllBooks} /&gt; &lt;/div&gt; ) } export default LocalStorage </code></pre> <p>Booklist.js</p> <pre><code>import React from 'react' const BookList = ({ items, removeSpecificBook, removeAllBooks }) =&gt; { return ( &lt;div className='container mx-auto'&gt; &lt;div className='mt-20 flex flex-wrap items-center justify-center'&gt; {items.map((item) =&gt; { return ( &lt;div key={item.id} className='p-2 m-2 bg-yellow-100 w-1/4'&gt; &lt;div className='p-1 m-1 flex justify-center'&gt; &lt;img className='object-contain h-52 w-52' src={item.uploadUrl} alt='some img' /&gt; &lt;/div&gt; &lt;div className='p-1 m-1'&gt; &lt;h5 className='font-semibold'&gt;Book Name&lt;/h5&gt; &lt;h3&gt;{item.bookName}&lt;/h3&gt; &lt;/div&gt; &lt;div className='p-1 m-1'&gt; &lt;h5 className='font-semibold'&gt;Writer Name&lt;/h5&gt; &lt;h3&gt;{item.writerName}&lt;/h3&gt; &lt;/div&gt; &lt;div className='p-1 m-1'&gt; &lt;h5 className='font-semibold'&gt;Total Page&lt;/h5&gt; &lt;h3&gt;{item.pageNumber}&lt;/h3&gt; &lt;/div&gt; &lt;div className='flex justify-end'&gt; &lt;button onClick={() =&gt; removeSpecificBook(item.id)} className='px-4 py-2 bg-red-500 rounded-full text-white' &gt; Remove &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; ) })} &lt;/div&gt; {items.length &gt; 1 &amp;&amp; ( &lt;div className='flex justify-center my-5'&gt; &lt;button onClick={removeAllBooks} className='px-8 py-4 bg-red-500 rounded-full text-white' &gt; Remove All &lt;/button&gt; &lt;/div&gt; )} &lt;/div&gt; ) } export default BookList </code></pre> <p>CreateBook.js</p> <pre><code>import React from 'react' const CreateBook = ({ bookName, writerName, pageNumber, handleSubmit, info, setBookName, setWriterName, setPageNumber, setImage, }) =&gt; { return ( &lt;div&gt; &lt;div&gt; &lt;nav className='bg-blue-500 text-center text-white px-6 py-3'&gt; Create Book &lt;/nav&gt; &lt;/div&gt; &lt;div className='bg-red-200 mx-auto w-96 rounded-lg flex justify-center mt-20'&gt; &lt;form onSubmit={handleSubmit}&gt; &lt;div&gt; &lt;div className='p-3 text-center'&gt; &lt;h6&gt;Enter Book Name&lt;/h6&gt; &lt;input value={bookName} onChange={(e) =&gt; setBookName(e.target.value)} className='rounded-md' type='text' placeholder='Book Name' /&gt; &lt;/div&gt; &lt;div className='p-3 text-center'&gt; &lt;h6&gt;Enter Writer Name&lt;/h6&gt; &lt;input value={writerName} onChange={(e) =&gt; setWriterName(e.target.value)} className='rounded-md' type='text' placeholder='Writer Name' /&gt; &lt;/div&gt; &lt;div className='p-3 text-center'&gt; &lt;h6&gt;Enter Total Page Number &lt;/h6&gt; &lt;input value={pageNumber} onChange={(e) =&gt; setPageNumber(e.target.value)} className='rounded-md' type='number' placeholder='Page Number' /&gt; &lt;/div&gt; &lt;div className='p-3 text-center'&gt; &lt;div&gt; &lt;h6&gt;Upload Image&lt;/h6&gt; &lt;/div&gt; &lt;div className='p-3'&gt; &lt;input type='file' onChange={(e) =&gt; setImage(e.target.files[0])} /&gt; &lt;/div&gt; &lt;/div&gt; &lt;div className='flex justify-center p-3'&gt; &lt;button className='bg-blue-500 py-3 px-6 rounded-full text-white'&gt; Submit &lt;/button&gt; &lt;/div&gt; &lt;div className='p-3 text-center text-white'&gt; &lt;h3&gt;{info}&lt;/h3&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; ) } export default CreateBook </code></pre> <p>Also please if you have any suggestions about my code structure, tell me. I dont have any programming history and trying to learn from beginning. I need every suggestions to go further learning programming. Thank you in advance.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T14:18:24.837", "Id": "519681", "Score": "1", "body": "When you need help debugging a problem please use [stackoverflow.com](https://stackoverflow.com/help/how-to-ask). Code Review is for code that is working as expected. We help you improve your coding skills rather than make code work." } ]
[ { "body": "<p>State won't be updated immediately after a state setter function call. Actually when you call a state setter function you tell React to update a state value and schedule a re-render. It means you get that value next time the component renders. The better explanation of how it works is available in the <a href=\"https://reactjs.org/docs/hooks-state.html#recap\" rel=\"nofollow noreferrer\">official docs</a>.</p>\n<p>Now, please take a deeper look at what is happening inside the <code>handleSubmit</code> function right after a response received. You call <code>setUploadUrl(result.url)</code> and it tells React to update <code>uploadUrl</code> value on the next render. The current <code>uploadUrl</code> value won't be changed. Thereby, when you get <code>uploadUrl</code> value a few lines later you still have the same value as you do before calling <code>setUploadUrl</code>. I know it could be unexpected but once you get to used to it, it becomes totally normal. Keep going!</p>\n<p>The solution is pretty simple. Just use <code>result.url</code> instead of <code>uploadUrl</code> when you create a <code>newBook</code>:</p>\n<pre><code> const newBook = {\n id: id,\n bookName: bookName,\n writerName: writerName,\n pageNumber: pageNumber,\n uploadUrl: result.url,\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T01:34:37.543", "Id": "519705", "Score": "0", "body": "Thanks for your answer. Sorry, I forgot to add, I was already able to solve it this way. I'm actually trying to figure out how to solve this problem using useEffect. I tried a couple things, but wasn't able to make it work." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T06:25:53.673", "Id": "263209", "ParentId": "263174", "Score": "2" } } ]
{ "AcceptedAnswerId": "263209", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T03:07:59.277", "Id": "263174", "Score": "0", "Tags": [ "javascript", "react.js" ], "Title": "React useState,useEffect - save variables to local storage" }
263174
<p>In this python program, I used lists and control flow to allow users to add items to a shopping list and display the list.</p> <p>I need advice on my code in terms of (architecture, risks, opportunities, design) so that I can learn how I can code better &amp; grow my skills.</p> <pre><code>shopping_list = [] # Add a function to allow users to ask for help when they need to def show_help(): print('What should we pick up at the store?') print(&quot;&quot;&quot; Enter 'DONE' to stop adding items. Enter 'HELP' for additional info. Enter 'SHOW' to see your shopping list &quot;&quot;&quot;) # Create a function that adds an item to the list def add_to_list(item): shopping_list.append(item) print('{} was added to your shopping list!'.format(item)) print('You have {} items on your list.'.format(len(shopping_list))) # Create a function to print all the items in the shopping list def show_list(): print('My Shopping List:') for item in shopping_list: print(item) show_help() while True: new_item = input('&gt; ') # If the user inputs 'DONE' exit the loop if new_item == 'DONE': break # If the user inputs 'HELP' show the help documentation elif new_item == 'HELP': show_help() continue # if the user inputs 'SHOW' show the list elif new_item == 'SHOW': show_list() continue # Call add_to_list with new item as an argument add_to_list(new_item) show_list() </code></pre>
[]
[ { "body": "<hr />\n<p><a href=\"http://%20https://blog.codinghorror.com/code-tells-you-how-comments-tell-you-why/\" rel=\"nofollow noreferrer\"><strong><code>Code Tells You How, Comments Tell You Why?</code></strong></a></p>\n<p>You have tried to document your code through comments, which is great! However, comments using <code>#</code> are mostly intended for other programmers, and is usually reserved for explaining terse parts of the code. A common way to <em>document</em> your code -- which is intended for the user -- is with <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">PEP 257 -- Docstring Conventions</a>.</p>\n<p>As stated in the title comments (<code>#</code>) should be used sparsely. First you should first strive to make your code as simple as possible to understand without relying on comments as a crutch. Only at the point where the code cannot be made easier to understand should you begin to add comments. I would further break it down into three</p>\n<ol>\n<li>Clarify the intent of your code through functions following the <a href=\"https://dev.to/annalara/solid-programming-part-1-single-responsibility-principle-1ki6\" rel=\"nofollow noreferrer\">single responsibility principle</a></li>\n<li>Clearify what each variable do through clear variable names that follows the standard python formating conventions</li>\n<li>If the &quot;why&quot; is not clear through the first two points, then, and only then do we add comments.</li>\n</ol>\n<hr />\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\"><strong><code>PEP8 - Style Guide for Python Code</code></strong></a></p>\n<p>As to pick the <em>lowest hanging fruits</em>. Consistency is a key part of programming, as it greatly increases readability. It also tells a bit about the coders eye for detail. Lets' look at how you have named your global constants:</p>\n<pre><code>shopping_list = []\n</code></pre>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Pep8</a> recommends the following <a href=\"https://www.python.org/dev/peps/pep-0008/#prescriptive-naming-conventions\" rel=\"nofollow noreferrer\">naming-conventions</a>:</p>\n<ul>\n<li><code>CAPITALIZED_WITH_UNDERSCORES</code> for constants</li>\n<li><code>UpperCamelCase</code> for class names</li>\n<li><code>lowercase_separated_by_underscores</code> for other names</li>\n</ul>\n<p>Now to be fair you mostly follow this standard, which is excellent! I am just pointing it out that it is smart to follow these standards.</p>\n<hr />\n<p><a href=\"https://imgur.com/X17puIB\" rel=\"nofollow noreferrer\"><strong><code>Handling user input</code></strong></a></p>\n<p>Jokes aside as a rule you should <em>never</em> except the user to use the correct input syntax. Instead you should build in checks, exceptions to handle these errors.</p>\n<p>What happens if I write in <code>help</code>? A better way is to let a function handle the user input.</p>\n<pre><code>def get_valid_user_input():\n\n options = [&quot;add&quot;, &quot;done&quot;, &quot;show&quot;]\n print(MENU)\n while True: \n choice = input(&quot;&gt; &quot;).lower()\n if choice not in options:\n print(f&quot;Ooops, you need to enter one of the valid options {options}&quot;)\n else:\n return choice\n</code></pre>\n<hr />\n<p><strong><code>Use of functions</code></strong></p>\n<p>A part that stuck out to me was</p>\n<pre><code>def show_help():\n print('What should we pick up at the store?')\n print(&quot;&quot;&quot;\n Enter 'DONE' to stop adding items.\n Enter 'HELP' for additional info.\n Enter 'SHOW' to see your shopping list\n &quot;&quot;&quot;)\n</code></pre>\n<p>A function should be a block of organized, reusable code that is used to perform a single, related <em>action</em>. Now, let us go through this checklist to see whether or not this should be a function</p>\n<ul>\n<li><p>Is the function called more than <em>twice</em>? ✔️</p>\n</li>\n<li><p>Does the function serve a <em>single purpose</em>? ✔️</p>\n</li>\n<li><p>Does the function perform an <em>action</em>? ❌</p>\n<pre><code>MENU = &quot;What should we pick up at the store?\\n\\n\nEnter 'DONE' to stop adding items.\\n\nEnter 'HELP' for additional info.\\n\nEnter 'SHOW' to see your shopping list&quot;\n</code></pre>\n</li>\n</ul>\n<p>Since the answer to the last question was no, your function takes no input, so it could be a <em>constant</em>.</p>\n<p><strong>Note:</strong> As a general rule of thumb triple quotation marks should be reserved for\n<a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings</a> and not be used for printing.</p>\n<hr />\n<p><a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\"><strong><code>f-strings</code></strong></a></p>\n<p>f-strings are the new way of formating strings in Python, and you should usually use them. For instance</p>\n<pre><code> print('{} was added to your shopping list!'.format(item))\n print('You have {} items on your list.'.format(len(shopping_list)))\n</code></pre>\n<p>becomes</p>\n<pre><code> print(f&quot;{item} was added to your shopping list!&quot;)\n print(f&quot;You have {len(shopping_list)} items on your list.&quot;)\n</code></pre>\n<hr />\n<p><strong><code>Nitpicking</code></strong></p>\n<ul>\n<li>Put the parts of your code that are the ones calling for execution behind a <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == &quot;__main__&quot;:</code></a> guard. This way you can import this python module from other places if you ever want to, and the guard prevents the main code from accidentally running on every import.</li>\n</ul>\n<hr />\n<p><strong><code>A deeper look</code></strong></p>\n<pre><code> What should we pick up at the store?\n\n Enter 'DONE' to stop adding items.\n Enter 'HELP' for additional info.\n Enter 'SHOW' to see your shopping list\n\n &gt;\n</code></pre>\n<p>This would be better if it read</p>\n<pre><code> Enter 'DONE' to stop adding items.\n Enter 'HELP' for additional info.\n Enter 'SHOW' to see your shopping list\n\n What should we pick up at the store?\n &gt;\n</code></pre>\n<p>Secondly what happens if I am unsure and type in help?\nI am then prompted with the same menu.</p>\n<pre><code> What should we pick up at the store?\n\n Enter 'DONE' to stop adding items.\n Enter 'HELP' for additional info.\n Enter 'SHOW' to see your shopping list\n\n &gt; HELP\n What should we pick up at the store?\n\n Enter 'DONE' to stop adding items.\n Enter 'HELP' for additional info.\n Enter 'SHOW' to see your shopping list\n\n &gt;\n</code></pre>\n<p>Not much help there I suppose. While this is semantics, you are handling user input both as an <code>item</code>, which is confusing. For instance</p>\n<pre><code># If the user inputs 'DONE' exit the loop\nif new_item == &quot;DONE&quot;:\n break\n</code></pre>\n<p>A better solution would be to use a different name, such as <code>user_input</code> and later change it to <code>item</code>, when it should be added to a cart. I present a slightly different way of handling this below.</p>\n<hr />\n<p><strong><code>My own attempt</code></strong></p>\n<ul>\n<li>I translated your comments into <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings</a>. They were well written and descriptive!</li>\n<li>I included the <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == &quot;__main__&quot;:</code></a> guard.</li>\n<li><em>Bells and whistles</em> I added typing hints, see <a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"nofollow noreferrer\">PEP484</a>.</li>\n<li>Your shopping list is better structured as a simple class. This makes it easier to maintain and add functionality. (What if you wanted to remove an item from your shopping list?)</li>\n<li>A more robust handling of user input. Try to write in something silly as input, what happens?</li>\n<li>I've separate business logic from user interface by doing my printing in <code>main</code> and keeping <code>ShoppingCart</code> clean.</li>\n<li><code>HELP</code> was removed and instead a <code>screen_clear()</code> was added in addition to showing the menu every time.</li>\n<li>A numerical menu was added as an user enchantment. Whether you think this menu style is an improvement is up to you. If you decide to keep your style, at the very least do <code>input(&quot;&gt; &quot;).upper()</code> to allow users to do <code>add</code>. Numerical inputs are faster to input, can be clearer, and are easier to expand to more options.</li>\n<li>The menu and adding items were split into two functions (Remember, you used <code>item</code> for both).</li>\n</ul>\n<hr />\n<p><strong><code>code</code></strong></p>\n<pre><code>import platform # For getting the operating system name\nimport subprocess # For executing a shell command\n\n\ndef clear_screen():\n &quot;&quot;&quot;Clears the terminal screen.&quot;&quot;&quot;\n\n # Clear command as function of OS\n command = &quot;cls&quot; if platform.system().lower() == &quot;windows&quot; else &quot;clear&quot;\n\n # Action\n return subprocess.call(command) == 0\n\n\nMENU_OPTIONS = [&quot;add item&quot;, &quot;see your shopping list&quot;, &quot;exit&quot;]\n\n\ndef get_user_menu_choice() -&gt; int:\n &quot;&quot;&quot;Gives the user a menu to choose from&quot;&quot;&quot;\n low, high = 1, len(MENU_OPTIONS)\n error_msg = f&quot;Woops, your input must be an integer in {low}...{high}\\n&quot;\n while True:\n print(&quot;Input a number from the list below:&quot;)\n for index, option in enumerate(MENU_OPTIONS):\n print(f&quot; {1+index:&gt;3d}: {option}&quot;)\n try:\n choice = int(input(&quot;\\nPlease enter a number: &quot;))\n if low &lt;= choice &lt;= high:\n return choice\n except ValueError:\n pass\n print(error_msg)\n\n\nclass ShoppingCart:\n def __init__(self):\n self.items = []\n\n def add(self, item: str):\n &quot;&quot;&quot;Create a function that adds an item to the list&quot;&quot;&quot;\n if item != &quot;&quot;:\n self.items.append(item)\n return item\n\n def get_items_from_user(self) -&gt; None:\n clear_screen()\n print(&quot;\\n\\n\\nWrite in the item you want to add to your shopping list!&quot;)\n print(&quot;[leave blank to return to menu]\\n&quot;)\n\n item = self.add(input(&quot;&gt; &quot;))\n while item:\n\n clear_screen()\n print(f&quot;{item} was added to your shopping list!&quot;)\n item_str = &quot;items&quot; if len(self.items) &gt; 1 else &quot;item&quot;\n print(f&quot;You have {len(self.items)} {item_str} in your list.&quot;)\n\n print(&quot;\\nWrite in the item you want to add to your shopping list!&quot;)\n print(&quot;[leave blank to return to menu]\\n&quot;)\n\n item = self.add(input(&quot;&gt; &quot;))\n\n def __str__(self) -&gt; str:\n &quot;&quot;&quot;Create a function to show all the items in the shopping list&quot;&quot;&quot;\n string = &quot;My Shopping List:\\n&quot;\n for index, item in enumerate(self.items):\n string += f&quot;\\n{1+index:&gt;3d}. {item}&quot;\n return string + &quot;\\n&quot;\n\n\ndef main() -&gt; None:\n\n choice, add_item, display_items, exit_program = 0, 1, 2, 3\n\n cart = ShoppingCart()\n\n clear_screen()\n while choice != exit_program:\n choice = get_user_menu_choice()\n if choice == add_item:\n cart.get_items_from_user()\n clear_screen()\n elif choice == display_items:\n clear_screen()\n print(cart)\n\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T16:26:11.277", "Id": "519613", "Score": "0", "body": "I don't see how your numeral menu is an improvement over the OP's strings." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T16:26:45.273", "Id": "519614", "Score": "2", "body": "_As a general rule of thumb triple quotation marks should be reserved for docstrings and not be used for printing_ is simply not true. Triple-quoted heredocs are useful any time that there's a multi-line string literal." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T16:34:06.583", "Id": "519615", "Score": "0", "body": "@Reinderien Ì've had issues with tripple quotation marks using `Sphinx`, `doctest` and other programs that reads and handles docstrings. Which is why I avoid using them. For your second point writing 1, 2 or 3 is much faster, than having to type in exactly `DONE`. An improvement is to allow both, but that is outside the scope of this answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T16:36:19.210", "Id": "519616", "Score": "0", "body": "It's fair to say that the numeral approach is a usability enhancement, but if so you should call it out in your answer and explain your theory as to why" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T16:37:30.360", "Id": "519617", "Score": "0", "body": "Also, `SCREEN_CLEAR` is not portable, and even for operating systems that support it, they might be in pipe mode for which this escape sequence will explode." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T17:09:31.207", "Id": "519624", "Score": "0", "body": "@Reinderien I agree with the `SCREAN_CLEAR` I was lazy and added a quick fix. Added a proper solution now. I also added a quick explenation for the menu choice." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T13:21:20.213", "Id": "263187", "ParentId": "263175", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T03:13:10.597", "Id": "263175", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Shopping list using Python 3" }
263175
<p>I'm looking for feedback on my solution to the following prompt:</p> <blockquote> <p>Given an array of ints, return the index such that the sum of the elements to the right of that index equals the sum of the elements to the left of that index. If there is no such index, return Nothing. If there is more than one such index, return the left-most index. Example: <code>peak([1,2,3,5,3,2,1]) = 3</code>, because the sum of the elements at indexes 0,1,2 == sum of elements at indexes 4,5,6. We don't sum index 3.</p> </blockquote> <p>Questions:</p> <ol> <li>Is the solution best defined recursively? Or is there some kind of higher-order function that I could use?</li> <li>The function <code>peak'</code> takes four arguments. That feels a little unwieldy. Any reasonable way to shorten that parameter list?</li> <li>Conventional programming wisdom says to avoid &quot;magic numbers&quot;, so I introduced some bindings in the <code>let</code> clause. Does that make <code>peak</code> easier to read, or does it just seem like bloat?</li> </ol> <pre><code>peak :: [Int] -&gt; Maybe Int peak numbers = let leftSum = 0 rightSum = sum numbers startingIndex = 0 in peak' numbers leftSum rightSum startingIndex peak' :: [Int] -&gt; Int -&gt; Int -&gt; Int -&gt; Maybe Int peak' [] _ _ _ = Nothing peak' (x:xs) leftSum rightSum index | leftSum + x == rightSum = Just index | otherwise = peak' xs (leftSum + x) (rightSum - x) (index + 1) </code></pre> <p>Prompt source: <a href="https://www.codewars.com/kata/5a61a846cadebf9738000076/train/haskell" rel="nofollow noreferrer">https://www.codewars.com/kata/5a61a846cadebf9738000076/train/haskell</a></p>
[]
[ { "body": "<ol>\n<li>You can use scans to implement this:</li>\n</ol>\n<pre class=\"lang-hs prettyprint-override\"><code>import Data.List\n\npeak :: [Int] -&gt; Maybe Int\npeak [] = Nothing\npeak xs = elemIndex True $ zipWith (==) (scanl1 (+) xs) (scanr1 (+) xs)\n</code></pre>\n<ol start=\"2\">\n<li>I don't think there is a way to reduce the number of arguments, but I think you can give them shorter names in the helper function and if you put the helper function in a where clause then you can also leave out the type signature:</li>\n</ol>\n<pre class=\"lang-hs prettyprint-override\"><code>peak :: [Int] -&gt; Maybe Int\npeak numbers = \n let leftSum = 0\n rightSum = sum numbers\n startingIndex = 0\n in peak' numbers leftSum rightSum startingIndex\n where\n peak' [] _ _ _ = Nothing\n peak' (x:xs) l r i\n | l + x == r = Just i\n | otherwise = peak' xs (l + x) (r - x) (i + 1) \n</code></pre>\n<p>Personally, I believe shorter code is usually more readable than long code. And the length of variable names should be proportional to the size of the scope in which they are used, i.e. local variables should get short names and global or top-level variables and functions should get longer names.</p>\n<ol start=\"3\">\n<li>I think it is bloat in this case, again I really like short code. And I think 0 is never really considered a magic number.</li>\n</ol>\n<p>And recursive helper functions are usually called <code>go</code> in Haskell. And if you put the list as the last argument in the helper function then you can eta-reduce the main function. So the end result would be:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>peak :: [Int] -&gt; Maybe Int\npeak = go 0 (sum xs) 0 where\n go _ _ _ [] = Nothing\n go l r i (x:xs) \n | l + x == r = Just i\n | otherwise = go (l + x) (r - x) (i + 1) xs\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T09:43:47.353", "Id": "263181", "ParentId": "263176", "Score": "2" } } ]
{ "AcceptedAnswerId": "263181", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T03:15:37.540", "Id": "263176", "Score": "1", "Tags": [ "beginner", "haskell", "recursion" ], "Title": "Equivalent partition sums" }
263176
<p>In <a href="https://codereview.stackexchange.com/q/258757/87743">my previous question</a>, one of the answers mentioned that I shouldn't be changing behavior based on the Event class</p> <blockquote> <p>The whole point of classing is that you can get result without having to decide based on instance.</p> </blockquote> <p>I don't disagree with this sentiment, and figured it was more in the acceptable realm due to <a href="https://kotlinlang.org/docs/sealed-classes.html#sealed-classes-and-when-expression" rel="nofollow noreferrer">Kotlin's documentation on the usage pattern with sealed classes</a>.</p> <p>What I'm really looking for is a way to coordinate an interaction between two different types of classes.</p> <p>I haven't used the Visitor pattern much before, but from what I've read this <em>may</em> be an okay use-case.</p> <hr /> <p>A Brazier is an Event-Sourced DDD Aggregate. Its state is reconstituted from Events. Extinguished Braziers can be lit, Lit Braziers can be extinguished. The Brazier encapsulates a finite-state transition, between lit, and extinguished. No change happens if we try to light a Lit Brazier, just as no change happens if we try to extinguish an Extinguished Brazier.</p> <p>When a command is executed, a List of Events is returned, rather than changing the State of the Brazier. The Events are then eventually persisted in an Event Store, and during reconstitution, the new State is initialized.</p> <p>There are two commands a Brazier supports, <code>light</code> and <code>extinguish</code>. There are two Events that result from these commands, <code>Lit</code> and <code>Extinguished</code>.</p> <p>There are two sections of code I'm going to present.</p> <p>The first demonstrates the code using a type-check with <code>when</code> to decide what the new State should be, based on the Event that is being processed.</p> <p>The second demonstrates the code using a (possibly naive) Visitor pattern to decide what the new State should be, based on the Event that is being processed. Here, the Event is the Visitor, calling the correct method on the State, depending on the concrete type of the State.</p> <p>The primary difference between the two is the interface of the Event hierarchy, and the <code>afterApplying</code> method in the State classes.</p> <p>This is a pretty small example of where and how I'd like to use this; in other places where I've ended up in this position, the Events are much more involved, and more State types may be used (6 Events and 5 States in one case).</p> <p>I don't have any plans to allow the State or Event hierarchies to be extended outside of the core I write, so we can assume that there will be a fairly fixed number of Events and States (less than 10 undoubtedly).</p> <h2>BrazierWithWhen</h2> <pre class="lang-kotlin prettyprint-override"><code>// === Point of Interest === sealed class BrazierEvent class LitEvent : BrazierEvent() class ExtinguishedEvent : BrazierEvent() sealed class BrazierState { abstract fun light(): List&lt;BrazierEvent&gt; abstract fun extinguish(): List&lt;BrazierEvent&gt; abstract fun lit(event: LitEvent): BrazierState abstract fun extinguished(event: ExtinguishedEvent): BrazierState abstract fun afterApplying(event: BrazierEvent): BrazierState } class LitState : BrazierState() { override fun light(): List&lt;BrazierEvent&gt; = emptyList() override fun extinguish(): List&lt;BrazierEvent&gt; = listOf(ExtinguishedEvent()) override fun lit(event: LitEvent): BrazierState = this override fun extinguished(event: ExtinguishedEvent): BrazierState = ExtinguishedState() // === Point of Interest === override fun afterApplying(event: BrazierEvent): BrazierState = when (event) { is LitEvent -&gt; lit(event) is ExtinguishedEvent -&gt; extinguished(event) } } class ExtinguishedState : BrazierState() { override fun light(): List&lt;BrazierEvent&gt; = listOf(LitEvent()) override fun extinguish(): List&lt;BrazierEvent&gt; = emptyList() override fun lit(event: LitEvent): BrazierState = LitState() override fun extinguished(event: ExtinguishedEvent): BrazierState = this // === Point of Interest === override fun afterApplying(event: BrazierEvent): BrazierState = when (event) { is LitEvent -&gt; lit(event) is ExtinguishedEvent -&gt; extinguished(event) } } class Brazier( private val state: BrazierState ) { companion object { fun fromEvents(events: List&lt;BrazierEvent&gt; = emptyList()): Brazier = events.fold( Brazier(ExtinguishedState()), Brazier::afterApplying) } fun light(): List&lt;BrazierEvent&gt; = state.light() fun extinguish(): List&lt;BrazierEvent&gt; = state.extinguish() private fun afterApplying(event: BrazierEvent): Brazier = Brazier(state.afterApplying(event)) } </code></pre> <h2>BrazierWithVisitor</h2> <pre class="lang-kotlin prettyprint-override"><code>// === Point of Interest === sealed class BrazierEvent { abstract fun visit(state: LitState): BrazierState abstract fun visit(state: ExtinguishedState): BrazierState } // === Point of Interest === class LitEvent : BrazierEvent() { override fun visit(state: LitState): BrazierState = state.lit(this) override fun visit(state: ExtinguishedState): BrazierState = state.lit(this) } // === Point of Interest === class ExtinguishedEvent : BrazierEvent() { override fun visit(state: LitState): BrazierState = state.extinguished(this) override fun visit(state: ExtinguishedState): BrazierState = state.extinguished(this) } sealed class BrazierState { abstract fun light(): List&lt;BrazierEvent&gt; abstract fun extinguish(): List&lt;BrazierEvent&gt; abstract fun lit(event: LitEvent): BrazierState abstract fun extinguished(event: ExtinguishedEvent): BrazierState abstract fun afterApplying(event: BrazierEvent): BrazierState } class LitState : BrazierState() { override fun light(): List&lt;BrazierEvent&gt; = emptyList() override fun extinguish(): List&lt;BrazierEvent&gt; = listOf(ExtinguishedEvent()) override fun lit(event: LitEvent): BrazierState = this override fun extinguished(event: ExtinguishedEvent): BrazierState = ExtinguishedState() // === Point of Interest === override fun afterApplying(event: BrazierEvent): BrazierState = event.visit(this) } class ExtinguishedState : BrazierState() { override fun light(): List&lt;BrazierEvent&gt; = listOf(LitEvent()) override fun extinguish(): List&lt;BrazierEvent&gt; = emptyList() override fun lit(event: LitEvent): BrazierState = LitState() override fun extinguished(event: ExtinguishedEvent): BrazierState = this // === Point of Interest === override fun afterApplying(event: BrazierEvent): BrazierState = event.visit(this) } class Brazier( private val state: BrazierState ) { companion object { fun fromEvents(events: List&lt;BrazierEvent&gt; = emptyList()): Brazier = events.fold( Brazier(ExtinguishedState()), Brazier::afterApplying) } fun light(): List&lt;BrazierEvent&gt; = state.light() fun extinguish(): List&lt;BrazierEvent&gt; = state.extinguish() private fun afterApplying(event: BrazierEvent): Brazier = Brazier(state.afterApplying(event)) } </code></pre> <h2>BrazierTests</h2> <pre class="lang-kotlin prettyprint-override"><code>import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test class BrazierTests { @Test fun `light extinguished brazier`() { val brazier = Brazier.fromEvents() val events = brazier.light() assertTrue(events.single() is LitEvent) } @Test fun `extinguish lit brazier`() { val brazier = Brazier.fromEvents(listOf( LitEvent() )) val events = brazier.extinguish() assertTrue(events.single() is ExtinguishedEvent) } @Test fun `light lit brazier`() { val brazier = Brazier.fromEvents(listOf( LitEvent() )) val events = brazier.light() assertTrue(events.isEmpty()) } @Test fun `extinguish extinguished brazier`() { val brazier = Brazier.fromEvents() val events = brazier.extinguish() assertTrue(events.isEmpty()) } } </code></pre> <hr /> <p>Both implementations perform well enough (1ms for each test), but what I'm most interested in is if this is the best way to avoid type-checks for something like this.</p> <p>Writing out all of the possible combinations, there are only a couple interesting Event-State transitions (Lit -&gt; Extinguished, Extinguished -&gt; Lit), and some others aren't terribly interesting (Lit -&gt; Lit, Extinguished -&gt; Extinguished). With a couple of commands and Events, it's not so bad, but with 5 and 6, the interface is going to get more verbose with the Visitor pattern (1 method per command, 1 method per Event, per State), whereas we can use <code>when+else</code> to only describe the interesting cases, and ignore the uninteresting ones.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T07:10:24.450", "Id": "263178", "Score": "3", "Tags": [ "kotlin", "type-safety", "immutability", "visitor-pattern" ], "Title": "Replacing type-check with Visitor in Immutable Event-Sourced Aggregate" }
263178
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/263071/231235">Two dimensional bicubic interpolation implementation in Matlab</a> and <a href="https://codereview.stackexchange.com/q/263024/231235">Two dimensional gaussian image generator in C</a>. Besides the Matlab version code, I am attempting to make a C version two dimensional bicubic interpolation function <code>BicubicInterpolation</code> here.</p> <p><strong>The experimental implementation</strong></p> <ul> <li><p><code>BicubicInterpolation</code> function implementation:</p> <pre><code>RGB* BicubicInterpolation(const RGB* const image, const int originSizeX, const int originSizeY, const int newSizeX, const int newSizeY) { RGB* output; output = malloc(sizeof *output * newSizeX * newSizeY); if (output == NULL) { printf(stderr, &quot;Memory allocation error!&quot;); return NULL; } float ratiox = (float)originSizeX / (float)newSizeX; float ratioy = (float)originSizeY / (float)newSizeY; for (size_t y = 0; y &lt; newSizeY; y++) { for (size_t x = 0; x &lt; newSizeX; x++) { for (size_t channel_index = 0; channel_index &lt; 3; channel_index++) { float xMappingToOrigin = (float)x * ratiox; float yMappingToOrigin = (float)y * ratioy; float xMappingToOriginFloor = floor(xMappingToOrigin); float yMappingToOriginFloor = floor(yMappingToOrigin); float xMappingToOriginFrac = xMappingToOrigin - xMappingToOriginFloor; float yMappingToOriginFrac = yMappingToOrigin - yMappingToOriginFloor; unsigned char* ndata; ndata = malloc(sizeof *ndata * 4 * 4); if (ndata == NULL) { printf(stderr, &quot;Memory allocation error!&quot;); return NULL; } for (int ndatay = -1; ndatay &lt; 2; ndatay++) { for (int ndatax = -1; ndatax &lt; 2; ndatax++) { ndata[(ndatay + 1) * 4 + (ndatax + 1)] = image[ clip(yMappingToOriginFloor + ndatay, 0, originSizeY - 1) * originSizeX + clip(xMappingToOriginFloor + ndatax, 0, originSizeX - 1) ].channels[channel_index]; } } unsigned char result = BicubicPolate(ndata, xMappingToOriginFrac, yMappingToOriginFrac); output[ y * newSizeX + x ].channels[channel_index] = result; free(ndata); } } } return output; } </code></pre> </li> <li><p>The other used functions:</p> <pre><code>unsigned char BicubicPolate(const unsigned char* const ndata, const float fracx, const float fracy) { float x1 = CubicPolate( ndata[0], ndata[1], ndata[2], ndata[3], fracx ); float x2 = CubicPolate( ndata[4], ndata[5], ndata[6], ndata[7], fracx ); float x3 = CubicPolate( ndata[8], ndata[9], ndata[10], ndata[11], fracx ); float x4 = CubicPolate( ndata[12], ndata[13], ndata[14], ndata[15], fracx ); float output = clip_float(CubicPolate( x1, x2, x3, x4, fracy ), 0.0, 255.0); return (unsigned char)output; } float CubicPolate(const float v0, const float v1, const float v2, const float v3, const float fracy) { float A = (v3-v2)-(v0-v1); float B = (v0-v1)-A; float C = v2-v0; float D = v1; return D + fracy * (C + fracy * (B + fracy * A)); } size_t clip(const size_t input, const size_t lowerbound, const size_t upperbound) { if (input &lt; lowerbound) { return lowerbound; } if (input &gt; upperbound) { return upperbound; } return input; } float clip_float(const float input, const float lowerbound, const float upperbound) { if (input &lt; lowerbound) { return lowerbound; } if (input &gt; upperbound) { return upperbound; } return input; } </code></pre> </li> <li><p><code>base.h</code></p> <pre><code>/* Develop by Jimmy Hu */ #ifndef BASE_H #define BASE_H #include &lt;math.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; #define MAX_PATH 256 #define FILE_ROOT_PATH &quot;./&quot; #define True true #define False false typedef struct RGB { unsigned char channels[3]; } RGB; typedef struct HSV { long double channels[3]; // Range: 0 &lt;= H &lt; 360, 0 &lt;= S &lt;= 1, 0 &lt;= V &lt;= 255 }HSV; typedef struct BMPIMAGE { char FILENAME[MAX_PATH]; unsigned int XSIZE; unsigned int YSIZE; unsigned char FILLINGBYTE; unsigned char *IMAGE_DATA; } BMPIMAGE; typedef struct RGBIMAGE { unsigned int XSIZE; unsigned int YSIZE; RGB *IMAGE_DATA; } RGBIMAGE; typedef struct HSVIMAGE { unsigned int XSIZE; unsigned int YSIZE; HSV *IMAGE_DATA; } HSVIMAGE; #endif </code></pre> </li> </ul> <p><strong>The full testing code</strong></p> <pre><code>/* Develop by Jimmy Hu */ #include &quot;base.h&quot; #include &quot;imageio.h&quot; RGB* BicubicInterpolation(const RGB* const image, const int originSizeX, const int originSizeY, const int newSizeX, const int newSizeY); unsigned char BicubicPolate(const unsigned char* ndata, const float fracx, const float fracy); float CubicPolate(const float v0, const float v1, const float v2, const float v3, const float fracy); size_t clip(const size_t input, const size_t lowerbound, const size_t upperbound); float clip_float(const float input, const float lowerbound, const float upperbound); int main(int argc, char** argv) { char *FilenameString; FilenameString = malloc( sizeof *FilenameString * MAX_PATH); printf(&quot;BMP image input file name:(ex:test): &quot;); scanf(&quot;%s&quot;, FilenameString); BMPIMAGE BMPImage1 = bmp_file_read(FilenameString, false); RGBIMAGE RGBImage1; RGBImage1.XSIZE = BMPImage1.XSIZE; RGBImage1.YSIZE = BMPImage1.YSIZE; RGBImage1.IMAGE_DATA = raw_image_to_array(BMPImage1.XSIZE, BMPImage1.YSIZE, BMPImage1.IMAGE_DATA); RGBIMAGE RGBImage2; RGBImage2.XSIZE = 1024; RGBImage2.YSIZE = 1024; RGBImage2.IMAGE_DATA = BicubicInterpolation(RGBImage1.IMAGE_DATA, RGBImage1.XSIZE, RGBImage1.YSIZE, RGBImage2.XSIZE, RGBImage2.YSIZE); printf(&quot;file name for saving:(ex:test): &quot;); scanf(&quot;%s&quot;, FilenameString); bmp_write(FilenameString, RGBImage2.XSIZE, RGBImage2.YSIZE, array_to_raw_image(RGBImage2.XSIZE, RGBImage2.YSIZE, RGBImage2.IMAGE_DATA)); free(FilenameString); free(RGBImage1.IMAGE_DATA); free(RGBImage2.IMAGE_DATA); return 0; } RGB* BicubicInterpolation(const RGB* const image, const int originSizeX, const int originSizeY, const int newSizeX, const int newSizeY) { RGB* output; output = malloc(sizeof *output * newSizeX * newSizeY); if (output == NULL) { printf(stderr, &quot;Memory allocation error!&quot;); return NULL; } float ratiox = (float)originSizeX / (float)newSizeX; float ratioy = (float)originSizeY / (float)newSizeY; for (size_t y = 0; y &lt; newSizeY; y++) { for (size_t x = 0; x &lt; newSizeX; x++) { for (size_t channel_index = 0; channel_index &lt; 3; channel_index++) { float xMappingToOrigin = (float)x * ratiox; float yMappingToOrigin = (float)y * ratioy; float xMappingToOriginFloor = floor(xMappingToOrigin); float yMappingToOriginFloor = floor(yMappingToOrigin); float xMappingToOriginFrac = xMappingToOrigin - xMappingToOriginFloor; float yMappingToOriginFrac = yMappingToOrigin - yMappingToOriginFloor; unsigned char* ndata; ndata = malloc(sizeof *ndata * 4 * 4); if (ndata == NULL) { printf(stderr, &quot;Memory allocation error!&quot;); return NULL; } for (int ndatay = -1; ndatay &lt; 2; ndatay++) { for (int ndatax = -1; ndatax &lt; 2; ndatax++) { ndata[(ndatay + 1) * 4 + (ndatax + 1)] = image[ clip(yMappingToOriginFloor + ndatay, 0, originSizeY - 1) * originSizeX + clip(xMappingToOriginFloor + ndatax, 0, originSizeX - 1) ].channels[channel_index]; } } unsigned char result = BicubicPolate(ndata, xMappingToOriginFrac, yMappingToOriginFrac); output[ y * newSizeX + x ].channels[channel_index] = result; free(ndata); } } } return output; } unsigned char BicubicPolate(const unsigned char* const ndata, const float fracx, const float fracy) { float x1 = CubicPolate( ndata[0], ndata[1], ndata[2], ndata[3], fracx ); float x2 = CubicPolate( ndata[4], ndata[5], ndata[6], ndata[7], fracx ); float x3 = CubicPolate( ndata[8], ndata[9], ndata[10], ndata[11], fracx ); float x4 = CubicPolate( ndata[12], ndata[13], ndata[14], ndata[15], fracx ); float output = clip_float(CubicPolate( x1, x2, x3, x4, fracy ), 0.0, 255.0); return (unsigned char)output; } float CubicPolate(const float v0, const float v1, const float v2, const float v3, const float fracy) { float A = (v3-v2)-(v0-v1); float B = (v0-v1)-A; float C = v2-v0; float D = v1; return D + fracy * (C + fracy * (B + fracy * A)); } size_t clip(const size_t input, const size_t lowerbound, const size_t upperbound) { if (input &lt; lowerbound) { return lowerbound; } if (input &gt; upperbound) { return upperbound; } return input; } float clip_float(const float input, const float lowerbound, const float upperbound) { if (input &lt; lowerbound) { return lowerbound; } if (input &gt; upperbound) { return upperbound; } return input; } </code></pre> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/263071/231235">Two dimensional bicubic interpolation implementation in Matlab</a> and</p> <p><a href="https://codereview.stackexchange.com/q/263024/231235">Two dimensional gaussian image generator in C</a>.</p> </li> <li><p>What changes has been made in the code since last question?</p> <p>I am attempting to make a C version two dimensional bicubic interpolation function in this post.</p> </li> <li><p>Why a new review is being asked for?</p> <p>If there is any possible improvement, please let me know.</p> </li> </ul>
[]
[ { "body": "<h1>Avoid unnecesary allocation of temporary storage</h1>\n<p>In the innermost loop, you do this:</p>\n<pre><code>unsigned char* ndata;\nndata = malloc(sizeof *ndata * 4 * 4);\n</code></pre>\n<p>This is slow and completely unnecessary; you can just declare an array on the stack like so:</p>\n<pre><code>unsigned char ndata[4 * 4];\n</code></pre>\n<h1>Possible improvements to the algorithm</h1>\n<p>It is likely that many of the intermediate values you are calculating in <code>BicubicPolate()</code> might be the same as those for neighbouring pixels. Also in <code>CubicPolate()</code>, none of the values of <code>A</code> to <code>D</code> depend on <code>fracy</code>, and some preprocessing of the image might allow you to avoid many of the operations.</p>\n<p>Also consider that the ratio between the source and destination can be larger than 1 or smaller than 1, and different algorithms might be better for each case, and ratios of the form <code>n</code> or <code>1 / n</code>, where <code>n</code> is an integer, might especially be candidates for algorithmic improvements.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T21:18:42.347", "Id": "263201", "ParentId": "263183", "Score": "3" } }, { "body": "<p>Ok let's try it, using <a href=\"https://en.wikipedia.org/wiki/File:Barns_grand_tetons.jpg\" rel=\"nofollow noreferrer\">this test image</a>. Frame 0 was resized (from a width of 512 to a width of 300) by other software, frame 1 by this code.</p>\n<p><a href=\"https://i.stack.imgur.com/UUP0i.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UUP0i.gif\" alt=\"barns\" /></a></p>\n<p>That regular pattern of darker pixels is not supposed to appear.</p>\n<p>It looks like <code>BicubicPolate</code> reads some entries from <code>ndata</code> (16 bytes) that were never written to (9 bytes are written to it).</p>\n<p>I'm not exactly sure how that is supposed to work, but changing the loops that fill <code>ndata</code> to go up to and <em>including</em> 2 seems to improve the output.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T13:20:22.000", "Id": "519675", "Score": "0", "body": "Yor're right. The loops that fill `ndata` should be from -1 to 2 and the 16 values are filled." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T22:26:46.507", "Id": "263205", "ParentId": "263183", "Score": "3" } } ]
{ "AcceptedAnswerId": "263201", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T10:18:38.400", "Id": "263183", "Score": "4", "Tags": [ "algorithm", "c", "reinventing-the-wheel", "image", "numerical-methods" ], "Title": "Two dimensional bicubic interpolation implementation in C" }
263183
<p>I have this code, which counts only adjacent letters in a string and returns the count of each letter.</p> <pre><code>const inputData = [ 'aabbc', 'xxxxvvhjh', 'PPPOM' ]; let output = []; inputData.forEach(str =&gt; { let strObj = {}; for (let i = 0; i &lt; str.length; i++) { if (strObj[str[i]] &amp;&amp; str[i] === str[i - 1]) { strObj[str[i]] = strObj[str[i]] += 1; } else { strObj[str[i]] = 1; } } const res = Object.keys(strObj).map((key) =&gt; `${key}${strObj[key]}`).join(''); output.push(res); }); console.log(output); </code></pre> <p>Output</p> <pre><code>[ 'a2b2c1','x4v2h1j1h1','P3O1M1'] </code></pre>
[]
[ { "body": "<p>I am not familiar with javascript, but seems like you are iterating over inputs twice, you really just need to iterate over it once. here is how(I might write a pseudo code later)\n<strong>at start:</strong></p>\n<ol>\n<li><p>create variable(char) <code>lastCharacter</code> and (int)<code>characterCount</code></p>\n</li>\n<li><p>create javascript equivalent of c++ struct (I will name this struct &quot;AdjacentCharacters&quot;) with variables:\n<code>character</code> and <code>count</code></p>\n</li>\n<li><p>create list/vector(or any other resizable array type) of &quot;AdjacentCharacters&quot;.</p>\n</li>\n</ol>\n<p><strong>in each iteration:</strong></p>\n<ol>\n<li>increment characterCount</li>\n<li>keep track of current character</li>\n<li>at the end of the iteration set lastCharacter to currentCharacter</li>\n<li>but before that, compare lastCharacter to currentCharacter, if it matchs or it's first iteration of the loop(since you don't have lastCharacter if it's first)increment characterCount.</li>\n<li>if it does not match then push in the &quot;AdjacentCharacters&quot; list and set character count to 0</li>\n</ol>\n<p><strong>Summary:</strong> you are basicaly iterating over string and keeping track of how many same characters you have met, if you meet different character than you reset characterCount to 0, because chain of same characters was broken,\nand you write down how many same characters you have met and what was that same character to the &quot;AdjacentCharacters&quot; struct and push it to list of &quot;AdjacentCharacters&quot;.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T15:44:32.240", "Id": "263193", "ParentId": "263188", "Score": "1" } }, { "body": "<p>The observation by George is correct- it does iterate over the inputs twice. The prescribed approach seems to work (see demonstration at the end of the post).</p>\n<h1>Suggestions</h1>\n<h2>line to increment count- extra assignment</h2>\n<p>This line looks like it is doing more than it needs to:</p>\n<blockquote>\n<pre><code>strObj[str[i]] = strObj[str[i]] += 1;\n</code></pre>\n</blockquote>\n<p>That appears to be</p>\n<ol>\n<li>setting the value of <code>strObj[str[i]]</code> to <code>strObj[str[i]]</code> + 1</li>\n<li>assigning that value to <code>strObj[str[i]]</code> again</li>\n</ol>\n<p>It could be simplified to just:</p>\n<pre><code>strObj[str[i]] += 1;\n</code></pre>\n<p>or even more simply:</p>\n<pre><code>strObj[str[i]]++;\n</code></pre>\n<h2>using <code>forEach</code> with <code>push</code></h2>\n<p>Whenever a <code>forEach</code> loop pushes into an array e.g. for <code>output</code>, this can be simplified to <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\"><code>array.map()</code></a></p>\n<h2>prefer <code>const</code> over <code>let</code></h2>\n<p>Variables <code>output</code> and <code>strObj</code> can be declared with <code>const</code> instead, since they are only assigned once. This can help avoid <a href=\"https://softwareengineering.stackexchange.com/a/278653/244085\">accidental re-assignment and other bugs</a>.</p>\n<h1>Current code simplified</h1>\n<p>This code incorporates the advice from suggestions above.</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 inputData = [\n 'aabbc',\n 'xxxxvvhjh',\n 'PPPOM'\n];\nconst output = inputData.map(str =&gt; {\n const strObj = {};\n for (let i = 0; i &lt; str.length; i++) {\n if (strObj[str[i]] &amp;&amp; str[i] === str[i - 1]) {\n strObj[str[i]]++;\n } else {\n strObj[str[i]] = 1;\n }\n }\n return Object.keys(strObj).map((key) =&gt; `${key}${strObj[key]}`).join('');\n});\nconsole.log(output);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h1>Simplified code with one iteration over each input</h1>\n<p>This code follows the advice George described, plus suggestions above</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 inputData = [\n 'aabbc',\n 'xxxxvvhjh',\n 'PPPOM'\n];\nconst output = inputData.map(str =&gt; {\n let lastChar, count = 0;\n const retVals = [];\n for (let i = 0; i &lt; str.length; i++) {\n if (!i || lastChar === str[i]) {\n count++;\n } else if (str[i] !== str[i - 1]) {\n retVals.push(str[i - 1], count);\n count = 1;\n if (i === str.length - 1) {\n retVals.push(str[i], 1);\n }\n }\n lastChar = str[i];\n }\n return retVals.join('');\n});\nconsole.log(output);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T17:45:34.633", "Id": "263197", "ParentId": "263188", "Score": "3" } }, { "body": "<h2>Bug</h2>\n<p>Your code has a bug.</p>\n<p>The result for the string <code>&quot;xxxxvvhjh&quot;</code> you defined to be <code>&quot;x4v2h1j1h1&quot;</code> however your function returns <code>&quot;x4v2h1j1&quot;</code> not counting the final <code>h</code></p>\n<p>The reason is that you are using an object to map the letters. When the same letter appears more than once but are not adjacent you only output that character once. Eg the string <code>&quot;hhahhh&quot;</code> your function returns <code>&quot;h3a1&quot;</code> rather than <code>&quot;h2a1h3&quot;</code></p>\n<p>That said your question states</p>\n<blockquote>\n<p><em>&quot;which counts only adjacent letters in string and gives out count.&quot;</em></p>\n</blockquote>\n<p>Which contradicts the output you have given</p>\n<blockquote>\n<p>[ 'a2b2c1','x4v2h1j1h1','P3O1M1']</p>\n</blockquote>\n<p>Assuming that the output you have given is correct and with the title <em>&quot;run length coder&quot;</em> (assume that is encoder) which reinforces the assumption and the fact that you give the wrong result for <code>&quot;hhahhh&quot;</code> I will presume you are attempting Run length encoding</p>\n<p>There is no easy way to correct your code as it is fundamentally flawed. All we can do is start a complete rewrite.</p>\n<p>There is no need to use a map as you have done with <code>strObj</code>. The encoding can be done in a single pass</p>\n<h2>Run length encoding</h2>\n<p>Is very simple and fast lossless compression method.</p>\n<p>You code should be as functions. With a function to encode a single string, and a second function to encode an array of strings.</p>\n<h3>Encode a string</h3>\n<p>Assuming that the string to encode is always 1 or more characters long</p>\n<pre><code>function encodeStr(str) {\n var i = 1, char = str[i], count = 1, result = &quot;&quot;;\n while (i &lt; str.length) {\n const next = str[i++];\n count = next === char ? count + 1 : (result += char + count, 1);\n char = next;\n }\n return result + char + count;\n}\n</code></pre>\n<h3>Encode strings</h3>\n<p>To encode an array of strings a second function just maps the array using the above function.</p>\n<pre><code>const encodeStrs = strs =&gt; strs.map(encodeStr);\n</code></pre>\n<p>To use</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> function encodeStr(str) {\n var i = 1, char = str[i], count = 1, result = \"\";\n while (i &lt; str.length) {\n const next = str[i++];\n count = next === char ? count + 1 : (result += char + count, 1);\n char = next;\n }\n return result + char + count;\n }\n const encodeStrs = strs =&gt; strs.map(encodeStr);\n console.log(encodeStrs([\"aabbc\", \"xxxxvvhjh\", \"PPPOM\"]))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T04:23:49.353", "Id": "519769", "Score": "0", "body": "Thanks @Blindman67, What does this part do? (result += char + count, 1)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T07:41:51.120", "Id": "519781", "Score": "0", "body": "@uday8486 The `()` defines a group https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Grouping with the comma separating expressions, the last expression `,1` is assigned to `count` at the start of the line `count = `" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T07:44:26.557", "Id": "519782", "Score": "0", "body": "@uday8486 ... And a link for more on the comma https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T15:27:59.570", "Id": "263220", "ParentId": "263188", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T14:10:23.520", "Id": "263188", "Score": "1", "Tags": [ "javascript", "strings", "ecmascript-6", "compression" ], "Title": "Run-length coder" }
263188
<p>I've written a small rust library that solves rust's problems with using recursive data types (e.g, linked lists).</p> <p>using the library, you can use <code>RecRef&lt;'_, List&gt;</code>, and use it to travel up and down your list dynamically and safely at will.</p> <p>It uses unsafe primitives but uses a clever trick to present to the user a safe interface.</p> <p>It's the first library I've ever published, and I worked hard on it. However, I would appreciate general feedback about the library. Specifically, I'm most interested in:</p> <ul> <li>Does the library conform to programming conventions?</li> <li>Is the documentation clear?</li> <li>Is the code safe? I'm sure the general idea is correct, but rust's unsafe code can be quite hairy, and maybe I missed an edge case, perhaps regarding the <code>Send</code> instance.</li> </ul> <p>For consistency with future readers, this is version 0.2.0 of the library, <code>recursive_reference</code>.</p> <p>links:</p> <ul> <li><a href="https://github.com/noamtashma/recursive_reference" rel="nofollow noreferrer">repository</a></li> <li><a href="https://crates.io/crates/recursive_reference/0.2.0" rel="nofollow noreferrer">crates.io</a></li> <li><a href="https://docs.rs/recursive_reference/0.2.0/recursive_reference/" rel="nofollow noreferrer">documentation</a></li> <li><a href="https://github.com/noamtashma/orchard/blob/master/src/trees/basic_tree/walker.rs" rel="nofollow noreferrer">a complicated example usage</a></li> </ul> <p>license: the library is dual licensed under MIT and APACHE-2.0.</p> <p>the library's code:</p> <pre class="lang-rust prettyprint-override"><code> //! Recursive reference. //! //!This crate provides a way to traverse recursive structures easily and safely. //!Rust's lifetime rules will usually force you to either only walk forward through the structure, //!or use recursion, calling your method recursively every time you go down a node, //!and returning every time you want to go back up, which leads to terrible code. //! //!Instead, you can use the [`RecRef`] type, to safely and dynamically walk up //!and down your recursive structure. //! //!# Examples //! //! Say we have a recursive linked list structure //! ---------------------------------------------- //!```rust //!enum List&lt;T&gt; { //! Root(Box&lt;Node&lt;T&gt;&gt;), //! Empty, //!} //!struct Node&lt;T&gt; { //! value: T, //! next: List&lt;T&gt;, //!} //!``` //! //! We can use a [`RecRef`] directly //! ---------------------------------------------- //!```rust //! # enum List&lt;T&gt; { //! # Root(Box&lt;Node&lt;T&gt;&gt;), //! # Empty, //! # } //! # struct Node&lt;T&gt; { //! # value: T, //! # next: List&lt;T&gt;, //! # } //! use recursive_reference::*; //! //! fn main() -&gt; Result&lt;(), ()&gt; { //! let node1 = Node { value : 5, next : List::Empty }; //! let mut node2 = Node { value : 2, next : List::Root(Box::new(node1)) }; //! //! let mut rec_ref = RecRef::new(&amp;mut node2); //! assert_eq!(rec_ref.value, 2); // rec_ref is a smart pointer to the current node //! rec_ref.value = 7; // change the value at the head of the list //! RecRef::extend_result(&amp;mut rec_ref, |node| match &amp;mut node.next { //! List::Root(next_node) =&gt; Ok(next_node), //! List::Empty =&gt; Err(()), //! })?; //! assert_eq!(rec_ref.value, 5); //! // extend the RecRef //! let res = RecRef::extend_result(&amp;mut rec_ref, |node| match &amp;mut node.next { //! List::Root(next_node) =&gt; Ok(next_node), //! List::Empty =&gt; Err(()), //! }); //! assert_eq!(res, Err(())); // could not go forward because it reached the end of the list //! assert_eq!(rec_ref.value, 5); //! let last = RecRef::pop(&amp;mut rec_ref).ok_or(())?; //! assert_eq!(last.value, 5); //! assert_eq!(rec_ref.value, 7) ; // moved back to the head of the list because we popped rec_ref //! Ok(()) //! } //!``` //! //! We can also wrap a [`RecRef`] in a walker struct //! ---------------------------------------------- //! Note: this time we are using a `RecRef&lt;List&lt;T&gt;&gt;` and not a `RecRef&lt;Node&lt;T&gt;&gt;`, to allow pointing //! at the empty end of the list. //!```rust //! # enum List&lt;T&gt; { //! # Root(Box&lt;Node&lt;T&gt;&gt;), //! # Empty, //! # } //! # struct Node&lt;T&gt; { //! # value: T, //! # next: List&lt;T&gt;, //! # } //! use recursive_reference::*; //! struct Walker&lt;'a, T&gt; { //! rec_ref : RecRef&lt;'a, List&lt;T&gt;&gt; //! } //! impl&lt;'a, T&gt; Walker&lt;'a, T&gt; { //! pub fn new(list: &amp;'a mut List&lt;T&gt;) -&gt; Self { //! Walker { //! rec_ref : RecRef::new(list) //! } //! } //! //! /// Returns `None` when at the tail end of the list //! pub fn next(&amp;mut self) -&gt; Option&lt;()&gt; { //! RecRef::extend_result(&amp;mut self.rec_ref, |current| match current { //! List::Empty =&gt; Err(()), //! List::Root(node) =&gt; Ok(&amp;mut node.next), //! }).ok() //! } //! //! /// Returns `None` when at the head of the list //! pub fn prev(&amp;mut self) -&gt; Option&lt;()&gt; { //! RecRef::pop(&amp;mut self.rec_ref)?; //! Some(()) //! } //! //! /// Returns `None` when at the tail end of the list //! pub fn value_mut(&amp;mut self) -&gt; Option&lt;&amp;mut T&gt; { //! match &amp;mut *self.rec_ref { //! List::Root(node) =&gt; Some(&amp;mut node.value), //! List::Empty =&gt; None, //! } //! } //! } //! //! fn main() -&gt; Result&lt;(), ()&gt; { //! let node1 = Node { value : 5, next : List::Empty }; //! let node2 = Node { value : 2, next : List::Root(Box::new(node1)) }; //! let mut list = List::Root(Box::new(node2)); //! //! let mut walker = Walker::new(&amp;mut list); //! assert_eq!(walker.value_mut().cloned(), Some(2)); //! *walker.value_mut().ok_or(())? = 7; //! walker.next().ok_or(())?; //! assert_eq!(walker.value_mut().cloned(), Some(5)); //! walker.next().ok_or(())?; //! assert_eq!(walker.value_mut().cloned(), None); // end of the list //! walker.prev().ok_or(())?; //! assert_eq!(walker.value_mut().cloned(), Some(5)); //! walker.prev().ok_or(())?; //! assert_eq!(walker.value_mut().cloned(), Some(7)); // we changed the value at the head //! Ok(()) //! } //!``` //! With a [`RecRef`] you can //! ---------------------------------------------- //! * Use the current reference (i.e, the top reference). //! the [`RecRef`] is a smart pointer to it. //! * Freeze the current reference //! and extend the [`RecRef`] with a new reference derived from it, using [`extend`][RecRef::extend] and similar functions. //! for example, push to the stack a reference to the child of the current node. //! * Pop the stack to get back to the previous reference, unfreezing it. //! //! # Safety //! The [`RecRef`] type is implemented using unsafe rust, but provides a safe interface. //! The [`RecRef`] methods' types guarantee that the references will always have a legal lifetime //! and will respect rust's borrow rules, even if that lifetime is not known in advance. //! //! The [`RecRef`] obeys rust's borrowing rules, by simulating freezing. Whenever //! you extend a [`RecRef`] with a reference `child_ref` that is derived from the current //! reference `parent_ref`, the [`RecRef`] freezes `parent_ref`, and no longer allows //! `parent_ref` to be used. //! When `child_ref` will be popped from the [`RecRef`], //! `parent_ref` will be allowed to be used again. //! //! This is essentially the same as what would have happened if you wrote your functions recursively, //! but it's decoupled from the actual call stack. //! //! Another important point to consider is the safety of //! the actual call to [`extend`][RecRef::extend]: see its documentation. #![no_std] #![doc(html_root_url = &quot;https://docs.rs/recursive_reference/0.2.0/recursive_reference/&quot;)] extern crate alloc; use alloc::vec::*; use core::marker::PhantomData; use core::ops::Deref; use core::ops::DerefMut; use void::ResultVoidExt; /// A Recursive reference. /// This struct is used to allow recursively reborrowing mutable references in a dynamic /// but safe way. /// /// `RecRef&lt;'a, T&gt;` represents a reference to a value of type `T`, with lifetime `'a`, /// which can move recursively into and out of its subfields of the same type `T`. /// /// With a [`RecRef`] you can /// ---------------------------------------------- /// * Use the current reference (i.e, the top reference). /// the [`RecRef`] is a smart pointer to it. /// * Freeze the current reference /// and extend the [`RecRef`] with a new reference derived from it, using [`extend`][RecRef::extend] and similar functions. /// for example, push to the stack a reference to the child of the current node. /// * Pop the stack to get back to the previous reference, unfreezing it. /// /// The methods' types guarantee that the references will always have a legal lifetime /// and will respect rust's borrow rules, even if that lifetime is not known in advance. /// /// Internally, the [`RecRef`] stores a [`Vec`] of pointers, that it extends and pops from. pub struct RecRef&lt;'a, T: ?Sized&gt; { head: *mut T, vec: Vec&lt;*mut T&gt;, phantom: PhantomData&lt;&amp;'a mut T&gt;, } // TODO: consider converting the pointers to values without checking for null values. // it's supposed to work, since the pointers only ever come from references. // otherwise, when 1.53 rolls out, convert to `NonNull`. // these aren't ever supposed to happen. but since we touch unsafe code, we might as well // have clear error message when we `expect()` const NULL_POINTER_ERROR: &amp;str = &quot;error! somehow got null pointer&quot;; impl&lt;'a, T: ?Sized&gt; RecRef&lt;'a, T&gt; { /// Creates a new RecRef containing only a single reference. pub fn new(r: &amp;'a mut T) -&gt; Self { RecRef { head: r as *mut T, vec: Vec::new(), phantom: PhantomData, } } /// Returns the size of `rec_ref`, i.e, the amount of references in it. /// It increases every time you extend `rec_ref`, and decreases every time you pop /// `rec_ref`. /// The size of a new [`RecRef`] is always `1`. pub fn size(rec_ref: &amp;Self) -&gt; usize { rec_ref.vec.len() + 1 } /// This function extends `rec_ref` one time. If the current /// reference is `current_ref: &amp;mut T`, then this call extends `rec_ref` /// with the new reference `ref2: &amp;mut T = func(current_ref)`. /// After this call, `rec_ref` will expose the new `ref2`, and `current_ref` /// will be frozen (As it is borrowed by `ref2`), until `ref2` is /// popped off, unfreezing `current_ref`. /// /// # Safety: /// Pay close attention to the type of `func`: we require that /// `F: for&lt;'b&gt; FnOnce(&amp;'b mut T) -&gt; &amp;'b mut T`. That is, for every lifetime `'b`, /// we require that `F: FnOnce(&amp;'b mut T) -&gt; &amp;'b mut T`. /// /// Let's define `'freeze_time` to be the time `ref2` will be in the [`RecRef`]. /// That is, `'freeze_time` /// is the time for which `ref2` will live, and the lifetime in which `current_ref` /// will be frozen by `ref2`. Then, the type of `func` should have been /// `FnOnce(&amp;'freeze_time mut T) -&gt; &amp;'freeze_time mut T`. If that woudld have been the type /// of `func`, the code would've followed rust's borrowing rules correctly. /// /// However, we can't know yet what that /// lifetime is: it will be whatever amount of time passes until the programmer decides /// to pop `ref2` out of the [`RecRef`]. And that hasn't even been decided at this point. /// Whatever lifetime `'freeze_time` that turns out to be, we will know /// after-the-fact that the type of `func` should have been /// `FnOnce(&amp;'freeze_time mut T) -&gt; &amp;'freeze_time mut T`. /// /// Therefore, the solution is to require that `func` will be able to work with any value of /// `'freeze_time`. Then we can be /// sure that the code would've worked correctly if we put the correct lifetime there. /// Therefore, we can always pick correct lifetimes after-the-fact, so the code must be safe. /// /// Also note: /// The type ensures that the current reference can't be leaked outside of `func`. /// `func` can't guarantee that /// `current_ref` will live for any length of time, so it can't store it outside anywhere /// or give it to anything. /// It can only use `current_ref` while still inside `func`, /// and use it in order to return `ref2`, which is the /// intended usage. pub fn extend&lt;F&gt;(rec_ref: &amp;mut Self, func: F) where F: for&lt;'b&gt; FnOnce(&amp;'b mut T) -&gt; &amp;'b mut T, { Self::extend_result(rec_ref, |r| Ok(func(r))).void_unwrap() } /// Same as [`Self::extend`], but allows the function to return an error value. pub fn extend_result&lt;E, F&gt;(rec_ref: &amp;mut Self, func: F) -&gt; Result&lt;(), E&gt; where F: for&lt;'b&gt; FnOnce(&amp;'b mut T) -&gt; Result&lt;&amp;'b mut T, E&gt;, { Self::extend_result_precise(rec_ref, |r, _phantom| func(r)) } /// Same as [`Self::extend`], but allows the function to return an error value, /// and also tells the inner function that `'a : 'b` using a phantom argument. pub fn extend_result_precise&lt;E, F&gt;(rec_ref: &amp;mut Self, func: F) -&gt; Result&lt;(), E&gt; where F: for&lt;'b&gt; FnOnce(&amp;'b mut T, PhantomData&lt;&amp;'b &amp;'a ()&gt;) -&gt; Result&lt;&amp;'b mut T, E&gt;, { // The compiler is told explicitly that the lifetime is `'a`. // Otherwise the minimal lifetime possible is chosen. // It probably doesn't matter, since we specifically require `func` to be able to work // with any lifetime, and the references are converted to pointers immediately. // However, that is the &quot;most correct&quot; lifetime - the reference's actual lifetime may // be anything up to `'a`, // depending on whether the user will pop it earlier than that. let head_ref: &amp;'a mut T = unsafe { rec_ref.head.as_mut() }.expect(NULL_POINTER_ERROR); match func(head_ref, PhantomData) { Ok(p) =&gt; { Self::push(rec_ref, p); Ok(()) } Err(e) =&gt; Err(e), } } /// This function maps the top of the [`RecRef`]. It's similar to [`Self::extend`], but /// it replaces the current reference instead of keeping it. See [`Self::extend`] for more details. pub fn map&lt;F&gt;(rec_ref: &amp;mut Self, func: F) where F: for&lt;'b&gt; FnOnce(&amp;'b mut T) -&gt; &amp;'b mut T, { Self::map_result(rec_ref, |r| Ok(func(r))).void_unwrap() } /// Same as [`Self::map`], but allows the function to return an error value. pub fn map_result&lt;E, F&gt;(rec_ref: &amp;mut Self, func: F) -&gt; Result&lt;(), E&gt; where F: for&lt;'b&gt; FnOnce(&amp;'b mut T) -&gt; Result&lt;&amp;'b mut T, E&gt;, { Self::map_result_precise(rec_ref, |r, _| func(r)) } /// Same as [`Self::map`], but allows the function to return an error value, /// and also tells the inner function that `'a : 'b` using a phantom argument. pub fn map_result_precise&lt;E, F&gt;(rec_ref: &amp;mut Self, func: F) -&gt; Result&lt;(), E&gt; where F: for&lt;'b&gt; FnOnce(&amp;'b mut T, PhantomData&lt;&amp;'b &amp;'a ()&gt;) -&gt; Result&lt;&amp;'b mut T, E&gt;, { // The compiler is told explicitly that the lifetime is `'a`. // Otherwise the minimal lifetime possible is chosen. // It probably doesn't matter, since we specifically require `func` to be able to work // with any lifetime, and the references are converted to pointers immediately. // However, that is the &quot;most correct&quot; lifetime - the reference's actual lifetime may // be anything up to `'a`, // depending on whether the user will pop it earlier than that. let head_ref: &amp;'a mut T = unsafe { rec_ref.head.as_mut() }.expect(NULL_POINTER_ERROR); match func(head_ref, PhantomData) { Ok(p) =&gt; { rec_ref.head = p as *mut T; Ok(()) } Err(e) =&gt; Err(e), } } /// Push another reference to the [`RecRef`], unrelated to the current one. /// `rec_ref.push(new_ref)` is morally equivalent to `rec_ref.extend_result_precise(move |_, _| { Ok(new_ref) })`. /// However, you might have some trouble making the anonymous function conform to the /// right type. pub fn push(rec_ref: &amp;mut Self, r: &amp;'a mut T) { rec_ref.vec.push(rec_ref.head); rec_ref.head = r as *mut T; /* alternative definition using a call to `extend_result_precise`. // in order to name 'x, replace the signature with: // pub fn push&lt;'x&gt;(rec_ref: &amp;'x mut Self, r : &amp;'a mut T) { // this is used in order to tell the closure to conform to the right type fn helper&lt;'a,'x, T : ?Sized, F&gt; (f : F) -&gt; F where F : for&lt;'b&gt; FnOnce(&amp;'b mut T, PhantomData&lt;&amp;'b &amp;'a ()&gt;) -&gt; Result&lt;&amp;'b mut T, void::Void&gt; + 'x { f } Self::extend_result_precise(rec_ref, helper::&lt;'a,'x&gt;(move |_, _phantom| { Ok(r) }) ).void_unwrap(); */ } /// Lets the user use the last reference for some time, and discards it completely. /// After the user uses it, the next time they inspect the [`RecRef`], it won't be there. /// If the [`RecRef`] has only one reference left, this returns `None`, because /// the [`RecRef`] can't be empty. pub fn pop(rec_ref: &amp;mut Self) -&gt; Option&lt;&amp;mut T&gt; { let res = unsafe { rec_ref.head.as_mut() }.expect(NULL_POINTER_ERROR); rec_ref.head = rec_ref.vec.pop()?; // We can't pop the original reference. In that case, Return None. Some(res) } /// Discards the [`RecRef`] and returns the last reference. /// The difference between this and using [`Self::pop`] are: /// * This will consume the [`RecRef`] /// * [`Self::pop`] will never pop the first original reference, because that would produce an /// invalid [`RecRef`]. [`Self::into_ref`] will. pub fn into_ref(rec_ref: Self) -&gt; &amp;'a mut T { unsafe { rec_ref.head.as_mut() }.expect(NULL_POINTER_ERROR) } } /// [`RecRef&lt;T&gt;`] represents a reference to a value of type `T`, /// which can move recursively into and out of its subfields of the same type `T`. /// Therefore, it implements `Deref` and `DerefMut` with `Item=T`. impl&lt;'a, T: ?Sized&gt; Deref for RecRef&lt;'a, T&gt; { type Target = T; fn deref(&amp;self) -&gt; &amp;T { unsafe { self.head.as_ref() }.expect(NULL_POINTER_ERROR) } } /// [`RecRef&lt;T&gt;`] represents a reference to a value of type `T`, /// which can move recursively into and out of its subfields of the same type `T`. /// Therefore, it implements `Deref` and `DerefMut` with `Item=T`. impl&lt;'a, T: ?Sized&gt; DerefMut for RecRef&lt;'a, T&gt; { fn deref_mut(&amp;mut self) -&gt; &amp;mut T { unsafe { self.head.as_mut() }.expect(NULL_POINTER_ERROR) } } impl&lt;'a, Q: ?Sized, T: ?Sized + AsRef&lt;Q&gt;&gt; AsRef&lt;Q&gt; for RecRef&lt;'a, T&gt; { fn as_ref(&amp;self) -&gt; &amp;Q { AsRef::as_ref(&amp;**self) } } impl&lt;'a, Q: ?Sized, T: ?Sized + AsMut&lt;Q&gt;&gt; AsMut&lt;Q&gt; for RecRef&lt;'a, T&gt; { fn as_mut(&amp;mut self) -&gt; &amp;mut Q { AsMut::as_mut(&amp;mut **self) } } impl&lt;'a, T: ?Sized&gt; From&lt;&amp;'a mut T&gt; for RecRef&lt;'a, T&gt; { fn from(r: &amp;'a mut T) -&gt; Self { Self::new(r) } } /// # Safety: /// Behaviorally, A [`RecRef`] is the same as `&amp;'a mut T`, and /// should be [`Send`] for the same reason. Additionally, it contains a [`Vec`]. /// The [`Send`] instance for [`Vec`] contains the bound `A: Send` for the allocator type `A`, /// so we should require that as well. However, we don't have direct access to the /// default allocator type. So instead we require `Vec&lt;&amp;'a mut T&gt;: Send`. unsafe impl&lt;'a, T: ?Sized + Send&gt; Send for RecRef&lt;'a, T&gt; where Vec&lt;&amp;'a mut T&gt;: Send {} /// # Safety: /// Behaviorally, A [`RecRef`] is the same as `&amp;'a mut T`, and /// should be [`Sync`] for the same reason. Additionally, it contains a [`Vec`]. /// The [`Sync`] instance for [`Vec`] contains the bound `A: Sync` for the allocator type `A`, /// so we should require that as well. However, we don't have direct access to the /// default allocator type. So instead we require `Vec&lt;&amp;'a mut T&gt;: Sync`. unsafe impl&lt;'a, T: ?Sized + Sync&gt; Sync for RecRef&lt;'a, T&gt; where Vec&lt;&amp;'a mut T&gt;: Sync {} </code></pre> <p>Cargo.toml:</p> <pre><code> [package] name = &quot;recursive_reference&quot; version = &quot;0.2.0&quot; # remember to bump the html_root_url as well authors = [&quot;Noam Ta Shma &lt;noam.tashma@gmail.com&gt;&quot;] edition = &quot;2018&quot; keywords = [&quot;recursive&quot;, &quot;data-structures&quot;, &quot;smart-pointer&quot;, &quot;reference&quot;] categories = [&quot;rust-patterns&quot;, &quot;data-structures&quot;, &quot;no-std&quot;] description = &quot;This crate provides a way to walk on recursive structures easily and safely.&quot; readme = &quot;README.md&quot; repository = &quot;https://github.com/noamtashma/recursive_reference&quot; license = &quot;MIT OR Apache-2.0&quot; # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] void = &quot;1.0&quot; [lib] name = &quot;recursive_reference&quot; path = &quot;src/lib.rs&quot; </code></pre> <p>The README.md file contains about the same information as the documentation in the library itself.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T16:19:51.643", "Id": "263194", "Score": "4", "Tags": [ "rust", "library" ], "Title": "Small generic helper library for working with recursive data structures" }
263194
<p>I am not very experienced with T-SQL and feel this can be done better. The script changes ownership of all &quot;user&quot; (non-system) databases to <code>sa</code>.</p> <p>Usage of a dynamic SQL expression seems unavoidable to me. Could I at least iterate the table names in a more elegant way — imperative code looks like a code smell in a SQL script. Nested query in the while loop absolutely hurts my eyes...</p> <p><strong>How to rewrite this script to be more idiomatic?</strong></p> <pre class="lang-sql prettyprint-override"><code>DROP TABLE IF EXISTS #databaseNames; SELECT name INTO #databaseNames FROM master.sys.databases WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb') DECLARE @tableCount INTEGER SELECT @tableCount = COUNT(*) FROM #databaseNames DECLARE @tableNumber INTEGER SET @tableNumber = 1 WHILE @tableNumber &lt;= @tableCount BEGIN DECLARE @tableName VARCHAR(1024) SELECT @tableName = name FROM ( SELECT ROW_NUMBER() OVER (ORDER BY name ASC) AS rowNumber, name FROM #databaseNames ) numberedDatabaseNames WHERE rowNumber = @tableNumber EXEC('ALTER AUTHORIZATION ON database::' + @tableName + ' to sa;') SET @tableNumber = @tableNumber + 1 END; </code></pre>
[]
[ { "body": "<p>You could use <a href=\"https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/system-information-schema-views-transact-sql?view=sql-server-ver15\" rel=\"nofollow noreferrer\">INFORMATION_SCHEMA.TABLES</a> instead (note that INFORMATION_SCHEMA is found in other ANSI-compliant DBMS and should be the preferred way to explore tables and other structures in a database).</p>\n<p>For example:</p>\n<pre><code>SELECT *\nfrom INFORMATION_SCHEMA.TABLES\nWHERE TABLE_CATALOG NOT IN ('master', 'tempdb', 'model', 'msdb')\nAND TABLE_TYPE = 'BASE TABLE'\n</code></pre>\n<p>Then you can fetch DB name (TABLE_CATALOG) and table name at the same time, and run your loop.</p>\n<p>Then you can simply use a CURSOR but a classic WHILE loop is doable too. But you'll still need some dynamic SQL, because you can't use variables for object names. But your script can be simplified.</p>\n<h2>Edit</h2>\n<p>Say you are only interested in changing ownership of databases, and not tables, here is some sample code:</p>\n<pre><code>DECLARE @db_name varchar(100)\n \nDeclare Cur_databases Cursor \nFor \n SELECT name\n --INTO #databaseNames\n FROM master.sys.databases\n WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb')\nFor Read only\n\nOPEN Cur_databases\nFETCH NEXT FROM Cur_databases \nINTO @db_name\n\nWHILE @@FETCH_STATUS = 0\nBEGIN\n print 'ALTER AUTHORIZATION ON database::' + @db_name + ' to sa;'\n -- EXEC('ALTER AUTHORIZATION ON database::' + @tableName + ' to sa;')\n\n FETCH NEXT FROM Cur_databases \n INTO @db_name\n\nEND\n\nCLOSE Cur_databases\nDEALLOCATE Cur_databases\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T05:11:28.900", "Id": "519660", "Score": "0", "body": "Could you please provide specific code to illustrate the simplified version?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T18:50:45.030", "Id": "519751", "Score": "0", "body": "I edited my post to add some code with a cursor. I did not bother to use a temp table to store results because it's probably unlikely that the list of databases would change during execution of this script." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T07:26:53.677", "Id": "519779", "Score": "0", "body": "Thank you! Definitely better than my variant. At least, in terms of the number of requests made. Like it! The `WHILE @@FETCH_STATUS = 0` hurts my eyes, but I guess I should get used to SQL's idioms..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T21:05:24.273", "Id": "263200", "ParentId": "263196", "Score": "3" } }, { "body": "<p>The current query would get all databases except system databases, ignoring the current owners. What I prefer is to include the <code>owner</code> in the filter as well, so it'll always have the databases with different owner than <code>sa</code>.</p>\n<p>here is a suggested revision :</p>\n<pre><code>SELECT db.name\nFROM sys.databases db\nLEFT JOIN sys.server_principals sp ON sp.sid = db.owner_sid\nWHERE \n db.name NOT IN ('master', 'tempdb', 'model', 'msdb')\nAND sp.name &lt;&gt; 'sa'\n</code></pre>\n<p>Now, you can use that to make it more reusable, such as having a procedure that would change the database owner to any given owner, or excluding some owners from the queries ..etc.</p>\n<p>narrowing your queries would avoid bugs and future changes hassles.</p>\n<p>If you're looking for a dynamic sql and avoid using <code>Cursor</code>, you can do this :</p>\n<pre><code>DECLARE \n @sql NVARCHAR(MAX)\n, @owner NVARCHAR(100) = 'sa'\n\n\nSELECT @sql = COALESCE(@sql + 'ALTER AUTHORIZATION ON database::' + db.name + ' to ' + @owner + '; ', '')\nFROM sys.databases db\nLEFT JOIN sys.server_principals s ON s.sid = db.owner_sid\nWHERE \n db.name NOT IN ('master', 'tempdb', 'model', 'msdb')\nAND s.name &lt;&gt; @owner\n\nEXEC sp_executesql @sql \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-19T20:39:08.153", "Id": "268163", "ParentId": "263196", "Score": "1" } } ]
{ "AcceptedAnswerId": "263200", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-18T17:16:19.957", "Id": "263196", "Score": "3", "Tags": [ "sql", "sql-server", "t-sql" ], "Title": "Alter authorization on all non-system SQL Server databases" }
263196
<p>I want to optimize my code for following question:</p> <blockquote> <p>A company sells dumbbells in pairs. These are weights for exercising. They receive a shipment of dumbbells weighing anywhere from 1 unit up to a certain maximum.</p> <p>A pair can only be sold if their weights are sufficiently close: no greater than 1 unit difference.</p> <p>Given an inventory of various weights, determine the maximum number of pairs the company can sell.</p> <p>For example, if there are 2 dumbbells of weight 1, 4 of weight 2, 3 of weight 3 and 1 of weight 4, (arr = [2,4,3,1])</p> <p>they can be paired as [1,1], [2,2], [2,2], [3,3], [3,4] for a total of 5 pairs.</p> <p>i-th element is the number of dumbbells with a weight of i+1.</p> </blockquote> <p>For example:</p> <pre class="lang-none prettyprint-override"><code>if arr = [3,5,4,3] number of pairs will be 7 as shown below: initial array is to be converted to [3(1's),5(2's),4(3's),3(4's)] i.e [1,1,1,2,2,2,2,2,3,3,3,3,4,4,4] </code></pre> <p>Now we need to make pairs like this <code>[1,1][1,2][2,2][2,2][3,3][3,3][4,4]</code> remaining last 4 is left as it is single. So total number of pairs is 7. Following is my solution for the same:</p> <pre><code>def taskOfPairing(arr): n = len(arr) count = 0 newList = [] for i, j in enumerate(arr): newList += [i + 1]*j print(newList) count1 = 0 k = 1 newList.sort() n1 = len(newList) l=0 r=0 while r&lt;n1: if newList[r]-newList[l] &lt; k: count1 += 1 newList.pop(l) newList.pop(r) n1 = len(newList) l=0 r=0 if len(newList) == 1: break return count1 arr= [3,5,4,3] print(taskOfPairing(arr)) </code></pre> <p><strong>output = 7</strong></p> <p>My output works but only when there is small numbers in list like <code>arr = [3,5,4,3]</code> or <code>[2,4,3,1]</code>.</p> <p>If I try putting large numbers in list for example, <code>arr = [100000,200000,300000,400000]</code> my code will not work and will cause a lot of delay in execution. Can anyone let me know what I am doing wrong in this code. My apologies to stack overflow for asking naive questions.</p>
[]
[ { "body": "<p>The task doesn't require to generate a list of pairs - just to count them. So:</p>\n<ul>\n<li>take as much 1-1 pairs as you can ('count += arr[0]//2');</li>\n<li>if one dumbbell is left ('arr[0]' is odd) and there are dumbbells of weight 2, increase count and reduce 'arr<a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">1</a>' by one;</li>\n<li>repeat the process for weights 2, 3 and so on.</li>\n</ul>\n<p>Also, the sorting is excessive - just FYI.</p>\n<p>Oh, and be sure to read <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> and apply it to your code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T15:16:54.803", "Id": "263218", "ParentId": "263213", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T10:23:44.490", "Id": "263213", "Score": "6", "Tags": [ "python" ], "Title": "Count the number of saleable pairs of items" }
263213
<p>This is how I handle configuration in my python code, currently, but I guess it might look magic to people, and it is cumbersome to code. How can this be improved? Are there better solutions?</p> <p>The purpose is to have a general working configuration stored in UPPER CASE in global variables at the beginning of the file. When first run, it creates a <code>config.json</code> file with that configuration. That can be edited by the user, and it would supersede the default configuration, if run again. In order to still benefit from typing hints in modern IDEs, the <code>cfg[]</code> dict is not used directly, but the configuration is written back to the global variables.</p> <p>This is cumbersome to code, and it contains a lot of repetition. Every variable is touched multiple times.</p> <p>How can I improve this system and make it more elegant and transparent?</p> <pre><code>import json from typing import Any, Dict CONFIG_FILE = 'config.json' GLOBAL_CONFIG_EXAMPLE_PORT = 3 def read_config() -&gt; Dict[str, Any]: try: with open(CONFIG_FILE) as config_file: return json.load(config_file) except FileNotFoundError: pass # generate standard config file cfg = { 'example': { 'port': GLOBAL_CONFIG_EXAMPLE_PORT, }, } with open(CONFIG_FILE, 'w') as f: json.dump(cfg, f) set_global_variables(cfg) return cfg def set_global_variables(cfg: Dict[str, Any]): global GLOBAL_CONFIG_EXAMPLE_PORT GLOBAL_CONFIG_EXAMPLE_PORT = cfg['example']['port'] def main(): cfg: Dict[str, Any] = read_config() print(cfg['example']['port'], GLOBAL_CONFIG_EXAMPLE_PORT) if __name__ == &quot;__main__&quot;: main() </code></pre> <p>A real-life config file would be this:</p> <pre><code>{ &quot;mqtt&quot;: { &quot;host&quot;: &quot;10.21.1.77&quot;, &quot;port&quot;: 1883, &quot;topic&quot;: &quot;EXTENSE/Lab/XYZ/move/#&quot;, &quot;topic_ack&quot;: &quot;EXTENSE/Lab/XYZ/move/ack&quot; }, &quot;signal&quot;: { &quot;save&quot;: true, &quot;length&quot;: 60 }, &quot;sensor&quot;: { &quot;num&quot;: 5, &quot;trigger&quot;: 4 }, &quot;logging&quot;: { &quot;level&quot;: 10, &quot;filename&quot;: &quot;log.txt&quot;, &quot;console&quot;: true, &quot;format&quot;: &quot;%(asctime)s %(levelname)s: %(message)s&quot; } } </code></pre> <p>PS: How would you go about writing a test for this, efficiently?</p> <p>Addendum: Is it feasible and sensible to do some magic on the variable name which is all upper case, split them by underscore, and create the dict automatically?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T12:12:35.143", "Id": "519672", "Score": "1", "body": "Can you include an example JSON file?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T12:45:03.167", "Id": "519673", "Score": "0", "body": "certainly, @Reinderien :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T17:52:55.033", "Id": "519824", "Score": "0", "body": "@Reinderien i updated the config file, perhaps this illustrates the use a little better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T02:00:30.457", "Id": "519842", "Score": "0", "body": "What is supposed to happen when a section (like 'mqtt') or an item (like 'host') is missing from the config file. Does it fall back to the default or is it an error?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T07:38:43.660", "Id": "519856", "Score": "0", "body": "@RootTwo The graceful thing would be to fall back on the default. For me, the concept of cascading configuration, overwriting what is specified, applies. It would be nice if the config file was updated with the missing information. That way you have one place with all the configuration information collected and easy to view." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T13:04:01.200", "Id": "519948", "Score": "1", "body": "I don't know if it's just me, but I just store configurations in .py files and import the variables from the files, and I used .__name__, repr() and json.dumps() and quotes and some code to print these configurations to python files. I know it's dirty but it is very effective." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T13:49:21.477", "Id": "519957", "Score": "0", "body": "@XeнεiΞэnвϵς where is some code to look at this? This idea had not occurred to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T13:53:55.880", "Id": "519958", "Score": "1", "body": "If you really want to know, I will post an answer tomorrow, but not today." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-26T08:48:55.510", "Id": "520164", "Score": "0", "body": "@XeнεiΞэnвϵς you wanted to post code here." } ]
[ { "body": "<p><code>read_config</code> does not do what's on the tin: it attempts to read the config, conditionally writes out a default config, and sets globals. Those obligations should be separated.</p>\n<p>Also, your <code>example</code> is a mystery: is it a section? Currently it offers no value and a flat dictionary would be simpler to manipulate.</p>\n<p><code>GLOBAL_CONFIG_EXAMPLE_PORT</code> on its own is not a useful global. Consider instead moving the entire default configuration dictionary to a global constant.</p>\n<p>Something like:</p>\n<pre><code>import json\nfrom typing import Any, Dict\n\nCONFIG_FILE = 'config.json'\n\nDEFAULT_CONFIG = {\n 'port': 3,\n}\n\n\ndef read_config() -&gt; Dict[str, Any]:\n with open(CONFIG_FILE) as f:\n return json.load(f)\n\n\ndef write_config(config: Dict[str, Any]) -&gt; None:\n with open(CONFIG_FILE, 'w') as f:\n json.dump(config, f)\n\n\ndef load_or_default_config() -&gt; None:\n try:\n config = read_config()\n except FileNotFoundError:\n config = DEFAULT_CONFIG\n write_config(config)\n\n globals().update(config)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T18:42:14.613", "Id": "519826", "Score": "0", "body": "thanks for telling me about globals()! I like your approach a lot, and it's a lot more elegant than mine. However, it lacks the list of global variables at the beginning of the program which I thought to be a part of a good python coding style, and replaces it with a dict. Do you think that's a step forward?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T18:55:26.387", "Id": "519827", "Score": "0", "body": "How would your approach handle multi-level global constants, like in the real-life config example above? @reinderien" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T19:01:39.963", "Id": "519828", "Score": "0", "body": "Spin up a `@dataclass` for each section so that the section variables have types; have a global class instance for each section" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T19:07:03.947", "Id": "519829", "Score": "0", "body": "and how would you combine those dataclasses into one? could you do the example in the (real life) config file and update your code, perhaps?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T19:26:17.617", "Id": "519831", "Score": "0", "body": "i mean: in my example you would have four global classes, because there are four sections. how do you combine those four classes into one dict to write into a config file, and how do you read them back into the right class, if there is a config file that you parsed and need to split up into the correct classes?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T13:50:56.170", "Id": "263283", "ParentId": "263215", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T11:12:14.927", "Id": "263215", "Score": "3", "Tags": [ "python", "json", "configuration" ], "Title": "How to handle configuration from a config file and global variables transparently in python?" }
263215
<p>phoneNumberCheck() is using 2 helper function to check if a users input of a phone number is valid.</p> <ol> <li><p>this is a client side check, if this code is ok should I check the same at the nodeJS back end?</p> </li> <li><p>is splitting the number validation function to validate length and another function to validate prefix consider as over engineering?</p> </li> </ol> <p>Critical, Optional and Positive feedback are more then welcome.</p> <p>Thanks,</p> <pre><code>// phone number input sanitizing const sanitizeNumber = (phoneNumber) =&gt; { return phoneNumber .split('') .map((e) =&gt; e.replace(/\D/g, '')) .join('') } // phone number validation: length and prefix const validateNumber = (sanitizedInput) =&gt; { return sanitizedInput.length != 10 ? 'bad number length' : sanitizedInput.startsWith('05') ? sanitizedInput : 'bad number prefix' } /* high level function to check phone number validity, returns valid number or error. */ const phoneNumberCheck = (userInput) =&gt; { // exit early if length is not correct (long strings) if (userInput.length === 10) { // sanitize const sanitizedNumber = sanitizeNumber(userInput) // validate return validateNumber(sanitizedNumber) } // implict else to return false return false } /* my test cases */ // returns false early console.log(phoneNumberCheck(`.05'@0&quot;12-34'5&quot;67`)) // returns length error console.log(phoneNumberCheck(`0501234-67`)) // returns prefix error console.log(phoneNumberCheck(`0601234567`)) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T16:23:24.617", "Id": "519687", "Score": "0", "body": "This doesn't seem to make sense to me. What exactly are valid inputs?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T17:58:41.127", "Id": "519690", "Score": "0", "body": "valid user input is specific, a string of 10 digits e.g: 05xxxxxxxx when the x's are digits" } ]
[ { "body": "<blockquote>\n<p>this is a client side check, if this code is ok should I check the same at the nodeJS back end?</p>\n</blockquote>\n<p>Yes! The server has no idea what's <em>really</em> running on the other side of the connection - all it knows is what data it gets. Maybe it's talking to an old version of the client that had a bug in its validation code. Maybe it's talking to a third-party client that thinks you're using another format, so it sends something it <em>thinks</em> is acceptable but really isn't. Maybe it's talking to a <em>fake</em> client that <em>wants</em> to put bad data in your database for some reason. Network input is <em>input</em> and must be treated like <em>any other input</em> - make <em>no</em> assumptions you don't check.</p>\n<blockquote>\n<p>is splitting the number validation function to validate length and another function to validate prefix consider as over engineering?</p>\n</blockquote>\n<p>Two simple functions is usually better than one complicated function - but one simple function is often better than two simple functions. So, in general no, that <em>could</em> be a valid way to organize this if you had more complicated rules for validation. But in this case, I'd say yes.</p>\n<p>On that note, I have opinions on your sanitation function in general:</p>\n<ul>\n<li>First off, the <code>join</code>ing and <code>split</code>ting is not needed here. You can accomplish the same thing with <code>phoneNumber.replaceAll(/\\D/g, '')</code></li>\n<li>But more importantly - what <em>useful</em> thing does this function do? When I call <code>sanitizeNumber</code> I don't end up with a sanitized phone number - I end up with a sanitized <em>something</em> and have to <em>check</em> whether it's a phone number. That doesn't seem very useful. Why do I have to check that myself? I already have a function that claims to turn a string into a phone number, why can it fail to do that and <em>not tell me</em>? Shouldn't it throw an exception or return <code>null</code> or something when given input it can't turn into a valid phone number?</li>\n<li>Finally, the way your code is written, any time the sanitation actually ends up <em>happening</em> it either changes an invalid number into a different invalid number (10 characters including x non-digits -&gt; 10-x digits, which is too short to be valid), or it leaves the input unchanged (not 10 characters -&gt; no sanitation; 10 digits -&gt; unchanged output). At that point, what are you even sanitizing? Either the input <em>was already a valid phone number</em> or it went from being an invalid phone number to <em>still</em> being an invalid phone number - so why not just check whether the input was a valid phone number in the first place? In this case, that'd be as simple as <code>userInput.match(/^05\\d{8}$/)</code></li>\n</ul>\n<p>Though I do want to point out that depending on your target audience, you might be making assumptions about phone numbers that you shouldn't be. Are you <em>sure</em> your user's phone number will be from the region you're in? The prefix check might be overzealous if not. Are you sure your users will all have phone numbers from <em>your country</em> (even if they live there)? If not, you shouldn't be assuming 10 digits. Phone numbers are <a href=\"https://github.com/google/libphonenumber/blob/master/FALSEHOODS.md\" rel=\"noreferrer\"><em>complicated</em></a>, and you may be better off finding a library that already handles that complexity than trying to roll your own implementation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T19:02:36.237", "Id": "519694", "Score": "0", "body": "Thank you Sara, this code is for specific people in a specific country and it comes with instructions this is why I didn't went with a library that handle phone numbers in general. as you might guess this isn't production code yet :D, I'll implement the validation at server side - one of the advantages of using JS as frontend and backend is the code practicly the same :D. about the functions split UncleBob says extract (method) and extract and extract until you can't do that anymore. In this case I think one simple function will do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T19:02:47.160", "Id": "519695", "Score": "0", "body": "sanitizeNumber purpuse was to strip all sql injection chars: `'\"| etc'. it's a great backend one liner to: return userInput.match(/^05\\d{8}$/) == null ? false : userInput. but doing that on the frontend I don't have the cause I can output to the user what the error is(missing digits? / check prefix...)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T23:52:50.757", "Id": "519703", "Score": "0", "body": "@hibih: If you're going to strip out the non-digits, you should at least do that *before* you check the length, not after. Otherwise, the user can add garbage characters to a too-short number to get a \"valid\" number that isn't actually valid, but passes your check." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T02:12:59.517", "Id": "519708", "Score": "0", "body": "Final points are important. Where I work (finance) we had to actually define, as a business, what a domestic phone number was due to internationally formatted mobile numbers validly connecting to domestic networks and vice-versa. End result was any number (with or without leading-zeroes where the length was above a minimum, ie 7) was valid. If the person was connected to a domestic network, then not a problem, otherwise they needed to organise an alternative." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T10:41:52.837", "Id": "519725", "Score": "0", "body": "@Kevin all the checks runs together on button click." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T10:46:42.100", "Id": "519726", "Score": "0", "body": "@Aaron: in this specific requirement it is by design that clients will not be able to use the service outside the country it intended." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T10:47:23.523", "Id": "519727", "Score": "0", "body": "Thanks everyone!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T17:12:58.927", "Id": "263222", "ParentId": "263217", "Score": "7" } } ]
{ "AcceptedAnswerId": "263222", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T14:50:27.803", "Id": "263217", "Score": "3", "Tags": [ "javascript", "node.js", "validation" ], "Title": "Sanitation and validation of a user input 10 digits phone number" }
263217
<p>This is my first asyncio/aiohttp web scraper. I am trying to wrap my head around Python's asyncio/aiohttp libs these days and I am not sure if I fully understand it or not yet. So I'd like have some constructive enhancement reviews here.</p> <p>I'm scraping <a href="https://www.spoonflower.com/" rel="nofollow noreferrer">Spoonflower</a>, which contains some public API's for design data and pricing per fabric type data. My challenge was to get the design name, creator name and price of each design as per fabric type. Design name and creator name comes from this endpoint</p> <blockquote> <p><a href="https://pythias.spoonflower.com/search/v1/designs?lang=en&amp;page_offset=0&amp;sort=bestSelling&amp;product=Fabric&amp;forSale=true&amp;showMatureContent=false&amp;page_locale=en" rel="nofollow noreferrer">https://pythias.spoonflower.com/search/v1/designs?lang=en&amp;page_offset=0&amp;sort=bestSelling&amp;product=Fabric&amp;forSale=true&amp;showMatureContent=false&amp;page_locale=en</a></p> </blockquote> <p>and other pricing per fabric type data coming from this endpoint.</p> <blockquote> <p><a href="https://api-gateway.spoonflower.com/alpenrose/pricing/fabrics/FABRIC_%27+%20fab_type%20+%27?quantity=1&amp;shipping_country=PK&amp;currency=EUR&amp;measurement_system=METRIC&amp;design_id=%27%20str(item%5B%27designId%27%5D)%20%27&amp;page_locale=en" rel="nofollow noreferrer">https://api-gateway.spoonflower.com/alpenrose/pricing/fabrics/FABRIC_'+%20fab_type%20+'?quantity=1&amp;shipping_country=PK&amp;currency=EUR&amp;measurement_system=METRIC&amp;design_id='%20str(item['designId'])%20'&amp;page_locale=en</a></p> </blockquote> <p>Each page has 84 items and 24 fabric types. I'm first getting all the names of the fabric types and storing in a list. I can loop through it and change the url dynamically then extracting <code>designName</code> and <code>screenName</code> from design page and finally extracting the price data.</p> <p>Here is my code:</p> <pre><code>import asyncio import aiohttp import json import requests from bs4 import BeautifulSoup from collections import OrderedDict item_endpoint = 'https://pythias.spoonflower.com/search/v1/designs?lang=en&amp;page_offset=0&amp;sort=bestSelling&amp;product=Fabric&amp;forSale=true&amp;showMatureContent=false&amp;page_locale=en' def get_fabric_names(): res = requests.get('https://www.spoonflower.com/spoonflower_fabrics') soup = BeautifulSoup(res.text, 'lxml') fabrics = [fabric.find('h2').text.strip() for fabric in soup.find_all('div', {'class': 'product_detail medium_text'})] fabric = [(&quot;_&quot;.join(fab.upper().replace(u&quot;\u2122&quot;, '').split())) for fab in fabrics] for index in range(len(fabric)): if 'COTTON_LAWN_(BETA)' in fabric[index]: fabric[index] = 'COTTON_LAWN_APPAREL' elif 'COTTON_POPLIN' in fabric[index]: fabric[index] = 'COTTON_POPLIN_BRAVA' elif 'ORGANIC_COTTON_KNIT' in fabric[index]: fabric[index] = 'ORGANIC_COTTON_KNIT_PRIMA' elif 'PERFORMANCE_PIQUÉ' in fabric[index]: fabric[index] = 'PERFORMANCE_PIQUE' elif 'CYPRESS_COTTON' in fabric[index]: fabric[index] = 'CYPRESS_COTTON_BRAVA' return fabric async def fetch_design_endpoint(session, design_url): async with session.get(design_url) as response: extracting_endpoint = await response.text() _json_object = json.loads(extracting_endpoint) return _json_object['page_results'] async def fetch_pricing_data(session, pricing_endpoint): async with session.get(pricing_endpoint) as response: data_endpoint = await response.text() _json_object = json.loads(data_endpoint) items_dict = OrderedDict() for item in await fetch_design_endpoint(session, item_endpoint): designName = item['name'] screenName = item['user']['screenName'] fabric_name = _json_object['data']['fabric_code'] try: test_swatch_meter = _json_object['data']['pricing']['TEST_SWATCH_METER']['price'] except: test_swatch_meter = 'N/A' try: fat_quarter_meter = _json_object['data']['pricing']['FAT_QUARTER_METER']['price'] except: fat_quarter_meter = 'N/A' try: meter = _json_object['data']['pricing']['METER']['price'] except: meter = 'N/A' #print(designName, screenName, fabric_name, test_swatch_meter,fat_quarter_meter, meter) if (designName, screenName) not in items_dict.keys(): items_dict[(designName, screenName)] = {} itemCount = len(items_dict[(designName, screenName)].values()) / 4 return items_dict[(designName, screenName)].update({'fabric_name_%02d' %itemCount: fabric_name, 'test_swatch_meter_%02d' %itemCount: test_swatch_meter, 'fat_quarter_meter_%02d' %itemCount: fat_quarter_meter, 'meter_%02d' %itemCount: meter}) async def main(): tasks = [] async with aiohttp.ClientSession() as session: fabric_type = get_fabric_names() design_page = await fetch_design_endpoint(session, item_endpoint) for item in design_page: for fab_type in fabric_type[0:-3]: pricing_url = 'https://api-gateway.spoonflower.com/alpenrose/pricing/fabrics/FABRIC_'+ fab_type +'?quantity=1&amp;shipping_country=PK&amp;currency=EUR&amp;measurement_system=METRIC&amp;design_id='+str(item['designId'])+'&amp;page_locale=en' print(pricing_url) await fetch_pricing_data(session, pricing_url) tasks.append(asyncio.create_task( fetch_pricing_data(session, pricing_url) ) ) content = await asyncio.gather(*tasks) return content results = asyncio.run(main()) print(results) </code></pre> <p>Any ideas and suggestions are welcome to make this scraper more Pythonic and smart.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T18:48:16.083", "Id": "519693", "Score": "0", "body": "Is there public documentation available for the site's API? If there is, could you add a link to it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T19:11:19.997", "Id": "519696", "Score": "1", "body": "I don't think so at least I am not aware of that if their public documentation is available or not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T00:58:45.873", "Id": "519762", "Score": "1", "body": "@dougj I would also recommend looking into [urllib.parse](https://docs.python.org/3/library/urllib.parse.html) as it makes parsing and maintaining urls a bit cleaner." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-26T16:28:01.073", "Id": "520172", "Score": "0", "body": "Please don't update the question, especially the code in the question after it has an answer. Everyone must be able to see the same question the person that wrote the answer saw. If you want to make changes based on the answer ask a follow up question that links to this question." } ]
[ { "body": "<p>I'm not too experienced with asyncio, but I have a couple of minor observations about your program.</p>\n<p>It is a code smell in modern Python to use an int to index over an array. Instead of</p>\n<pre><code>for index in range(len(fabric)):\n</code></pre>\n<p>You could say</p>\n<pre><code>for fabric_type in fabric:\n</code></pre>\n<p>Another observation in that you are using naked except blocks instead of catching &quot;KeyError&quot; explicitly. If you do so you save the reader some mental effort going back to see why you would be expecting a problem to be raised.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T00:06:51.797", "Id": "519704", "Score": "2", "body": "The loop over the index actually uses the index to modify the array. To avoid the `range(len)` approach here you'd have to use `enumerate` as in `for index, fabric_type in enumerate(fabric):`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T08:53:33.217", "Id": "519718", "Score": "0", "body": "Actually I want in place changes to modify the list that is why I have to use range(len)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T12:15:30.183", "Id": "519730", "Score": "1", "body": "@dougj not quite. In python you can iterate over the index and the value at the same time using `enumerate`. For example: `for index, value in enumerate(['zero', 'one', 'two'])` would return a tuple like this at each iteration: `(0, 'zero',)`, `(1, 'one',)`, `(2, 'two',)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T12:37:12.383", "Id": "519731", "Score": "0", "body": "Ah!Nice to know that I will give it a try." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T17:36:07.630", "Id": "263223", "ParentId": "263221", "Score": "3" } }, { "body": "<p>While you <em>can</em> put request parameters in the URI directly, it's usually neater to pass those using the <code>params</code> argument of <code>session.get</code>. So for example <code>pricing_url</code> could just be <code>&quot;https://api-gateway.spoonflower.com/alpenrose/pricing/fabrics/FABRIC_&quot; + fab_type</code> and you could pass the rest as <code>params={&quot;quantity&quot;: 1, &quot;shipping_country&quot;: &quot;PK&quot;, &quot;currency&quot;: &quot;EUR&quot;, ...})</code>. That's usually more readable.</p>\n<p><code>get_fabric_names</code> is very different than the others - it uses <code>requests</code> rather than <code>aiohttp</code> and it hardcodes its URI instead of taking it as a parameter. I'm not saying that's a <em>problem</em>, but it feels a bit inconsistent.</p>\n<p><code>aiohttp</code> has JSON parsing built into its responses. If all you're going to do with <code>some_response.text()</code> is pass it to <code>json.loads</code>, you may be better off just calling <code>some_response.json()</code> and drop the <code>data_endpoint</code> and <code>extracting_endpoint</code> variables.</p>\n<p>I find it a bit strange that, even though there's a public-facing API, the way you obtain a list of fabric names is by extracting it from an HTML document. Now, I don't know Spoonflower's API, maybe that's the best (or only) way available, but it <em>feels</em> like there should be a better option.</p>\n<p>Is the <code>return</code> from <code>fetch_pricing_data</code> really supposed to be <em>inside</em> the loop? It doesn't look like there are any <code>continue</code>s or other ways to skip it, so the loop will only run for one iteration, right? It seems a bit strange to use a loop in that case.</p>\n<p>The output format of <code>fetch_pricing_data</code> is a bit unusual. If I'm understanding this correctly, each fabric type gets a <code>dict</code> shaped like:</p>\n<pre><code># I have no idea what actual values you'll work with, so I'm making some up\n{\n 'fabric_name_00': 'some name',\n 'fabric_name_01': 'some other name',\n 'test_swatch_meter_00': 20,\n 'test_swatch_meter_01': 20,\n 'fat_quarter_meter_00': 25,\n 'fat_quarter_meter_01': 25,\n 'meter_00': 5,\n 'meter_01': 6,\n ...: ...\n}\n</code></pre>\n<p>...which seems really awkward to me. If each number will contain all of those (which you seem to assume), I feel like an easier-to-work-with format could be:</p>\n<pre><code>[\n {\n 'fabric_name': 'some name',\n 'test_swatch_meter': 20,\n 'fat_quarter_meter': 25,\n 'meter': 5\n },\n {\n 'fabric_name': 'some other name',\n 'test_swatch_meter': 20,\n 'fat_quarter_meter': 25,\n 'meter': 6\n },\n ...\n]\n</code></pre>\n<p>The manual replacement of fabric names in <code>get_fabric_names</code> feels a bit clunky. Now, depending on how the API is designed that might be the only way to actually get those fabric IDs, but even if that's the case I'd think it best to keep the list of replacements elsewhere - it looks like the kind of thing that might need changing over time, so putting it in a variable somewhere or even in a separate data file might make sense.</p>\n<p>It's not at all clear why you skip the last 3 values in <code>fabric_type</code>. If it's because they aren't fabric types, I think it should be <code>get_fabric_names</code>'s responsibility to not return them in the first place.</p>\n<p>Finally, some nitpicks about variable names:</p>\n<ul>\n<li><code>fabric</code> is a bit of a weird name considering it's a list of <em>multiple</em> fabrics. Maybe <code>fabric_names</code>? Or maybe call it <code>fabrics</code> and rename the existing <code>fabrics</code> to something like <code>fabric_headers</code>? Or both!</li>\n<li>Same for <code>fabric_type</code> in <code>main</code> - why not <code>fabric_types</code>?</li>\n<li>Most of your variables called <code>*_endpoint</code> are URIs you can send requests to. Clear and consistent. But <code>data_endpoint</code> and <code>extracting_endpoint</code> are responses to queries, which is mildly confusing on its own and also goes against the convention you establish.</li>\n<li>The name <code>items_dict</code> is a bit redundant. Isn't <code>items</code> enough?</li>\n<li>You seem to pretty consistently use <code>this_casing_scheme</code> for variable names (as is conventional in Python), except for <code>designName</code>, <code>screenName</code> and <code>itemCount</code>. You might want to rename those for consistency</li>\n<li>Why the leading <code>_</code> in <code>_json_object</code>?</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T08:52:12.037", "Id": "519717", "Score": "0", "body": "Thanks for your constructive feedback I will improve it soon." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T09:15:24.900", "Id": "519720", "Score": "0", "body": "fabric_names using requests because it's only job to get the names of all the fabric from only page so I thought it doesn't make much sense to make it async." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T09:18:17.573", "Id": "519721", "Score": "0", "body": "Actually there were 27 fabric types and the last 3 wasn't associated to any other designs if I iterate over those it gives weird results so that's why I slice it till [0:-3]" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T20:43:26.093", "Id": "263227", "ParentId": "263221", "Score": "10" } }, { "body": "<p>Something not included in the other answers:</p>\n<p>These two lines in your <code>main</code> function mean that you request and parse each page twice. It also means your code is not really async, because you loop over all fabrics and just <code>await</code> each of them. You should be able to just remove the first one.</p>\n<pre><code>await fetch_pricing_data(session, pricing_url)\ntasks.append(asyncio.create_task(fetch_pricing_data(session, pricing_url))\n</code></pre>\n<p>In addition, you could spawn async tasks in that function instead of the simple <code>for</code> loop you currently have:</p>\n<pre><code>for item in await fetch_design_endpoint(session, item_endpoint)\n</code></pre>\n<p>This will speed up your code by quite a lot, probably, once you have fixed the return value of that function to be outside the loop.</p>\n<p>However, your function <code>fetch_design_endpoint</code> does not actually depend on anything specific in <code>fetch_pricing_data</code>. This is either a bug (did you want to change the URL?) or you could retrieve the results only once.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T08:54:42.200", "Id": "519719", "Score": "0", "body": "Yeah it makes much more sense." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T06:35:19.753", "Id": "263243", "ParentId": "263221", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T17:02:57.973", "Id": "263221", "Score": "11", "Tags": [ "python", "python-3.x", "web-scraping", "async-await" ], "Title": "Asynchronously scrape fabric information" }
263221
<p>Loader - load commands files(classes) from directory of commands and module, if the commands are very simple and similar, then I put them in 1 file with the name of the module and load them through the loop in the same way as usual commands</p> <pre><code> public async load_Commands():Promise&lt;void&gt; { for (const module of readdirSync(`${this.directory}commands/`)) { const Commands = readdirSync(`${this.directory}commands/${module}/`).filter((file) =&gt; file.endsWith('.js')); for (const commandFile of Commands) { const {name} = path.parse(commandFile); const File = await import (`${this.directory}Commands/${module}/${commandFile}`) if([&quot;fun&quot;].includes(name)){ console.log(File) for(const [name, command_class] of Object.entries(File)) { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const command = new command_class(this.client) command.name = name command.settings.category ??= module; this.client.commands.set(command.name, command); } } else { const command: Command = new File.default(this.client); command.name ??= path.parse(commandFile).name command.settings.category ??= module; this.client.commands.set(command.name, command); } } } } </code></pre> <p>Normal command</p> <p>commands/fun/avatar.ts</p> <pre><code>import {Message, MessageEmbed} from 'discord.js'; import Command from &quot;../../Structures/Classes/Command&quot;; import {Command_Run} from &quot;../../Structures/Interfaces/Command&quot;; export default class Avatar extends Command { run:Command_Run = async(message:Message, [user]) =&gt; { const member = await this.member(message, user) if(this.stop === true) return; await message.channel.send(new MessageEmbed() .setColor('RANDOM') .setTitle(`${this.language.commands.avatar.parameters.avatar} ${member.user.username}!`) .setImage(member.user.avatarURL({ dynamic: true })) .setTimestamp()); } } </code></pre> <p>Module commands</p> <p>commands/fun/fun.ts</p> <pre><code>import ImageCommand from &quot;../../Structures/Abstracts/Fun&quot;; export class Dog extends ImageCommand { async getImage():Promise&lt;string&gt; { return this.fetch(&quot;https://random.dog/woof.json&quot;) } getSuccessMessage():string { return this.language.commands.dog.parameters.successful } } export class Cat extends ImageCommand { async getImage():Promise&lt;string&gt; { return this.fetch(&quot;https://some-random-api.ml/img/cat&quot;) } getSuccessMessage():string { return this.language.commands.cat.parameters.successful } } export class Fox extends ImageCommand { async getImage():Promise&lt;string&gt; { return this.fetch(&quot;https://randomfox.ca/floof/&quot;) } getSuccessMessage():string { return this.language.commands.fox.parameters.successful } } </code></pre> <p>Abstract for fun module commands ./../Structures/Abstracts/Fun</p> <pre><code>import {Message} from &quot;discord.js&quot;; import Command from &quot;../Classes/Command&quot;; export default abstract class ImageCommand extends Command { abstract getImage(): Promise&lt;string&gt; abstract getSuccessMessage(): string run = async(message: Message):Promise&lt;void&gt; =&gt; { await this.embed.fun(this.getSuccessMessage(), message, await this.getImage()) } } </code></pre> <p>Is there an opportunity here to simplify loader commands code? increase speed, readability, make it smaller?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T21:01:30.897", "Id": "519699", "Score": "2", "body": "It's difficult to review code without knowing what it does and why. Could you please add a description of what your code is intended to do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T06:47:32.280", "Id": "519711", "Score": "0", "body": "@SaraJ edited post" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-19T19:35:04.340", "Id": "263225", "Score": "0", "Tags": [ "node.js", "typescript", "dynamic-loading" ], "Title": "Commands loader" }
263225
<p>I would like to return or save for later use in the ParallelSums function what I currently have printing out to the console in the findAllSubsetsRec function.</p> <p>If I pass the ParallelSums function an int array of [16, 22, 35, 8, 20, 1, 21, 11] I currently get the console output from the findAllSubsetsRec of:</p> <pre><code>22 20 16 8 1 22 21 16 8 35 20 11 1 35 21 11 </code></pre> <p>I would like each line that is seen above to be returned to my ParallelSums function, probably in multiple lists or in a way that I can later put them in multiple lists/arrays, so that I can do some further processing on them.</p> <p>Below is the code I have so far:</p> <pre><code>using System; using System.Linq; using System.Collections.Generic; class MainClass { static void findAllSubsetsRec(int []arr, int n, List&lt;int&gt; v, int target) { List&lt;int&gt; subList = new List&lt;int&gt;(); // if the remaining target is 0, add elements to subList if(target == 0) { for (int i=0; i&lt;v.Count; i++) { Console.Write(v[i]+ &quot; &quot;); subList.Add(v[i]); } Console.WriteLine(); return; } // if there are no elements remaining return if (n == 0) { return; } // two cases to consider for every element // 1. we won't include the last element // 2. we will include the last element in current subset findAllSubsetsRec(arr, n-1, v, target); List&lt;int&gt; v1 = new List&lt;int&gt;(v); v1.Add(arr[n-1]); findAllSubsetsRec(arr, n-1, v1, target-arr[n-1]); } public static int ParallelSums(int[] arr) { // variable initialization // manually set number of sub arrays we are looking to use // so we can write code to work for anything and then restrict // it to work for this particular case int numOfSubArr = 2; // determine if we have enough elements in arr to allow for // an even number of elements for each sub array per requirements int evenNumElementsPerArr = arr.Length%numOfSubArr; // find our target number for our sub arrays to equal int arrSum = arr.Sum(); int target = arr.Sum()/numOfSubArr; int possibleTarget = arrSum%numOfSubArr; Console.WriteLine(&quot;possibleTarget = &quot; + possibleTarget); Console.WriteLine(&quot;Target Number = {0}&quot;, target); Console.WriteLine(&quot;Possible target for equal length sub arrays? &quot; + ((possibleTarget==0)?&quot;yes&quot;:&quot;no&quot;)); Console.WriteLine(&quot;Even number of elements per array? &quot; + ((evenNumElementsPerArr==0)?&quot;yes&quot;:&quot;no&quot;)); // validation checks if (evenNumElementsPerArr != 0 || possibleTarget != 0) { Console.WriteLine(&quot;Array of odd numbered length or can't be equally divided into sub arrays&quot;); return -1; } else { Console.WriteLine(&quot;We have an even number of elements and sub array lengths&quot;); // initialize arrays and variables for sums int n = arr.Length; List&lt;int&gt; v = new List&lt;int&gt;(); // sort our input array Array.Sort(arr); findAllSubsetsRec(arr, n, v, target); } // will eventually return my desired results, but for now will just return 1 return 1; } static void Main() { // keep this function call here Console.WriteLine(ParallelSums(Console.ReadLine())); } } </code></pre> <p>The end goal is to take all of these lists and determine which 2 contain all the numbers from the input array, without using any twice, while both lists have an equal length/count of elements.</p> <p>In my example below the list of [22,21,16,8] and [35,20,11,1] would ultimately be the two correct lists to solve my problem.</p> <p>Any help would be very much appreciated and I'm open to changing my methodology if something else makes more sense than what I'm doing now.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T08:28:25.117", "Id": "519714", "Score": "2", "body": "Only working as intended code is suitable for Code Review. You may ask the question on [StackOverflow](https://stackoverflow.com/) instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T04:32:53.183", "Id": "519771", "Score": "1", "body": "Welcome to Code Review. I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>I added a <code>private static Dictionary&lt;int, List&lt;List&lt;int&gt;&gt;&gt; _dictionary = new Dictionary&lt;int, List&lt;List&lt;int&gt;&gt;&gt;();</code> so that I can access the dictionary at any level of the recursion and then enter values like this:</p>\n<pre><code>if (!_dictionary.ContainsKey(v.Count))\n{\n _dictionary.Add(v.Count, new List&lt;List&lt;int&gt;&gt;());\n}\n\n_dictionary[v.Count].Add(v);\n</code></pre>\n<p>You can then see which entries you actually care about by using only the ones that are exactly half of the input array. From there, you can do any other processing you might need.</p>\n<p>One other thing I would ask is how you are planning to handle duplicates in the original array? It should be simple enough to keep track by removing the values as you compare and then resetting if the arrays don't meet your criteria but, if not handled properly, could flag a failed case accidentally if not handled.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T01:57:40.053", "Id": "519707", "Score": "1", "body": "Thank you for your input Trevor. I hadn't fully considered duplicates in my original array input, but figured I'd get some output first and then see what I needed to do to clean up those cases. I'll give your dictionary a go and follow up once I have more." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T14:08:05.430", "Id": "519737", "Score": "0", "body": "@MaxVarner I can't comment on your update but the reason your output looks the way it does is you aren't printing correctly. You are printing all lists with a certain key on one line instead of breaking them up by line. You can fix this in one of two ways: either move your `Console.Write(\"\\n\" + i.Key + \":\");` statement in one foreach loop OR add a `Console.WriteLine()` before the innermost foreach so each line is on its own line." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T19:50:01.193", "Id": "519753", "Score": "0", "body": "Ahh yes! I see. I've made the changed of moving my `Console.Write(\"\\n\" + i.Key + \":\");` to the second foreach loop and now I have the output as expected. I was thinking that I needed unique keys for each item in the dictionary to be able to access them later individually, but I can, and probably should, just transition those lists out of the dictionary to do my additional logic for determining the correct ones to ultimately output. I haven't used dictionaries before so I'm not fully familiar with all the things they can do at this time. Thank you again Trevor!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T00:53:40.130", "Id": "519914", "Score": "1", "body": "Limiting the output in the dictionary from findAllSubsetsRec() to only add the items to a temp list that had a key value equal to half of my original array length; I was able to see that the first key value number of items in the temp list and the last key value number of items in the list seemed to always be a matching subset that contained all of the values in the original array while not duplicating any across each subset. This seemed to hold true even if I had duplicate numbers in my original array. This pattern continued as you moved to the second and second to last subset and so on." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T01:43:14.420", "Id": "263234", "ParentId": "263229", "Score": "0" } } ]
{ "AcceptedAnswerId": "263234", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T00:39:09.507", "Id": "263229", "Score": "0", "Tags": [ "c#", "recursion" ], "Title": "Return Lists from Recursive Function C#" }
263229
<p>For an integer array <code>nums</code>, an inverse pair is a pair of integers <code>[i, j]</code> where <code>0 &lt;= i &lt; j &lt; nums.length</code> and <code>nums[i] &gt; nums[j]</code>.</p> <p>Given two integers n and k, return the number of different arrays consisting of numbers from 1 to n such that there are exactly k inverse pairs. Since the answer can be huge, return it modulo <span class="math-container">\$10^9 + 7\$</span>.</p> <p><a href="https://leetcode.com/problems/k-inverse-pairs-array/solution/" rel="nofollow noreferrer">https://leetcode.com/problems/k-inverse-pairs-array/solution/</a></p> <p>Brute Force Solution:</p> <pre><code>from itertools import permutations, combinations class Solution: def kInversePairs(self, n: int, k: int) -&gt; int: array = [x for x in range(1,n+1)] array_permutations = list(permutations(array)) memoized = {} count = 0 for each_permutation in array_permutations: each_permutation = list(each_permutation) if self.has_exactly_k_inverse_pair(k, each_permutation, memoized): count += 1 return count % 1000000007 def has_exactly_k_inverse_pair(self, k, array, memoized): count = 0 list_of_sequential_pairs = combinations(array, 2) for item_i, item_j in list_of_sequential_pairs: cached = memoized.get((item_i, item_j), None) if not cached: result = self.is_inverse_pair((item_i, item_j)) if result: memoized[(item_i, item_j)] = result count += 1 else: count += 1 if count &gt; k: return False return count == k def is_inverse_pair(self, tup): return tup[0] &gt; tup[1] </code></pre> <p>I am looking for code review just for the brute force solutions. I am looking to get constructive feedback mainly with:</p> <ul> <li>Using <code>memoized</code> dictionary for storing <code>True</code> entries only.</li> <li>Being able to pass memoized and update it.</li> <li>Using tuples as keys in Python.</li> <li>Overall best coding practices.</li> </ul>
[]
[ { "body": "<p><strong>The memoization is not helping</strong>. In fact, it's slowing things down\nconsiderably. I executed your code for all pairs of <code>n</code> and <code>k</code> from <code>0</code>\nthrough <code>9</code>, inclusive: it took 16 seconds on my computer. Then I commented out the memoization\ninfrastructure and the <code>is_inverse_pair()</code> method and instead just tested for\n<code>item_i &gt; item_j</code> directly: it finished in 6 seconds and got the same result.\nThis failure of memoization was caused by overfactoring: in almost all\nsituations, it hurts both readability and speed to write a function to perform\nsimple mathematical evaluations. I haven't benchmarked it recently, but calling\nany function (even a no-op) is almost certainly slower than comparing two\nintegers. And when you're doing something that's already fast, there's no\nbenefit to memoization: I would not be surprised if even a dict-lookup is\nslower than integer comparison (again, I haven't benchmarked it).</p>\n<p><strong>The check for <code>count &gt; k</code> is helping</strong>. How do I know? Same benchmarking\nsetup: it takes 10 seconds without the guard.</p>\n<p><strong>If you care about speed, make it easy to test and measure</strong>. My first step\nwhen working on your code was to exercise it with a test case across a variety\nof inputs (as described), put everything in a dict mapping <code>(n, k)</code> inputs to\nresulting outputs, print that dict and then put it into a big <code>EXPECTED</code>\nconstant in the code. This quickly gave me an automated way to make sure my\nchanges did not mess anything up, and also an easy way to do some simple speed\ncomparisons as I experimented. This programming habit was learned the hard way,\nthrough trial, much error, and even more pain. I encourage you to start\nadopting similar habits, both in your code and in your coding questions on\nsites like this (give readers some helpful test code to work with, not just\nyour proposed answer).</p>\n<p><strong>Don't convert generators to actual sequences needlessly</strong>. You don't need\n<code>array_permutations</code> as an actual list, because you can iterate directly over\nthe values yielded by <code>permutations(array)</code>. Doing so speeds things up a bit\nmore: 4.8 seconds for the same benchmark. And the same thing applies to\n<code>each_permutation</code>: you don't need to listify it. Instead, just pass the\ngenerator to the next function, where it will be iterated directly without the\ncost of creating an actual list. Dropping that change got my simple benchmark\ndown to 4.2 seconds. You also don't need <code>array</code> to be a list. Just give the\nrange directly to <code>permutations()</code> (because <code>n</code> is small in my benchmark, this\nchange had no observable speed-effect for me, but the same principle would apply\nif <code>n</code> were large).</p>\n<p><strong>Tuples make great dict keys</strong>. You asked about this, and it's an excellent\nthing to have in your tool kit. For example, sometimes <code>d[x, y]</code> is a more\nconvenient way to organize data than <code>d[x][y]</code>. Note also that parentheses are\nnot required: you don't need to use <code>d[(x, y)]</code>. The comma creates the tuple,\nnot the parentheses.</p>\n<p><strong>Speaking over overfactoring</strong>. You can get another small speed boost\nby dropping <code>has_exactly_k_inverse_pair()</code>. Function calls take time,\nso if you're really wanting to eek out gains, inline the code. Of course,\nthat can come at a readability cost, but in this case (given the changes\nnoted above), I don't feel too bad about it.</p>\n<p>Here's the code I ended up with:</p>\n<pre><code>from itertools import permutations, combinations\n\nEXPECTED = {\n (0, 0): 1, (0, 1): 0, (0, 2): 0, (0, 3): 0, (0, 4): 0, (0, 5): 0, (0, 6): 0, (0, 7): 0, (0, 8): 0, (0, 9): 0,\n (1, 0): 1, (1, 1): 0, (1, 2): 0, (1, 3): 0, (1, 4): 0, (1, 5): 0, (1, 6): 0, (1, 7): 0, (1, 8): 0, (1, 9): 0,\n (2, 0): 1, (2, 1): 1, (2, 2): 0, (2, 3): 0, (2, 4): 0, (2, 5): 0, (2, 6): 0, (2, 7): 0, (2, 8): 0, (2, 9): 0,\n (3, 0): 1, (3, 1): 2, (3, 2): 2, (3, 3): 1, (3, 4): 0, (3, 5): 0, (3, 6): 0, (3, 7): 0, (3, 8): 0, (3, 9): 0,\n (4, 0): 1, (4, 1): 3, (4, 2): 5, (4, 3): 6, (4, 4): 5, (4, 5): 3, (4, 6): 1, (4, 7): 0, (4, 8): 0, (4, 9): 0,\n (5, 0): 1, (5, 1): 4, (5, 2): 9, (5, 3): 15, (5, 4): 20, (5, 5): 22, (5, 6): 20, (5, 7): 15, (5, 8): 9, (5, 9): 4,\n (6, 0): 1, (6, 1): 5, (6, 2): 14, (6, 3): 29, (6, 4): 49, (6, 5): 71, (6, 6): 90, (6, 7): 101, (6, 8): 101, (6, 9): 90,\n (7, 0): 1, (7, 1): 6, (7, 2): 20, (7, 3): 49, (7, 4): 98, (7, 5): 169, (7, 6): 259, (7, 7): 359, (7, 8): 455, (7, 9): 531,\n (8, 0): 1, (8, 1): 7, (8, 2): 27, (8, 3): 76, (8, 4): 174, (8, 5): 343, (8, 6): 602, (8, 7): 961, (8, 8): 1415, (8, 9): 1940,\n (9, 0): 1, (9, 1): 8, (9, 2): 35, (9, 3): 111, (9, 4): 285, (9, 5): 628, (9, 6): 1230, (9, 7): 2191, (9, 8): 3606, (9, 9): 5545,\n}\n\ndef main():\n LIMIT = 10\n got = {\n (n, k) : Solution().kInversePairs(n, k)\n for n in range(LIMIT)\n for k in range(LIMIT)\n }\n assert got == EXPECTED\n\nclass Solution:\n\n def kInversePairs(self, n: int, k: int) -&gt; int:\n count = 0\n for perm in permutations(range(1, n + 1)):\n n = 0\n for item_i, item_j in combinations(perm, 2):\n if item_i &gt; item_j:\n n += 1\n if n &gt; k:\n break\n if n == k:\n count += 1\n return count % 1000000007\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T00:35:10.797", "Id": "263301", "ParentId": "263230", "Score": "5" } } ]
{ "AcceptedAnswerId": "263301", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T00:44:21.497", "Id": "263230", "Score": "5", "Tags": [ "python", "dynamic-programming" ], "Title": "K Inverse Pairs Array - Brute Force" }
263230
<p>I'm using <code>ManagementEventWatcher</code> to monitoring some process. It works well but I think the code's kinda repetitive. I was wondering what would be the correct way for more than once single process, if I had more than two process it'd become a mess. Thanks!</p> <pre><code>private async void Form1_Load(object sender, EventArgs e) { string tick = &quot;0.1&quot;; string lcuProcess = &quot;LeagueClientUx.exe&quot;; string gameProcess = &quot;League of legends.exe&quot;; string lcuQuery = String.Format(@&quot; SELECT * FROM __InstanceOperationEvent WITHIN {0} WHERE TargetInstance ISA 'Win32_Process' AND TargetInstance.Name = '{1}'&quot;, tick, lcuProcess ); string gameQuery = String.Format(@&quot; SELECT * FROM __InstanceOperationEvent WITHIN {0} WHERE TargetInstance ISA 'Win32_Process' AND TargetInstance.Name = '{1}'&quot;, tick, gameProcess ); string scope = @&quot;\\.\root\CIMV2&quot;; ManagementEventWatcher watcherLCU = new ManagementEventWatcher(scope, lcuQuery); watcherLCU.EventArrived += new EventArrivedEventHandler(OnEventArrived_lcu); watcherLCU.Start(); ManagementEventWatcher watcherGame = new ManagementEventWatcher(scope, gameQuery); watcherGame.EventArrived += new EventArrivedEventHandler(OnEventArrived_game); watcherGame.Start(); } private static void OnEventArrived_lcu(object sender, EventArrivedEventArgs e) { // Do something... } private static void OnEventArrived_game(object sender, EventArrivedEventArgs e) { // Do something... } </code></pre>
[]
[ { "body": "<pre class=\"lang-cs prettyprint-override\"><code>private async void Form1_Load\n</code></pre>\n<p>Why <code>async</code> without <code>await</code>? Remove <code>async</code>.</p>\n<p>The query can be a constant like</p>\n<pre class=\"lang-cs prettyprint-override\"><code>const string queryPattern = @&quot;\nSELECT * \nFROM __InstanceOperationEvent \nWITHIN {0} \nWHERE TargetInstance ISA 'Win32_Process' \nAND TargetInstance.Name = '{1}'&quot;;\n</code></pre>\n<p>Then you can reuse it multiple times.</p>\n<p>But you may modify the query to catch event for both apps like</p>\n<pre class=\"lang-cs prettyprint-override\"><code>const string queryPattern = @&quot;\nSELECT * \nFROM __InstanceOperationEvent \nWITHIN {0} \nWHERE TargetInstance ISA 'Win32_Process' \nAND (TargetInstance.Name = '{1}' OR TargetInstance.Name = '{2}')&quot;;\n</code></pre>\n<p>Also <code>Form_Load</code> handler can do multiple jobs. To avoid mixing code in one method, and improve readability, move the code to a separate method.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private void Form1_Load(object sender, EventArgs e)\n{\n SetupEventWatcher();\n}\n\nprivate void SetupEventWatcher()\n{\n const string tick = &quot;0.1&quot;;\n const string lcuProcess = &quot;LeagueClientUx.exe&quot;;\n const string gameProcess = &quot;League of legends.exe&quot;;\n const string queryPattern = @&quot;\n SELECT * \n FROM __InstanceOperationEvent \n WITHIN {0} \n WHERE TargetInstance ISA 'Win32_Process' \n AND (TargetInstance.Name = '{1}' OR TargetInstance.Name = '{2}')&quot;;\n\n string query = string.Format(queryPattern, tick, lcuProcess, gameProcess);\n string scope = @&quot;\\\\.\\root\\CIMV2&quot;;\n\n ManagementEventWatcher watcher = new ManagementEventWatcher(scope, query);\n watcher.EventArrived += new EventArrivedEventHandler(OnEventArrived);\n watcher.Start();\n}\n\nprivate static void OnEventArrived(object sender, EventArrivedEventArgs e)\n{\n // EventArrivedEventArgs can be helpful to determine which process caused the event to occur\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T12:47:22.027", "Id": "519732", "Score": "0", "body": "Thanks for your reply! Just one thing, at the moment I'm using `e.NewEvent.ClassPath.ClassName.Contains(\"InstanceDeletionEvent\")` and `e.NewEvent.ClassPath.ClassName.Contains(\"InstanceCreationEvent\")` to detect when the process is opened/closed. Now that I'm handling with two process in the same event who could I know what process is each? Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T13:07:44.933", "Id": "519733", "Score": "1", "body": "@Omar I didn't use WMI yet. Sorry. Probably [`Process.GetProcessesByName`](https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.getprocessesbyname?view=netcore-3.1) may help or something like that, in case `EventArrivedEventArgs` doesn't contain the required data." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T09:35:15.413", "Id": "263247", "ParentId": "263232", "Score": "1" } } ]
{ "AcceptedAnswerId": "263247", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T01:32:46.443", "Id": "263232", "Score": "1", "Tags": [ "c#" ], "Title": "ManagementEventWatcher, process monitoring" }
263232
<p>I have various texts that are inconsistent in how paragraphs are formatted. Some texts use the <code>&lt;P&gt; &lt;/P&gt;</code> tags to specify a paragraph, while others use two break tags (<code>&lt;br&gt;&lt;br&gt;</code>). Sometimes the user forgets to close a <code>&lt;p&gt;</code> tag too. Also, a tag could contain whitespace. I need to &quot;normalise&quot; these texts so that they all specify paragraphs in the same way. Below is some Python code I wrote to achieve this goal. The code scans the input for the start or end of a paragraph and puts each paragraph it finds into an array, which I can then output in whatever format the business wants. I wrote it in Python, but this is not the language the actual solution will be implemented in. The language is so obscure and old that there is no point in posting it here. This language doesn't even have regular expressions, which is why I do not use regular expressions in the Python code. The plan is to translate this python code into the obscure old language we use at work. The array <code>PARAGRAPH_DELIMITERS</code> contains all of the strings that specify the the start or end of a paragraph.</p> <pre><code>PARAGRAPH_DELIMITERS = [&quot;&lt;p&gt;&quot;,&quot;&lt;/p&gt;&quot;,&quot;&lt;br&gt;&lt;br&gt;&quot;,&quot;&lt;br&gt;&lt;/br&gt;&lt;br&gt;&lt;/br&gt;&quot;, &quot;&lt;br/&gt;&lt;br/&gt;&quot;] class Input: def __init__ (self,html): self.pos = 0 self.html = html self.length = len(html) def get_next_char(self): return self.html[self.pos] def get_paragraphs(input): paragraphs = [] paragraph = &quot;&quot; while(input.pos &lt; input.length): if new_paragraph(input): # We found a new paragraph, add it to the list of paragraphs. if paragraph != &quot;&quot;: paragraphs.append(paragraph) paragraph = &quot;&quot; else: paragraph += input.get_next_char() input.pos += 1 if paragraph != &quot;&quot;: # We found a new paragraph, add it to the list of paragraphs. paragraphs.append(paragraph) return paragraphs def new_paragraph(input): if input.get_next_char() != &quot;&lt;&quot;: return False lookahead_pos = input.pos new_paragraph_found = False potential_paragraph_delimiter = &quot;&quot; while(lookahead_pos &lt; input.length): if input.html[lookahead_pos] == &quot; &quot;: # Skip whitespace. lookahead_pos += 1 else: potential_paragraph_delimiter += input.html[lookahead_pos].lower() match_possible = False for i in range(len(PARAGRAPH_DELIMITERS)): if PARAGRAPH_DELIMITERS[i].startswith(potential_paragraph_delimiter): match_possible = True if len(potential_paragraph_delimiter) == len(PARAGRAPH_DELIMITERS[i]): new_paragraph_found = True if not match_possible: break; if new_paragraph_found: break; lookahead_pos += 1 if new_paragraph_found: input.pos = lookahead_pos + 1 return new_paragraph_found html = &quot;&lt;p&gt;hello this is paragraph 1&lt;P&gt;hello this is paragraph 2&lt;/p&gt;&lt;p &gt;hellow this is paragraph 3&lt;br&gt;&lt;br&gt;this is paragraph 4&quot; input = Input(html) paragraphs = get_paragraphs(input) print(paragraphs) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T08:44:07.653", "Id": "519715", "Score": "0", "body": "If you are planning on writing the algorithm in another language, it might be better if you post your code in that language. Using python you could fairly easily solve the problem you have given (besides using regex), using `str.split` (based on the sample data you have provided). And this functionality might or might not be available in the language you are planning to use to write the algorithm" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T08:45:53.683", "Id": "519716", "Score": "0", "body": "str.split won't work because the paragraph delimiters could contain spaces. Am I mistaken? Posting the other language is pointless as it's used by fewer than 100 people worldwide. I'm more interested in the algorithm than python best practices." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T23:40:10.997", "Id": "519758", "Score": "0", "body": "If delimiters can contain whitespace, I would encourage you to add that wrinkle to the provided example `html`. It's a surprising and crucial fact: you should emphasize it, and the best way to do that is by embedding it in the test case everyone will use." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T23:45:54.710", "Id": "519759", "Score": "0", "body": "Also, when you say whitespace is allowed in delimiters, do you mean it fully: for example, what about `< b r >< b r >`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T23:52:42.003", "Id": "519760", "Score": "0", "body": "Yes, a whitespace can occur anywhere in a delimiter. The users who create these texts don't really know what they are doing and they enter all sorts of rubbish." } ]
[ { "body": "<p>You seem to be interested in algorithmic alternatives more than\na typical Python best-practices review. Here's one approach\nthat seems simpler to me: just one function, and no need for\nan <code>Input</code> class wrapping the input text. Like your solution,\nthis one does build up the delimiter character-by-character,\nfor the reason you articulate in your comments.</p>\n<pre><code>def get_paragraphs(text, delimiters):\n # Positions (current and limit), paragraphs (current and all),\n # and delimiters (current target and viable candidates).\n i = 0\n limit = len(text)\n para = ''\n paragraphs = []\n target = ''\n candidates = list(delimiters)\n while i &lt; limit:\n # Get character and just continue on spaces.\n c = text[i]\n i += 1\n if c == ' ':\n para += c\n continue\n # Add non-space to delimiter-target, counting remaining candidates:\n # - Exact match: reset to bypass the matched delimiter.\n # - Opening angle and no candidates: reset target.\n # - Otherwise, just add character to current paragraph.\n target += c.lower()\n candidates = [d for d in candidates if d.startswith(target)]\n n = len(candidates)\n if n == 1 and candidates[0] == target:\n para = ''\n target = ''\n candidates = list(delimiters)\n elif n == 0 and c == '&lt;':\n paragraphs.append(para)\n para = c\n target = c\n candidates = list(delimiters)\n else:\n para += c\n if para:\n paragraphs.append(para)\n return paragraphs\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T23:06:17.250", "Id": "519757", "Score": "0", "body": "Thank you for your comments. I think you are overlooking something though. The reason I go character by character on the current delimiter is that the current delimiter could contain whitespace. Your solution would fail if the delimiter looked liked this <{white space}p>" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T20:22:59.917", "Id": "519832", "Score": "0", "body": "@user1235598399 Revised in light of my clearer understanding of the situation." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T18:21:55.193", "Id": "263254", "ParentId": "263242", "Score": "1" } } ]
{ "AcceptedAnswerId": "263254", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T05:28:16.170", "Id": "263242", "Score": "3", "Tags": [ "python", "html" ], "Title": "HTML Paragraph Identifier" }
263242
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/263024/231235">Two dimensional gaussian image generator in C</a>, <a href="https://codereview.stackexchange.com/q/263183/231235">Two dimensional bicubic interpolation implementation in C</a> and <a href="https://codereview.stackexchange.com/q/251570/231235">A SubPlane Method for Generic Two Dimensional Data Plane in C#</a>. Besides gaussian image generating and bicubic interpolation, I am attempting to make a C version subimage function in this post so that the <a href="https://en.wikipedia.org/wiki/Region_of_interest" rel="nofollow noreferrer">ROI (Region of interest)</a> of an image can be extracted.</p> <p>The output subimage example:</p> <p><a href="https://i.stack.imgur.com/jIDuU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jIDuU.png" alt="SubImage" /></a></p> <p><strong>The experimental implementation</strong></p> <ul> <li><p><code>SubMonoImage</code> function implementation: subimage extracting operation for <code>MONOIMAGE</code> structure.</p> <pre><code>MONOIMAGE SubMonoImage(const MONOIMAGE image, unsigned int locationx, unsigned int locationy, unsigned int sizex, unsigned int sizey) { MONOIMAGE output = CreateMonoImage(sizex, sizey); for (size_t y = 0; y &lt; sizey; y++) { for (size_t x = 0; x &lt; sizex; x++) { if ((locationy + y) &lt; image.XSIZE &amp;&amp; (locationx + x) &lt; image.YSIZE) // valid location { output.IMAGE_DATA[GetMonoImageIndex(x, y, output)] = image.IMAGE_DATA[GetMonoImageIndex((locationx + x), (locationy + y), image)]; } } } return output; } </code></pre> </li> <li><p><code>SubRGBImage</code> function implementation: subimage extracting operation for <code>RGBIMAGE</code> structure.</p> <pre><code>RGBIMAGE SubRGBImage(const RGBIMAGE image, unsigned int locationx, unsigned int locationy, unsigned int sizex, unsigned int sizey) { MONOIMAGE R = SubMonoImage(GetPlaneR(image), locationx, locationy, sizex, sizey); MONOIMAGE G = SubMonoImage(GetPlaneG(image), locationx, locationy, sizex, sizey); MONOIMAGE B = SubMonoImage(GetPlaneB(image), locationx, locationy, sizex, sizey); RGBIMAGE output = CreateRGBImageFromMonoImages(sizex, sizey, R, G, B); DeleteMonoImage(R); DeleteMonoImage(G); DeleteMonoImage(B); return output; } </code></pre> </li> <li><p><code>basic_functions.h</code>: Contains several basic function declarations</p> <pre><code>/* Develop by Jimmy Hu */ #ifndef BASIC_FUNCTIONS_H #define BASIC_FUNCTIONS_H #include &quot;base.h&quot; #include &quot;imageio.h&quot; MONOIMAGE CreateMonoImage(const unsigned int, const unsigned int); void DeleteMonoImage(MONOIMAGE); MONOIMAGE GetPlaneR(const RGBIMAGE); MONOIMAGE GetPlaneG(const RGBIMAGE); MONOIMAGE GetPlaneB(const RGBIMAGE); RGBIMAGE CreateRGBImage(const unsigned int, const unsigned int); RGBIMAGE CreateRGBImageFromMonoImages(const unsigned int, const unsigned int, MONOIMAGE, MONOIMAGE, MONOIMAGE); void DeleteRGBImage(RGBIMAGE); size_t GetMonoImageIndex(const size_t, const size_t, const MONOIMAGE); size_t GetRGBImageIndex(const size_t, const size_t, const RGBIMAGE); size_t clip(const size_t, const size_t, const size_t); float clip_float(const float, const float, const float); #endif </code></pre> </li> <li><p><code>basic_functions.c</code>: Contains several basic function definitions</p> <pre><code>/* Develop by Jimmy Hu */ #include &quot;basic_functions.h&quot; MONOIMAGE CreateMonoImage(const unsigned int sizex, const unsigned int sizey) { MONOIMAGE output; output.XSIZE = sizex; output.YSIZE = sizey; output.IMAGE_DATA = malloc(sizeof *output.IMAGE_DATA * sizex * sizey); if(output.IMAGE_DATA == NULL) { printf(stderr, &quot;Memory allocation error!&quot;); return output; } return output; } void DeleteMonoImage(MONOIMAGE image) { free(image.IMAGE_DATA); return; } MONOIMAGE GetPlaneR(const RGBIMAGE image) { MONOIMAGE output = CreateMonoImage(image.XSIZE, image.YSIZE); for (size_t y = 0; y &lt; image.YSIZE; y++) { for (size_t x = 0; x &lt; image.XSIZE; x++) { output.IMAGE_DATA[GetMonoImageIndex(x, y, output)] = image.IMAGE_DATA[GetRGBImageIndex(x, y, image)].channels[0]; } } return output; } MONOIMAGE GetPlaneG(const RGBIMAGE image) { MONOIMAGE output = CreateMonoImage(image.XSIZE, image.YSIZE); for (size_t y = 0; y &lt; image.YSIZE; y++) { for (size_t x = 0; x &lt; image.XSIZE; x++) { output.IMAGE_DATA[GetMonoImageIndex(x, y, output)] = image.IMAGE_DATA[GetRGBImageIndex(x, y, image)].channels[1]; } } return output; } MONOIMAGE GetPlaneB(const RGBIMAGE image) { MONOIMAGE output = CreateMonoImage(image.XSIZE, image.YSIZE); for (size_t y = 0; y &lt; image.YSIZE; y++) { for (size_t x = 0; x &lt; image.XSIZE; x++) { output.IMAGE_DATA[GetMonoImageIndex(x, y, output)] = image.IMAGE_DATA[GetRGBImageIndex(x, y, image)].channels[2]; } } return output; } RGBIMAGE CreateRGBImage(const unsigned int sizex, const unsigned int sizey) { RGBIMAGE output; output.XSIZE = sizex; output.YSIZE = sizey; output.IMAGE_DATA = malloc(sizeof *output.IMAGE_DATA * sizex * sizey); if(output.IMAGE_DATA == NULL) { printf(stderr, &quot;Memory allocation error!&quot;); return output; } return output; } RGBIMAGE CreateRGBImageFromMonoImages(const unsigned int sizex, const unsigned int sizey, MONOIMAGE R, MONOIMAGE G, MONOIMAGE B) { RGBIMAGE output; output.XSIZE = sizex; output.YSIZE = sizey; output.IMAGE_DATA = malloc(sizeof *output.IMAGE_DATA * sizex * sizey); if (output.IMAGE_DATA == NULL) { printf(stderr, &quot;Memory allocation error!&quot;); return output; } if ((R.XSIZE != G.XSIZE) || (G.XSIZE != B.XSIZE) || (R.XSIZE != B.XSIZE) || (R.YSIZE != G.YSIZE) || (G.YSIZE != B.YSIZE) || (R.YSIZE != B.YSIZE)) { printf(stderr, &quot;Input size inequal!&quot;); return output; } for (size_t y = 0; y &lt; R.YSIZE; y++) { for (size_t x = 0; x &lt; R.XSIZE; x++) { output.IMAGE_DATA[GetRGBImageIndex(x, y, output)].channels[0] = R.IMAGE_DATA[GetMonoImageIndex(x, y, R)]; output.IMAGE_DATA[GetRGBImageIndex(x, y, output)].channels[1] = G.IMAGE_DATA[GetMonoImageIndex(x, y, G)]; output.IMAGE_DATA[GetRGBImageIndex(x, y, output)].channels[2] = B.IMAGE_DATA[GetMonoImageIndex(x, y, B)]; } } return output; } void DeleteRGBImage(RGBIMAGE image) { free(image.IMAGE_DATA); return; } size_t GetMonoImageIndex(const size_t x, const size_t y, const MONOIMAGE image) { return y * image.XSIZE + x; } size_t GetRGBImageIndex(const size_t x, const size_t y, const RGBIMAGE image) { return y * image.XSIZE + x; } size_t clip(const size_t input, const size_t lowerbound, const size_t upperbound) { if (input &lt; lowerbound) { return lowerbound; } if (input &gt; upperbound) { return upperbound; } return input; } float clip_float(const float input, const float lowerbound, const float upperbound) { if (input &lt; lowerbound) { return lowerbound; } if (input &gt; upperbound) { return upperbound; } return input; } </code></pre> </li> <li><p><code>base.h</code>: Contains the basic type implementation</p> <pre><code>/* Develop by Jimmy Hu */ #ifndef BASE_H #define BASE_H #include &lt;math.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; #define MAX_PATH 256 #define FILE_ROOT_PATH &quot;./&quot; #define True true #define False false typedef struct RGB { unsigned char channels[3]; } RGB; typedef struct HSV { long double channels[3]; // Range: 0 &lt;= H &lt; 360, 0 &lt;= S &lt;= 1, 0 &lt;= V &lt;= 255 }HSV; typedef struct BMPIMAGE { char FILENAME[MAX_PATH]; unsigned int XSIZE; unsigned int YSIZE; unsigned char FILLINGBYTE; unsigned char *IMAGE_DATA; } BMPIMAGE; typedef struct RGBIMAGE { unsigned int XSIZE; unsigned int YSIZE; RGB *IMAGE_DATA; } RGBIMAGE; typedef struct HSVIMAGE { unsigned int XSIZE; unsigned int YSIZE; HSV *IMAGE_DATA; } HSVIMAGE; typedef struct MONOIMAGE { unsigned int XSIZE; unsigned int YSIZE; unsigned char *IMAGE_DATA; } MONOIMAGE; typedef struct DOUBLEIMAGE { unsigned int XSIZE; unsigned int YSIZE; double *IMAGE_DATA; }; #endif </code></pre> </li> </ul> <p><strong>The full testing code</strong></p> <pre><code>/* Develop by Jimmy Hu */ #include &quot;base.h&quot; #include &quot;basic_functions.h&quot; #include &quot;imageio.h&quot; MONOIMAGE BicubicInterpolationMonoImage(MONOIMAGE image, const int, const int); RGBIMAGE BicubicInterpolationRGBImage(RGBIMAGE image, const int, const int); unsigned char BicubicPolate(const unsigned char*, const float, const float); float CubicPolate(const float, const float, const float, const float, const float); /* Subimage extracting operation for MONOIMAGE structure */ MONOIMAGE SubMonoImage(const MONOIMAGE, unsigned int, unsigned int, unsigned int, unsigned int); /* Subimage extracting operation for RGBIMAGE structure */ RGBIMAGE SubRGBImage(const RGBIMAGE, unsigned int, unsigned int, unsigned int, unsigned int); int main(int argc, char** argv) { char *FilenameString; FilenameString = malloc( sizeof *FilenameString * MAX_PATH); printf(&quot;BMP image input file name:(ex:test): &quot;); scanf(&quot;%s&quot;, FilenameString); BMPIMAGE BMPImage1 = bmp_file_read(FilenameString, false); RGBIMAGE RGBImage1; RGBImage1.XSIZE = BMPImage1.XSIZE; RGBImage1.YSIZE = BMPImage1.YSIZE; RGBImage1.IMAGE_DATA = raw_image_to_array(BMPImage1.XSIZE, BMPImage1.YSIZE, BMPImage1.IMAGE_DATA); RGBIMAGE RGBImage2 = SubRGBImage(RGBImage1, 150, 100, 250, 300); RGBIMAGE RGBImage3 = BicubicInterpolationRGBImage(RGBImage2, RGBImage2.XSIZE * 2, RGBImage2.YSIZE * 2); printf(&quot;file name for saving:(ex:test): &quot;); scanf(&quot;%s&quot;, FilenameString); bmp_write(FilenameString, RGBImage3.XSIZE, RGBImage3.YSIZE, array_to_raw_image(RGBImage3.XSIZE, RGBImage3.YSIZE, RGBImage3.IMAGE_DATA)); free(FilenameString); DeleteRGBImage(RGBImage1); DeleteRGBImage(RGBImage2); DeleteRGBImage(RGBImage3); return 0; } MONOIMAGE BicubicInterpolationMonoImage(MONOIMAGE image, const int newSizeX, const int newSizeY) { MONOIMAGE output = CreateMonoImage(newSizeX, newSizeY); int originSizeX = image.XSIZE; int originSizeY = image.YSIZE; if (output.IMAGE_DATA == NULL) { printf(stderr, &quot;Memory allocation error!&quot;); return output; } float ratiox = (float)originSizeX / (float)newSizeX; float ratioy = (float)originSizeY / (float)newSizeY; for (size_t y = 0; y &lt; newSizeY; y++) { for (size_t x = 0; x &lt; newSizeX; x++) { float xMappingToOrigin = (float)x * ratiox; float yMappingToOrigin = (float)y * ratioy; float xMappingToOriginFloor = floor(xMappingToOrigin); float yMappingToOriginFloor = floor(yMappingToOrigin); float xMappingToOriginFrac = xMappingToOrigin - xMappingToOriginFloor; float yMappingToOriginFrac = yMappingToOrigin - yMappingToOriginFloor; unsigned char ndata[4 * 4]; for (int ndatay = -1; ndatay &lt;= 2; ndatay++) { for (int ndatax = -1; ndatax &lt;= 2; ndatax++) { ndata[(ndatay + 1) * 4 + (ndatax + 1)] = image.IMAGE_DATA[ clip(yMappingToOriginFloor + ndatay, 0, originSizeY - 1) * originSizeX + clip(xMappingToOriginFloor + ndatax, 0, originSizeX - 1) ]; } } output.IMAGE_DATA[ y * newSizeX + x ] = BicubicPolate(ndata, xMappingToOriginFrac, yMappingToOriginFrac); } } return output; } RGBIMAGE BicubicInterpolationRGBImage(RGBIMAGE image, const int newSizeX, const int newSizeY) { MONOIMAGE R = BicubicInterpolationMonoImage(GetPlaneR(image), newSizeX, newSizeY); MONOIMAGE G = BicubicInterpolationMonoImage(GetPlaneG(image), newSizeX, newSizeY); MONOIMAGE B = BicubicInterpolationMonoImage(GetPlaneB(image), newSizeX, newSizeY); RGBIMAGE output = CreateRGBImageFromMonoImages(newSizeX, newSizeY, R, G, B); DeleteMonoImage(R); DeleteMonoImage(G); DeleteMonoImage(B); return output; } unsigned char BicubicPolate(const unsigned char* const ndata, const float fracx, const float fracy) { float x1 = CubicPolate( ndata[0], ndata[1], ndata[2], ndata[3], fracx ); float x2 = CubicPolate( ndata[4], ndata[5], ndata[6], ndata[7], fracx ); float x3 = CubicPolate( ndata[8], ndata[9], ndata[10], ndata[11], fracx ); float x4 = CubicPolate( ndata[12], ndata[13], ndata[14], ndata[15], fracx ); float output = clip_float(CubicPolate( x1, x2, x3, x4, fracy ), 0.0, 255.0); return (unsigned char)output; } float CubicPolate(const float v0, const float v1, const float v2, const float v3, const float fracy) { float A = (v3-v2)-(v0-v1); float B = (v0-v1)-A; float C = v2-v0; float D = v1; return D + fracy * (C + fracy * (B + fracy * A)); } MONOIMAGE SubMonoImage(const MONOIMAGE image, unsigned int locationx, unsigned int locationy, unsigned int sizex, unsigned int sizey) { MONOIMAGE output = CreateMonoImage(sizex, sizey); for (size_t y = 0; y &lt; sizey; y++) { for (size_t x = 0; x &lt; sizex; x++) { if ((locationy + y) &lt; image.XSIZE &amp;&amp; (locationx + x) &lt; image.YSIZE) // valid location { output.IMAGE_DATA[GetMonoImageIndex(x, y, output)] = image.IMAGE_DATA[GetMonoImageIndex((locationx + x), (locationy + y), image)]; } } } return output; } RGBIMAGE SubRGBImage(const RGBIMAGE image, unsigned int locationx, unsigned int locationy, unsigned int sizex, unsigned int sizey) { MONOIMAGE R = SubMonoImage(GetPlaneR(image), locationx, locationy, sizex, sizey); MONOIMAGE G = SubMonoImage(GetPlaneG(image), locationx, locationy, sizex, sizey); MONOIMAGE B = SubMonoImage(GetPlaneB(image), locationx, locationy, sizex, sizey); RGBIMAGE output = CreateRGBImageFromMonoImages(sizex, sizey, R, G, B); DeleteMonoImage(R); DeleteMonoImage(G); DeleteMonoImage(B); return output; } </code></pre> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/263024/231235">Two dimensional gaussian image generator in C</a>,</p> <p><a href="https://codereview.stackexchange.com/q/263183/231235">Two dimensional bicubic interpolation implementation in C</a> and</p> <p><a href="https://codereview.stackexchange.com/q/251570/231235">A SubPlane Method for Generic Two Dimensional Data Plane in C#</a>.</p> </li> <li><p>What changes has been made in the code since last question?</p> <p>I am attempting to make a C version subimage function in this post.</p> </li> <li><p>Why a new review is being asked for?</p> <p>If there is any possible improvement, please let me know.</p> </li> </ul> <p><strong>Reference</strong></p> <ul> <li><a href="http://www.cs.cmu.edu/%7Echuck/lennapg/" rel="nofollow noreferrer">The Lenna Story</a></li> </ul>
[]
[ { "body": "<p>There are image representations that lend themselves much better to passing around views of rectangular crops:</p>\n<pre><code>struct Image {\n void *pixels;\n enum format pixel_format;\n size_t width;\n size_t height;\n size_t stride;\n}\n</code></pre>\n<p>With <code>pixels</code> pointing to the top-left position in the source image, and <code>stride</code> copied from the source's stride, then we don't need to copy the data. If we do want to copy, then that can be a separate function. That helps separate our concerns.</p>\n<p>Unrelated, please don't use ALL_CAPS names for C identifiers. It's usual to use capitals for preprocessor macros; these need to be distinguished because they are text substitutions rather than names, and are not confined to a particular scope. When ordinary names are all-caps, it makes it harder to pick out the macros and give them the caution they require.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T10:22:09.467", "Id": "263248", "ParentId": "263246", "Score": "1" } } ]
{ "AcceptedAnswerId": "263248", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T09:24:22.480", "Id": "263246", "Score": "0", "Tags": [ "c", "reinventing-the-wheel", "error-handling", "image", "memory-management" ], "Title": "SubImage function implementation in C" }
263246
<p>I have a test suite that queries a localhost-based server. The server process needs to be running in order for the server to work. The process may be running already for debugging work, but it might not be. If a server process is running, it's probably safe to assume it's the correct one. If we started the process, we should kill it when we're done, but if it was already running, we should leave it.</p> <p>I've written a bash script which seems to work, but isn't quite perfect.</p> <pre><code>if [ -z `pgrep -x server-process` ]; then mkdir ./data server-process ./data &amp; sleep 1; # Wait for server to print output, # reporting initialization details etc. fi # Set up environment variables... run-test-suite $@ if jobs %1 2&gt;/dev/null; then kill %1 rm -R ./data; fi </code></pre> <p>In particular:</p> <ul> <li>Is there a more robust way to do this?</li> <li>Are there any edge cases I've missed?</li> <li>Is there a better way to wait for <code>server-process</code>'s initial output, rather than <code>sleep 1</code> (which is often not long enough anyway)? <code>server-process</code> doesn't close the pipe - it could still report errors - I don't mind if these are interleaved with test suite output. I just want to wait until after the server has printed it's initial config information.</li> </ul>
[]
[ { "body": "<p>Welcome to Code Review, Ari.</p>\n<h1>Good</h1>\n<ul>\n<li>indentation</li>\n<li>useful comments</li>\n</ul>\n<h1>Major suggestions</h1>\n<ul>\n<li>Regarding your server-process: it would be nice for it to have a proper &quot;init&quot; script to start it. Things have changed in systemd-land and you should follow that style if your system is based on systemd. Either way, having this in a proper init/systemd setup will make life easier for your admins and your developers.</li>\n<li>If you're in systemd-land then your <code>systemctl start</code> will take care of waiting for the process to start. If you're in init-land you will need to find some other way to verify that the process is started. Is there a log message you can wait for or a socket you can check? If you are just waiting for output, redirect that to a file and wait for it to contain something. Somehow, find something to verify and loop until that happens.</li>\n<li>Once you've got a clean way to start it you can remove the backgrounding on your server-process and the sleep after it. The start command (either style) should not exit until your process is actually started.</li>\n<li>Your start script should also handle stopping so you won't need to check for whether it is running anymore. Just run your script with the stop argument (or run systemctl) and it will go away. If it died earlier, you might get a message. But then you can remove the data tree.</li>\n</ul>\n<h1>Small nits</h1>\n<ul>\n<li>You don't need to end lines with semicolons. The shell takes each line as a command unless there's a backslach at the end of a line. Using the semicolon to put the <code>then</code> on the same line as the <code>if</code> is good. It is one commonly-seen example of putting multiple commands on one line.</li>\n<li>Use double square brackets for conditionals to avoid some surprises.</li>\n<li>Try shellcheck. It will have some suggestions I've left out.</li>\n<li>Put the directory into a variable and then refer to that variables instead of <code>./data</code>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T20:47:47.480", "Id": "263258", "ParentId": "263251", "Score": "2" } }, { "body": "<p>Capturing the output of <code>pgrep</code> and testing whether it's empty doesn't seem the best way to use that utility, given that it returns a true value when it finds one or more processes:</p>\n<pre><code>if ! pgrep -x server-process &gt;/dev/null 2&gt;&amp;1\nthen\n mkdir ./data\n server-process ./data &amp;\n sleep 1; # Wait for server to print output,\n # reporting initialization details etc.\nfi\n</code></pre>\n<p>Using job specifications with <code>%1</code> is a convenience for interactive shells. We can write more robust code using <code>$!</code>:</p>\n<pre><code>server_pid=0\n\nif\nthen\n server-process ./data &amp;\n server_pid=$!\nfi\n</code></pre>\n<p>This has the advantage of being <em>portable</em> - i.e. we can use <code>/bin/sh</code> as interpreter rather than requiring <code>/bin/bash</code>.</p>\n<p>Actually, instead of remembering the pid and conditionally using it at end of script, we can immediately register the action to be taken:</p>\n<pre><code>if\nthen\n server-process ./data &amp;\n trap &quot;kill $!; rm -r ./data&quot; EXIT\nfi\n</code></pre>\n<p>Unless there's a compelling reason to create the data directory inside the current working directory, it's probably better to use <code>mktemp</code> to create us a nice empty initial directory.</p>\n<hr />\n<p>Putting it all together:</p>\n<pre><code>#!/bin/sh\n\nset -eu\n\nif ! pgrep -x server-process &gt;/dev/null 2&gt;&amp;1\nthen\n data_dir=$(mktemp -d)\n server-process &quot;$data_dir&quot; &amp;\n trap &quot;kill $!; rm -r '$data_dir'&quot; EXIT\n sleep 1; # Wait for server to initialise\nfi\n\nrun-test-suite &quot;$@&quot;\n</code></pre>\n<hr />\n<p>Without knowing the details of <code>server-process</code> I can only speculate, but perhaps there's a better alternative to the arbitrary <code>sleep</code>. Is there perhaps a file whose appearance in <code>$data_dir</code> might indicate that the server can be used? Or a socket which starts responding?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T07:36:19.987", "Id": "263272", "ParentId": "263251", "Score": "2" } } ]
{ "AcceptedAnswerId": "263272", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T16:52:22.960", "Id": "263251", "Score": "3", "Tags": [ "bash" ], "Title": "Test harness that uses server process" }
263251
<p>I've just started learning python, mostly by some YouTube videos and other online tutorials.</p> <p>Now I want to create a dictionary of callables (actions) asking for user input (a hotkey), but the user should also be able to pass more arguments to the actions.</p> <p>My problem is, that my current solution doesn't seem very <em>elegant</em> and feels kind of <em>wrong</em> to me.</p> <p>Is this really the only way to achieve what I want, or is there a better/correct implementation?</p> <p>This is my example code so far:</p> <pre class="lang-py prettyprint-override"><code>from collections import OrderedDict # functions that prints all the possible hotkys and a description def add_action(actions: dict, hotkey: str, action: object, name: str): actions[hotkey.lower()] = action actions[hotkey.upper()] = action print('- {}: {}'.format(hotkey, name)) # all the functions that we want to execute def do_a(name: str): print('Hello ' + name + ' this is A') def do_b(): print('This is B') def do_c(): print('This is C') # function to create a dictionary with all the callables and the corresponding hotkyes def get_available_actions(): actions = OrderedDict() add_action(actions, hotkey='a', action=do_a, name='Action A will also print your name (use like a john') add_action(actions, hotkey='b', action=do_b, name='Action B') add_action(actions, hotkey='c', action=do_c, name='Action C') return actions # the main function that is executed to ask the user what to do def choose_action(): action = None while not action: available_actions = get_available_actions() # this is the current solution to get arguments # first get the whole input command = input('\nWhat do you want to do? ') action_input = None arg = None # check if the user typed in more than one string spereated by a whitespace and split it if ' ' in command: action_input, arg = command.split(' ') else: action_input = command # now get the action based on the hotkey, which should have been the first argument # using get here to avoid, that the input is a &quot;hotkey&quot; that we don't have in our dictionary action = available_actions.get(action_input) if action: # and if we have an argument, pass it to the action if arg: action(arg.strip()) else: action() else: print('Not found, choose again') choose_action() <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>If you are not trying to reinvent the wheel, what you want is to use some library that allows you to easily create a CLI. For example, <a href=\"https://pypi.org/project/click/\" rel=\"nofollow noreferrer\">click</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T05:18:03.943", "Id": "519845", "Score": "0", "body": "Thanks for the feedback, I guess with Python I'll haveto learn a lot about the usage of libraries :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T20:36:58.690", "Id": "263257", "ParentId": "263252", "Score": "1" } }, { "body": "<p>So it is great that you are starting learning Python! It is a fun and easy language to get started using. I will echo <a href=\"http://%20https://blog.codinghorror.com/code-tells-you-how-comments-tell-you-why/\" rel=\"nofollow noreferrer\">m-alorda</a> and recommend you use some library specifically designed to do this as there are many pitfalls.</p>\n<p>However, if you want to know how to improve your coding keep reading.</p>\n<hr />\n<h4>General feedback</h4>\n<p><a href=\"http://%20https://blog.codinghorror.com/code-tells-you-how-comments-tell-you-why/\" rel=\"nofollow noreferrer\"><strong><code>Code Tells You How, Comments Tell You Why?</code></strong></a></p>\n<p>You have tried to document your code through comments, which is great! However, comments using <code>#</code> are mostly intended for other programmers, and is usually reserved for explaining terse parts of the code. A common way to <em>document</em> your code -- which is intended for the user -- is with <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">PEP 257 -- Docstring Conventions</a>.</p>\n<p>As stated in the title comments (<code>#</code>) should be used sparsely. First you should first strive to make your code as simple as possible to understand without relying on comments as a crutch. Only at the point where the code cannot be made easier to understand should you begin to add comments.</p>\n<p>Your code is already quite clear so I would remove all your comments, and replace them with <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings</a>.</p>\n<hr />\n<p><strong><code>upper lower</code></strong></p>\n<p>This</p>\n<pre><code>actions[hotkey.lower()] = action\nactions[hotkey.upper()] = action\n</code></pre>\n<p>Can be replaced by using <code>lower</code> on the input.</p>\n<p><a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\"><strong><code>f-strings</code></strong></a></p>\n<p>f-strings are the new way of formating strings in Python, and you should usually use them. For instance</p>\n<pre><code>print('- {}: {}'.format(hotkey, name))\n</code></pre>\n<p>becomes</p>\n<pre><code>print(f'- {hotkey}: {name}')\n</code></pre>\n<p>Which is easier to read.</p>\n<p><a href=\"https://softwareengineering.stackexchange.com/questions/127245/how-can-i-separate-the-user-interface-from-the-business-logic-while-still-mainta\"><strong><code>business logic and user interface</code></strong></a></p>\n<p>Business logic or domain logic is that part of the program which encodes the real-world business rules that determine how data can be created, stored, and changed. It is important to separate how you <em>handle</em> your data (business logic) from how you <em>present</em> it to the user (user interface).</p>\n<p>So this</p>\n<pre><code>def do_a(name: str):\n print('Hello ' + name + ' this is A')\n</code></pre>\n<p>Should really be this</p>\n<pre><code>def do_a(name: str):\n return 'Hello ' + name + ' this is A'\n</code></pre>\n<p>Note that this allows us to change how we present the results from <code>do_a</code>, maybe we want to decorate, add or remove something before we present it to the user.</p>\n<hr />\n<pre><code>actions = OrderedDict()\n</code></pre>\n<p>I would rather just use a list instead of an <code>OrderedDict</code>, but we will get back to that.</p>\n<pre><code>add_action(actions, hotkey='a', action=do_a, name='Action A will also print your name (use like a john')\nadd_action(actions, hotkey='b', action=do_b, name='Action B')\nadd_action(actions, hotkey='c', action=do_c, name='Action C')\n</code></pre>\n<p>Here you are mixing two concepts, do you see which? <code>name</code>is not really just a name is it? You use <code>name</code> as a name for B and C, but for A you also use it as a description. It would be better to seperate these two.</p>\n<p>Secondly, note that your names are just the hotkey capitalized. So this could instead be</p>\n<pre><code>`f'Action {hotkey.upper()}'`\n</code></pre>\n<p>Again utilizing those nifty <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">f-strings</a></p>\n<hr />\n<p><a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><strong><code>if __name__ == &quot;__main__&quot;:</code></strong></a></p>\n<p>Put the parts of your code that are the ones calling for execution behind a <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == &quot;__main__&quot;:</code></a> guard. This way you can import this python module from other places if you ever want to, and the guard prevents the main code from accidentally running on every import.</p>\n<p>So this</p>\n<pre><code># the main function that is executed to ask the user what to do\n\ndef choose_action():\n action = None\n.\n.\n.\n</code></pre>\n<p>becomes</p>\n<pre><code>def main():\n&quot;&quot;&quot;Summary of the function goes here&quot;&quot;&quot;\n.\n.\n.\n\n`if __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n<hr />\n<p><strong><code>nitpicking</code></strong></p>\n<p>Use a proper linter / editor. A proper linter would probably warn you that\n<code>action_input = None</code> is never called. Do you see why?</p>\n<pre><code> action_input = None\n if ' ' in command:\n action_input, arg = command.split(' ')\n else:\n action_input = command\n</code></pre>\n<p>You also had some minor spacing issues between your functions which is why I suspect you could use a better editor =)</p>\n<p><strong><code>user interface</code></strong></p>\n<p>I really like your user interface, it is mostly clear what you want your users to do. I would recommend some clearer naming</p>\n<pre><code>'\\nWhat do you want to do? '\n</code></pre>\n<p>Is at best vague ^^</p>\n<hr />\n<h4>Suggestion</h4>\n<ul>\n<li><p>Implemented all the suggestions above.</p>\n</li>\n<li><p>Use a class to keep track of which functions we want to be callable (allowing every function is bad from a security standpoint).</p>\n</li>\n<li><p>We store the allowed actions as a <a href=\"https://docs.python.org/3/library/collections.html#collections.namedtuple\" rel=\"nofollow noreferrer\"><code>namedtuple</code></a>.</p>\n</li>\n<li><p>When adding functions we make sure they are <a href=\"https://stackoverflow.com/a/59912861/1048781\">callable</a>.</p>\n</li>\n<li><p>Added options for more than one argument. This is done by <a href=\"https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters\"><code>*args</code></a></p>\n</li>\n<li><p>The printing is left to the <a href=\"https://www.geeksforgeeks.org/str-vs-repr-in-python/\" rel=\"nofollow noreferrer\"><code>__str__</code></a> part of the class.</p>\n</li>\n<li><p>Rewrote parts of the code to suit the new <a href=\"https://www.geeksforgeeks.org/walrus-operator-in-python-3-8/\" rel=\"nofollow noreferrer\">walrus operator <code>:=</code></a></p>\n</li>\n<li><p>Rewrote parts of the code to have fewer <em>exit points</em>. Do note that I am not trying to strictly follow the <em>single entry / single exit</em> mantra, as it can be <a href=\"https://ncrcoe.gitbooks.io/java-for-small-teams/content/badadvice/100_single_exit_point_rules.html\" rel=\"nofollow noreferrer\">harmful in some circumstances</a>. Sometimes, however, it can make the <em>intent</em> of the code clearer.</p>\n<p><strong>before</strong></p>\n<pre><code>if hotkey.lower() in ACTIONS.hotkeys:\n print(ACTIONS.call_function_by_hotkey(hotkey, args))\nelse: \n print(&quot;Not found, choose again&quot;)\n</code></pre>\n<p><strong>after</strong></p>\n<pre><code>print(\n ACTIONS.call_function_by_hotkey(hotkey, args)\n if hotkey.lower() in ACTIONS.hotkeys\n else &quot;Not found, choose again&quot;\n)\n</code></pre>\n<p>In the second the most important part comes first: the <code>print</code>. Then an conditional is applied. Both styles are fine, just be comfortable with both.</p>\n</li>\n</ul>\n<p><strong><code>code</code></strong></p>\n<pre><code>from collections import namedtuple\n\n\ndef do_a(name, bobby=&quot;&quot;):\n string = f&quot;Hello {name} this is A&quot;\n return string if not bobby else f&quot;{string}\\nHello {bobby} this is {name}&quot;\n\n\ndef do_b():\n return &quot;This is B&quot;\n\n\ndef do_c():\n return &quot;This is C&quot;\n\n\nLINEWIDTH = 79\nLINEBREAK = &quot;\\n&quot; + &quot;=&quot; * LINEWIDTH + &quot;\\n&quot;\n\n\nclass Actions:\n\n Action = namedtuple(&quot;Action&quot;, [&quot;hotkey&quot;, &quot;name&quot;, &quot;function&quot;, &quot;description&quot;])\n\n def __init__(self):\n self.hotkeys = dict()\n self.functions = []\n\n def add(self, hotkey, function, description, name=None):\n if not self.is_function(function):\n raise NameError(&quot;Function &quot; + function + &quot;() is not defined&quot;)\n name = &quot;Action &quot; + hotkey.upper() if name is None else name\n self.hotkeys[hotkey] = self.Action(\n hotkey, name, function, description.capitalize()\n )\n self.functions.append(function)\n\n def is_function(self, function):\n try:\n if eval(&quot;callable(&quot; + function + &quot;)&quot;):\n return True\n except NameError:\n return False\n except SyntaxError:\n return False\n\n def function_2_string(self, function, args, strings=True):\n return function + (\n &quot;()&quot;\n if len(args) == 0\n else &quot;(&quot;\n + &quot;, &quot;.join(args if not strings else [&quot;'&quot; + str(arg) + &quot;'&quot; for arg in args])\n + &quot;)&quot;\n )\n\n def call_function_by_hotkey(self, hotkey, args):\n if function := self.hotkeys[hotkey].function if hotkey in self.hotkeys else &quot;&quot;:\n return eval(self.function_2_string(function, args))\n raise NameError(&quot;Hotkey &quot; + hotkey + &quot; is not defined&quot;)\n\n def __str__(self):\n string = LINEBREAK + &quot;ACTIONS&quot;.center(LINEWIDTH) + LINEBREAK\n action_strings = []\n for hotkey, name, _, description in self.hotkeys.values():\n action_strings.append(f&quot;- {hotkey}: {name}&quot;)\n if description:\n action_strings.append(&quot; -- &quot; + description)\n return string + &quot;\\n&quot;.join(action_strings) + LINEBREAK\n\n\nEXIT_ = set(&quot;&quot;, &quot;exit&quot;, &quot;return&quot;, &quot;end&quot;, &quot;break&quot;) \nACTIONS = Actions()\nACTIONS.add(\n hotkey=&quot;a&quot;, function=&quot;do_a&quot;, description=&quot;args: (str) name \\n optional: (str) bobby&quot;\n)\nACTIONS.add(hotkey=&quot;b&quot;, function=&quot;do_b&quot;, description=&quot;&quot;)\nACTIONS.add(hotkey=&quot;c&quot;, function=&quot;do_c&quot;, description=&quot;&quot;)\n\n\ndef main():\n title_txt = str(ACTIONS)\n title_txt += &quot;\\nPick an hotkey from the list above to perform that action\\n&quot;\n while (command := input(title_txt + &quot;&gt; &quot;)) not in EXIT_:\n\n if &quot; &quot; in command:\n hotkey, *args = command.split(&quot; &quot;)\n else:\n hotkey, args = command, []\n\n print(\n ACTIONS.call_function_by_hotkey(hotkey, args)\n if hotkey in ACTIONS.hotkeys\n else &quot;Not found, choose again&quot;\n )\n\n\nif __name__ == &quot;__main__&quot;:\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T05:17:23.937", "Id": "519844", "Score": "0", "body": "Thank you very much for the immense feedback.\nI've written some of the comments just for the post here, but I'll review the real code more in regards to your suggestions.\nHelps a lot!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T22:58:07.073", "Id": "263261", "ParentId": "263252", "Score": "4" } }, { "body": "<h1>Exception</h1>\n<p>Your code makes no attempt to determine if the called function takes arguments or not. If you provide an argument to <code>do_b</code> or <code>do_c</code>, the code will crash with:</p>\n<p><code>TypeError: do_b() takes 0 positional argument by more were given</code></p>\n<p>You should surround the call in a <code>try ... except TypeError: ...</code> block, and report to the user the problem, instead of crashing.</p>\n<h1>Exception</h1>\n<p>If the user enters more than one argument, the code crashes at:</p>\n<p><code> action_input, arg = command.split(' ')</code></p>\n<p>due to assigning a list of length 3 or more to a tuple of length 2. Worse, if they only give one argument, but accidentally used two or more spaces between the command and the argument, the problem will still exist. Finally, if they separate the command and the argument with a tab instead of space, the code won’t even recognize that an argument is present.</p>\n<p><code>command.split()</code> is a special variant of the <code>split</code> method. It splits the string on any white space character (spaces, tabs, etc). Moreover, it treats consecutive white space characters as only one separator, so accidentally using two spaces between the command and the argument is not a problem.</p>\n<p>Much, much worse, your code is very inflexible. If you did want to allow 2 or more arguments, you would have to count spaces to try and guess at the correct number of arguments, and assign different variable names to each, like <code>arg1</code>, <code>arg2</code>, <code>arg3</code>, and so on. The code would get unmanageable very quickly. Instead, you want to use an argument <code>list</code>.</p>\n<p>The splat operator (<code>*</code>) is used to expand a list of items into multiple arguments, and collect multiple arguments into a single list. We can use this to dramatically simplify the code.</p>\n<pre class=\"lang-py prettyprint-override\"><code> command = input('\\nWhat do you want to do? ')\n\n action_input, *args = command.split()\n\n action = available_actions.get(action_input)\n\n if action:\n try:\n action(*args)\n except TypeError as type_error:\n print(&quot;Incorrect arguments:&quot;, type_error)\n else:\n print('Not found, choose again')\n</code></pre>\n<p>Notice there is no checking if any arguments are given, and no different paths for 0 arguments or 1 argument. If “a john” is given as input, it is split into <code>[&quot;a&quot;, &quot;john&quot;]</code>. The assignment takes the first item of the list and assigns it to <code>action_input</code>, and the remaining items in the list are collected into the <code>args</code> variable as the list <code>[&quot;john&quot;]</code>, where as if “b” is given as input, <code>args</code> becomes the empty list <code>[]</code>. When <code>action(*args)</code> is called, if <code>args</code> has 0 items, it calls <code>action</code> with no arguments, if <code>args</code> has 1 item, it calls <code>action</code> with 1 argument, if <code>args</code> has 2 items, it calls <code>action</code> with 2 arguments, and so on. You are free to define functions with any number of arguments (including default arguments), and <code>action(*args)</code> will populate the function’s parameter list with the items in <code>args</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T05:19:26.383", "Id": "519847", "Score": "0", "body": "Thanks for the feedback. Better understanding of Exception handling and sanitizing user input is also on my \"to do/learning goals\" list.\nMuch apprrciated.\nCurrently I've modified the code already to prevent these exceptions, I just didn't change the example here.\nBut your suggestion is cleaner and I'll learn more about this." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T04:49:49.153", "Id": "263304", "ParentId": "263252", "Score": "1" } } ]
{ "AcceptedAnswerId": "263261", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T17:01:13.460", "Id": "263252", "Score": "3", "Tags": [ "python-3.x" ], "Title": "Better solution to pass arguments to function in a dictionary" }
263252
<p>I've decided to rewrite the standard library list in a smaller version. This is similar to another question of mine, where my main concern is memory management. I allocate a new array each time the user wants to modify the list. I want to know if there are any memory leaks that I need to plug. I've been liberal using <code>delete[]</code>, but I need to know I've covered all my bases.</p> <p>As always, best practices and other improvements are always welcome and appreciated.</p> <pre><code>#include &lt;iostream&gt; #include &lt;initializer_list&gt; template&lt;class T&gt; class list { private: size_t length = 0; T* elements = nullptr; /** * Determines if there will be an out of bound error. If so, handles * it nicely and displays the range of acceptable integers allowed. * * @param position The index passed by the user. * * @return (void). **/ void checkRangeError(const int&amp; position) const { if (position &lt; 0 || position &gt;= this-&gt;length) { std::cout &lt;&lt; &quot;error: (position) parameter needs to be in range [0, &quot; &lt;&lt; this-&gt;length &lt;&lt; &quot;)&quot; &lt;&lt; std::endl; exit(1); } } public: list() {} list(std::initializer_list&lt;T&gt; args) { for (auto arg : args) { this-&gt;append(arg); } } ~list() { delete[] this-&gt;elements; } // Capacity Functions // /** * Determines if the current list is empty. * * @return (bool) True if empty, False otherwise. **/ bool empty(void) const { return this-&gt;length != 0; } /** * Returns the current length of the list. * * @return (size_t) Length of list. **/ size_t size(void) const { return this-&gt;length; } // Element Access Functions // /** * Returns the element at the front of the list. Does not pop, but * simply returns the value. * * @return (T) First item in the list. **/ T front(void) const { return this-&gt;elements[0]; } /** * Returns the element at the end of the list. Does not pop, but * simply returns the value. * * @return (T) Last item in the list. **/ T back(void) const { return this-&gt;elements[this-&gt;length - 1]; } // Modifier Functions // /** * Adds an element to the end of the list. Grows the list size by one. * * @param value Element to add to the list. * * @return (void). **/ void append(const T&amp; value) { if (this-&gt;length == 0) { this-&gt;elements = new T[1]; this-&gt;elements[this-&gt;length++] = value; return; } T* previous = new T[this-&gt;length]; for (int i = 0; i &lt; this-&gt;length; i++) previous[i] = this-&gt;elements[i]; this-&gt;elements = new T[++this-&gt;length]; for (int i = 0; i &lt; this-&gt;length; i++) this-&gt;elements[i] = previous[i]; this-&gt;elements[this-&gt;length - 1] = value; delete[] previous; } /** * Inserts an element at the given position. Shifts every element after down one. * * @param position Index to place value. * @param value Element to add to list. * * @return (void). **/ void insert(const int&amp; position, const T&amp; value) { this-&gt;checkRangeError(position); T* previous = new T[this-&gt;length]; if (position == 0) { for (int i = 0; i &lt; this-&gt;length; i++) previous[i] = this-&gt;elements[i]; this-&gt;elements = new T[++this-&gt;length]; this-&gt;elements[0] = value; for (int i = 1; i &lt; this-&gt;length - 1; i++) this-&gt;elements[i] = previous[i]; delete[] previous; return; } for (int i = 0; i &lt; this-&gt;length; i++) previous[i] = this-&gt;elements[i]; this-&gt;elements = new T[++this-&gt;length]; for (int i = 0; i &lt; position; i++) this-&gt;elements[i] = previous[i]; this-&gt;elements[position] = value; for (int i = position; i &lt; this-&gt;length - 1; i++) this-&gt;elements[i + 1] = previous[i]; delete[] previous; } /** * Replaces the value at the given position with the new value. * * @param position Index to replace value. * @param value New element to place in list. * * @return (void). **/ void replace(const int&amp; position, const T&amp; value) { this-&gt;checkRangeError(position); this-&gt;elements[position] = value; } /** * Erases the value at the given position, shrinking the size of the list by one. * * @param position Index to erase value. * * @return (void). **/ void erase(const int&amp; position) { this-&gt;checkRangeError(position); T* previous = new T[this-&gt;length]; for (int i = 0; i &lt; this-&gt;length; i++) previous[i] = this-&gt;elements[i]; this-&gt;elements = new T[--this-&gt;length]; for (int i = 0; i &lt; position; i++) this-&gt;elements[i] = previous[i]; for (int i = position; i &lt;= this-&gt;length - 1; i++) this-&gt;elements[i] = previous[i + 1]; delete[] previous; } /** * Shrinks the size of the list, keeping only the elements that fit into the new size. * The new size must be less than the current length of the list, or the function will exit. * * @param newSize New length of the list. * * @return (void). **/ void shrink(const int&amp; newSize) { if (newSize &gt;= this-&gt;length) { std::cout &lt;&lt; &quot;error: (newSize) must be less than the current length of the list!&quot; &lt;&lt; std::endl; exit(1); } size_t len = this-&gt;length - newSize; for (int i = 0; i &lt; len; i++) this-&gt;erase(this-&gt;length - 1); } /** * Swaps two elements at their given indexes. * * @param indexOne First index to swap. * @param indexTwo Second index to swap. * * @return (void). **/ void swap(const int&amp; indexOne, const int&amp; indexTwo) { T temp = this-&gt;elements[indexOne]; this-&gt;elements[indexOne] = this-&gt;elements[indexTwo]; this-&gt;elements[indexTwo] = temp; } /** * Performs an in-place bubble sort on the current list. * * @return (void). **/ void sort(void) { for (int i = 0; i &lt; this-&gt;length; i++) for (int j = 0; j &lt; this-&gt;length - i - 1; j++) if (this-&gt;elements[j] &gt; this-&gt;elements[j + 1]) this-&gt;swap(j, j + 1); // Swap using index, not value. } /** * Clears the list of all elements and resetting the length to zero. * * @return (void). **/ void clear(void) { this-&gt;elements = nullptr; this-&gt;length = 0; } /** * Prints the list to the console, all on one line. * * @return (void). **/ void print(void) const { for (int i = 0; i &lt; this-&gt;length; i++) std::cout &lt;&lt; this-&gt;elements[i] &lt;&lt; &quot; &quot;; std::cout &lt;&lt; std::endl; } /** * Overload operator[] for list. **/ T&amp; operator[](const int&amp; position) const { this-&gt;checkRangeError(position); return this-&gt;elements[position]; } /** * Overload operator== for list. **/ bool operator==(list&amp; rhs) const { if (this-&gt;size() != rhs.size()) return false; for (int i = 0; i &lt; this-&gt;length; i++) if (this-&gt;elements[i] != rhs[i]) return false; return true; } }; </code></pre> <p>And here's how I'm compiling:</p> <p><strong>run.sh</strong></p> <pre><code>g++ program.cpp -std=c++2a -o program ./program rm program </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T22:16:52.037", "Id": "519755", "Score": "6", "body": "So this is not a reimplementation of `std::list` anymore, but rather of `std::vector`. By the way, what exactly do you mean with \"smaller version\"? Do you want to reduce the code size, or the size of the memory used by your `list`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T22:42:46.723", "Id": "519756", "Score": "0", "body": "@G.Sliepen A bit of both. I wanted a simple header file I could include without all the std overhead, and I want to use as little memory as possible (but with template classes I can't really predict how much I will use)." } ]
[ { "body": "<ol>\n<li>As mentioned, this is a re-implementation of <code>std::vector</code>, not <code>std::list</code>.</li>\n</ol>\n<hr />\n<ol start=\"2\">\n<li>The default constructor can be set as <code>default</code>.</li>\n</ol>\n<hr />\n<ol start=\"3\">\n<li><p>You're not following <a href=\"https://en.cppreference.com/w/cpp/language/rule_of_three\" rel=\"noreferrer\">rule of 0-3-5</a>. Consider this snippet of code:</p>\n<pre><code>int main()\n{\n list&lt;int&gt; l1 = {1, 2, 3};\n list&lt;int&gt; l2 = l1;\n}\n</code></pre>\n<p>As things stand, your implementation is invoking undefined behavior because both <code>l1</code> and <code>l2</code> point to the same region of memory. When both are destroyed, they both try to delete the same pointer, causing a double free.</p>\n</li>\n</ol>\n<hr />\n<ol start=\"4\">\n<li>Your <code>front</code> and <code>back</code> methods should return a reference to the object. Additionally, there should be two versions, a const and a non-const version, returning a const reference and a non-const reference respectively.</li>\n</ol>\n<hr />\n<ol start=\"5\">\n<li>You don't need to use <code>void</code> to signify an empty parameter list. Unlike C, an empty parameter list signifies no arguments.</li>\n</ol>\n<hr />\n<ol start=\"6\">\n<li>You don't actually need to use <code>this</code> to refer to member functions and data. Unlike some other languages, <code>this</code> is generally used only whenever one needs to explicitly use the pointer to the current object.</li>\n</ol>\n<hr />\n<ol start=\"7\">\n<li>If you're re-implementing a STL container/function, you should keep the interface the same. That means <code>append</code> becomes <code>push_back</code>.</li>\n</ol>\n<hr />\n<ol start=\"8\">\n<li><p>The way you're growing the array is very inefficient. You're essentially allocating a new array and copying elements over every time you append. This means your <code>append</code> method has a time complexity of O(N), where N is the number of elements in the array.</p>\n<p>Typical implementations allocate more memory than needed, and keep track of how much memory is allocated and how much memory is actually used. If they are both equal, only then new memory is allocated and the elements copied over.</p>\n<p>How much new memory to allocate? Implementations typically allocated 2 or 1.5 times the original capacity. This gives you an amortized O(1) append.</p>\n<p>There's some other optimizations you can do in C++. You can allocate raw memory and create an object only when required (using placement <code>new</code>). This avoids the objects being default constructed whenever you allocate memory (which might be expensive). You can also check if <code>T</code>'s move constructor is <code>noexcept</code> (using <code>std::is_nothrow_move_constructible</code>) and then moving the elements over, instead of copying them.</p>\n</li>\n</ol>\n<hr />\n<ol start=\"9\">\n<li><p>The way that you're moving elements is also very inefficient. This is what you're doing:</p>\n<ol>\n<li>Allocate temp memory (will be default constructed)</li>\n<li>Copy all elements to temp memory</li>\n<li>Allocate new list memory</li>\n<li>Copy all elements in temp memory to new list memory</li>\n<li>Delete temp memory</li>\n</ol>\n<p>whereas, a more efficient way would be</p>\n<ol>\n<li>Allocate temp memory (whose size is old memory * 2)</li>\n<li>Copy all elements to temp memory</li>\n<li>Swap temp memory and list memory pointers</li>\n<li>Delete temp memory</li>\n</ol>\n</li>\n</ol>\n<hr />\n<ol start=\"10\">\n<li>Your class is not exception safe. Any of the calls to <code>new</code> can return <code>std::bad_alloc</code>.</li>\n</ol>\n<hr />\n<ol start=\"11\">\n<li>Instead of exiting the entire program when something goes wrong, throw an exception, or use some other kind of mechanism, to notify the caller and let the caller handle it.</li>\n</ol>\n<hr />\n<ol start=\"12\">\n<li>Instead of providing a <code>print</code> function, a more idiomatic way in C++ to print an object is to overload the <code>operator&lt;&lt;</code> method.</li>\n</ol>\n<hr />\n<ol start=\"13\">\n<li>Instead of providing a <code>sort</code> function, you should provide iterators (which are simply <code>T*</code> in this case) in the form of <code>begin()</code> and <code>end()</code> functions, so that one can use <code>std::sort</code>.</li>\n</ol>\n<hr />\n<ol start=\"14\">\n<li>Use <code>std::size_t</code> instead of <code>int</code> to represent indices or size. Also, you don't need to pass trivial types such as <code>int</code> using const reference; pass them by value instead. They are small enough to fit in registers.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T09:10:23.107", "Id": "519786", "Score": "3", "body": "On point 14, you may as well fix one of the mistakes in the standard library and avoid needless use of unsigned integers if you're going to implement your own. Otherwise agree." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T16:09:14.530", "Id": "519818", "Score": "4", "body": "@JackAidley Is it a mistake? From a certain point of view, on modern systems, signed integers might sometimes provide an advantage." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T21:37:07.537", "Id": "519907", "Score": "1", "body": "You're saying the same thing, @Deduplicator. Yes, it was a mistake to use unsigned integers throughout the standard library. Bjarne has admitted as much. An unsigned integer should only be used when you have a bit field, not simply because you know that the result will not be negative. This is due to a flaw in C++'s type system which allows aggressive automatic conversion between signed and unsigned integers, making it all too easy to pass a signed integer literal to a function that expects an unsigned integer, have it automatically converted, and end up unable to even detect the error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T21:38:25.913", "Id": "519908", "Score": "0", "body": "However, at this point, one has to decide whether they want to comply with the mistakes of the standard library and thereby make interoperability easier, or whether they want to fix the mistakes made by the standard library and thereby make interoperability harder. The only real solution is \"safe\" casts; that is, casts which thwart automatic conversion and add range checking." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T21:48:57.503", "Id": "519909", "Score": "0", "body": "@CodyGray Conversely, what about the error when passing a big unsigned number to a function expecting a signed number? Also, signed arithmetic overflow is still UB, while unsigned arithmetic wraparound is well-defined. And did he say it was an error then, or that now on bigger machines it is? Also, reasons instead of appeal to authority which isn't even actually quoted is so much better to reason about." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T06:58:21.373", "Id": "519926", "Score": "0", "body": "He said it was an error then. It was about implicit promotions, as I described in the original comment. There's a lot of prior discussion about this question, all of which can be found with an Internet search." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T00:19:54.307", "Id": "263262", "ParentId": "263259", "Score": "26" } }, { "body": "<p>The <code>front</code>, <code>back</code>, and swap methods don't check for an empty <code>list</code>.</p>\n<p>You leak a lot of memory. Most/all of the places where you have <code>this-&gt;elements = new</code> you haven't freed the previous memory stored in <code>this-&gt;elements</code>, resulting in a leak. <code>clear</code> does not free memory.</p>\n<p><code>append</code> reads one past the end of the memory block stored in <code>previous</code> because the loop that copies the previous elements into the new memory block uses the new size, not the old one.</p>\n<p><code>insert</code> at position 0 does not shift the existing elements. You lose the old element 0, and have a default constructed last element.</p>\n<p><code>shrink</code> can be rewritten to be faster by just allocating the new block and copying the elements that won't be lost.</p>\n<p><code>operator[]</code> should have const and non-const versions. Your current version is a const function that returns a non-const reference to your internal data.</p>\n<p>Your <code>list</code> can only store default constructable objects.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T08:31:52.653", "Id": "519933", "Score": "0", "body": "\"*The front, back, and swap methods don't check for an empty list.*\" should they? It's a design decision, you can either decide to do it like standard library and have fast but UB-capable implementation, or you can add additional checks to not allow UB, but at cost of extra runtime calculation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T16:01:55.573", "Id": "519967", "Score": "1", "body": "@Yksisarvinen I added that note because there are some operations (including `operator[]`) that check for a valid position index. `front` and `back` both use fixed indexes, while `swap` uses the same access as `operator[]`. It seems like if you're going to check bounds with the indexing operator you'll want to do the same for other places that do indexing." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T01:15:25.727", "Id": "263263", "ParentId": "263259", "Score": "10" } }, { "body": "<p>As has already been mentioned, this is something like <a href=\"https://en.cppreference.com/w/cpp/container/vector\" rel=\"nofollow noreferrer\"><code>std::vector</code></a>, but nothing like <a href=\"https://en.cppreference.com/w/cpp/container/list\" rel=\"nofollow noreferrer\"><code>std::list</code></a>.</p>\n<p>You should at least learn what containers exist and what their characteristics are before you start reimplementing them.</p>\n<blockquote>\n<p>my main concern is memory management</p>\n</blockquote>\n<p>My main concern about this code is also memory management. It's not a simple topic and it requires more care than you're giving it here.</p>\n<pre><code>void checkRangeError(const int&amp; position) const {\n</code></pre>\n<p>You can just pass value types by value, unless you have some persuasive reason not to. Passing an int by const reference isn't optimizing anything, it just makes the code noisier. Conversely, in</p>\n<pre><code>T front(void) const\n</code></pre>\n<p>you (as the library writer) don't know up-front what type <code>T</code> is, so you can't possibly say whether it's expensive to copy. This <em>should</em> return a const ref (and there should really be a non-const overloads of this &amp; the other accessors too).</p>\n<p>Similarly,</p>\n<pre><code>T&amp; operator[](const int&amp; position) const\n</code></pre>\n<p>should probably return a const ref (so you can't mutate the contents of a const container) and also have a non-const overload.</p>\n<pre><code>T* previous = new T[this-&gt;length];\n</code></pre>\n<p>why is the new array called <em>previous</em>? Surely this should be the <em>next</em> version of the array?</p>\n<p>Note that you're going to default construct all N elements and <em>then</em> copy-assign all N elements again. This is wasteful (you're initializing everything twice) and places an unnecessary constraint on <code>T</code> (it has to be default constructible).</p>\n<pre><code>this-&gt;elements = new T[++this-&gt;length];\n</code></pre>\n<p>You haven't released the <em>old</em> copy yet, so that's a memory leak. And you've also missed one of the key things about pointer indirection: you don't need to copy everything out of the way just to copy it back later, like swapping two values.</p>\n<p>You can just write</p>\n<pre><code>T* new_elements = allocate_and_move(elements, length);\ndelete [] elements;\nelements = new_elements;\n</code></pre>\n<p>with a little effort, you can placement-move-construct the old elements into their new location instead of initializing them twice. At the very least you don't have to copy them <em>back</em> again, and it doesn't leak memory.</p>\n<blockquote>\n<p>I've been liberal using <code>delete[]</code>, but I need to know I've covered all my bases.</p>\n</blockquote>\n<p>Don't be liberal using delete - double-freeing memory is just as bad as leaking it. Try to avoid manual memory management in the first place, especially if you're having a hard time understanding what state things are in. So we could improve the three lines above to:</p>\n<pre><code>std::unique_ptr&lt;T[]&gt; new_elements = allocate_and_move(elements, length);\nelements.swap(new_elements);\n</code></pre>\n<p>(obviously you still need to write <code>allocate_and_move</code>, and I do encourage you to learn how to <em>move</em> your elements instead of copying them).</p>\n<hr />\n<p>Finally, consider the performance of this container. It's <em>terrible</em>.</p>\n<p><code>std::list</code> has O(1) insert because the time to insert a single element in a linked list doesn't depend on the size of the list.</p>\n<p><code>std::vector</code> has <em>amortized</em> O(1) insert because although growing the array is expensive (linear although with a lower coefficient than your code), it avoids growing the array on every insert.</p>\n<p>Your container has O(N) insert (with a really high coefficient due to default-initializing every element before copying it twice).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T09:21:17.277", "Id": "263274", "ParentId": "263259", "Score": "6" } }, { "body": "<p><code>T back(void) const</code><br />\nDon't use <code>(void)</code> for empty parameter lists. Stroustrup calls this &quot;an abomination&quot;. C needed that when (optional) signatures were added; C++ never did.</p>\n<pre><code> if (this-&gt;length == 0) {\n this-&gt;elements = new T[1];\n this-&gt;elements[this-&gt;length++] = value;\n</code></pre>\n<p>Don't use <code>this-&gt;</code> for every member access! Just use the member name.</p>\n<p><code>length == 0</code> is better expressed as <code>empty()</code>.</p>\n<hr />\n<p>How is this an implementation similar to <code>std::list</code>? It looks more like <code>vector</code>.</p>\n<hr />\n<pre><code> /**\n * Performs an in-place bubble sort on the current list.\n * \n * @return (void).\n **/\n void sort(void) {\n</code></pre>\n<p>Why is this necessary as a bespoke member function? <code>std::sort</code> should work on your collection class. At the very worst, you should be able to call <code>std::sort</code> on the internal array as the implementation of this member.</p>\n<hr />\n<pre><code> /**\n * Clears the list of all elements and resetting the length to zero.\n * \n * @return (void).\n **/\n void clear(void) {\n this-&gt;elements = nullptr;\n this-&gt;length = 0;\n }\n</code></pre>\n<p>You seem to have forgotten to <code>delete</code> the memory!</p>\n<hr />\n<p><code> void shrink(const int&amp; newSize) {</code><br />\nWhy are you passing an <code>int</code> by reference?</p>\n<hr />\n<p>Your <code>shrink</code> function is grossly inefficient. It reallocates (copies) the entire array for each element deleted, instead of just once.<br />\nThe constructor that takes an <code>initialization_list</code> is the same: why reallocate/copy again for each element, instead of doing it once?</p>\n<hr />\n<p>When you reallocate and copy your array, you require that <code>T</code> has a default constructor, and you use assignment to set its value. The <code>std::</code> collections have no such requirement. The <code>std::vector</code> initializes the elements directly from the item it's being set to, using the copy constructor, move constructor, or (when using <code>emplace_back</code>) calling some specified constructor directly in-place.</p>\n<hr />\n<pre><code>for (int i = 0; i &lt; this-&gt;length; i++)\n this-&gt;elements[i] = previous[i];\n</code></pre>\n<p>Just use <code>std::copy</code> algorithm.<br />\nYou need to be aware of what's available in the library.</p>\n<hr />\n<pre><code> T* previous = new T[this-&gt;length];\n for (int i = 0; i &lt; this-&gt;length; i++)\n previous[i] = this-&gt;elements[i];\n this-&gt;elements = new T[++this-&gt;length];\n for (int i = 0; i &lt; this-&gt;length; i++)\n this-&gt;elements[i] = previous[i];\n</code></pre>\n<p>Holy , you are copying the current array, then copying it again! And you're completely forgetting to delete <code>elements</code> before overwriting that pointer.</p>\n<p>The &quot;normal&quot; way to do this would be to copy to a longer array, then just assign that pointer back to the <code>elements</code> member; you don't have to copy it again. I think you're not understanding that <code>elements</code> is a <strong>pointer</strong> not a built-in collection of some kind. Your like <code>this-&gt;element= new...</code> is not re-allocating the existing array, but allocating a different array and assigning a pointer to the first element to <code>elements</code>, losing the old pointer value (dropping it on the floor without deleting it).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T15:12:34.863", "Id": "263286", "ParentId": "263259", "Score": "1" } } ]
{ "AcceptedAnswerId": "263262", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-20T21:44:20.287", "Id": "263259", "Score": "9", "Tags": [ "c++", "reinventing-the-wheel", "c++20" ], "Title": "std::list reimplementation" }
263259
<p>I was working in a class, but there are a lot of things that I'm not sure if they're a good practice or not. For example, the <code>=&gt;</code> instead of the <code>{ }</code>. When should I use it? Also, I'm not pretty sure about the keywords <code>const</code> and <code>readonly</code>. For example, <code>uriImage</code> and <code>key</code> it's something that won't change. So, I assume it'll be <code>const</code>. Nevertheless, <code>summonerName</code> or <code>currentVersion</code> despite they won't change, they will be initialized later. That's why I assumed they should be <code>readonly</code>.</p> <p>Another thing that I was wondering is the Key Api. What'd be the correct way of using a Key api? They could do reversing to the program and take the keyApi?</p> <p>All good practice tips, and so on, are welcome, thank you very much in advance.</p> <pre><code>class GameApi { private const string uriImage = &quot;http://opgg-static.akamaized.net/images/lol/champion/&quot;; private const string key = &quot;XXX-XXXXX-XXXXXXXX-XXXXXX-XXXXXX&quot;; private readonly string summonerName; private readonly string currentVersion; private ChampionListStatic championList; private Summoner summonerObject; private RiotApi api; public GameApi(string _summonerName) { api = RiotApi.GetDevelopmentInstance(key); summonerName = _summonerName; try { // gets currentVersion so I can work with the GetAllAsync() method. // Save all champions in championList to work with it in the GetImageUri method. currentVersion = api.DataDragon.Versions.GetAllAsync().Result.First(); summonerObject = api.Summoner.GetSummonerByNameAsync(RiotSharp.Misc.Region.Euw, _summonerName).Result; championList = api.DataDragon.Champions.GetAllAsync(currentVersion).Result; } catch (RiotSharpException) { // Exception bla bla } } public IEnumerable&lt;CurrentGameParticipant&gt; getEnemyTeam() { // Get the 10 participants in the current game. List&lt;CurrentGameParticipant&gt; currentMatch = api.Spectator.GetCurrentGameAsync(Region.Euw, summonerObject.Id).Result.Participants; // Get the ID team that summonerName belongs to. long teamId = currentMatch.Where(p =&gt; p.SummonerName == summonerName).First().TeamId; // Return the (5) participants that doens't belong to the same team than summonerName. return currentMatch.Where(p =&gt; p.TeamId != teamId); } public string getImageUri(long championId) =&gt; // Return the uri to load in the pictureBox.ImageLocation propriety uriImage + championList.Champions.Where(p =&gt; p.Value.Id == championId).First().Value.Image.Full; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T03:54:00.723", "Id": "519764", "Score": "0", "body": "`string key` need less than minute to get the key from the compiled executable file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T03:55:41.277", "Id": "519766", "Score": "0", "body": "Sorry, what do you mean? @aepot" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T05:39:10.983", "Id": "519772", "Score": "1", "body": "I mean storing api key in a constant string is insecure." } ]
[ { "body": "<blockquote>\n<p><code>=&gt;</code> instead of the <code>{ }</code></p>\n</blockquote>\n<p>This is personal preference. My preference, for example, is to generally use <code>{ }</code> because I like it more, stylistically. I will say if it's more than a line, using <code>=&gt;</code> (again, in my opinion) becomes hard to read</p>\n<blockquote>\n<p>I'm not pretty sure about the keywords <code>const</code> and <code>readonly</code></p>\n</blockquote>\n<p><code>const</code> is used for compile time constants and <code>readonly</code> are for things that are set when the object is constructed. This can be either on a field or property that is initialized (ie set) where it is declared OR set in a constructor. You also can't use <code>const</code> with objects that you have to new. For example, you can't do <code>private const List&lt;string&gt; _someList = new List&lt;string&gt;()</code>.</p>\n<p>From what I see here, <code>championList</code>, <code>summonerObject</code>, and <code>api</code> can all be <code>readonly</code>.</p>\n<blockquote>\n<p>correct way of using a Key api</p>\n</blockquote>\n<p>Depends on what you're doing. Since you're asking about it, it sounds like you are deploying this somewhere (and possibly have this code in a repo somewhere that is available to others). You should not have the secret stored in the repo. Going in depth for what you should do is a bit out of scope for an answer here.</p>\n<blockquote>\n<p>good practice tips</p>\n</blockquote>\n<p>Since this is a small snapshot of your application, I'm going to make a few guesses.</p>\n<p>You're abusing async calls here quite a bit by just putting <code>.Result</code> on the end of each call. The reason you need to do that is you can't make the constructor async. Since you don't need any of that information that you're getting in the constructor in the constructor itself, you can do what's called &quot;Lazy Load&quot; the information later. Essentially, you check if you have the object before you use it (if it's not <code>null</code>) and, if you don't, you get it.</p>\n<p>Making this change pushes all of the api calls to <code>getEnemyTeam</code>, which should be <code>async</code> already (<code>public async Task&lt;IEnumerable&lt;CurrentGameParticipant&gt;&gt; getEnemyTeam()</code>) and change lines where you use <code>.Result</code> to use <code>await</code> instead.</p>\n<p>From the sound of the class <code>GameApi</code>, it's not meant for a single summoner but a single instance could check any number of summoners. Instead of passing a single summoner to the constructor, you could pass it in to whatever method you would need. Same goes for the region, for example. Instead of hardcoding it to a single region, you could pass it in (but if it's for your own use and that's your region, so be it).</p>\n<p>You don't need to do separate <code>Where</code> and <code>First</code> clauses here: <code>currentMatch.Where(p =&gt; p.SummonerName == summonerName).First().TeamId</code>. It can become <code>currentMatch.First(p =&gt; p.SummonerName == summonerName).TeamId</code>. As an aside, what if you pass in a different casing of <code>summonerName</code> than what's expected? Instead of using <code>==</code>, you can do <code>summonerName.Equals(p.SummonerName, StringComparison.OrdinalIgnoreCase)</code>.</p>\n<p>The way you are getting the image URI, you could consider using a Dictionary. Also, here again, you can combine the <code>Where</code> and <code>First</code> methods. I also, personally, would break up that method to use <code>{ }</code> and split it to multiple lines for readability.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T04:14:53.263", "Id": "519767", "Score": "0", "body": "Thanks a lot for all these tips and corrections. I have felt that I learned a lot from your reading. Would you mind going a bit in depth with the subject of the key? (Any link or methodology name is enough, so we dont have to go out of scope) Thanks a lot! :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T04:22:17.203", "Id": "519768", "Score": "2", "body": "@Omar I'll do my best but when I usually deal with secrets, it's at the enterprise level and I have certain technologies available that you might not have.\n\nYou could inject a secret a few different ways. If you encrypt the value and have the certificate available to you wherever you are deployed, you can decrypt at run time. You could also inject it with an environment variable on the machine you are deploying to. If you're running in a docker container, you again can use an environment variable.\n\nI don't have much advice beyond that though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T04:25:42.690", "Id": "519770", "Score": "0", "body": "It's enough, thanks a lot!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T10:48:04.340", "Id": "519796", "Score": "0", "body": "@Trevor using Expression-bodied members `=>` over curly brackets `{}` it's a mix of personal preference and compatibilities. (supported on C# 6 and above).\nhttps://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members#read-only-properties" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T04:00:58.343", "Id": "263266", "ParentId": "263264", "Score": "5" } } ]
{ "AcceptedAnswerId": "263266", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T01:54:51.327", "Id": "263264", "Score": "0", "Tags": [ "c#", "api", "classes" ], "Title": "Good practices for a class" }
263264
<p>Here is a coroutine generator class... Just like Python yields. It was a bit tedious to support both <code>co_yield</code> and <code>co_return</code> (should manage the cases flow out of function body and <code>co_return</code> separately) but it works. I wonder if it's okay, especially from the point of view of undefined behavior and memory leaks.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;coroutine&gt; #include &lt;functional&gt; using namespace std; template&lt;typename T&gt; class generator { public: struct promise_type { T t_; bool returned_with_value_{false}; promise_type() = default; ~promise_type() = default; std::suspend_always initial_suspend() { return {}; } std::suspend_always final_suspend() {} void unhandled_exception() {} generator get_return_object() { return {std::coroutine_handle&lt;promise_type&gt;::from_promise(*this)}; } std::suspend_always yield_value(T t) { t_ = t; return {}; } void return_value(T t) { t_ = t; returned_with_value_ = true; } void return_void() {} }; private: std::coroutine_handle&lt;promise_type&gt; h_; auto&amp; promise() { return h_.promise(); } public: generator(std::coroutine_handle&lt;promise_type&gt; h) : h_(h) {} ~generator() = default; bool operator()() { if(promise().returned_with_value_) // From previous operator() call { h_.destroy(); return false; } h_(); if(!promise().returned_with_value_ &amp;&amp; h_.done()) { h_.destroy(); return false; } else { return true; } } [[nodiscard]] const T&amp; get() const { return h_.promise().t_; } operator const T&amp;() const { return get(); } }; generator&lt;int&gt; foo() { int i = 0; while(1) { co_yield ++i; if( i == 100) co_return i; } } int main() { auto handle = foo(); while(handle()) { cout &lt;&lt; &quot;val: &quot; &lt;&lt; handle.get() &lt;&lt; endl; } return 0; } </code></pre>
[]
[ { "body": "<h1>Minor compile issues</h1>\n<p>Not all <a href=\"https://en.cppreference.com/w/cpp/compiler_support\" rel=\"noreferrer\">compilers support</a> coroutines fully yet, and at least on GCC 10 your <code>generator</code> fails to compile, because:</p>\n<pre><code>gen.cc:70:16: error: the coroutine promise type ‘std::__n4861::__coroutine_traits_impl&lt;generator&lt;int&gt;, void&gt;::promise_type’ {aka ‘generator&lt;int&gt;::promise_type’} declares both ‘return_value’ and ‘return_void’\n</code></pre>\n<p>It is indeed mentioned in the C++20 standard, in <a href=\"https://timsong-cpp.github.io/cppwp/n4868/dcl.fct.def.coroutine#6\" rel=\"noreferrer\">§9.5.4 paragraph 6</a>, that:</p>\n<blockquote>\n<p>The unqualified-ids <code>return_void</code> and <code>return_value</code> are looked up in the scope of the promise type. If both\nare found, the program is ill-formed.</p>\n</blockquote>\n<p>So it seems GCC is correct here. There is also an example implementation of <code>struct generator</code> in the standard, that suggests that you should implement <code>yield_value()</code> and <code>return_void()</code>. Having the latter is important, since as user673679 mentioned, without it it leads to undefined behavior if you don't have a <code>co_return</code> statement in your coroutine.</p>\n<h1>What about the copy and move constructors?</h1>\n<p>You didn't specify any copy or move constructors. What happens if I copy <code>handle</code> in <code>main()</code>? What if I move from <code>handle</code>? This currently does not work correctly. Either delete the unwanted constructors or add implementations that make sure the copy or move is handled correctly. Also think about the assignment operators when you do this; in particular, follow the <a href=\"https://en.cppreference.com/w/cpp/language/rule_of_three\" rel=\"noreferrer\">rule of zero, three or five</a>.</p>\n<h1>The value <code>100</code> is returned twice</h1>\n<p>Your example generator <code>foo()</code> returns the last value twice. A more natural way to write it would be:</p>\n<pre><code>generator&lt;int&gt; foo()\n{\n for (int i = 0; i &lt;= 100; ++i)\n co_yield i;\n}\n</code></pre>\n<p>Which works fine with your <code>generator</code> implementation.</p>\n<h1>Make it work with range-<code>for</code></h1>\n<p>Your <code>generator</code> doesn't have <code>begin()</code> and <code>end()</code> functions, so you cannot use it in a range-<code>for</code> expression. In particular, it would be nice if your <code>main()</code> function could have been written this way:</p>\n<pre><code>int main()\n{\n for (auto &amp;i: foo())\n std::cout &lt;&lt; i &lt;&lt; '\\n';\n}\n</code></pre>\n<h1>Going further</h1>\n<p>Your generator works for the simple example you have written. However, in real applications you might want to use generators to return objects that might not be copy constructible, or want to be allocator-aware, or have other properties that you did not think about. If you want this to be usable in real applications, then I suggest you create a test suite first, where you cover all the possible use cases of your generator, and then improve your implementation. Also look at how others have tried to create a generator class, in particular look at <a href=\"https://github.com/lewissbaker/cppcoro\" rel=\"noreferrer\">Lewis Baker's cppcoro library</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T10:20:58.727", "Id": "263275", "ParentId": "263265", "Score": "7" } }, { "body": "<ul>\n<li>Don't do <code>using namespace std;</code> <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">it can lead to name collisions and other issues</a>. (It looks like it's only being used for <code>cout</code> and <code>endl</code> anyway).</li>\n</ul>\n<hr />\n<pre><code> T t_;\n bool returned_with_value_{false};\n</code></pre>\n<ul>\n<li><p>It would be better to use a <code>std::optional&lt;T&gt; t_;</code>. This would allow us to support types without default constructors, and be certain that the value has actually been initialized and set to something when we access it.</p>\n</li>\n<li><p>As you say, it would be better to have separate return and yield values. We could do that with two separate <code>std::optional</code>s. Perhaps we could use separate template arguments for the return and yield types.</p>\n</li>\n<li><p>Of course, we might need to select from one of several <code>promise_type</code> classes if we want to support void return values, void yield values and combinations of them. Right now it's very hard to write multi-purpose or reusable coroutine code in C++.</p>\n</li>\n<li><p>Note that this generator doesn't need a <code>return_value</code>.</p>\n</li>\n</ul>\n<hr />\n<pre><code> std::suspend_always final_suspend() {}\n</code></pre>\n<p>Doesn't this need a <code>return {};</code> to compile? If not, consider turning up your compiler warning level, and set warnings to errors.</p>\n<p>According to the GCC it must also be declared <code>noexcept</code>:</p>\n<pre><code> std::suspend_always final_suspend() noexcept { return {}; }\n</code></pre>\n<hr />\n<pre><code> void return_value(T t) { t_ = t; returned_with_value_ = true; }\n void return_void() {}\n</code></pre>\n<p>This also produces a compiler error on GCC:</p>\n<blockquote>\n<p>error: the coroutine promise type\n'std::__n4861::__coroutine_traits_impl&lt;generator,\nvoid&gt;::promise_type' {aka 'generator::promise_type'} declares\nboth 'return_value' and 'return_void'</p>\n</blockquote>\n<p>I can't actually find anything definite specifying that coroutines must only have one or the other... so I don't know if that error is correct. Though I guess it's at consistent with the rest of C++, where functions can only have a single return type. /o\\</p>\n<p>Of course, we then have to be careful about falling off the end of the function without returning anything (apparently that's undefined behavior and not anything sane like a compiler error - thanks O'Bjarne!).</p>\n<hr />\n<pre><code>bool operator()()\n{\n if(promise().returned_with_value_) // From previous operator() call\n {\n h_.destroy();\n return false;\n }\n\n h_();\n\n if(!promise().returned_with_value_ &amp;&amp; h_.done())\n {\n h_.destroy();\n return false;\n }\n else\n {\n return true;\n }\n}\n</code></pre>\n<ul>\n<li><p>I'd suggest giving this function a meaningful name (e.g. <code>resume()</code>), so the user knows exactly what it does.</p>\n</li>\n<li><p>This function seems unnecessarily complicated. We can instead require that the function is only called when it's actually possible to resume. <code>destroy()</code> can be handled in the class destructor. e.g. something like:</p>\n</li>\n</ul>\n<pre><code> ~generator()\n {\n if (h_)\n h_.destroy();\n }\n \n bool is_resumable() const\n {\n return h_ &amp;&amp; !h_.done();\n }\n \n bool resume()\n {\n assert(is_resumable());\n \n h_();\n \n return !h_.done();\n }\n</code></pre>\n<ul>\n<li>We need to consider copy and move of the generator object too (even if it's just to <code>= delete</code> those operators).</li>\n</ul>\n<hr />\n<pre><code>operator const T&amp;() const\n{\n return get();\n}\n</code></pre>\n<p>Implicit conversions are generally a bad idea. This operator should at least be <code>explicit</code>, but it would be better to just delete it and use a <code>get_return_value</code> or <code>get_yield_value</code> function.</p>\n<hr />\n<p>This <a href=\"https://en.cppreference.com/w/cpp/coroutine/coroutine_handle\" rel=\"noreferrer\"><code>coroutine_handle</code> reference page</a> has a decent example of how to write a generator supporting range-based for loop iteration.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T10:58:35.460", "Id": "263278", "ParentId": "263265", "Score": "5" } } ]
{ "AcceptedAnswerId": "263275", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T03:26:49.253", "Id": "263265", "Score": "5", "Tags": [ "c++", "c++20" ], "Title": "C++20 Coroutine Generator" }
263265
<p>I have implemented a simple <em>NFA</em> that recognizes words in parallel. All the code is on GitHub, <a href="https://github.com/alexfertel/atl" rel="noreferrer">here</a>.</p> <ul> <li><p>A main <code>recognizes</code> method tells if a <code>word</code> (<code>&amp;str</code>) is recognized by an <em>NFA</em>. Inside this method, I set up a thread pool and a <em>channel</em> and call a <code>recognizes_in_parallel</code> method.</p> </li> <li><p>The <code>recognizes_in_parallel</code> takes a <code>word</code> and a <code>state</code> and handles two things:</p> <ol> <li>It spawns a new <code>thread</code> each time the transition function results in more than one state, i.e., when non-determinism occurs.</li> <li>It tells if starting at the <code>state</code> argument, the automaton recognizes the <code>word</code> argument.</li> </ol> </li> <li><p>The <code>recognizes_in_parallel</code> method sends the result of trying to recognize the word through the channel.</p> </li> <li><p>The main thread then receives until a <code>true</code> is sent or when all the threads have hung up or sent <code>false</code>.</p> </li> </ul> <p>I am very new to <em>Rust</em>, just finished reading <em>The Rust Book</em> a couple of weeks ago, and I want to know if this code can be improved regarding readability, efficiency, and organization.</p> <p>Are there good quality unit tests that could be written for the parallelization? Can I improve the use of locks here? Can I write less verbose initialization? I think I abused the <code>Copy</code> and <code>Clone</code> traits, is there a way to reduce their use?</p> <p>Two things to keep in mind:</p> <ul> <li><code>ThreadPool</code> is not <code>Sync</code>, that's why we need the <code>Mutex</code> (or so I understood).</li> <li>I don't understand why the following change breaks the code, i.e., it does not halt.</li> </ul> <pre class="lang-rust prettyprint-override"><code>// Works!! pool.lock().unwrap().execute(move || { root_nfa.recognize_in_parallel(&amp;word[..], root_nfa.start, tx, pool_clone); }); --- // Does not work :( let pool = pool.lock().unwrap(); pool.execute(move || { root_nfa.recognize_in_parallel(&amp;word[..], root_nfa.start, tx, pool_clone); }); </code></pre> <p>Finally, here's the relevant code:</p> <pre class="lang-rust prettyprint-override"><code>// state.rs #[cfg(test)] #[path = &quot;./state.test.rs&quot;] mod tests; #[derive(PartialEq, Eq, Debug, Hash, Copy, Clone)] pub struct State { pub id: i32, } impl State { pub fn new(id: i32) -&gt; State { State { id } } } </code></pre> <pre class="lang-rust prettyprint-override"><code>// symbol.rs #[derive(PartialEq, Eq, Debug, Hash, Copy, Clone)] pub enum Symbol { Epsilon, Identifier(char), } </code></pre> <pre class="lang-rust prettyprint-override"><code>// nfa.rs use crate::{state::State, symbol::Symbol}; use std::collections::{HashMap, HashSet}; use std::sync::{mpsc, Arc, Mutex}; use threadpool::ThreadPool; #[cfg(test)] #[path = &quot;./nfa.test.rs&quot;] mod tests; const WORKER_COUNT: usize = 1024; #[derive(Debug, PartialEq, Eq, Clone)] pub struct NFA { states: HashSet&lt;State&gt;, alphabet: HashSet&lt;Symbol&gt;, start: State, transition_function: HashMap&lt;(State, Symbol), HashSet&lt;State&gt;&gt;, accepting_states: HashSet&lt;State&gt;, } impl NFA { pub fn new( states: HashSet&lt;State&gt;, alphabet: HashSet&lt;Symbol&gt;, start: State, transition_function: HashMap&lt;(State, Symbol), HashSet&lt;State&gt;&gt;, accepting_states: HashSet&lt;State&gt;, ) -&gt; NFA { NFA { states, alphabet, start, transition_function, accepting_states, } } pub fn add_transition( &amp;mut self, source_state: State, symbol: Symbol, destination_states: HashSet&lt;State&gt;, ) { self.transition_function .insert((source_state, symbol), destination_states); } fn step(&amp;self, ch: char, state: State) -&gt; HashSet&lt;State&gt; { let symbol_states = self .transition_function .get(&amp;(state, Symbol::Identifier(ch))) .expect(&amp;format!(&quot;No transition found for ({:?}, {:?})&quot;, state, ch)); match self.transition_function.get(&amp;(state, Symbol::Epsilon)) { Some(set) =&gt; symbol_states.union(set).cloned().collect(), None =&gt; symbol_states.to_owned(), } } fn recognize_in_parallel&lt;'a&gt;( &amp;self, word: &amp;str, state: State, tx: mpsc::Sender&lt;bool&gt;, pool: Arc&lt;Mutex&lt;ThreadPool&gt;&gt;, ) { let mut state = state; for ch in word.chars() { let next_states = self.step(ch, state); if next_states.len() == 1 { state = *next_states.iter().next().unwrap(); } else { let mut next_states = next_states.iter(); state = *next_states.next().unwrap(); for &amp;state in next_states { let tx = tx.clone(); let child_nfa = self.clone(); let word = word.to_owned(); let pool_clone = Arc::clone(&amp;pool); pool.lock().unwrap().execute(move || { child_nfa.recognize_in_parallel(&amp;word[1..], state, tx, pool_clone); }) } } } tx.send(self.accepting_states.contains(&amp;state)).unwrap(); } pub fn recognizes(&amp;self, word: &amp;str) -&gt; bool { let pool = threadpool::ThreadPool::new(WORKER_COUNT); let pool = Arc::new(Mutex::new(pool)); let (tx, rx) = mpsc::channel(); let root_nfa = self.clone(); let word = word.to_owned(); let pool_clone = Arc::clone(&amp;pool); pool.lock().unwrap().execute(move || { root_nfa.recognize_in_parallel(&amp;word[..], root_nfa.start, tx, pool_clone); }); let did_recognize = rx.iter().any(|did_recognize| did_recognize); // If we don't join here, `rx` would be droped // and a thread might try to send to a closed channel. pool.lock().unwrap().join(); did_recognize } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T06:02:07.760", "Id": "519849", "Score": "0", "body": "Regarding the `Does not work :(` part: the lifetime of a temporary value in a `let` binding extends to the end of the enclosing scope, whereas temporary values in an expression statement (an expression followed by `;`) are discarded at the end of the statement." } ]
[ { "body": "<p>Welcome to Rust, and welcome to Code Review.</p>\n<h1>File organization</h1>\n<p>First of all, the placement of test modules is unconventional:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>#[cfg(test)]\n#[path = &quot;./dfa.test.rs&quot;]\nmod tests;\n</code></pre>\n<p>The common approach is to either simply put the tests at the end of\nthe module, or create a folder for the module:</p>\n<pre><code>- src/\n - lib.rs\n - dfa/\n - mod.rs # equivalent to src/dfa.rs\n - tests.rs # can be accessed within `mod.rs` as `mod tests;`\n</code></pre>\n<p>Using <code>#[path = &quot;...&quot;]</code> is overkill here. (It also refused to work on\nmy computer for weird reasons, so I had to relocate the files.)</p>\n<h1>Warnings</h1>\n<p>The compiler emits a bunch of dead code warnings:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>warning: associated function is never used: `new`\n --&gt; src\\dfa.rs:18:12\n |\n18 | pub fn new(\n | ^^^\n |\n = note: `#[warn(dead_code)]` on by default\n\nwarning: associated function is never used: `add_transition`\n --&gt; src\\dfa.rs:34:12\n |\n34 | pub fn add_transition(&amp;mut self, source_state: State, symbol: char, destination_state: State) {\n | ^^^^^^^^^^^^^^\n\nwarning: associated function is never used: `recognizes`\n --&gt; src\\dfa.rs:39:12\n |\n39 | pub fn recognizes(&amp;self, word: &amp;str) -&gt; bool {\n | ^^^^^^^^^^\n\nwarning: constant is never used: `WORKER_COUNT`\n --&gt; src\\nfa.rs:10:1\n |\n10 | const WORKER_COUNT: usize = 1024;\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nwarning: associated function is never used: `new`\n --&gt; src\\nfa.rs:22:12\n |\n22 | pub fn new(\n | ^^^\n\nwarning: associated function is never used: `add_transition`\n --&gt; src\\nfa.rs:38:12\n |\n38 | pub fn add_transition(\n | ^^^^^^^^^^^^^^\n\nwarning: associated function is never used: `step`\n --&gt; src\\nfa.rs:48:8\n |\n48 | fn step(&amp;self, ch: char, state: State) -&gt; HashSet&lt;State&gt; {\n | ^^^^\n\nwarning: associated function is never used: `recognize_in_parallel`\n --&gt; src\\nfa.rs:60:8\n |\n60 | fn recognize_in_parallel(\n | ^^^^^^^^^^^^^^^^^^^^^\n\nwarning: associated function is never used: `recognizes`\n --&gt; src\\nfa.rs:93:12\n |\n93 | pub fn recognizes(&amp;self, word: &amp;str) -&gt; bool {\n | ^^^^^^^^^^\n\nwarning: associated function is never used: `new`\n --&gt; src\\state.rs:11:12\n |\n11 | pub fn new(id: i32) -&gt; State {\n | ^^^\n\nwarning: variant is never constructed: `Epsilon`\n --&gt; src\\symbol.rs:3:5\n |\n3 | Epsilon,\n | ^^^^^^^\n\nwarning: variant is never constructed: `Identifier`\n --&gt; src\\symbol.rs:4:5\n |\n4 | Identifier(char),\n | ^^^^^^^^^^^^^^^^\n\nwarning: 12 warnings emitted\n\nwarning: associated function is never used: `add_transition`\n --&gt; src\\nfa.rs:38:12\n |\n38 | pub fn add_transition(\n | ^^^^^^^^^^^^^^\n |\n = note: `#[warn(dead_code)]` on by default\n\nwarning: 1 warning emitted\n</code></pre>\n<p>These warnings reveal two issues:</p>\n<ol>\n<li><code>dfa</code>, <code>nfa</code>, <code>state</code>, and <code>symbol</code> are declared as private modules\nin <code>lib.rs</code>, so they can only be used within the crate rooted at\n<code>lib.rs</code>. Therefore, they produce dead code warnings even though\ntheir items are marked as <code>pub</code>.</li>\n</ol>\n<ul>\n<li>Solution: add <code>pub</code> to all lines in <code>lib.rs</code>.</li>\n</ul>\n<ol start=\"2\">\n<li>Instead of using the crate rooted at <code>lib.rs</code>, you <em>re-declare</em> all\nmodules in <code>main.rs</code>. In essence, you have two separately compiled\ncrates that happen to share some of their source files, which is\nclearly not what we want.</li>\n</ol>\n<ul>\n<li>Solution: remove the module declarations in <code>main.rs</code> and prefix\nmodule names with <code>atl::</code>. Alternatively, group all <code>use</code>\ndeclarations together, which I prefer: (I recommend the same for\n<code>use</code> declarations in other files)</li>\n</ul>\n<pre class=\"lang-rust prettyprint-override\"><code>use {\n atl::{nfa::NFA, state::State, symbol::Symbol},\n std::{\n collections::{HashMap, HashSet},\n iter::FromIterator,\n },\n};\n</code></pre>\n<h1><code>clippy</code></h1>\n<p>Running <code>cargo clippy</code> results in more warnings:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>warning: name `DFA` contains a capitalized acronym\n --&gt; src\\dfa\\mod.rs:8:12\n |\n8 | pub struct DFA {\n | ^^^ help: consider making the acronym lowercase, except the initial letter: `Dfa`\n |\n = note: `#[warn(clippy::upper_case_acronyms)]` on by default\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#upper_case_acronyms\n\nwarning: name `NFA` contains a capitalized acronym\n --&gt; src\\nfa\\mod.rs:12:12\n |\n12 | pub struct NFA {\n | ^^^ help: consider making the acronym lowercase, except the initial letter: `Nfa`\n |\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#upper_case_acronyms\n\nwarning: use of `expect` followed by a function call\n --&gt; src\\dfa\\mod.rs:43:22\n |\n43 | .expect(&amp;format!(\n | ______________________^\n44 | | &quot;No transition found for ({:?}, {:?})&quot;,\n45 | | *current_state, symbol\n46 | | ))\n | |______________________^ help: try this: `unwrap_or_else(|| panic!(&quot;No transition found for ({:?}, {:?})&quot;, *current_state, symbol))`\n |\n = note: `#[warn(clippy::expect_fun_call)]` on by default\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#expect_fun_call\n\nwarning: use of `expect` followed by a function call\n --&gt; src\\nfa\\mod.rs:51:14\n |\n51 | .expect(&amp;format!(&quot;No transition found for ({:?}, {:?})&quot;, state, ch));\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `unwrap_or_else(|| panic!(&quot;No transition found for ({:?}, {:?})&quot;, state, ch))`\n |\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#expect_fun_call\n\nwarning: 4 warnings emitted\n\nwarning: redundant clone\n --&gt; src\\main.rs:36:15\n |\n36 | states.clone(),\n | ^^^^^^^^ help: remove this\n |\n = note: `#[warn(clippy::redundant_clone)]` on by default\nnote: this value is dropped without further use\n --&gt; src\\main.rs:36:9\n |\n36 | states.clone(),\n | ^^^^^^\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_clone\n\nwarning: redundant clone\n --&gt; src\\main.rs:37:17\n |\n37 | alphabet.clone(),\n | ^^^^^^^^ help: remove this\n |\nnote: this value is dropped without further use\n --&gt; src\\main.rs:37:9\n |\n37 | alphabet.clone(),\n | ^^^^^^^^\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_clone\n\nwarning: redundant clone\n --&gt; src\\main.rs:39:28\n |\n39 | transition_function.clone(),\n | ^^^^^^^^ help: remove this\n |\nnote: this value is dropped without further use\n --&gt; src\\main.rs:39:9\n |\n39 | transition_function.clone(),\n | ^^^^^^^^^^^^^^^^^^^\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_clone\n\nwarning: redundant clone\n --&gt; src\\main.rs:40:25\n |\n40 | accepting_states.clone(),\n | ^^^^^^^^ help: remove this\n |\nnote: this value is dropped without further use\n --&gt; src\\main.rs:40:9\n |\n40 | accepting_states.clone(),\n | ^^^^^^^^^^^^^^^^\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_clone\n\nwarning: usage of `FromIterator::from_iter`\n --&gt; src\\main.rs:20:9\n |\n20 | HashSet::from_iter([State::new(1), State::new(2)].iter().cloned()),\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use `.collect()` instead of `::from_iter()`: `[State::new(1), State::new(2)].iter().cloned().collect::&lt;HashSet::from_iter([State::new(1), State&lt;_&gt;&gt;()`\n |\n = note: `#[warn(clippy::from_iter_instead_of_collect)]` on by default\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#from_iter_instead_of_collect\n\nwarning: usage of `FromIterator::from_iter`\n --&gt; src\\main.rs:24:9\n |\n24 | HashSet::from_iter([State::new(2)].iter().cloned()),\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use `.collect()` instead of `::from_iter()`: `[State::new(2)].iter().cloned().collect::&lt;HashSet::from_iter([State&lt;_&gt;&gt;()`\n |\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#from_iter_instead_of_collect\n\nwarning: usage of `FromIterator::from_iter`\n --&gt; src\\main.rs:28:9\n |\n28 | HashSet::from_iter([State::new(2)].iter().cloned()),\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use `.collect()` instead of `::from_iter()`: `[State::new(2)].iter().cloned().collect::&lt;HashSet::from_iter([State&lt;_&gt;&gt;()`\n |\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#from_iter_instead_of_collect\n\nwarning: usage of `FromIterator::from_iter`\n --&gt; src\\main.rs:32:9\n |\n32 | HashSet::from_iter([State::new(2)].iter().cloned()),\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: use `.collect()` instead of `::from_iter()`: `[State::new(2)].iter().cloned().collect::&lt;HashSet::from_iter([State&lt;_&gt;&gt;()`\n |\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#from_iter_instead_of_collect\n\nwarning: 8 warnings emitted\n</code></pre>\n<p>There are four groups of warnings here:</p>\n<ol>\n<li><p>According to the standard Rust naming conventions, <a href=\"https://rust-lang.github.io/rust-clippy/master/index.html#upper_case_acronyms\" rel=\"nofollow noreferrer\">acronyms are\ncapitalized as one word in <code>CamelCase</code> names</a>, so <code>DFA</code> and <code>NFA</code>\nare supposed to be <code>Dfa</code> and <code>Nfa</code> respectively.</p>\n</li>\n<li><p>The argument to <code>expect</code> is <a href=\"https://rust-lang.github.io/rust-clippy/master/index.html#expect_fun_call\" rel=\"nofollow noreferrer\">always evaluated even if it is not\nused</a>. Use <code>unwrap_or_else(|| panic!(/* ... */))</code> instead.</p>\n</li>\n<li><p>When a value is used the last time, <a href=\"https://rust-lang.github.io/rust-clippy/master/index.html#redundant_clone\" rel=\"nofollow noreferrer\">it can be moved instead of\ncloned</a> to save allocations.</p>\n</li>\n<li><p><code>from_iter</code> is not supposed to be used directly — <a href=\"https://rust-lang.github.io/rust-clippy/master/index.html#from_iter_instead_of_collect\" rel=\"nofollow noreferrer\">use\n<code>collect</code> instead</a>.</p>\n</li>\n</ol>\n<h1>Synchronization model</h1>\n<p>You created a <code>bool</code> channel, sent <code>false</code> and <code>true</code> values to report\nthe results of each step, waited to receive a <code>true</code> value, and then\nwaited for all the threads to finish computing, only to get their\nresults discarded.</p>\n<p>This model is inefficient. Perhaps we can use a <code>AtomicBool</code> as the\nsuccess flag and make all workers stop when a successful result is\nobtained.</p>\n<h1>Miscellaneous</h1>\n<p>Let's go through the code.</p>\n<p>This is a scary number:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>const WORKER_COUNT: usize = 1024;\n</code></pre>\n<p>Are you sure the system you are working with is actually capable of\nrunning <code>1024</code> threads concurrently? If not, you are probably just\nadding the overhead of spawning threads. A more appropriate value\nmight be somewhere around <code>4</code> or <code>8</code>, depending on the system. See\n<a href=\"https://softwareengineering.stackexchange.com/q/238729\">Can recursion be done in parallel? Would that make sense?</a>.</p>\n<p>Instead of constructors like this:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>pub fn new(\n states: HashSet&lt;State&gt;,\n alphabet: HashSet&lt;Symbol&gt;,\n start: State,\n transition_function: HashMap&lt;(State, Symbol), HashSet&lt;State&gt;&gt;,\n accepting_states: HashSet&lt;State&gt;,\n) -&gt; Nfa {\n Nfa {\n states,\n alphabet,\n start,\n transition_function,\n accepting_states,\n }\n}\n</code></pre>\n<p>just mark the fields <code>pub</code>. We don't even need <code>add_transition</code>.</p>\n<p>When you clone something righteously, use <code>clone</code>, not <code>to_owned</code>.</p>\n<p>Instead of <code>let mut state = state;</code>, simply mark the argument <code>mut</code>.</p>\n<p>Types like <code>State</code> are usually defined as tuple structs:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>#[derive(/* ... */)]\npub struct State(pub i32);\n</code></pre>\n<p>(Note that I skipped the tests since you didn't post them, but there\nare many opportunities for improvement in them as well!)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T13:42:12.483", "Id": "519866", "Score": "0", "body": "Thank you! This is a very thorough and thoughtful answer! Would you mind commenting on these questions?\n\n\"Are there good quality unit tests that could be written for the parallelization? Can I improve the use of locks here? I think I abused the Copy and Clone traits, is there a way to reduce their use?\"\n\nAnd also, any suggestions about tests would be very much appreciated! I feel like I upgraded my Rust skills a lot just from reading your answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T14:22:56.207", "Id": "519869", "Score": "1", "body": "@alexfertel Glad to be of help! I don't think parallelism is a big concern when writing tests - just testing the results should be fine. Some benchmarking may also be helpful. I briefly discussed the locking issue in the section \"Synchronization model\", but there are always different options and tradeoffs for synchronization - I'm not an expert on this either :) I don't really see how you \"abused the Copy and Clone traits\", so don't worry about that. Cloning isn't problematic in and of itself; appropriately placed `.clone()`s are nothing to worry about if the semantics calls for them." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T08:03:44.133", "Id": "263313", "ParentId": "263267", "Score": "2" } } ]
{ "AcceptedAnswerId": "263313", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T04:26:33.000", "Id": "263267", "Score": "5", "Tags": [ "rust" ], "Title": "Parallel word recognition in a Non-deterministic finite automaton in Rust" }
263267
<p>Created FilePickerComponent recently. I'm new to React/Web development. Could you please help reviewing this code -</p> <pre><code>export const FilePickerButton: React.FunctionComponent&lt;FilePickerButtonFCProps&gt; = ({ position, ariaLabel, ariaDescription, disabled, iconName, toolbarButtonId, acceptParams, onClickEvent, ...props }) =&gt; { const uploadRef = React.useRef&lt;HTMLInputElement&gt;(null); const fileUploadRefLink: (e: FluentButtonEventType) =&gt; void = React.useCallback( (e) =&gt; { uploadRef.current?.click(); const currentTarget = e.currentTarget as HTMLElement; (currentTarget.closest('.ms-Button') as HTMLElement)?.blur(); }, [uploadRef] ); const onClick = React.useCallback((e) =&gt; { // uploading same file again works with clearing up cache e.target.value = ''; }, []); return ( &lt;&gt; &lt;input type=&quot;file&quot; ref={uploadRef} id={`${toolbarButtonId}`} accept={acceptParams} onChange={onClickEvent} onClick={onClick} className=&quot;fileUploadPicker&quot; /&gt; &lt;ToolbarButton ariaLabel={ariaLabel} ariaDescription={ariaDescription} disabled={disabled} iconName={iconName} id={toolbarButtonId} position={position} onClick={fileUploadRefLink} {...props} /&gt; &lt;/&gt; ); }; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T06:03:17.823", "Id": "263268", "Score": "2", "Tags": [ "react.js", "jsx" ], "Title": "File Picker Component - React" }
263268
<p>This is a Python script that generates ngrams using a set of rules of what letters can follow a letter stored in a dictionary.</p> <p>The output is then preliminarily processed using another script, then it will be filtered further using an api of sorts by number of words containing the ngrams, the result will be used in pseudoword generation.</p> <p>This is the generation part:</p> <pre class="lang-py prettyprint-override"><code>from string import ascii_lowercase import sys LETTERS = set(ascii_lowercase) VOWELS = set('aeiouy') CONSONANTS = LETTERS - VOWELS BASETAILS = { 'a': CONSONANTS, 'b': 'bjlr', 'c': 'chjklr', 'd': 'dgjw', 'e': CONSONANTS, 'f': 'fjlr', 'g': 'ghjlrw', 'h': '', 'i': CONSONANTS, 'j': '', 'k': 'hklrvw', 'l': 'l', 'm': 'cm', 'n': 'gn', 'o': CONSONANTS, 'p': 'fhlprst', 'q': '', 'r': 'hrw', 's': 'chjklmnpqstw', 't': 'hjrstw', 'u': CONSONANTS, 'v': 'lv', 'w': 'hr', 'x': 'h', 'y': 'sv', 'z': 'hlvw' } tails = dict() for i in ascii_lowercase: v = BASETAILS[i] if type(v) == set: v = ''.join(sorted(v)) tails.update({i: ''.join(sorted('aeiou' + v))}) def makechain(invar, target, depth=0): depth += 1 if type(invar) == str: invar = set(invar) chain = invar.copy() if depth == target: return sorted(chain) else: for i in invar: for j in tails[i[-1]]: chain.add(i + j) return makechain(chain, target, depth) if __name__ == '__main__': invar = sys.argv[1] target = int(sys.argv[2]) if invar in globals(): invar = eval(invar) print(*makechain(invar, target), sep='\n') </code></pre> <p>I want to ask about the <code>makechain</code> function, I used <code>set</code>s because somehow the results can contain duplicates if I used <code>list</code>s, though the result can be cast to <code>set</code>, I used a nested <code>for</code> loop and a recursive function to simulate a variable number of for loops.</p> <p>For example, <code>makechain(LETTERS, 4)</code> is equivalent to:</p> <pre class="lang-py prettyprint-override"><code>chain = set() for a in LETTERS: chain.add(a) for a in LETTERS: for b in tails[a]: chain.add(a + b) for a in LETTERS: for b in tails[a]: for c in tails[b]: chain.add(a + b + c) for a in LETTERS: for b in tails[a]: for c in tails[b]: for d in tails[c]: chain.add(a + b + c + d) </code></pre> <p>Obviously <code>makechain(LETTERS, 4)</code> is much better than the nested for loop approach, it is much more flexible.</p> <p>I want to know, is there anyway I can use a function from <code>itertools</code> instead of the nested <code>for</code> loop to generate the same results more efficiently?</p> <p>I am thinking about <code>itertools.product</code> and <code>itertools.combinations</code> but I just can't figure out how to do it.</p> <p>Any help will be appreciated.</p>
[]
[ { "body": "<blockquote>\n<p>Any help will be appreciated</p>\n</blockquote>\n<p>A few suggestions on something that I noticed:</p>\n<ul>\n<li><p>In the function <code>makechain</code> the <code>else</code> after the <code>return</code> is not necessary.</p>\n</li>\n<li><p>Typo in: <code>VOWELS = set('aeiouy')</code>, there is an extra <code>y</code>.</p>\n</li>\n<li><p>This part:</p>\n<pre><code>LETTERS = set(ascii_lowercase)\nVOWELS = set('aeiou')\nCONSONANTS = LETTERS - VOWELS\n\nBASETAILS = {\n 'a': CONSONANTS,\n 'b': 'bjlr',\n 'c': 'chjklr',\n 'd': 'dgjw',\n ....\n }\n\ntails = dict()\n\nfor i in ascii_lowercase:\n v = BASETAILS[i]\n if type(v) == set:\n v = ''.join(sorted(v))\n tails.update({i: ''.join(sorted('aeiou' + v))})\n</code></pre>\n<p>seems to do the following:</p>\n<ol>\n<li>Create a dictionary with mixed value's type (strings and sets)</li>\n<li>Convert all values to string</li>\n<li>Sort dictionary's values</li>\n</ol>\n<p>It could be simplified to:</p>\n<ol>\n<li>Create a dictionary where all values are strings</li>\n<li>Sort dictionary's values</li>\n</ol>\n<p>Additionally, having <code>VOWELS</code> as a set and <code>CONSONANTS</code> as a string is a bit confusing. Would be better to use only one type.</p>\n<p>Code with suggestions above:</p>\n<pre><code>LETTERS = ascii_lowercase\nVOWELS = 'aeiou'\nCONSONANTS = ''.join(set(LETTERS) - set(VOWELS))\n\nBASETAILS = {\n 'a': CONSONANTS,\n 'b': 'bjlr',\n 'c': 'chjklr',\n 'd': 'dgjw',\n ....\n }\n\ntails = dict()\n\nfor i in ascii_lowercase:\n v = BASETAILS[i]\n tails.update({i: ''.join(sorted(VOWELS + v))})\n</code></pre>\n<p>In this way, you also avoid sorting twice.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T11:05:14.927", "Id": "263279", "ParentId": "263271", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T06:58:24.067", "Id": "263271", "Score": "3", "Tags": [ "python", "performance", "beginner", "python-3.x" ], "Title": "Python script that makes ngrams" }
263271
<p>This is a Python 3.9 script that pulls data from a MySQL database and converts it to a list of named tuples and then passing it to <code>PyQt6.QTreeWidget</code>.</p> <p>It has to be a <code>list</code> of <code>namedtuples</code>, because I am going to store lists of tags packed in strings dumped from <code>json.dumps</code> in single fields, then using <code>json.loads</code> to unpack the lists. This way, filter by tags can easily done with <code>issubset</code>method.</p> <p>This will be the main interface of a GUI music player project I am working on, though it is still bare bones, at least the tree hierarchy part is complete.</p> <p>This is the glimpse of the database:</p> <p><a href="https://i.stack.imgur.com/NMd2R.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NMd2R.jpg" alt="enter image description here" /></a></p> <p>This is what the window looks like:</p> <p><a href="https://i.stack.imgur.com/AfUFg.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AfUFg.jpg" alt="enter image description here" /></a></p> <p>And here is the code:</p> <pre class="lang-py prettyprint-override"><code>import sys import mysql.connector from collections import namedtuple from PyQt6.QtWidgets import QApplication, QTreeWidget, QTreeWidgetItem song = namedtuple('song', 'artist title album') app = QApplication(sys.argv) conn = mysql.connector.connect(user='Estranger', password=********, host='127.0.0.1', port=3306, database='Music') cursor = conn.cursor() cursor.execute('select artist, title, album from songs') songs = [song(*i) for i in cursor.fetchall()] conn.commit() tree = QTreeWidget() tree.resize(1280,720) tree.setWindowTitle('tree') frame = tree.frameGeometry() center = tree.screen().availableGeometry().center() frame.moveCenter(center) tree.move(frame.topLeft()) tree.setColumnCount(4) tree.setHeaderLabels(['Name', 'Artist', 'Album', 'Title']) entries = [] for p in sorted(set([_.artist for _ in songs])): artist = QTreeWidgetItem([p]) for a in sorted(set([_.album for _ in songs if _.artist == p])): album = QTreeWidgetItem([a, p, a]) for s in [_.title for _ in songs if _.artist == p and _.album == a]: song = QTreeWidgetItem([s, p, a, s]) album.addChild(song) artist.addChild(album) entries.append(artist) tree.insertTopLevelItems(0, entries) tree.show() sys.exit(app.exec()) </code></pre> <p>(Password obscured for obvious reasons)</p> <p>I adapted my code from here: <a href="https://doc.qt.io/qtforpython-6/tutorials/basictutorial/treewidget.html" rel="nofollow noreferrer">https://doc.qt.io/qtforpython-6/tutorials/basictutorial/treewidget.html</a></p> <p>The code there:</p> <pre class="lang-py prettyprint-override"><code>import sys from PySide6.QtWidgets import QApplication, QTreeWidget, QTreeWidgetItem data = {&quot;Project A&quot;: [&quot;file_a.py&quot;, &quot;file_a.txt&quot;, &quot;something.xls&quot;], &quot;Project B&quot;: [&quot;file_b.csv&quot;, &quot;photo.jpg&quot;], &quot;Project C&quot;: []} app = QApplication() tree = QTreeWidget() tree.setColumnCount(2) tree.setHeaderLabels([&quot;Name&quot;, &quot;Type&quot;]) items = [] for key, values in data.items(): item = QTreeWidgetItem([key]) for value in values: ext = value.split(&quot;.&quot;)[-1].upper() child = QTreeWidgetItem([value, ext]) item.addChild(child) items.append(item) tree.insertTopLevelItems(0, items) tree.show() sys.exit(app.exec()) </code></pre> <p>In the example, the data is already hierarchical, it is a dictionary structured like a tree, but my data is a list of named tuples which is kind of flat and more suitable for a table.</p> <p>But I prefer using a tree-like view to present the data.</p> <p>Because my data is flat, and the example code structure needs the data to be hierarchical, I used list comprehensions plus cast to <code>set</code> plus <code>sorted</code> function to make the hierarchy on the fly, which generates a lot of loops overhead, which is silly.</p> <p>I am really new to this, this is my first attempt at creating a GUI program, I have Google searched for days and haven't find a way to populate a <code>QTreeView</code> or <code>QTreeWidget</code> with data from a flat list, so I wrote my own.</p> <p>My question is, what is a smarter, more efficient way to achieve the same result (populate a tree-like structure with data from a list of named tuples), and how can I use <code>QTreeView</code> instead of <code>QTreeWidget</code>(if there is any difference)?</p> <p>Any help is appreciated.</p>
[]
[ { "body": "<ul>\n<li>You have a pile of unstructured, global code; this needs to be organized into functions and maybe classes</li>\n<li>Close your cursor once you're done with it, ideally via context management</li>\n<li>Order your query using the database itself, to make grouping less painful; also query in order of hierarchy (artist, album, song)</li>\n<li>You don't need <code>entries</code>; just add items one at a time</li>\n<li>4 should not be hard-coded</li>\n<li>Your repeated set comprehensions can be greatly simplified (i.e. abolished) via <code>itertools.groupby</code></li>\n</ul>\n<p>This example code localises the MySQL import because I don't have it; I've generated fake data instead.</p>\n<pre><code>import sys\nfrom dataclasses import dataclass\nfrom itertools import groupby\nfrom typing import Iterable, Callable\n\nfrom PyQt6.QtWidgets import QApplication, QTreeWidget, QTreeWidgetItem\n\n\n@dataclass\nclass Song:\n artist: str\n album: str\n title: str\n\n @classmethod\n def from_db(cls) -&gt; Iterable['Song']:\n from mysql.connector import connect\n\n with connect(\n user='Estranger',\n password='********',\n host='127.0.0.1',\n port=3306,\n database='Music',\n ) as conn, conn.cursor() as cursor:\n cursor.execute(\n 'select artist, album, title from songs '\n 'order by artist, album'\n )\n for row in cursor.fetchall():\n yield cls(*row)\n\n @classmethod\n def fake_rows(cls) -&gt; Iterable['Song']:\n return (\n cls('Weird Al Yankovic', 'Running with Scissors', 'Pretty Fly for a Rabbi'),\n cls('Weird Al Yankovic', 'Running with Scissors', 'Albuquerque'),\n cls('Weird Al Yankovic', 'Off the Deep End', &quot;I Can't Watch This&quot;),\n cls('Weird Al Yankovic', 'Off the Deep End', 'Smells like Nirvana'),\n cls('The Arrogant Worms', &quot;C'est Cheese&quot;, 'Mounted Animal Nature Trail'),\n )\n\n def by_artist(self): return self.artist\n def by_album(self): return self.album\n\n\nclass GUI:\n HEADERS = ('Name', 'Artist', 'Album', 'Title')\n\n def __init__(self, songs):\n app = QApplication(sys.argv)\n\n tree = QTreeWidget()\n # a reference needs to be held or this will be garbage-collected\n self.tree = tree\n tree.resize(1280, 720)\n tree.setWindowTitle('tree')\n frame = tree.frameGeometry()\n center = tree.screen().availableGeometry().center()\n frame.moveCenter(center)\n tree.move(frame.topLeft())\n tree.setColumnCount(len(self.HEADERS))\n tree.setHeaderLabels(self.HEADERS)\n\n for artist, after_artist in groupby(songs, Song.by_artist):\n artist_node = QTreeWidgetItem((artist,))\n for album, after_album in groupby(after_artist, Song.by_album):\n album_node = QTreeWidgetItem((album, artist, album))\n for song in after_album:\n song_node = QTreeWidgetItem((song.title, artist, album, song.title))\n album_node.addChild(song_node)\n artist_node.addChild(album_node)\n tree.addTopLevelItem(artist_node)\n\n tree.show()\n\n self.run: Callable[[], int] = app.exec\n\n\ndef main() -&gt; None:\n songs = Song.fake_rows()\n gui = GUI(songs)\n exit(gui.run())\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/PJIYp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PJIYp.png\" alt=\"test run\" /></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T19:56:59.927", "Id": "263294", "ParentId": "263273", "Score": "5" } } ]
{ "AcceptedAnswerId": "263294", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T08:01:46.040", "Id": "263273", "Score": "4", "Tags": [ "python", "performance", "python-3.x", "gui", "pyqt" ], "Title": "Python PyQt6 populate QTreeWidget with a list of named tuples" }
263273
<p>No problem yet with the code.</p> <p>Here is a function that can be saved as add in and used as UDF in Microsoft excel to convert a number to text. For example, <code>4556.45</code> to <code>RUPEES Four Thousand Five Hundred Fifty Six &amp; PAISE Forty Five</code> (Defaults being set to Indian Rupee). But the function can be adopted to <strong>any currency</strong> through suitable parameters making it <strong>very flexible</strong>. Submitting for review. Kindly suggest any modifications required. Thank you.</p> <hr /> <p>Function Arguments</p> <p>myNumber = Number to be converted to text</p> <hr /> <p>Optional NumberSystem = DEFAULT Value = 2, 1 for International (Thousand,Million,Billion), 2 for Indian (Thousand,Lakh,Crore), Default Value 1</p> <hr /> <p>Optional CurrencyConversion = DEFAULT Value = &quot;YES&quot;, _ Yes to convert the number to currency, Default Value Yes.</p> <hr /> <p>Optional CurrSYMSingular = DEFAULT Value = &quot;RUPEE&quot;, 'for example USD or US DOLLAR, INR or Indian Rupee for one unit of currency, Default Value Rupee</p> <hr /> <p>Optional CurrSYMPlural = DEFAULT Value = &quot;RUPEES&quot;, for example USDs or US DOLLARs, INRs or Indian Rupees for multiple units of currency, Default Value Rupees</p> <hr /> <p>Optional FractionSize = DEFAULT Value = 100, _ for example 100 for one INR = 100 Paise, one USD = 100 Cents, Default value 100</p> <hr /> <p>Optional FracSYMSingular = DEFAULT Value = &quot;PAISA&quot;, for example Cent for US DOLLAR, Paisa for Indian Rupee for one unit of currency fraction, Default Value Paisa</p> <hr /> <p>Optional FracSYMPlural = DEFAULT Value = &quot;PAISE&quot;, for example Cents for US DOLLAR, Paise for Indian Rupee for multiple units of currency fraction, Default Value Paise</p> <hr /> <p>Optional TextStyle = DEFAULT Value = 1 1 for CurrencySYM and Amount, 2 for Amount and CurrencySYM, Default Value 1&quot;</p> <hr /> <p><strong>Main function</strong> and other private functions supporting it are as below.</p> <pre><code>Function TextCurrency(ByVal myNumber, Optional NumberSystem = 2, Optional CurrencyConversion = &quot;YES&quot;, _ Optional CurrSYMSingular = &quot;RUPEE&quot;, Optional CurrSYMPlural = &quot;RUPEES&quot;, Optional FractionSize = 100, _ Optional FracSYMSingular = &quot;PAISA&quot;, Optional FracSYMPlural = &quot;PAISE&quot;, Optional TextStyle = 1) 'Refer to following webpage for fractional units and sizes of different currencies 'https://en.wikipedia.org/wiki/List_of_circulating_currencies ' Maximum fraction size is 1000 (eg. OMR). Dim Temp, myNumberInt, myNumberFrac, DecimalPlace, Count, RUPEEs, PAISE If Val(myNumber) &lt;&gt; 0 Then myNumber = Trim(Str(myNumber)) DecimalPlace = InStr(myNumber, &quot;.&quot;) End If If DecimalPlace &gt; 0 Then myNumberInt = Trim(Left(myNumber, DecimalPlace - 1)) myNumberFrac = Trim(Mid(myNumber, DecimalPlace + 1)) If UCase(CurrencyConversion) = &quot;YES&quot; Then If FractionSize &lt;= 1000 Then myNumberFrac = Left(myNumberFrac &amp; &quot;000&quot;, 3) If FractionSize &lt;= 100 Then myNumberFrac = Left(myNumberFrac &amp; &quot;00&quot;, 2) If FractionSize &lt;= 10 Then myNumberFrac = Left(myNumberFrac &amp; &quot;0&quot;, 1) End If Else myNumberInt = myNumber End If If NumberSystem = 2 Then If Val(myNumberFrac) &lt;&gt; 0 Then TextCurrency = NumberINTtoINDtext(myNumberInt) &amp; &quot; POINT &quot; &amp; NumberFRACtotext(myNumber) Else TextCurrency = NumberINTtoINDtext(myNumberInt) End If Else If Val(myNumberFrac) &lt;&gt; 0 Then TextCurrency = NumberINTtotext(myNumberInt) &amp; &quot; POINT &quot; &amp; NumberFRACtotext(myNumber) Else TextCurrency = NumberINTtotext(myNumberInt) End If End If If UCase(CurrencyConversion) = &quot;YES&quot; Then If NumberSystem = 2 Then If Val(myNumberFrac) &lt;&gt; 0 Then RUPEEs = NumberINTtoINDtext(myNumberInt) PAISE = NumberINTtotext(myNumberFrac) Else RUPEEs = NumberINTtoINDtext(myNumberInt) End If Else If Val(myNumberFrac) &lt;&gt; 0 Then RUPEEs = NumberINTtotext(myNumberInt) PAISE = NumberINTtotext(myNumberFrac) Else RUPEEs = NumberINTtotext(myNumberInt) End If End If If Val(myNumber) = 0 Then TextCurrency = CurrSYMSingular &amp; &quot; &quot; &amp; &quot;ZERO&quot; If TextStyle = 1 Then Select Case RUPEEs Case &quot;&quot; RUPEEs = &quot;&quot; Case &quot;One&quot; RUPEEs = CurrSYMSingular &amp; &quot; One&quot; Case Else RUPEEs = CurrSYMPlural &amp; &quot; &quot; &amp; RUPEEs End Select Select Case PAISE Case &quot;&quot; PAISE = &quot;&quot; Case &quot;One&quot; If RUPEEs = &quot;&quot; Then PAISE = FracSYMSingular &amp; &quot; One&quot; Else PAISE = &quot; &amp; &quot; &amp; FracSYMSingular &amp; &quot; One&quot; End If Case Else If RUPEEs = &quot;&quot; Then PAISE = FracSYMPlural &amp; &quot; &quot; &amp; PAISE Else PAISE = &quot; &amp; &quot; &amp; FracSYMPlural &amp; &quot; &quot; &amp; PAISE End If End Select Else Select Case RUPEEs Case &quot;&quot; RUPEEs = &quot;&quot; Case &quot;One&quot; RUPEEs = &quot;One &quot; &amp; CurrSYMSingular Case Else RUPEEs = RUPEEs &amp; &quot; &quot; &amp; CurrSYMPlural End Select Select Case PAISE Case &quot;&quot; PAISE = &quot;&quot; Case &quot;One&quot; If RUPEEs = &quot;&quot; Then PAISE = &quot;One &quot; &amp; FracSYMSingular Else PAISE = &quot; &amp; One &quot; &amp; FracSYMSingular End If Case Else If RUPEEs = &quot;&quot; Then PAISE = PAISE &amp; &quot; &quot; &amp; FracSYMPlural Else PAISE = &quot; &amp; &quot; &amp; PAISE &amp; &quot; &quot; &amp; FracSYMPlural End If End Select End If TextCurrency = RUPEEs &amp; PAISE End If End Function '___________________________________________________________ Private Function ConvertHundreds(ByVal myNumber) Dim Result As String ' Exit if there is nothing to convert. If Val(myNumber) = 0 Then Exit Function ' Append leading zeros to number. myNumber = Right(&quot;000&quot; &amp; myNumber, 3) 'Debug.Print myNumber ' Do we have a hundreds place digit to convert? If Left(myNumber, 1) &lt;&gt; &quot;0&quot; Then Result = ConvertDigit(Left(myNumber, 1)) &amp; &quot; Hundred &quot; End If ' Do we have a tens place digit to convert? If Mid(myNumber, 2, 1) &lt;&gt; &quot;0&quot; Then Result = Result &amp; ConvertTens(Mid(myNumber, 2)) Else ' If not, then convert the ones place digit. Result = Result &amp; ConvertDigit(Mid(myNumber, 3)) End If ConvertHundreds = Trim(Result) End Function '___________________________________________________________ Private Function ConvertTens(ByVal MyTens) Dim Result As String ' Is value between 10 and 19? If Val(Left(MyTens, 1)) = 1 Then Select Case Val(MyTens) Case 10: Result = &quot;Ten&quot; Case 11: Result = &quot;Eleven&quot; Case 12: Result = &quot;Twelve&quot; Case 13: Result = &quot;Thirteen&quot; Case 14: Result = &quot;Fourteen&quot; Case 15: Result = &quot;Fifteen&quot; Case 16: Result = &quot;Sixteen&quot; Case 17: Result = &quot;Seventeen&quot; Case 18: Result = &quot;Eighteen&quot; Case 19: Result = &quot;Nineteen&quot; Case Else End Select Else ' .. otherwise it's between 20 and 99. Select Case Val(Left(MyTens, 1)) Case 2: Result = &quot;Twenty &quot; Case 3: Result = &quot;Thirty &quot; Case 4: Result = &quot;Forty &quot; Case 5: Result = &quot;Fifty &quot; Case 6: Result = &quot;Sixty &quot; Case 7: Result = &quot;Seventy &quot; Case 8: Result = &quot;Eighty &quot; Case 9: Result = &quot;Ninety &quot; Case Else End Select ' Convert ones place digit. Result = Result &amp; ConvertDigit(Right(MyTens, 1)) End If ConvertTens = Result End Function '___________________________________________________________ Private Function ConvertDigit(ByVal MyDigit) Select Case Val(MyDigit) Case 1: ConvertDigit = &quot;One&quot; Case 2: ConvertDigit = &quot;Two&quot; Case 3: ConvertDigit = &quot;Three&quot; Case 4: ConvertDigit = &quot;Four&quot; Case 5: ConvertDigit = &quot;Five&quot; Case 6: ConvertDigit = &quot;Six&quot; Case 7: ConvertDigit = &quot;Seven&quot; Case 8: ConvertDigit = &quot;Eight&quot; Case 9: ConvertDigit = &quot;Nine&quot; Case Else: ConvertDigit = &quot;&quot; End Select End Function '___________________________________________________________ Private Function NumberINTtotext(ByVal myNumber) If Len(myNumber) = 0 Or IsNumeric(myNumber) = False Then NumberINTtotext = &quot;&quot; Exit Function End If Dim Temp Dim myNumberInt, myNumberInteger Dim DecimalPlace, Count ReDim Place(9) As String Place(2) = &quot; Thousand &quot; Place(3) = &quot; Million &quot; Place(4) = &quot; Billion &quot; Place(5) = &quot; Trillion &quot; ' Convert MyNumber to a string, trimming extra spaces. myNumber = Trim(Str(myNumber)) ' Find decimal place. DecimalPlace = InStr(myNumber, &quot;.&quot;) ' If we find decimal place... If DecimalPlace &gt; 0 Then myNumberInt = Trim(Left(myNumber, DecimalPlace - 1)) Else myNumberInt = Trim(myNumber) End If If Val(myNumberInt) &lt;&gt; 0 Then Count = 1 Do While myNumberInt &lt;&gt; &quot;&quot; ' Convert last 3 digits of MyNumber to English GBP. Temp = ConvertHundreds(Right(myNumberInt, 3)) If Temp &lt;&gt; &quot;&quot; Then myNumberInteger = Temp &amp; Place(Count) &amp; myNumberInteger If Len(myNumberInt) &gt; 3 Then ' Remove last 3 converted digits from MyNumber. myNumberInt = Left(myNumberInt, Len(myNumberInt) - 3) Else myNumberInt = &quot;&quot; End If Count = Count + 1 Loop Else myNumberInteger = &quot;ZERO&quot; End If NumberINTtotext = myNumberInteger If Val(myNumber) = 0 Then NumberINTtotext = &quot;ZERO&quot; End Function '___________________________________________________________ Private Function NumberINTtoINDtext(ByVal myNumber) If Len(myNumber) = 0 Or Val(myNumber) = 0 Or IsNumeric(myNumber) = False Then NumberINTtoINDtext = &quot;&quot; Exit Function End If Dim Temp Dim RUPEEs, PAISE Dim DecimalPlace, Count ReDim Place(9) As String Place(2) = &quot; Thousand &quot; Place(3) = &quot; Lac &quot; Place(4) = &quot; Crore &quot; 'Place(5) = &quot; Arawb &quot; 'Place(6) = &quot; Kharawb &quot; 'Place(7) = &quot; Neel &quot; myNumber = Trim(Str(myNumber)) DecimalPlace = InStr(myNumber, &quot;.&quot;) If DecimalPlace &gt; 0 Then myNumber = Trim(Left(myNumber, DecimalPlace - 1)) End If Do Count = 2 If Len(myNumber) &gt; 0 Then Hundreds = ConvertHundreds(Right(myNumber, WorksheetFunction.Min(3, Len(myNumber)))) RUPEEs = Hundreds &amp; RUPEEs myNumber = Left(myNumber, Len(myNumber) - WorksheetFunction.Min(3, Len(myNumber))) End If Do While Count &lt; 4 Temp = ConvertHundreds(Right(myNumber, WorksheetFunction.Min(2, Len(myNumber)))) If Temp &lt;&gt; &quot;&quot; Then RUPEEs = Temp &amp; Place(Count) &amp; RUPEEs myNumber = Left(myNumber, Len(myNumber) - WorksheetFunction.Min(2, Len(myNumber))) Count = Count + 1 Loop If Len(myNumber) &lt;&gt; 0 And Count = 4 Then RUPEEs = &quot; Crore &quot; &amp; RUPEEs Loop While Val(Len(myNumber)) &gt; 0 NumberINTtoINDtext = RUPEEs End Function '___________________________________________________________ Private Function NumberFRACtotext(ByVal myNumber) Dim Temp, myNumberFrac, myNumberFraction, DecimalPlace, Count If Len(myNumber) = 0 Or IsNumeric(myNumber) = False Then NumberFRACtotext = &quot;&quot; Exit Function End If ' Convert MyNumber to a string, trimming extra spaces. myNumber = Trim(Str(myNumber)) ' Find decimal place. DecimalPlace = InStr(myNumber, &quot;.&quot;) ' If we find decimal place... If DecimalPlace &gt; 0 Then myNumberFrac = Trim(Mid(myNumber, DecimalPlace + 1)) Else NumberFRACtotext = &quot;ZERO&quot; Exit Function End If Count = DecimalPlace + 1 Temp = &quot;&quot; Do While Val(Mid(myNumber, Count, 1)) = 0 Temp = Temp &amp; &quot;ZERO &quot; Count = Count + 1 Loop Do While Count &lt;&gt; Len(myNumber) + 1 If Val(Mid(myNumber, Count, 1)) = 0 Then Temp = Temp &amp; &quot;ZERO &quot; Else Temp = Temp &amp; ConvertDigit(Val(Mid(myNumber, Count, 1))) &amp; &quot; &quot; End If Count = Count + 1 Loop NumberFRACtotext = Temp End Function </code></pre> <p>After installing the function as add-in and before using the function, run this procedure to see the parameter descriptions in the function dialogue box. Better to save such procedures in personal excel book and to make it run on excel start.</p> <pre><code>Sub AddUDFToCustomCategory() Application.MacroOptions Macro:=&quot;TextCurrency&quot;, Description:=&quot;Converts number to text&quot;, _ ArgumentDescriptions:=Array(&quot;Number to be converted to text&quot;, _ &quot;1 for International (Thousand,Million,Billion),&quot; &amp; vbCrLf &amp; &quot;2 for Indian (Thousand,Lakh,Crore),&quot; &amp; vbCrLf &amp; &quot;Default Value 2&quot;, _ &quot;Yes to convert the number to currency, Else please enter No&quot; &amp; vbCrLf &amp; &quot;Make sure the number is rounded to best suit the fraction size of the desired currency&quot; &amp; vbCrLf &amp; &quot;Default Value Yes&quot;, _ &quot;for example USD or US DOLLAR, INR or Indian Rupee for one unit of currency,&quot; &amp; vbCrLf &amp; &quot;Default Value Rupee&quot;, _ &quot;for example USDs or US DOLLARs, INRs or Indian Rupees for multiple units of currency,&quot; &amp; vbCrLf &amp; &quot;Default Value Rupees&quot;, _ &quot;for example 100&quot; &amp; vbCrLf &amp; &quot;for one INR = 100 Paise, one USD = 100 Cents, One OMR = 1000 Baizas&quot; &amp; vbCrLf &amp; &quot;Default value 100&quot;, _ &quot;for example Cent for US DOLLAR, Paisa for Indian Rupee for one unit of currency fraction,&quot; &amp; vbCrLf &amp; &quot;Default Value Paisa&quot;, _ &quot;for example Cents for US DOLLAR, Paise for Indian Rupee for multiple units of currency fraction,&quot; &amp; vbCrLf &amp; &quot;Default Value Paise&quot;, _ &quot;1 for CurrencySYM and Amount, for eample USD One Hundred Fifty,&quot; &amp; vbCrLf &amp; &quot;2 for Amount and CurrencySYM, for eample One Hundred Fifty USD&quot; &amp; vbCrLf &amp; &quot;Default Value 1&quot;) End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T06:40:13.720", "Id": "519852", "Score": "0", "body": "For numbers, one can also refer to [Microsoft webpage](https://support.microsoft.com/en-us/office/convert-numbers-into-words-a0d166fb-e1ea-4090-95c8-69442cd55d98)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T06:41:39.590", "Id": "519853", "Score": "2", "body": "I have rolled back your edits. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T06:58:20.747", "Id": "519854", "Score": "0", "body": "@Heslacher .. Thank you; was not sure of that." } ]
[ { "body": "<p>After a <em>very</em> quick glance, at an absolute minimum, you should declare a specific <code>Type</code> for all your parameters and variables, and ensure that they're the <em>appropriate</em> type.</p>\n<p>For example, <code>CurrencyConversion</code> is a <code>Variant</code>, but it <em>should</em> be a <code>Boolean</code>, since that's how you're using it. The <code>Boolean</code> type is defined to handle simple Yes/No or True/False data types and to make dealing with them much easier. It would allow you to change:</p>\n<pre><code>If UCase(CurrencyConversion) = &quot;YES&quot; Then\n</code></pre>\n<p>to a much more simple, clear and readable:</p>\n<pre><code>If CurrencyConversion Then\n</code></pre>\n<p>You would do this by changing this part of the function signature from:</p>\n<pre><code>Optional CurrencyConversion = &quot;YES&quot;,\n</code></pre>\n<p>to:</p>\n<pre><code>Optional CurrencyConversion As Boolean = True,\n</code></pre>\n<p>You'll end up with much more readable code that's easier to use, less prone to odd run-time errors due to accidental implicit conversions or the accidental misspelling of <code>CurencyConversion</code> (which will cause the VBA run-time to create a whole new variant variable initialized to... something), <em>and</em>, as a bonus, it'll run a bit faster since the VBA run-time engine won't have to figure out what type of data it's working with each and every single time it's referencing any one of your variables.</p>\n<p>The very best way to ensure all your variables are declared is to use</p>\n<pre><code>Option Explicit\n</code></pre>\n<p>At the top of each and every code module. In fact, the VBE makes it easy to do this - simply go to the <em>Tools</em> menu, select <em>Options</em>, then ensure the <em>Require Variable Declaration</em> option is checked.\n<a href=\"https://i.stack.imgur.com/hCX6g.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/hCX6g.png\" alt=\"enter image description here\" /></a></p>\n<p>Note that this will add <code>Option Explicit</code> to all <em>new</em> modules you create, but it won't go back and add it to existing ones - you'll have to do that by hand. What it will do, though, is cause a <em>compile</em> time error any time you attempt to use an undeclared variable, and that will catch typos like using <code>CurencyConvert</code> when you meant to use <code>CurrencyConvert</code>.</p>\n<p>You can use the <a href=\"http://www.rubberduckvba.com/\" rel=\"noreferrer\">RubberDuck</a><sup>*</sup> add-in for the VBE to catch these undeclared variables and offer you a simple way to fix them. It will also catch that you're not using <code>Option Explicit</code> and offer to insert it into all your code modules for you. This is just one of the dozens of static code analysis tools it offers, as well as many, many other features that help drag the VBE much closer to the standards of other, more modern code editors.</p>\n<p><sup>*</sup>NOTE: RubberDuck is a free, open source project hosted on <a href=\"http://www.github.com/rubberduck-vba/Rubberduck\" rel=\"noreferrer\">GitHub</a>, I'm a big fan of RubberDuck and use it regularly in my daily work. I've also made a few contributions to the project.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T06:34:37.897", "Id": "519851", "Score": "1", "body": "Thank you. Edited to code as per your suggestion. Also, noticed and removed some redundant variables. Sure will get RubberDuck, new learning for me :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T11:49:10.220", "Id": "263280", "ParentId": "263277", "Score": "9" } }, { "body": "<p>While I understand it's not generally done, I'm adding a review of the <em>slightly updated</em> code which should <em>not</em> have been posted as an answer. There seem to be sufficiently few changes made that it's not that much different than the original.</p>\n<ul>\n<li>Implicit Variants - There are a large number of variables that are <code>Dim</code>med, but no type is defined. These are implicitly declared <code>Variant</code> by the runtime engine and can lead to a variety of issues, the least of which is slower execution, the worst of which is probably future programmers (including future-you) misusing a variable because the &quot;compiler&quot; doesn't warn you that you're putting a <code>String</code> where a <code>Long</code> should be (for example), leading to run-time errors.\n<ul>\n<li>One example: <code>Function TextCurrency(ByVal myNumber, ...</code> right there at the top of the code block</li>\n</ul>\n</li>\n<li>Declaring multiple values in one <code>Dim</code> statement. While there's nothing <em>inherently</em> wrong with doing so, and some may consider it simply a matter of code style, it's generally frowned upon by &quot;real&quot; programmers, mostly because:\n<ul>\n<li>It's easy to miss that there are multiple variables declared on one line - most programmers assume one declaration per physical line and mentally stop reading after the first one</li>\n<li>It's easy to forget to declare types for one or more of the variables in a line, for example, <code>Dim X, Y, Z as Long</code> is <em>assumed</em> by many to declare 3 variables of type <code>Long</code>, however, only <code>Z</code> is a <code>Long</code>, while <code>X</code> and <code>Y</code> are actually <code>Variant</code>.</li>\n<li>It's preferred to declare variables as close to their initial use as possible and declaring multiple variables on one line tends to lead to a &quot;wall of declarations&quot; and a lot of scrolling to see what's actually going on</li>\n</ul>\n</li>\n<li>Declaring variables as <code>Integer</code>.\n<ul>\n<li>Internally, VBA works with 32-bit integers (i.e. <code>Long</code>) and it converts each 16-bit <code>Integer</code> to a 32-bit <code>Long</code> each time it needs to operate on one, so you may as well just declare them all as <code>Long</code> to begin with.</li>\n<li>Frankly, there's no need to use <code>Integer</code> unless you're calling a function in some external DLL (like the WinAPI) that requires the use of a 16-bit integer.</li>\n<li>You'll gain tiny bits of performance improvement with each <code>Integer</code> to <code>Long</code> change you make (by the runtime engine <em>not</em> having to do the conversion for you), and you'll remove (or at least put off) another opportunity for an overflow error.</li>\n</ul>\n</li>\n<li>Parameters are passed <code>ByVal</code>, yet are assigned a value\n<ul>\n<li>Once again <code>Function TextCurrency(ByVal myNumber, ...</code> is a culprit. The very first <code>If</code> statement contains <code>myNumber = Trim(Str(myNumber))</code>.</li>\n<li>If you're expecting <code>myNumber</code> to be returned to the calling code different than how it's sent it, it should be <code>ByRef</code> so the changes can be reflected externally.</li>\n<li>If you're <em>not</em> expecting to be returned, it makes more sense to use a local copy of it to be explicit and to write code that &quot;Says what it does and does what it says&quot;.</li>\n</ul>\n</li>\n<li>Using <code>&quot;&quot;</code> to represent an empty string when there's a perfectly good built-in constant <code>vbNullString</code> to do so.\n<ul>\n<li>This is something of a matter of style, and it's certainly shorter to type <code>&quot;&quot;</code></li>\n<li>Using <code>vbNullString</code> makes it very explicitly clear what you mean, where <code>&quot;&quot;</code> <em>could</em> mean that you forgot to put something between those quotes.</li>\n</ul>\n</li>\n<li>Parameters are passed <code>ByRef</code> by default, but none are explicitly declared as such, and most appear to not need to be.\n<ul>\n<li>For example in <code>Function TextCurrency(ByVal myNumber, Optional NumberSystem As Byte = 2, ...</code> the 2nd parameter <code>NumberSystem</code> is passed <code>ByRef</code> but is never assigned to and could (and should) be passed <code>ByVal</code> to make it abundantly clear that this is the case</li>\n<li><code>Function TextCurrency(ByVal myNumber, Optional ByVal NumberSystem As Byte = 2, ...</code></li>\n</ul>\n</li>\n<li><code>TextCurrency</code> implicitly returns a <code>Variant</code>. You <em>did</em> remember to declare a return type for all your other functions. It should have <code>As String</code> at the end of the signature to help &quot;Say what you mean and mean what you say&quot;.</li>\n</ul>\n<p>The above are all issues that RubberDuck's Code Inspections caught (but not all the issues it found). The built in QuickFixes will give you one or more options and actually fix the code for you.</p>\n<hr>\n<p>These are other observations:</p>\n<h3>Variable Naming</h3>\n<ul>\n<li>Variable names are <em>somewhat</em> declared with Hungarian Notation, yet are inconsistent with their variable type\n<ul>\n<li><code>Dim myNumberInt As String</code> made me think that this should hold an <code>Int</code>, yet it's declared as <code>String</code>.</li>\n<li>Either the variable type is wrong or the variable name is poor.</li>\n<li>Naming variables is <em>hard</em>!</li>\n<li>Based on use, it appears that <code>myNumberInt</code> is the whole number portion of the value passed to the function. I'd suggest something like <code>inputValueIntegerPart</code>, or, maybe a simpler <code>integerPortion</code>. While that's a lot to type, the VBE <em>does</em> offer auto-complete by pressing <code>&lt;Ctrl&gt;-&lt;Space&gt;</code> which will either complete the word for you or offer up a list of everything starting with what you've typed so far, so you don't have to type the whole thing every time.</li>\n</ul>\n</li>\n<li><code>myNumber</code> isn't particularly descriptive of <em>what</em> it holds.\n<ul>\n<li>Something along the lines of <code>inputValue</code> or <code>originalCurrencyAmount</code> or <code>completeCurrencyAmount</code> are more descriptive and help you remember, many lines later, what you're dealing with.</li>\n</ul>\n</li>\n<li>Capitalization consistency\n<ul>\n<li>You declare the &quot;camelCase&quot; <code>myNumber</code>, yet use &quot;PascalCase&quot; for <code>NumberSystem</code>, and &quot;SHOUTCASE&quot; for <code>RUPEEs</code> and <code>PAISE</code>.</li>\n<li>Convention says that methods (<code>Sub</code> and <code>Function</code>) are &quot;PascalCase&quot;, while variables are &quot;camelCase&quot; and constants are &quot;SHOUTCASE&quot;.</li>\n<li>Of course, there isn't <em>much</em> convention in VBA (other than &quot;no convention at all&quot;), but since you care enough to get your code reviewed, you probably won't be writing VBA forever, and you may want to consider training your brain <em>now</em> for other languages in the future.</li>\n<li>You don't have to follow that convention by any means (especially if you're a programming shop of 1), but pick <em>some</em> convention and follow it. It will make your life much easier.</li>\n<li>Do be aware, however, than VBA &quot;helpfully&quot; fixes casing for you, and that can lead to annoying situations later. For example, if you <code>Dim value As Long</code>, you will end up with <code>ThisWorkbook.Cells(&quot;A1&quot;).Value</code> being &quot;helpfully&quot; fixed to <code>ThisWorkbook.Cells(&quot;A1&quot;).value</code> (note the lower case &quot;v&quot;). So A) try not to use common method names as variables (even though the scope is different and you can get away with it), and B) If you ever do, a simple <code>Dim Value</code> will &quot;fix&quot; all the occurrences in your code, then you can delete the line.</li>\n</ul>\n</li>\n</ul>\n<h3>Indentation</h3>\n<ul>\n<li>This is always tricky as often formatting is mangled/lost when pasting code into the text entry box.</li>\n<li>While code indention doesn't matter one wit to the VBA compiler, it matters hugely to the poor soul who has to read it. This example is a particularly egregious one:</li>\n</ul>\n<pre><code> If CurrencyConversion Then\n If FractionSize &lt;= 1000 Then myNumberFrac = Left(myNumberFrac &amp; &quot;000&quot;, 3)\n If FractionSize &lt;= 100 Then myNumberFrac = Left(myNumberFrac &amp; &quot;00&quot;, 2)\n If FractionSize &lt;= 10 Then myNumberFrac = Left(myNumberFrac &amp; &quot;0&quot;, 1)\n End If\n</code></pre>\n<ul>\n<li>You have a multi-line <code>If</code> statement wrapping several single-line <code>If</code> statements. The lack of indention in the outer <code>If</code>/<code>End If</code> block makes it harder to mentally parse and requires a new reader (or future you) to slow down and take more time to understand what's going on. Our brains will naturally associate the <code>End If</code> with the <em>last</em> <code>If</code> statement, when in fact, it's actually associated with the <em>first</em> <code>If</code> statement.</li>\n</ul>\n<pre><code> If CurrencyConversion Then\n If FractionSize &lt;= 1000 Then myNumberFrac = Left(myNumberFrac &amp; &quot;000&quot;, 3)\n If FractionSize &lt;= 100 Then myNumberFrac = Left(myNumberFrac &amp; &quot;00&quot;, 2)\n If FractionSize &lt;= 10 Then myNumberFrac = Left(myNumberFrac &amp; &quot;0&quot;, 1)\n End If\n</code></pre>\n<ul>\n<li>Is functionally identical, but makes the code structure <em>much</em> more obvious.</li>\n</ul>\n<h3>Function size</h3>\n<ul>\n<li>You have some bits of code pulled out into their own functions, and that's good, but the main <code>TextCurrency</code> function is still rather large.</li>\n<li>There are a number of &quot;chunks&quot; of code that could stand on their own to make the main function more readable, for example:</li>\n</ul>\n<pre><code> If Val(myNumber) &lt;&gt; 0 Then\n myNumber = Trim(Str(myNumber))\n DecimalPlace = InStr(myNumber, &quot;.&quot;)\n End If\n</code></pre>\n<p>Could become</p>\n<pre><code>DecimalPlace = FindDecimalPlace(myNumber)\n</code></pre>\n<p>followed later by the function declaration:</p>\n<pre><code>Private Function FindDecimalPlace(ByVal inValue As Double) As Long\n\n If Val(inValue) &lt;&gt; 0 Then\n Dim valueAsString As Double\n valueAsString = Trim(Str(inValue))\n FindDecimalPlace = InStr(valueAsString, &quot;.&quot;)\n End If\n\nEnd Function\n</code></pre>\n<ul>\n<li><p>This replaces five lines of code in the main function with only one line, making the main function more readable and it's very explicit that this line is going to <code>FindDecimalPlace</code> and assign it to a variable to use later.</p>\n</li>\n<li><p>Another example would be extracting this into its own function:</p>\n</li>\n</ul>\n<pre><code>If DecimalPlace &gt; 0 Then\n myNumberInt = Trim(Left(myNumber, DecimalPlace - 1))\n myNumberFrac = Trim(Mid(myNumber, DecimalPlace + 1))\n If CurrencyConversion Then\n If FractionSize &lt;= 1000 Then myNumberFrac = Left(myNumberFrac &amp; &quot;000&quot;, 3)\n If FractionSize &lt;= 100 Then myNumberFrac = Left(myNumberFrac &amp; &quot;00&quot;, 2)\n If FractionSize &lt;= 10 Then myNumberFrac = Left(myNumberFrac &amp; &quot;0&quot;, 1)\n End If\nElse\nmyNumberInt = myNumber\nEnd If\n</code></pre>\n<ul>\n<li>As I was reviewing, looking to see how to refactor this, I ended up with the following:</li>\n</ul>\n<pre><code> Dim RUPEEs As String, PAISE As String\n 'NOTE: I removed the `decimalPlace` variable declaration from above. \n 'because there are multiple declarations on this line, I had to edit the line instead of just deleting it\n\n 'decimalPlace = FindDecimalPlace(myNumber)\n 'NOTE: This line is being removed. I'm commenting it here to make it obvious, but it should be removed once code is proved to still work correctly, don't leave it behind, that doesn't help readability\n \n myNumberFrac = SetFractionSize(myNumber, myNumberInt, myNumberFrac)\n\n 'the remainder of the TextCurrency function is here, followed later by\n\nPrivate Function SetFractionSize(ByVal originalCurrencyAmount As Double, ByVal currencyConversion As Boolean, ByVal fractionSize As Long, _\n ByRef outIntegerPortion As String, ByRef outDecimalPortion As String) As String\n\n Dim decimalPlaceLocation As Long\n decimalPlaceLocation = FindDecimalPlace(originalCurrencyAmount)\n \n If decimalPlaceLocation &gt; 0 Then\n outIntegerPortion = Trim(Left(originalCurrencyAmount, decimalPlaceLocation - 1))\n outDecimalPortion = Trim(Mid(originalCurrencyAmount, decimalPlaceLocation + 1))\n If currencyConversion Then\n If fractionSize &lt;= 1000 Then SetFractionSize = Left(outDecimalPortion &amp; &quot;000&quot;, 3)\n If fractionSize &lt;= 100 Then SetFractionSize = Left(outDecimalPortion &amp; &quot;00&quot;, 2)\n If fractionSize &lt;= 10 Then SetFractionSize = Left(outDecimalPortion &amp; &quot;0&quot;, 1)\n End If\n Else\n outIntegerPortion = originalCurrencyAmount\n End If\n\nEnd Function\n</code></pre>\n<ul>\n<li><p>Pay attention to the comments in the code block they explain a few of the things done and why</p>\n</li>\n<li><p>Also, note that the call to <code>FindDecimalPlace</code> was moved into this function since the original <code>DecimalPlace</code> variable is not used anywhere else in <code>TextCurrency</code>, therefore, it doesn't need to exist in <code>TextCurrency</code>, only in this function where it's actually used.</p>\n</li>\n<li><p>Also, all the <code>ByVal</code> parameters are listed first, followed by the <code>ByRef</code> parameters</p>\n<ul>\n<li>While there's no convention that I'm aware of that encourages this, I did this to help mentally separate them</li>\n<li>Also, the <code>ByRef</code> parameters use <a href=\"https://www.joelonsoftware.com/2005/05/11/making-wrong-code-look-wrong/\" rel=\"nofollow noreferrer\"><em>Systems</em> Hungariation Notation</a> to indicate that they are expected to be set in the function and return a value to be used &quot;on the outside&quot;.</li>\n</ul>\n</li>\n<li><p>This changes the beginning of the <code>TextCurrency</code> function from a bulky:</p>\n</li>\n</ul>\n<pre><code>Dim DecimalPlace As Integer, RUPEEs As String, PAISE As String\n\nIf Val(myNumber) &lt;&gt; 0 Then\n myNumber = Trim(Str(myNumber))\n DecimalPlace = InStr(myNumber, &quot;.&quot;)\nEnd If\n \nIf DecimalPlace &gt; 0 Then\n myNumberInt = Trim(Left(myNumber, DecimalPlace - 1))\n myNumberFrac = Trim(Mid(myNumber, DecimalPlace + 1))\n If CurrencyConversion Then\n If FractionSize &lt;= 1000 Then myNumberFrac = Left(myNumberFrac &amp; &quot;000&quot;, 3)\n If FractionSize &lt;= 100 Then myNumberFrac = Left(myNumberFrac &amp; &quot;00&quot;, 2)\n If FractionSize &lt;= 10 Then myNumberFrac = Left(myNumberFrac &amp; &quot;0&quot;, 1)\n End If\nElse\nmyNumberInt = myNumber\nEnd If\n</code></pre>\n<p>To a much more svelte and readable:</p>\n<pre><code> Dim RUPEEs As String, PAISE As String\n\n myNumberFrac = SetFractionSize(myNumber, currencyConversion, fractionSize, myNumberInt, myNumberFrac)\n</code></pre>\n<ul>\n<li>There are <em>many</em> more opportunities for refactoring, I've only shown the first two obvious ones, and hope that the reasoning for them will help you find others.</li>\n</ul>\n<h2>Keep it DRY</h2>\n<ul>\n<li><p>DRY: Don't Repeat Yourself</p>\n<ul>\n<li>If you discover you're writing the same line(s) of code over and over (or even just twice), refactor those lines into a function and call the function.</li>\n<li>It makes the code more readable and more maintainable</li>\n</ul>\n</li>\n<li><p>You repeat this line in at least 3 locations:</p>\n<pre><code>DecimalPlace = InStr(myNumber, &quot;.&quot;)\n</code></pre>\n</li>\n<li><p>Each of those can now be replaced with:</p>\n<pre><code>DecimalPlace = FindDecimalPlace(myNumber) 'or whatever variable is appropriate to pass in\n</code></pre>\n<ul>\n<li>If you ever need to change the way you find the decimal point, or you find a bug, now you only need to fix it in the one function instead of tracking down everywhere the old version is and fixing it multiple times, most likely missing at least one of them.</li>\n<li>Maybe you want to internationalize it and allow for a <code>,</code> as the decimal separator instead of the US (and, I am a bit surprised to find out, also Indian) <code>.</code> as the decimal separator - again, you only change it in one place</li>\n</ul>\n</li>\n<li><p>You also repeat this line in a number of places</p>\n<pre><code>myNumber = Trim(Str(myNumber))\n</code></pre>\n<ul>\n<li>Remember above where it's also flagged as being passed <code>ByVal</code>, yet is assigned a value.</li>\n<li>This is a good place to declare a new variable with a scope internal to <code>TextCurrency</code> and assign it one time, then assign that new variable to the return value of your newly written function.</li>\n<li>You'll only <em>use</em> <code>myNumber</code> and never assign anything to it, plus you can skip all the other times you're <code>Trim()</code>ing it because you know it's already been cleaned up.</li>\n</ul>\n</li>\n</ul>\n<h3>Code Separators</h3>\n<ul>\n<li>You have</li>\n</ul>\n<pre><code>'______________________________________________\n</code></pre>\n<p>Before every one of your functions. I fully understand why, however... Back in the &quot;Tools&quot;, &quot;Options&quot; menu, check the &quot;Procedure Separator&quot; box and watch <em>magic</em> happen! :)\n<a href=\"https://i.stack.imgur.com/J5Oyt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/J5Oyt.png\" alt=\"enter image description here\" /></a></p>\n<hr>\n<p>There are a variety of other things you could do, too, but these are the big stand-outs that will make your code easier to read, easier to follow, easier to maintain in the future (for other programmers and future-you) and, much more importantly, less bug prone for all those reasons.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T16:04:53.747", "Id": "519875", "Score": "2", "body": "Wow, what an behemoth of an answer! +1" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T16:33:26.770", "Id": "519881", "Score": "1", "body": "You've hung out here, @N3buchadnezzar, this one is short compared to some..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T05:28:17.773", "Id": "519922", "Score": "0", "body": "Can I upvote twice on this answer? :) Accepting this answer as I find it more specific towards code improvement. Really appreciate time and efforts you have given. Thank you. It's great to learn here. Also, thought of removing my answer as someone upvoted it,. But your this answer is referring to it." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T14:44:26.410", "Id": "263329", "ParentId": "263277", "Score": "6" } } ]
{ "AcceptedAnswerId": "263329", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T10:55:29.680", "Id": "263277", "Score": "6", "Tags": [ "vba", "excel" ], "Title": "VBA - Excel add in Convert number to Text currency" }
263277
<blockquote> <p>Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month.</p> <p>The following variables contain values as described below:</p> <p><code>balance</code> - the outstanding balance on the credit card</p> <p><code>annualInterestRate</code> - annual interest rate as a decimal</p> <p><code>monthlyPaymentRate</code> - minimum monthly payment rate as a decimal</p> <p>For each month, calculate statements on the monthly payment and remaining balance. At the end of 12 months, print out the remaining balance. Be sure to print out no more than two decimal digits of accuracy - so print</p> <p><code>Remaining balance: 813.41</code></p> <p>instead of</p> <p><code>Remaining balance: 813.4141998135</code></p> <p>So your program only prints out one thing: the remaining balance at the end of the year in the format:</p> <p><code>Remaining balance: 4784.0</code></p> <p>A summary of the required math is found below:</p> <p><span class="math-container">\begin{align*} \text{Monthly interest rate} &amp;= \frac{\text{Annual interest rate}}{12} \\ \text{Minimum monthly payment} &amp;= \text{Minimum monthly payment rate} \times \text{Previous balance} \\ \text{Monthly unpaid balance} &amp;= \text{Previous balance} \\ &amp;- \text{Minimum monthly payment} \\ \text{Updated balance each month} &amp;= \text{Monthly unpaid balance} \\ &amp;+ (\text{Monthly interest rate} \times \text{Monthly unpaid balance}) \end{align*}</span></p> </blockquote> <h1>Code</h1> <pre class="lang-py prettyprint-override"><code>def balances(initial_balance, annual_interest_rate, minimum_monthly_payment_rate): balance = initial_balance monthly_interest_rate = annual_interest_rate / 12 for month in range(13): minimum_monthly_payment = balance * minimum_monthly_payment_rate monthly_unpaid_balance = balance - minimum_monthly_payment yield {'month': month, 'minimum_monthly_payment': minimum_monthly_payment, 'balance': balance} balance = monthly_unpaid_balance + (monthly_unpaid_balance * monthly_interest_rate) def main(): *bs, remaining_balance = balances(balance, annualInterestRate, monthlyPaymentRate) print('Remaining Balance: {}'.format(round(remaining_balance['balance'], 2))) # Testing data balance = 484 annualInterestRate = .2 monthlyPaymentRate = .04 ## ifname_main does not work in grader if __name__ == '__main__': main() </code></pre> <p>Thanks in advance.</p>
[]
[ { "body": "<p>The <code>balances</code> function is a bit long. The contents of the loop can be another function. This function shall be responsible to satisfy this requirement:</p>\n<blockquote>\n<p>For each month, calculate statements on the monthly payment and remaining balance</p>\n</blockquote>\n<p>Instead of <code>yield</code>-ing a structure with <code>month</code>, <code>minimum_monthly_payment</code>, and <code>balance</code> for each iteration of the loop, you can <code>return</code> at the end of the loop. Actually, <code>month</code> and <code>minimum_monthly_payment</code> is not used at all, so you may only return the remaining <code>balance</code> at the end of 12 months.</p>\n<p>Since the <code>balances</code> function now returns only a single number, you can get rid of the complex code at <code>main</code>. Just get that number and print it.</p>\n<p>After those changes, rename the <code>balances</code> method to something more meaningful.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T19:20:29.890", "Id": "263291", "ParentId": "263287", "Score": "1" } }, { "body": "<ul>\n<li>Could use some PEP484 type hints</li>\n<li><code>range(13)</code> is awkward - there's no point in yielding the initial balance, so just yield adjusted balances and do it 12 times</li>\n<li>No point in yielding the month, payment and balance; just yield the balance. Even if you needed to yield all three, a dictionary is not a great way to do it. Tuples are standard; or a dataclass is better-structured.</li>\n<li>No need to call <code>format</code> or <code>round</code>. Just use <code>.2f</code>. Note that this contravenes the specification's <code>Remaining balance: 4784.0</code> but that's dumb; this is a money quantity so the precision should be fixed.</li>\n<li>Your <code>balances</code> is fine as a generator, but why limit it to 12 iterations? The more generic and useful implementation simply iterates forever. Use <code>islice</code> to pull 12 values, ignoring all but the last.</li>\n</ul>\n<h2>Suggested (iterative)</h2>\n<pre><code>from itertools import islice\nfrom typing import Iterable\n\n\ndef balances(\n initial_balance: float,\n annual_interest_rate: float,\n minimum_monthly_payment_rate: float,\n) -&gt; Iterable[float]:\n balance = initial_balance\n monthly_interest_rate = annual_interest_rate / 12\n\n while True:\n minimum_monthly_payment = balance * minimum_monthly_payment_rate\n monthly_unpaid_balance = balance - minimum_monthly_payment\n balance = monthly_unpaid_balance * (1 + monthly_interest_rate)\n yield balance\n\n\ndef main():\n for balance in islice(\n balances(\n initial_balance=484.00,\n annual_interest_rate=0.20,\n minimum_monthly_payment_rate=0.04,\n ),\n 12,\n ):\n pass\n\n print(f'Remaining Balance: {balance:.2f}')\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>Simplifying the inner loop would replace it with</p>\n<pre><code>balance *= (1 - minimum_monthly_payment_rate) * (1 + monthly_interest_rate)\n</code></pre>\n<p>which is equivalent.</p>\n<h2>Suggested (compound)</h2>\n<p>Even better is to get rid of the loop entirely, and just use a power:</p>\n<pre><code>def compound(\n initial_balance: float,\n annual_interest_rate: float,\n minimum_monthly_payment_rate: float,\n months: int,\n) -&gt; float:\n monthly_interest_rate = annual_interest_rate / 12\n\n return initial_balance * (\n (1 - minimum_monthly_payment_rate) * (1 + monthly_interest_rate)\n ) ** months\n\n\ndef main():\n balance = compound(\n initial_balance=484.00,\n annual_interest_rate=0.20,\n minimum_monthly_payment_rate=0.04,\n months=12,\n )\n\n print(f'Remaining Balance: {balance:.2f}')\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T15:35:08.323", "Id": "519873", "Score": "0", "body": "Wouldn't it be useless to yield negative balances?\n\nMaybe make it `while balance >= 0`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T15:56:25.327", "Id": "519874", "Score": "0", "body": "Possible. Add that if you want. There are some (non-credit-card) account types that would benefit from being able to represent both credit and debit states." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T16:58:15.290", "Id": "519884", "Score": "0", "body": "That said, do a little math and you'll find that the balance never goes to or below zero for a finite number of iterations." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T01:17:31.360", "Id": "263303", "ParentId": "263287", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T15:45:42.960", "Id": "263287", "Score": "3", "Tags": [ "python", "programming-challenge", "generator" ], "Title": "Q: Paying Debt Off a Year, MIT edX 6.001 U2/PS2/P1" }
263287
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/263183/231235">Two dimensional bicubic interpolation implementation in C</a> and <a href="https://codereview.stackexchange.com/q/257757/231235">A recursive_transform Template Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++</a>. Besides the C version code, I am attempting to make a C++ version bicubic interpolation function <code>bicubicInterpolation</code> which can be applied on two dimensional nested vectors <code>std::vector&lt;std::vector&lt;&gt;&gt;</code> structure.</p> <p>Example input matrix:</p> <pre><code>1 1 1 1 100 1 1 1 1 </code></pre> <p>Output matrix (bicubic interpolation result from the input matrix above):</p> <pre><code>1 1 1 1 1 1 1 1 1 1 1 1 1 9 19 27 30 27 19 9 1 0 0 0 1 19 39 56 62 56 39 19 1 0 0 0 1 27 56 79 89 79 56 27 1 0 0 0 1 30 62 89 100 89 62 30 1 0 0 0 1 27 56 79 89 79 56 27 1 0 0 0 1 19 39 56 62 56 39 19 1 0 0 0 1 9 19 27 30 27 19 9 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 2 2 1 1 0 0 0 0 0 0 0 1 2 2 1 1 0 0 0 0 0 0 0 1 1 1 1 </code></pre> <p><strong>The experimental implementation</strong></p> <ul> <li><p>namespace: <code>TinyDIP</code></p> </li> <li><p><code>bicubicInterpolation</code> function implementation:</p> <pre><code>constexpr auto bicubicInterpolation(const int&amp; newSizeX, const int&amp; newSizeY) { auto output = Image&lt;ElementT&gt;(newSizeX, newSizeY); auto ratiox = (float)this-&gt;getSizeX() / (float)newSizeX; auto ratioy = (float)this-&gt;getSizeY() / (float)newSizeY; for (size_t y = 0; y &lt; newSizeY; y++) { for (size_t x = 0; x &lt; newSizeX; x++) { float xMappingToOrigin = (float)x * ratiox; float yMappingToOrigin = (float)y * ratioy; float xMappingToOriginFloor = floor(xMappingToOrigin); float yMappingToOriginFloor = floor(yMappingToOrigin); float xMappingToOriginFrac = xMappingToOrigin - xMappingToOriginFloor; float yMappingToOriginFrac = yMappingToOrigin - yMappingToOriginFloor; ElementT ndata[4 * 4]; for (int ndatay = -1; ndatay &lt;= 2; ndatay++) { for (int ndatax = -1; ndatax &lt;= 2; ndatax++) { ndata[(ndatay + 1) * 4 + (ndatax + 1)] = this-&gt;get( clip(xMappingToOriginFloor + ndatax, 0, this-&gt;getSizeX() - 1), clip(yMappingToOriginFloor + ndatay, 0, this-&gt;getSizeY() - 1)); } } output.set(x, y, bicubicPolate(ndata, xMappingToOriginFrac, yMappingToOriginFrac)); } } return output; } </code></pre> </li> <li><p>Helper functions for <code>bicubicInterpolation</code> function:</p> <pre><code>template&lt;class InputT&gt; constexpr auto bicubicPolate(const ElementT* const ndata, const InputT&amp; fracx, const InputT&amp; fracy) { auto x1 = cubicPolate( ndata[0], ndata[1], ndata[2], ndata[3], fracx ); auto x2 = cubicPolate( ndata[4], ndata[5], ndata[6], ndata[7], fracx ); auto x3 = cubicPolate( ndata[8], ndata[9], ndata[10], ndata[11], fracx ); auto x4 = cubicPolate( ndata[12], ndata[13], ndata[14], ndata[15], fracx ); return clip(cubicPolate( x1, x2, x3, x4, fracy ), 0.0, 255.0); } template&lt;class InputT1, class InputT2&gt; constexpr auto cubicPolate(const InputT1&amp; v0, const InputT1&amp; v1, const InputT1&amp; v2, const InputT1&amp; v3, const InputT2&amp; frac) { auto A = (v3-v2)-(v0-v1); auto B = (v0-v1)-A; auto C = v2-v0; auto D = v1; return D + frac * (C + frac * (B + frac * A)); } template&lt;class InputT1, class InputT2, class InputT3&gt; constexpr auto clip(const InputT1&amp; input, const InputT2&amp; lowerbound, const InputT3&amp; upperbound) { if (input &lt; lowerbound) { return static_cast&lt;InputT1&gt;(lowerbound); } if (input &gt; upperbound) { return static_cast&lt;InputT1&gt;(upperbound); } return input; } </code></pre> </li> <li><p><code>Image</code> template class implementation (<code>image.h</code>):</p> <pre><code>/* Develop by Jimmy Hu */ #ifndef Image_H #define Image_H #include &lt;algorithm&gt; #include &lt;array&gt; #include &lt;chrono&gt; #include &lt;complex&gt; #include &lt;concepts&gt; #include &lt;functional&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;list&gt; #include &lt;numeric&gt; #include &lt;string&gt; #include &lt;type_traits&gt; #include &lt;variant&gt; #include &lt;vector&gt; #include &quot;basic_functions.h&quot; namespace TinyDIP { template &lt;typename ElementT&gt; class Image { public: Image() { } Image(const int newWidth, const int newHeight) { this-&gt;image_data.resize(newHeight); for (size_t i = 0; i &lt; newHeight; ++i) { this-&gt;image_data[i].resize(newWidth); } this-&gt;image_data = recursive_transform&lt;2&gt;(this-&gt;image_data, [](ElementT element) { return ElementT{}; }); return; } Image(const int newWidth, const int newHeight, const ElementT initVal) { this-&gt;image_data.resize(newHeight); for (size_t i = 0; i &lt; newHeight; ++i) { this-&gt;image_data[i].resize(newWidth); } this-&gt;image_data = recursive_transform&lt;2&gt;(this-&gt;image_data, [initVal](ElementT element) { return initVal; }); return; } Image(const std::vector&lt;std::vector&lt;ElementT&gt;&gt;&amp; input) { this-&gt;image_data = recursive_transform&lt;2&gt;(input, [](ElementT element) {return element; } ); // Deep copy return; } template&lt;class OutputT&gt; constexpr auto cast() { return this-&gt;transform([](ElementT element) { return static_cast&lt;OutputT&gt;(element); }); } constexpr auto get(const unsigned int locationx, const unsigned int locationy) { return this-&gt;image_data[locationy][locationx]; } constexpr auto set(const unsigned int locationx, const unsigned int locationy, const ElementT&amp; element) { this-&gt;image_data[locationy][locationx] = element; return *this; } template&lt;class InputT&gt; constexpr auto set(const unsigned int locationx, const unsigned int locationy, const InputT&amp; element) { this-&gt;image_data[locationy][locationx] = static_cast&lt;ElementT&gt;(element); return *this; } constexpr auto getSizeX() { return this-&gt;image_data[0].size(); } constexpr auto getSizeY() { return this-&gt;image_data.size(); } constexpr auto getData() { return this-&gt;transform([](ElementT element) { return element; }); // Deep copy } void print() { for (auto&amp; row_element : this-&gt;toString()) { for (auto&amp; element : row_element) { std::cout &lt;&lt; element &lt;&lt; &quot;\t&quot;; } std::cout &lt;&lt; &quot;\n&quot;; } std::cout &lt;&lt; &quot;\n&quot;; return; } constexpr auto toString() { return this-&gt;transform([](ElementT element) { return std::to_string(element); }); } constexpr auto bicubicInterpolation(const int&amp; newSizeX, const int&amp; newSizeY) { auto output = Image&lt;ElementT&gt;(newSizeX, newSizeY); auto ratiox = (float)this-&gt;getSizeX() / (float)newSizeX; auto ratioy = (float)this-&gt;getSizeY() / (float)newSizeY; for (size_t y = 0; y &lt; newSizeY; y++) { for (size_t x = 0; x &lt; newSizeX; x++) { float xMappingToOrigin = (float)x * ratiox; float yMappingToOrigin = (float)y * ratioy; float xMappingToOriginFloor = floor(xMappingToOrigin); float yMappingToOriginFloor = floor(yMappingToOrigin); float xMappingToOriginFrac = xMappingToOrigin - xMappingToOriginFloor; float yMappingToOriginFrac = yMappingToOrigin - yMappingToOriginFloor; ElementT ndata[4 * 4]; for (int ndatay = -1; ndatay &lt;= 2; ndatay++) { for (int ndatax = -1; ndatax &lt;= 2; ndatax++) { ndata[(ndatay + 1) * 4 + (ndatax + 1)] = this-&gt;get( clip(xMappingToOriginFloor + ndatax, 0, this-&gt;getSizeX() - 1), clip(yMappingToOriginFloor + ndatay, 0, this-&gt;getSizeY() - 1)); } } output.set(x, y, bicubicPolate(ndata, xMappingToOriginFrac, yMappingToOriginFrac)); } } return output; } Image&lt;ElementT&gt;&amp; operator=(Image&lt;ElementT&gt; const&amp; input) // Copy Assign { this-&gt;image_data = input.getData(); return *this; } Image&lt;ElementT&gt;&amp; operator=(Image&lt;ElementT&gt;&amp;&amp; other) // Move Assign { this-&gt;image_data = std::move(other.image_data); std::cout &lt;&lt; &quot;move assigned\n&quot;; return *this; } Image(const Image&lt;ElementT&gt; &amp;input) // Copy Constructor { this-&gt;image_data = input.getData(); } /* Move Constructor */ Image(Image&lt;ElementT&gt; &amp;&amp;input) : image_data(std::move(input.image_data)) { } private: std::vector&lt;std::vector&lt;ElementT&gt;&gt; image_data; template&lt;class F&gt; constexpr auto transform(const F&amp; f) { return recursive_transform&lt;2&gt;(this-&gt;image_data, f); } template&lt;class InputT&gt; constexpr auto bicubicPolate(const ElementT* const ndata, const InputT&amp; fracx, const InputT&amp; fracy) { auto x1 = cubicPolate( ndata[0], ndata[1], ndata[2], ndata[3], fracx ); auto x2 = cubicPolate( ndata[4], ndata[5], ndata[6], ndata[7], fracx ); auto x3 = cubicPolate( ndata[8], ndata[9], ndata[10], ndata[11], fracx ); auto x4 = cubicPolate( ndata[12], ndata[13], ndata[14], ndata[15], fracx ); return clip(cubicPolate( x1, x2, x3, x4, fracy ), 0.0, 255.0); } template&lt;class InputT1, class InputT2&gt; constexpr auto cubicPolate(const InputT1&amp; v0, const InputT1&amp; v1, const InputT1&amp; v2, const InputT1&amp; v3, const InputT2&amp; frac) { auto A = (v3-v2)-(v0-v1); auto B = (v0-v1)-A; auto C = v2-v0; auto D = v1; return D + frac * (C + frac * (B + frac * A)); } template&lt;class InputT1, class InputT2, class InputT3&gt; constexpr auto clip(const InputT1&amp; input, const InputT2&amp; lowerbound, const InputT3&amp; upperbound) { if (input &lt; lowerbound) { return static_cast&lt;InputT1&gt;(lowerbound); } if (input &gt; upperbound) { return static_cast&lt;InputT1&gt;(upperbound); } return input; } }; } #endif </code></pre> </li> <li><p><code>base_types.h</code>: The base types</p> <pre><code>/* Develop by Jimmy Hu */ #ifndef BASE_H #define BASE_H #include &lt;cmath&gt; #include &lt;cstdbool&gt; #include &lt;cstdio&gt; #include &lt;cstdlib&gt; #include &lt;string&gt; #define MAX_PATH 256 #define FILE_ROOT_PATH &quot;./&quot; #define True true #define False false typedef unsigned char BYTE; typedef struct RGB { unsigned char channels[3]; } RGB; typedef BYTE GrayScale; typedef struct HSV { long double channels[3]; // Range: 0 &lt;= H &lt; 360, 0 &lt;= S &lt;= 1, 0 &lt;= V &lt;= 255 }HSV; #endif </code></pre> </li> <li><p><code>basic_functions.h</code>: The basic functions</p> <pre><code>/* Develop by Jimmy Hu */ #ifndef BasicFunctions_H #define BasicFunctions_H #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;execution&gt; #include &lt;exception&gt; #include &lt;functional&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;list&gt; #include &lt;map&gt; #include &lt;mutex&gt; #include &lt;numeric&gt; #include &lt;optional&gt; #include &lt;ranges&gt; #include &lt;stdexcept&gt; #include &lt;string&gt; #include &lt;tuple&gt; #include &lt;type_traits&gt; #include &lt;utility&gt; #include &lt;variant&gt; #include &lt;vector&gt; namespace TinyDIP { template&lt;typename T&gt; concept is_back_inserterable = requires(T x) { std::back_inserter(x); }; template&lt;typename T&gt; concept is_inserterable = requires(T x) { std::inserter(x, std::ranges::end(x)); }; // recursive_invoke_result_t implementation template&lt;typename, typename&gt; struct recursive_invoke_result { }; template&lt;typename T, std::invocable&lt;T&gt; F&gt; struct recursive_invoke_result&lt;F, T&gt; { using type = std::invoke_result_t&lt;F, T&gt;; }; template&lt;typename F, template&lt;typename...&gt; typename Container, typename... Ts&gt; requires ( !std::invocable&lt;F, Container&lt;Ts...&gt;&gt;&amp;&amp; std::ranges::input_range&lt;Container&lt;Ts...&gt;&gt;&amp;&amp; requires { typename recursive_invoke_result&lt;F, std::ranges::range_value_t&lt;Container&lt;Ts...&gt;&gt;&gt;::type; }) struct recursive_invoke_result&lt;F, Container&lt;Ts...&gt;&gt; { using type = Container&lt;typename recursive_invoke_result&lt;F, std::ranges::range_value_t&lt;Container&lt;Ts...&gt;&gt;&gt;::type&gt;; }; template&lt;typename F, typename T&gt; using recursive_invoke_result_t = typename recursive_invoke_result&lt;F, T&gt;::type; // recursive_transform implementation (the version with unwrap_level) template&lt;std::size_t unwrap_level = 1, class T, class F&gt; constexpr auto recursive_transform(const T&amp; input, const F&amp; f) { if constexpr (unwrap_level &gt; 0) { recursive_invoke_result_t&lt;F, T&gt; output{}; std::ranges::transform( std::ranges::cbegin(input), std::ranges::cend(input), std::inserter(output, std::ranges::end(output)), [&amp;f](auto&amp;&amp; element) { return recursive_transform&lt;unwrap_level - 1&gt;(element, f); } ); return output; } else { return f(input); } } 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::ranges::begin(output), std::ranges::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)); } } } #endif </code></pre> </li> </ul> <p><strong>The full testing code</strong></p> <p>The <a href="https://en.wikipedia.org/wiki/Grayscale" rel="nofollow noreferrer">grayscale</a> type data has been tested here.</p> <pre><code>/* Develop by Jimmy Hu */ #include &quot;base_types.h&quot; #include &quot;basic_functions.h&quot; #include &quot;image.h&quot; void bicubicInterpolationTest(); int main() { bicubicInterpolationTest(); return 0; } void bicubicInterpolationTest() { TinyDIP::Image&lt;GrayScale&gt; image1(3, 3, 1); std::cout &lt;&lt; &quot;Width: &quot; + std::to_string(image1.getSizeX()) + &quot;\n&quot;; std::cout &lt;&lt; &quot;Height: &quot; + std::to_string(image1.getSizeY()) + &quot;\n&quot;; image1 = image1.set(1, 1, 100); image1.print(); auto image2 = image1.bicubicInterpolation(12, 12); image2.print(); } </code></pre> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/263183/231235">Two dimensional bicubic interpolation implementation in C</a> and</p> <p><a href="https://codereview.stackexchange.com/q/257757/231235">A recursive_transform Template Function with Unwrap Level 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>I am attempting to make a C++ version bicubic interpolation function <code>bicubicInterpolation</code> which can be applied on two dimensional nested vectors <code>std::vector&lt;std::vector&lt;&gt;&gt;</code> structure.</p> </li> <li><p>Why a new review is being asked for?</p> <p>If there is any possible improvement, please let me know.</p> </li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T18:31:30.963", "Id": "519825", "Score": "2", "body": "Can't help but notice that the bug from last time (filling 9 out of 16 entries in `ndata`) is still in here" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T00:08:14.213", "Id": "519839", "Score": "0", "body": "@harold I apologize for the missing point you mentioned. The question has been updated." } ]
[ { "body": "<p>I like <code>auto</code> for lots of things, but not as a return type unless it's actually necessary.</p>\n<p>For example, to understand what <code>cast</code> returns it's necessary to dig through several template functions, layers of meta-templates, and then understand what <code>std::invoke_result_t</code> does in this particular case.</p>\n<p>Please just write out the return type.</p>\n<hr />\n<pre><code> template&lt;class InputT1, class InputT2, class InputT3&gt;\n constexpr auto clip(const InputT1&amp; input, const InputT2&amp; lowerbound, const InputT3&amp; upperbound)\n {\n if (input &lt; lowerbound)\n {\n return static_cast&lt;InputT1&gt;(lowerbound);\n }\n if (input &gt; upperbound)\n {\n return static_cast&lt;InputT1&gt;(upperbound);\n }\n return input;\n }\n</code></pre>\n<p><a href=\"https://en.cppreference.com/w/cpp/algorithm/clamp\" rel=\"noreferrer\">The standard library already provides std::clamp</a> so this isn't necessary.</p>\n<p>Note that providing a single template argument is safer than separate arguments for all the inputs. Conversions (and thus comparisons) between different types may not be well-defined since types have different ranges.</p>\n<hr />\n<pre><code>#define True true\n#define False false\n</code></pre>\n<p>Why? C++ uses <code>true</code> and <code>false</code>.</p>\n<hr />\n<pre><code> std::vector&lt;std::vector&lt;ElementT&gt;&gt; image_data;\n</code></pre>\n<p>It's faster (and usually easier) to use a one-dimensional vector: <code>std::vector&lt;ElementT&gt; image_data;</code> containing <code>width * height</code> elements, and calculate indices when necessary as <code>y * width + x</code>.</p>\n<p>So this:</p>\n<pre><code> Image(const int newWidth, const int newHeight)\n {\n this-&gt;image_data.resize(newHeight);\n for (size_t i = 0; i &lt; newHeight; ++i) {\n this-&gt;image_data[i].resize(newWidth);\n }\n this-&gt;image_data = recursive_transform&lt;2&gt;(this-&gt;image_data, [](ElementT element) { return ElementT{}; });\n return;\n }\n</code></pre>\n<p>Should simply be:</p>\n<pre><code> Image(const unsigned int width, const unsigned int height):\n m_width(width),\n m_height(height),\n m_image_data(width * height) { }\n</code></pre>\n<p>Note that the <code>std::vector</code> constructor (and resize function) will &quot;value-initialize&quot; elements, so we don't need to do that separately.</p>\n<p>We should also be using an unsigned type for the size, or at least checking that the integer isn't less than or equal to zero.</p>\n<hr />\n<pre><code> template&lt;class OutputT&gt;\n constexpr auto cast()\n {\n return this-&gt;transform([](ElementT element) { return static_cast&lt;OutputT&gt;(element); });\n }\n</code></pre>\n<p>I don't think this belongs inside the class. If we want to do something with the internal data, it would be better to expose the internal data in a function like:</p>\n<pre><code> std::vector&lt;ElementT&gt; const&amp; getImageData() const { return m_imageData; }\n</code></pre>\n<p>The user can then use <code>std::transform</code> or whatever as they need to.</p>\n<hr />\n<pre><code> constexpr auto get(const unsigned int locationx, const unsigned int locationy)\n {\n return this-&gt;image_data[locationy][locationx];\n }\n\n constexpr auto set(const unsigned int locationx, const unsigned int locationy, const ElementT&amp; element)\n {\n this-&gt;image_data[locationy][locationx] = element;\n return *this;\n }\n\n template&lt;class InputT&gt;\n constexpr auto set(const unsigned int locationx, const unsigned int locationy, const InputT&amp; element)\n {\n this-&gt;image_data[locationy][locationx] = static_cast&lt;ElementT&gt;(element);\n return *this;\n }\n</code></pre>\n<p>It's more idiomatic in C++ to provide two versions of a <code>get</code> function, one returning a mutable reference, and the other a const-reference.</p>\n<pre><code>constexpr ElementT&amp; at(const unsigned int x, const unsigned int y) { return m_image_data[y * width + x]; }\nconstexpr ElementT const&amp; at(const unsigned int x, const unsigned int y) const { return m_image_data[y * width + x]; }\n</code></pre>\n<hr />\n<pre><code> constexpr auto getData()\n {\n return this-&gt;transform([](ElementT element) { return element; }); // Deep copy\n }\n</code></pre>\n<p>As with <code>cast</code> above we don't need this function. We can just expose a <code>const&amp;</code> of the image data.</p>\n<hr />\n<pre><code> void print()\n {\n for (auto&amp; row_element : this-&gt;toString())\n {\n for (auto&amp; element : row_element)\n {\n std::cout &lt;&lt; element &lt;&lt; &quot;\\t&quot;;\n }\n std::cout &lt;&lt; &quot;\\n&quot;;\n }\n std::cout &lt;&lt; &quot;\\n&quot;;\n return;\n }\n</code></pre>\n<p>It's more flexible to provide an output stream operator, since we can specify the stream to print to.</p>\n<p>We definitely don't want to be creating a temporary copy filled with strings to do this!!!</p>\n<p>We can simply use ElementT's <code>operator&lt;&lt;</code> and send the elements directly to the output stream.</p>\n<hr />\n<pre><code> constexpr auto toString()\n {\n return this-&gt;transform([](ElementT element) { return std::to_string(element); });\n }\n</code></pre>\n<p>This seems an unlikely thing for anyone to want to do. Again, we can expose the image data by <code>const&amp;</code> and let the user use <code>std::transform</code> if they really want to.</p>\n<hr />\n<pre><code> constexpr auto bicubicInterpolation(const int&amp; newSizeX, const int&amp; newSizeY) ...\n</code></pre>\n<p>There's no point in using references for the size parameters. Again, they should be unsigned, or we have to check that the values are above 0.</p>\n<p>This function would probably be better as a free function, e.g.:</p>\n<pre><code> template&lt;ElementT&gt;\n Image&lt;ElementT&gt; copyResizeBicubic(Image&lt;ElementT&gt; const&amp; image, int width, int height);\n</code></pre>\n<hr />\n<pre><code> Image&lt;ElementT&gt;&amp; operator=(Image&lt;ElementT&gt; const&amp; input) // Copy Assign\n {\n this-&gt;image_data = input.getData();\n return *this;\n }\n\n Image&lt;ElementT&gt;&amp; operator=(Image&lt;ElementT&gt;&amp;&amp; other) // Move Assign\n {\n this-&gt;image_data = std::move(other.image_data);\n std::cout &lt;&lt; &quot;move assigned\\n&quot;;\n return *this;\n }\n\n Image(const Image&lt;ElementT&gt; &amp;input) // Copy Constructor\n {\n this-&gt;image_data = input.getData();\n }\n\n /* Move Constructor\n */\n Image(Image&lt;ElementT&gt; &amp;&amp;input) : image_data(std::move(input.image_data))\n {\n }\n</code></pre>\n<p>These can all be <code>= default</code> no?</p>\n<p>Note that we can write <code>Image&lt;ElementT&gt;</code> as just <code>Image</code> inside the class.</p>\n<hr />\n<pre><code> template&lt;class InputT&gt;\n constexpr auto bicubicPolate(const ElementT* const ndata, const InputT&amp; fracx, const InputT&amp; fracy)\n {\n auto x1 = cubicPolate( ndata[0], ndata[1], ndata[2], ndata[3], fracx );\n auto x2 = cubicPolate( ndata[4], ndata[5], ndata[6], ndata[7], fracx );\n auto x3 = cubicPolate( ndata[8], ndata[9], ndata[10], ndata[11], fracx );\n auto x4 = cubicPolate( ndata[12], ndata[13], ndata[14], ndata[15], fracx );\n\n return clip(cubicPolate( x1, x2, x3, x4, fracy ), 0.0, 255.0);\n }\n\n template&lt;class InputT1, class InputT2&gt;\n constexpr auto cubicPolate(const InputT1&amp; v0, const InputT1&amp; v1, const InputT1&amp; v2, const InputT1&amp; v3, const InputT2&amp; frac)\n {\n auto A = (v3-v2)-(v0-v1);\n auto B = (v0-v1)-A;\n auto C = v2-v0;\n auto D = v1;\n return D + frac * (C + frac * (B + frac * A));\n }\n</code></pre>\n<p>These functions don't need to access any class data. They be static, or even non-member helper functions in another file.</p>\n<p>As small POD types, the parameters should be passed by value, not <code>const&amp;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T07:34:07.113", "Id": "520014", "Score": "1", "body": "Thank you for the answer. _We can simply use ElementT's `operator<<` and send the elements directly to the output stream._ How about `TinyDIP::Image<GrayScale> image1` here? The `GrayScale` type is defined from `unsigned char` (8-bits per pixel), but `operator<<` in `unsigned char` can't print number correctly. The `std::to_string` is still needed here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T07:51:58.167", "Id": "520015", "Score": "1", "body": "True. I'd forgotten about that. It is possible to use the `+` trick to force numeric output instead, see: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T10:27:27.337", "Id": "263320", "ParentId": "263289", "Score": "5" } } ]
{ "AcceptedAnswerId": "263320", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T17:53:45.530", "Id": "263289", "Score": "3", "Tags": [ "c++", "reinventing-the-wheel", "image", "template", "c++20" ], "Title": "Two dimensional bicubic interpolation implementation in C++" }
263289
<p>I have written a simple parser in Java for a study project. Can anyone see how I might improve the code below. I have been looking at the code myself for the last few days but I couldn't come up with anything.</p> <pre><code>int counter = 0; int cacheCounter = 0; for(Map.Entry&lt;String, File[]&gt; path : queriedCache.entrySet()) { String[] array = new String[path.getValue().length]; for(File file : queriedCache.get(path.getKey())) { if(file.listFiles() != null) { array = new String[Objects.requireNonNull(file.listFiles()).length + 1]; for(File gif : Objects.requireNonNull(file.listFiles())) { array[counter] = gif.getAbsolutePath(); counter++; } counter = 0; } else { array[counter] = file.getAbsolutePath(); } counter++; } counter = 0; cache[cacheCounter] = new CacheDto(); cache[cacheCounter].setQuery(path.getKey()); cache[cacheCounter].setGifs(array); cacheCounter++; } return cache; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T21:03:34.180", "Id": "519836", "Score": "3", "body": "Hi @Vadym - is there a reason why you have counter (other than for debugging?). Perhaps some javadoc might help. And if one of the Files for that query is a directory you get all elements in that directory - what if some aren't GIFs, and what if there's a sub-sub-directory of GIFS??" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T04:13:19.663", "Id": "519843", "Score": "7", "body": "Please explain what the code is supposed to do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T06:05:19.020", "Id": "519850", "Score": "4", "body": "Code Review requires code with sufficient context for reviewers to understand how that code is used. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-26T12:20:32.337", "Id": "520166", "Score": "3", "body": "This doesn't appear to be a _parser_. What is the intent of the code? Also, it looks incomplete - no classes, missing imports, undefined variables. It's really not ready for review, but that you could easily fix that." } ]
[ { "body": "<p>First off, it would've been nice to see the entire method, or preferrably even the entire class. Having less context makes reviewing harder.</p>\n<p>That said, I feel there was enough for a review, so here goes.</p>\n<p>You call <code>file.listFiles</code> 3 times per file. It would probably be more efficient to store the result in a variable the first time you call it so you don't have to do it again.</p>\n<p>On that note, both your <code>Objects.requireNonNull</code> calls are redundant - they're in a branch where you've already checked <code>file.listFiles()</code> isn't <code>null</code>.</p>\n<p>Your code's behaviour seems <em>weird</em> when operating on a path containing both directories and files. At best the return value is weird and/or inconsistent. At worst, you might get an <code>ArrayIndexOutOfBoundsException</code>. To see how, let's look at a directory with the following content:</p>\n<pre><code>some_file.gif\nsome_folder/\n cat.gif\n dog.gif\nthing.gif\nthing2.gif\nthing3.gif\nthing4.gif\n</code></pre>\n<p>Now, we don't <em>know</em> what order <code>listFiles()</code> will return those files in. But let's assume they'll be returned in the order I listed them in above. What your code will do in that case is:</p>\n<ul>\n<li>Create an array <code>array</code> with length 6</li>\n<li>Iterate over the content of that folder:\n<ul>\n<li>Add <code>some_file.gif</code> to <code>array</code></li>\n<li>Notice that <code>some_folder</code> is a directory and iterate over that:\n<ul>\n<li>Replace <code>array</code> with a brand-new array with length 3. <code>some_file.gif</code> is lost in the process, which is not ideal</li>\n<li>Add <code>some_folder/cat.gif</code> and <code>some_folder/dog.gif</code> to that array</li>\n<li>Reset <code>counter</code> to 0</li>\n</ul>\n</li>\n<li>Add <code>thing.gif</code> to <code>array</code> at index 0, overwriting <code>some_folder/cat.gif</code> - not sure we want that</li>\n<li>Add <code>thing2.gif</code> to <code>array</code> at index 1, overwriting <code>some_folder/dog.gif</code> too</li>\n<li>Add <code>thing3.gif</code> to <code>array</code> at index 2. Fortunately, <code>array</code> has 3 spaces in it, so it fits</li>\n<li>Add <code>thing4.gif</code> to <code>array</code> at index 3. <code>array</code> doesn't have an index 3, so we get an <code>ArrayIndexOutOfBoundsException</code></li>\n</ul>\n</li>\n</ul>\n<p>I think what you want to do is use some sort of dynamically-sized <code>Collection&lt;String&gt;</code> to collect file paths. Much easier than keeping track of counters. Same for <code>cache</code>. If you really need arrays at the end, collections have a <code>toArray</code> method.</p>\n<p>When you have a <code>Map.EntrySet</code>, you already know what values are associated with each key. Unless you're updating the map as you're working (which you aren't), <code>someMap.get(entry.getKey())</code> is just a more complicated way to say <code>entry.getValue()</code></p>\n<p>And, as Mr R pointed out in a comment, you only check for one level of directories. If you have a structure like:</p>\n<pre><code>one/\n two/\n three/\n hello.gif\n</code></pre>\n<p>...you'll return <code>one/two</code>, but I think you'd want to return <code>one/two/three/hello.gif</code>. If you want to check for arbitrary depths, you may want to look into a different approach for traversing the file system.</p>\n<p>Putting it all together, I might do something a bit like</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static CacheDto[] makeDTOs(Map&lt;String, File[]&gt; queriedCache) {\n Collection&lt;CacheDto&gt; cache = new ArrayList&lt;&gt;();\n\n for (Map.Entry&lt;String, File[]&gt; entry : queriedCache.entrySet()) {\n Collection&lt;String&gt; paths = new ArrayList&lt;&gt;();\n Queue&lt;File&gt; filesToCheck = new PriorityQueue&lt;&gt;(Arrays.asList(entry.getValue()));\n\n while ( ! filesToCheck.isEmpty() ) {\n File file = filesToCheck.poll();\n if (file.isDirectory()) {\n for (File child : file.listFiles()) {\n filesToCheck.add(child);\n }\n } else {\n files.add(file.getAbsolutePath());\n }\n }\n\n CacheDto dto = new CacheDto();\n dto.setQuery(entry.getKey());\n dto.setGifs(paths.toArray(new String[0]));\n\n cache.add(dto);\n }\n\n return cache.toArray(new CacheDto[0]);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-27T12:31:22.800", "Id": "520227", "Score": "0", "body": "This question has one vote to close specifically for the reasons you cite at the beginning of the answer. I left the question open because you provided a good answer but in the future it might be better not to answer questions that seem to be off-topic." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T23:34:14.993", "Id": "263297", "ParentId": "263292", "Score": "10" } } ]
{ "AcceptedAnswerId": "263297", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T19:35:34.947", "Id": "263292", "Score": "2", "Tags": [ "java", "spring" ], "Title": "How can I rewrite the below parser code in Java" }
263292
<p>I am working on detection the selfish node based on this equation Using awk File : (Node Communication Ratio) NCR= ((Get Route Request-(Get Route Request-Reply Route Request))/Get Route Request)*100</p> <p>Is the code correct?</p> <pre><code>BEGIN { ReqCounter=0; RepCounter=0; NCRCounter=0; Normalcounter=0; } {action=$1; node=$5 if(action == &quot;s&quot; || action == &quot;r&quot; || action == &quot;f&quot;) { if(($61 == &quot;REQUEST&quot;)) ReqCounter++; if(($57 == &quot;REPLY&quot;)) RepCounter++; } } END { NCR= ((ReqCounter-(ReqCounter-RepCounter))/ReqCounter)*100; for (i=0; i&lt;20; i++) { if(NCR &lt;= 30) NCRCounter++; else Normalcounter++; } printf &quot;number of nodes:%d \n&quot;, i; printf &quot;REQUEST Count:%d \n&quot;, ReqCounter; printf &quot;REPLY Count:%d \n&quot;, RepCounter; printf &quot;number of selfish nodes:%d \n&quot;, NCRCounter; printf &quot;number of normal nodes:%d \n&quot;, Normalcounter; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T11:51:12.247", "Id": "519861", "Score": "2", "body": "Net simulator NS-2 : As usual, an analyzing awk script must be a match for the trace.tr . ... If you want an answer, then the file.tcl or the trace.tr must be available." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T17:37:29.453", "Id": "519888", "Score": "0", "body": "Welcome to Code Review. Did you test the code you wrote? Did it appear to function correctly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T18:19:35.633", "Id": "519896", "Score": "0", "body": "https://drive.google.com/drive/folders/1IX9dz7PJIR3S_g8_l89ecsFhRY6fX_vj?usp=sharing" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T18:22:30.557", "Id": "519897", "Score": "0", "body": "It always shows me that all the nodes are selfish.. I don't know if the problem is from the awk file or from the tcl file" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T20:43:36.130", "Id": "263295", "Score": "1", "Tags": [ "awk" ], "Title": "detection the selfish node Using awk File" }
263295
<p>I made a trival snake game below to practice my C++ and Win32 programming skills.</p> <pre><code>/* g++ snake.cpp -o snake -lgdi32 -Wl,-subsystem,windows */ #include &lt;deque&gt; #include &lt;vector&gt; #include &lt;cstdio&gt; #include &lt;ctime&gt; #include &lt;Windows.h&gt; #define ID_TIMER 1 constexpr int WND_WIDTH = 500; constexpr int WND_HEIGHT = 500; struct Cell { int row, col; Cell(int row, int col) : row(row), col(col) {} }; class Snake { public: Snake(int rows, int cols); ~Snake(); void Update(HWND hWnd); void DrawBitmap(HDC hdc, RECT *rect, BITMAPINFO info); void HandleKey(WPARAM wParam); int GetScore(); private: enum Direction { UP = 0, DOWN, LEFT, RIGHT }; enum CellType { EMPTY = 0, SNAKE, FOOD }; std::vector&lt;BYTE&gt; pixels; std::deque&lt;Cell&gt; snake; int rows; int cols; int dir; void MakeFood(); void SetCell(int row, int col, CellType type); CellType GetCellType(int row, int col); Cell Move(const Cell&amp; cell); }; Snake::Snake(int rows, int cols) : rows(rows), cols(cols) { pixels.resize(rows * cols * 4); srand(static_cast&lt;unsigned int&gt;(time(NULL))); Snake::MakeFood(); snake.push_back(Cell(rows / 2, cols / 2)); dir = UP; } Snake::~Snake() {} void Snake::Update(HWND hWnd) { snake.push_back(Snake::Move(snake.back())); Cell head = snake.back(); bool eaten = false; if (Snake::GetCellType(head.row, head.col) == FOOD) { snake.push_back(Snake::Move(head)); Cell newHead = snake.back(); Snake::SetCell(newHead.row, newHead.col, SNAKE); eaten = true; } else if (Snake::GetCellType(head.row, head.col) == SNAKE) { char buff[200]; snprintf(buff, sizeof(buff), &quot;Score: %d&quot;, Snake::GetScore()); KillTimer(hWnd, ID_TIMER); MessageBox(hWnd, TEXT(buff), &quot;Game Over!&quot;, MB_OK | MB_ICONINFORMATION); DestroyWindow(hWnd); } Snake::SetCell(head.row, head.col, SNAKE); Cell tail = snake.front(); snake.pop_front(); Snake::SetCell(tail.row, tail.col, EMPTY); if (eaten) Snake::MakeFood(); } void Snake::DrawBitmap(HDC hdc, RECT *rect, BITMAPINFO info) { int width = rect-&gt;right - rect-&gt;left; int height = rect-&gt;bottom - rect-&gt;top; StretchDIBits(hdc, 0, 0, width, height, 0, 0, cols, rows, &amp;pixels[0], &amp;info, DIB_RGB_COLORS, SRCCOPY); } void Snake::HandleKey(WPARAM wParam) { switch (wParam) { case VK_UP: dir = UP; break; case VK_DOWN: dir = DOWN; break; case VK_LEFT: dir = LEFT; break; case VK_RIGHT: dir = RIGHT; break; default: break; } } int Snake::GetScore() { return snake.size(); } void Snake::MakeFood() { int row = rand() % rows; int col = rand() % cols; while (Snake::GetCellType(row, col) == SNAKE) { row = rand() % rows; col = rand() % cols; } Snake::SetCell(row, col, FOOD); } void Snake::SetCell(int row, int col, CellType type) { int offset = row * cols * 4 + col * 4; switch (type) { case EMPTY: pixels[offset] = 0; pixels[offset + 1] = 0; pixels[offset + 2] = 0; pixels[offset + 3] = 255; break; case SNAKE: pixels[offset] = 0; pixels[offset + 1] = 255; pixels[offset + 2] = 0; pixels[offset + 3] = 255; break; case FOOD: pixels[offset] = 0; pixels[offset + 1] = 0; pixels[offset + 2] = 255; pixels[offset + 3] = 255; break; default: break; } } Snake::CellType Snake::GetCellType(int row, int col) { int offset = row * rows * 4 + col * 4; int red = pixels[offset + 2]; int green = pixels[offset + 1]; int blue = pixels[offset]; if (red == 0 &amp;&amp; green == 0 &amp;&amp; blue == 0) return EMPTY; if (red == 0 &amp;&amp; green == 255 &amp;&amp; blue == 0) return SNAKE; if (red == 255 &amp;&amp; green == 0 &amp;&amp; blue == 0) return FOOD; return EMPTY; // should never reach here } Cell Snake::Move(const Cell&amp; cell) { Cell c(cell.row, cell.col); switch (dir) { case UP: c.row += 1; break; case DOWN: c.row -= 1; break; case LEFT: c.col -= 1; break; case RIGHT: c.col += 1; break; } // teleportation if (c.row == -1) c.row = rows - 1; if (c.row == rows) c.row = 0; if (c.col == -1) c.col = cols - 1; if (c.col == cols) c.col = 0; return c; } LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { static BITMAPINFO info; static Snake *snake; switch (msg) { case WM_CREATE: { int rows = 40; int cols = 40; info.bmiHeader.biSize = sizeof(info.bmiHeader); info.bmiHeader.biWidth = cols; info.bmiHeader.biHeight = rows; info.bmiHeader.biPlanes = 1; info.bmiHeader.biBitCount = 32; info.bmiHeader.biCompression = BI_RGB; info.bmiHeader.biSizeImage = 0; info.bmiHeader.biXPelsPerMeter = 0; info.bmiHeader.biYPelsPerMeter = 0; info.bmiHeader.biClrUsed = 0; info.bmiHeader.biClrImportant = 0; snake = new Snake(rows, cols); if(!SetTimer(hWnd, ID_TIMER, 80, NULL)) { MessageBox(hWnd, &quot;Could not set timer!&quot;, &quot;Error&quot;, MB_OK | MB_ICONEXCLAMATION); PostQuitMessage(1); } break; } case WM_PAINT: { RECT rcClient; PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &amp;ps); GetClientRect(hWnd, &amp;rcClient); snake-&gt;DrawBitmap(hdc, &amp;rcClient, info); EndPaint(hWnd, &amp;ps); break; } case WM_TIMER: { RECT rcClient; HDC hdc = GetDC(hWnd); GetClientRect(hWnd, &amp;rcClient); snake-&gt;Update(hWnd); snake-&gt;DrawBitmap(hdc, &amp;rcClient, info); ReleaseDC(hWnd, hdc); break; } case WM_KEYDOWN: snake-&gt;HandleKey(wParam); break; case WM_CLOSE: DestroyWindow(hWnd); break; case WM_DESTROY: delete snake; PostQuitMessage(0); break; default: return DefWindowProc(hWnd, msg, wParam, lParam); } return 0; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { const TCHAR szClassName[] = TEXT(&quot;MyClass&quot;); WNDCLASS wc; HWND hWnd; MSG msg; wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wc.lpszMenuName = NULL; wc.lpszClassName = szClassName; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); if (!RegisterClass(&amp;wc)) { MessageBox(NULL, TEXT(&quot;Window Registration Failed!&quot;), TEXT(&quot;Error!&quot;), MB_ICONEXCLAMATION | MB_OK); return 1; } hWnd = CreateWindow(szClassName, TEXT(&quot;Snake&quot;), WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, /* this window style prevents window resizing */ CW_USEDEFAULT, CW_USEDEFAULT, WND_WIDTH, WND_HEIGHT, NULL, NULL, hInstance, NULL); if (hWnd == NULL) { MessageBox(NULL, TEXT(&quot;Window Creation Failed!&quot;), TEXT(&quot;Error!&quot;), MB_ICONEXCLAMATION | MB_OK); return 1; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); while (GetMessage(&amp;msg, NULL, 0, 0) &gt; 0) { TranslateMessage(&amp;msg); DispatchMessage(&amp;msg); } return (int) msg.wParam; } </code></pre> <p>I'm looking for some ways to improve the quality and efficiency of my C++ code. I'm worried if I'm misusing some data structures. Is Win32 bitmap a good choice for representing a snake game board?</p> <p>Did I properly structure my code? Is there any way I can improve my code organization?</p> <p>Miscellaneous feedbacks are welcome!</p> <p>This is my first time asking for a code review on C++. I hope I get decent feedbacks.</p>
[]
[ { "body": "<p><code>#define ID_TIMER 1</code></p>\n<p>Just because you're using it with Win32 API calls doesn't change the fact that MACROS==BAD, constexpr==good.</p>\n<pre><code>struct Cell\n{\n int row, col;\n Cell(int row, int col) : row(row), col(col)\n {}\n};\n</code></pre>\n<p>Your constructor doesn't add anything over what the built-in aggregate initialization would offer, and having it prevents the class from being &quot;trivial&quot;. It's best to leave it out in this case. You just have to use the C++11 style (curly brace) uniform initialization; e.g. <code>snake.push_back(Cell{rows / 2, cols / 2});</code>. But actually the class name is not even necessary here, and you can write <code>snake.push_back({rows / 2, cols / 2});</code>.</p>\n<p>In general, you are not using uniform initialization anywhere.</p>\n<pre><code>Snake::~Snake()\n{}\n</code></pre>\n<p>Write, in the class body, <code>~Snake() = default;</code> instead. It is better for a number of reasons.</p>\n<p>Your <code>Snake</code> class uses the auto-generated copy constructor and assignment operator. So I wonder why you bothered mentioning the destructor when it doesn't need anything beyond what's automatically supplied, too. Did you mean for the class to be able to be duplicated and assigned?</p>\n<pre><code>static Snake *snake;\n ...\n snake = new Snake(rows, cols);\n</code></pre>\n<p>Why do you use <code>new</code> instead of using a variable of that type?\n<code>rows</code> and <code>cols</code> are declared locally but not <code>const</code> or <code>constexpr</code>, though they seem like they are constants.</p>\n<p>There's nothing in the class that would require its construction to be delayed until\nthe WM_CREATE message. Just declare it, with initializer, as a global variable.</p>\n<hr />\n<p>The raw use of Win32 API functions and types, in an otherwise C++ program, is brutal. I would always add wrappers and whatnot to improve things. For example, use RAII/RFID for the various HANDLE types.</p>\n<hr />\n<pre><code>Cell Snake::Move(const Cell&amp; cell)\n{\n Cell c(cell.row, cell.col);\n \n switch (dir)\n {\n case UP: c.row += 1; break;\n case DOWN: c.row -= 1; break;\n case LEFT: c.col -= 1; break;\n case RIGHT: c.col += 1; break;\n }\n \n // teleportation\n if (c.row == -1) c.row = rows - 1;\n if (c.row == rows) c.row = 0;\n if (c.col == -1) c.col = cols - 1;\n if (c.col == cols) c.col = 0;\n \n return c;\n}\n</code></pre>\n<p>You are passing in a reference to an original cell, but then immediately duplicating it to make a local copy, and then ignoring the one you passed in.\nFirst of all, you're copying it the hard way. Just write <code>Cell c = cell;</code> to invoke the copy constructor. Second, what is the point of passing by reference (avoid making a copy) just to make a local copy anyway? You get the same effect, more efficiently, if you just pass by value.</p>\n<p><code>Cell Snake::Move(Cell c)</code></p>\n<hr />\n<pre><code>if (Snake::GetCellType(head.row, head.col) == FOOD)\n {...}\nelse if (Snake::GetCellType(head.row, head.col) == SNAKE)\n</code></pre>\n<p>You're calling to look up the <code>GetCellType</code> repeatedly for the same cell! You already looked it up once, why do so again?</p>\n<p>The chained <code>if</code> statements should really be a <code>switch</code> statement, which will automatically prevent you from repeating the lookup code.</p>\n<p>This is in a member function for <code>Snake</code>, so why do you need to qualify the calls to <code>GetCellType</code> with the same class that you're already in?</p>\n<hr />\n<pre><code>char buff[200];\nsnprintf(buff, sizeof(buff), &quot;Score: %d&quot;, Snake::GetScore());\n</code></pre>\n<p>Isn't there a form of <code>snprintf</code> that automatically picks up the size of an array when passed as the buffer? I know a lot of Microsoft's added &quot;buffer overflow safe&quot; functions have this. It's better to let it pick up the size automatically.</p>\n<hr />\n<pre><code> int width = rect-&gt;right - rect-&gt;left;\n int height = rect-&gt;bottom - rect-&gt;top;\n</code></pre>\n<p>In general, use <code>const</code> more.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T00:38:36.373", "Id": "519913", "Score": "0", "body": "Thanks for the review! I have a long way to go... What is RAII/RFID?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T13:43:32.740", "Id": "519956", "Score": "1", "body": "https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization Resource Acquisition Is Initialization / Resource Freeing Is Destruction. When the HANDLE goes out of scope, it is automatically closed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T14:16:36.423", "Id": "263328", "ParentId": "263298", "Score": "2" } } ]
{ "AcceptedAnswerId": "263328", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-21T23:38:51.103", "Id": "263298", "Score": "2", "Tags": [ "c++", "windows", "snake-game", "winapi" ], "Title": "Win32 Snake game" }
263298
<p>I use the following code in order to assess the quality of an audio, which is based on this <a href="https://github.com/lochenchou/MOSNet" rel="nofollow noreferrer">original-project: MOSNet</a>. I call <code>compute_mosnet_score()</code> in a loop with a different audio file in each iteration.</p> <pre><code>import os import scipy import librosa import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import Model, layers from tensorflow.keras.constraints import max_norm from tensorflow.keras.layers import Dense, Dropout, Conv2D from tensorflow.keras.layers import LSTM, TimeDistributed, Bidirectional class MOSNet(): def __init__(self, window, wave_handler, hop=None): # init self.wave_handler = wave_handler # constants self.fixed_rate = 16000 self.mono = True self.absolute = True self.FFT_SIZE = 512 self.SGRAM_DIM = self.FFT_SIZE // 2 + 1 self.HOP_LENGTH = 256 self.WIN_LENGTH = 512 _input = keras.Input(shape=(None, 257)) re_input = layers.Reshape((-1, 257, 1), input_shape=(-1, 257))(_input) # CNN conv1 = (Conv2D(16, (3, 3), strides=(1, 1), activation='relu', padding='same'))(re_input) conv1 = (Conv2D(16, (3, 3), strides=(1, 1), activation='relu', padding='same'))(conv1) conv1 = (Conv2D(16, (3, 3), strides=(1, 3), activation='relu', padding='same'))(conv1) conv2 = (Conv2D(32, (3, 3), strides=(1, 1), activation='relu', padding='same'))(conv1) conv2 = (Conv2D(32, (3, 3), strides=(1, 1), activation='relu', padding='same'))(conv2) conv2 = (Conv2D(32, (3, 3), strides=(1, 3), activation='relu', padding='same'))(conv2) conv3 = (Conv2D(64, (3, 3), strides=(1, 1), activation='relu', padding='same'))(conv2) conv3 = (Conv2D(64, (3, 3), strides=(1, 1), activation='relu', padding='same'))(conv3) conv3 = (Conv2D(64, (3, 3), strides=(1, 3), activation='relu', padding='same'))(conv3) conv4 = (Conv2D(128, (3, 3), strides=(1, 1), activation='relu', padding='same'))(conv3) conv4 = (Conv2D(128, (3, 3), strides=(1, 1), activation='relu', padding='same'))(conv4) conv4 = (Conv2D(128, (3, 3), strides=(1, 3), activation='relu', padding='same'))(conv4) re_shape = layers.Reshape((-1, 4 * 128), input_shape=(-1, 4, 128))(conv4) # BLSTM blstm1 = Bidirectional(LSTM(128, return_sequences=True, dropout=0.3, recurrent_dropout=0.3, recurrent_constraint=max_norm(0.00001)), merge_mode='concat')(re_shape) # DNN flatten = TimeDistributed(layers.Flatten())(blstm1) dense1 = TimeDistributed(Dense(128, activation='relu'))(flatten) dense1 = Dropout(0.3)(dense1) frame_score = TimeDistributed(Dense(1), name='frame')(dense1) average_score = layers.GlobalAveragePooling1D(name='avg')(frame_score) self.model = Model(outputs=[average_score, frame_score], inputs=_input) # weights are in the directory of this file pre_trained_dir = &quot;resources&quot; # load pre-trained weights. CNN_BLSTM is reported as best self.model.load_weights(os.path.join(pre_trained_dir, 'cnn_blstm.h5')) def compute_mosnet_score(self, wav_file, fs): &quot;&quot;&quot; Evaluate the audio quality using a MOSnet (neural network). &quot;&quot;&quot; # compute mosnet score sig4mosnet, sig4mosnetlen = self.wave_handler.ffmpeg_load_audio(wav_file, fs) mosnet_scores, avg_mos_score = self.predict_mos(sig4mosnet, self.fixed_rate) return avg_mos_score def predict_wrapper(self, mag): res = self.model.predict(mag, verbose=0, batch_size=1, steps=1) return res def get_mag(self, audios, rate): &quot;&quot;&quot; Get signal magnitude. &quot;&quot;&quot; # stft. D: (1+n_fft//2, T) -&gt; magnitude spectrogram mag = np.abs(librosa.stft(y=np.asfortranarray(audios), n_fft=self.FFT_SIZE, hop_length=self.HOP_LENGTH, win_length=self.WIN_LENGTH, window=scipy.signal.hamming)) # (1+n_fft/2, T) # shape in (T, 1+n_fft/2) -&gt; now call the actual MOSnet mag = np.transpose(mag.astype(np.float32)) return mag[None, ...] def predict_mos(self, audios, rate): &quot;&quot;&quot; Predict the Mean Objective Score of a given frame. &quot;&quot;&quot; mag = self.get_mag(audios, rate) res = self.predict_wrapper(mag) return res[1][0], round(res[0][0][0], 3) </code></pre> <p>Since each iteration, the code computes the score using a different audio, it means the input size changes. This causes the following warning:</p> <pre><code>WARNING:tensorflow:6 out of the last 12 calls to &lt;function _make_execution_function.&lt;locals&gt;.distributed_function at 0x7f999459e170&gt; triggered tf.function retracing. Tracing is expensive and the excessive number of tracings is likely due to passing python objects instead of tensors. Also, tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. Please refer to https://www.tensorflow.org/tutorials/customization/performance#python_or_tensor_args and https://www.tensorflow.org/api_docs/python/tf/function for more details. </code></pre> <p><strong>Unfortunately, this retracing is slowing down the code so is there any alternatives here that will disable retracing or accelerate the code?</strong> Obviously, I can use GPU accelerations, but those are not an option in my case. I already tried to frame the audio signal and feed it to the prediction fucntion, which reduces the warnings but doesn't remove them all. However that is not practical since it add extra calls and slows the code down. I also tried <code>@tf.function</code> and <code>@tf.function( experimental_relax_shapes=True)</code> for <code>def predict_wrapper(self, mag)</code> but it resulted in a <code>ValueError: in converted code</code>.</p> <p>*I am using :</p> <pre><code>tensorflow-base 2.1.0 tensorflow-estimator 2.1.0 </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T00:34:28.010", "Id": "263299", "Score": "2", "Tags": [ "python", "performance", "tensorflow", "keras" ], "Title": "How to avoid retracing in tensorflow when predicting scores for inputs with different sizes" }
263299
<p>I created a rough implementation of a component that lists stuff based on data has the option to enable searching for that data. I've not used React all that much so it's probably a terrible way to implement it. I looked into passing state upwards and the most common way I saw was to do what I did and pass the setter function as a prop. One thing that isn't clean is having to pass <code>renderBans</code> as a prop but I wasn't sure how else to render each item from the given data and update the state.</p> <p>The list component</p> <pre><code>import Ban from './Ban' import styles from '../styles/BansList.module.css' import React, { useState, useEffect } from 'react'; import Search from './Search' const BansList = ({title, bans, search=false}) =&gt; { const bansPerRender = 3; const [bansToRender, setBansToRender] = useState(); const [next, setNext] = useState(3); const showMore = () =&gt; { setBansToRender(renderBans(bans.slice(0, next+bansPerRender))) setNext(next+bansPerRender) } const renderBans = bans =&gt; { let holdBans = [] bans.map((ban, index) =&gt; { // convert from Unix timestamp to HH:MM:SS let banDate = new Date(ban.timestamp*1000) // if ban not expired if(new Date().getTime() &lt; banDate.setMinutes(banDate.getMinutes() + ban.bantime)) isExpired = false // reset banDate to original banDate = new Date(ban.timestamp * 1000) let permaBan; ban.bantime === 0 ? permaBan = true : permaBan = false; holdBans.push(&lt;Ban key={index} offenderName={ban.offender_name} offenderSteamId={ban.offender_steamid} banDate={banDate} adminName={ban.admin_name} banReason={ban.reason} banLength={ban.bantime} isExpired={false} permaBan={permaBan}/&gt;) }) return holdBans; } useEffect(() =&gt; { setBansToRender(renderBans(bans.slice(0, bansPerRender))) }, []) return ( &lt;&gt; &lt;div className={styles.wrapper}&gt; {search &amp;&amp; &lt;Search toSearch={bans} sendResults={setBansToRender} renderFunc={renderBans} resultsToSend={bansPerRender}/&gt;} &lt;h1&gt;{title}&lt;/h1&gt; {bansToRender} &lt;button onClick={() =&gt; {showMore()}}&gt;Show More&lt;/button&gt; &lt;/div&gt; &lt;/&gt; ) } export default BansList; </code></pre> <p>The search component</p> <pre><code>import React, { useState, useEffect, useContext } from 'react'; import Fuse from 'fuse.js' import SearchResults from './SearchResults' const Search = ({toSearch, sendResults, renderFunc, resultsToSend='all'}) =&gt; { // setup state for search const [query, setQuery] = useState(&quot;&quot;); const [searchResults, setSearchResults] = useState(); let isExpired = true; const search = (query) =&gt; { if(!query) { setSearchResults(toSearch) return; } const fuseGuardban = new Fuse(toSearch, { keys: [&quot;offender_name&quot;, &quot;admin_name&quot;, &quot;offender_steamid&quot;], useExtendedSearch: true }); const result = fuseGuardban.search(query) const matches = [] if (!result.length) { setSearchResults([]); } else { result.forEach(({item}) =&gt; { matches.push(item); }); setSearchResults(matches); } if(searchResults || searchResults == []) sendResults(renderFunc(searchResults.slice(0, resultsToSend))) } return ( &lt;&gt; &lt;input type=&quot;search&quot; placeholder=&quot;Search by name&quot; onChange={e =&gt; search(e.target.value)}/&gt; &lt;span&gt;{query}&lt;/span&gt; &lt;/&gt; ) } export default Search; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T00:39:58.630", "Id": "263302", "Score": "4", "Tags": [ "react.js", "jsx" ], "Title": "React - Show more and search functionality" }
263302
<p>In the process of trying to learn python, and also help my daughter with some elementary math practice over the summer, I'm trying to write a simple math quiz which will reinforce what she learned over the last year. I am using the following, which works okay:</p> <pre><code>import random import operator def quiz(): print('Welcome! This is a 42 question quiz!\n') score = 0 for i in range(42): correct = askQuestion() if correct: score += 1 print('Correct!') print('Score', score, '\n') else: print('Incorrect!') print('Score', score, '\n') print('Your score was {}/42'.format(score)) def askQuestion(): answer = randomCalc() guess = float(input()) return guess == answer def randomCalc(): ops = {'+':operator.add, '-':operator.sub} num1 = random.randint(0,20) num2 = random.randint(0,20) op = random.choice(list(ops.keys())) answer = ops.get(op)(num1,num2) print('What is {} {} {}?'.format(num1, op, num2)) return answer quiz() </code></pre> <p>The problem that I have is that this quiz asks subtraction questions which return negative numbers. As my daughter is in elementary school, I would need the questions to focus on basic subtraction which return <strong>non-negative</strong> numbers only. I don't need to go that far off the rails yet.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T08:52:23.787", "Id": "519858", "Score": "2", "body": "Micro-review: comparing floating-point values with `==` is risky in any language, due to precision issues." } ]
[ { "body": "<p>You made a wise choice wanting to tango with the snake. Just as a mean teacher I will pick apart your code in excruciating detail. I really like your code for a beginner. It is clearly structured, it works and your naming is good.\nWith that being said, you do make some classical beginner mistakes</p>\n<hr />\n<h2><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8 - Style Guide for Python Code</a></h2>\n<p>Just as learning a new language it is important to learn its <em>grammar</em>. Your speech can be <em>technically</em> correct and understandable, but one can tell it is not your mother tongue. The same can be said for your code. It looks like you have experience from a different language, and I would recommend getting familiar with Python's grammar.</p>\n<p>PEP 8 recommends the following <a href=\"https://www.python.org/dev/peps/pep-0008/#prescriptive-naming-conventions\" rel=\"nofollow noreferrer\">naming-conventions</a>:</p>\n<ul>\n<li><code>CAPITALIZED_WITH_UNDERSCORES</code> for constants</li>\n<li><code>UpperCamelCase</code> for class names</li>\n<li><code>lowercase_separated_by_underscores</code> for other names</li>\n</ul>\n<p>So your functions should not follow cammelcase.</p>\n<hr />\n<h2><a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic numbers</a></h2>\n<p>A concept you might find amusing is magic numbers. This is known as a code smell; something which should be avoided when programming. Programming is about making life easier, and to automate the boring stuff. Hardcoding numbers goes against this, and therefore should be avoided. The solution is to extract these numbers into constants following the <a href=\"https://www.python.org/dev/peps/pep-0008/#prescriptive-naming-conventions\" rel=\"nofollow noreferrer\">PEP8 naming-conventions</a>.</p>\n<pre><code>QUESTIONS = 42\n\ndef quiz():\n print(f'Welcome! This is a {QUESTIONS} question quiz!\\n')\n score = 0\n for i in range(QUESTIONS):\n</code></pre>\n<hr />\n<h2><a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">f-strings</a></h2>\n<p>Did you notice the <code>f</code> in the last code snippet? f-strings is the new way of formating strings in Python, and you should usually use them. For instance</p>\n<pre><code>print('What is {} {} {}?'.format(num1, op, num2))\n</code></pre>\n<p>becomes</p>\n<pre><code>print(f'What is {num1} {op} {num2}?')\n</code></pre>\n<p>Which is easier to read.</p>\n<hr />\n<h2><a href=\"https://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow noreferrer\">KISS (Keep it simple stupid)</a></h2>\n<p>While I have nothing againt using libraries or the <code>operator</code> module, I would suggest sticking to the basics when starting out. This part is heavily opinionated, but I would suggest not using code you do not understand. If you come back to the code half a year later, will you still remember the intricacies of <code>op</code>?</p>\n<p>You already know how to use <code>if-else</code> so you could have done</p>\n<pre><code>operator_choice = random.randint(0, 1)\nif operator_choice == 0:\n answer = num1 - num2\nelif operator_choice == 1:\n answer = num1 + num2\n</code></pre>\n<hr />\n<h2>handling user input</h2>\n<p><em>Never</em> assume that your users input things exactly in the format you want.</p>\n<pre><code>def askQuestion():\n answer = randomCalc()\n guess = float(input())\n return guess == answer\n</code></pre>\n<p>Here you need to do some checks to make sure the <code>guess</code> is sanitized. What happens if the user inputs <code>2*3</code>? or <code>exit</code>? A vague idea is something like</p>\n<pre><code>def get_valid_user_input():\n try:\n return float(input())\n except ValueError:\n print('Ooops, you need to input a number!')\n</code></pre>\n<hr />\n<h2><a href=\"https://stackoverflow.com/q/419163\"><code>if __name__ == &quot;__main__&quot;</code>:</a></h2>\n<p>Put the parts of your code that are the ones calling for execution behind a <a href=\"https://stackoverflow.com/q/419163\"><code>if __name__ == &quot;__main__&quot;:</code></a>. This way you can import this python module from other places if you ever want to, and the guard prevents the main code from accidentally running on every import.</p>\n<hr />\n<h2>negative numbers</h2>\n<p>I gave you two suggestions to enforce positive numbers:</p>\n<pre><code>num1 = random.randint(0,20)\nnum2 = random.randint(0,20)\nnum1, num2 = max(num1, num2), min(num1, num2)\n</code></pre>\n<p>or</p>\n<pre><code>num1 = random.randint(0,20)\nnum2 = random.randint(0,num1)\n</code></pre>\n<p>I would recommend trying out these two solutions and try to figure out the difference. As a mathematician there is a difference in the type of numbers you get. Note that the first one also could have been implemented as</p>\n<pre><code>num1 = random.randint(0, MAX_NUM1)\nnum2 = random.randint(0, MAX_NUM2)\nif num1 &lt; num2:\n num1, num2 = num2, num1\n</code></pre>\n<p>If you are not that comfortable with <code>min</code> and <code>max</code>.</p>\n<hr />\n<h1>Round two</h1>\n<p>I looked over your code again and found a few more things which I found odd. Remember how we talked about grammar at the start? It is somewhat peculiar when you say &quot;this code does X&quot; when it really does &quot;X and Y&quot; or even worse just &quot;Y&quot;.</p>\n<pre><code>def askQuestion():\n answer = randomCalc()\n guess = float(input())\n return guess == answer\n</code></pre>\n<p>This is not code that's just asking a question. It (1) takes in an answer from <code>randomCalc</code>, (2) takes in a guess from the user, and (3) checks whether the guess from the user matches the answer. You are not <em>really</em> interested in <em>asking</em> a question, that would be more akin to</p>\n<pre><code>def askQuestion(question):\n print(question)\n</code></pre>\n<p>What you <em>are</em> interested in is getting feedback from the user. So something akin to <code>get_guess_from_player</code> is probably a better name.\nSimilarly <code>randomCalc</code> is <em>not</em> just an calculator! It also asks the question!</p>\n<pre><code>def randomCalc():\n .\n .\n .\n print('What is {} {} {}?'.format(num1, op, num2))\n</code></pre>\n<p>Lastly you are doing something like</p>\n<pre><code>for i in range(42):\n</code></pre>\n<p>Which from a &quot;grammar&quot; (Pythonic way) should be</p>\n<pre><code>for _ in range(42):\n</code></pre>\n<p>since you never use the <code>_</code>. However, since you never use\nthe <code>for</code> loop, we can instead use something smarter.</p>\n<hr />\n<h2>suggestions</h2>\n<p>A clearer structure would be something like this: we define a function that <em>only</em> generates the question. We extract the magic numbers into constants at the start of the code</p>\n<pre><code>OPERATORS = [&quot;+&quot;, &quot;-&quot;]\nMAX_NUMBER = 20\nQUESTIONS = 42\n\ndef generate_question():\n operator = random.choice(OPERATORS)\n num1 = random.randint(0, MAX_NUMBER)\n num2 = random.randint(0, MAX_NUMBER)\n if num2 &gt; num1:\n num1, num2 = num2, num1\n return f&quot;{num1} {operator} {num2}&quot;\n</code></pre>\n<p>We create a function that <em>only</em> gets a valid guess from the user.</p>\n<pre><code>def get_guess():\n try:\n return float(input(&quot;&gt; &quot;))\n except ValueError:\n print(&quot;Ooops, you need to write in a number!&quot;)\n</code></pre>\n<p>Some fancy f-strings and a bit of cleanup the main function looks something like this.</p>\n<pre><code>def quiz():\n print(f&quot;Welcome! This is a {QUESTIONS} question quiz!\\n&quot;)\n score = 0\n for _ in range(QUESTIONS):\n print(question)\n guess = get_guess()\n if guess == eval(question):\n</code></pre>\n<hr />\n<h1>Be wary; dragons lie ahead</h1>\n<p>A trap many new programmers falls into is premature optimization. However, I can not avoid noticing that the logic in the code could be improved. If you are asking multiple questions; why not generate all the numbers and operators at the start? It would lead to a cleaner and faster code. Notice how our main loop now reads</p>\n<pre><code>for question in generated_questions():\n</code></pre>\n<p>Much more Pythonic! I also included Toby's suggestion even if it is 100% overkill when doing basic arithmetic.</p>\n<pre><code>import numpy as np\n\nQUESTIONS = 42\nBAN_NEGATIVE_NUMBERS = True\nOPERATORS = [&quot;-&quot;, &quot;+&quot;]\nMAX_NUMBER, DECIMALS = 20, 2\nMAX_ERROR = 10 ** (1 - DECIMALS)\n\ndef generate_questions():\n operators = np.random.choice(a=OPERATORS, size=(QUESTIONS, 1))\n numbers = np.random.choice(a=MAX_NUMBER, size=(QUESTIONS, 2))\n for operator, (num1, num2) in zip(operators, numbers):\n if num1 &lt; num2 and operator == &quot;-&quot; and BAN_NEGATIVE_NUMBERS:\n num1, num2 = num2, num1\n yield f&quot;{num1} {operator[0]} {num2}&quot;\n\ndef get_guess():\n try:\n return float(input(&quot;&gt; &quot;))\n except ValueError:\n print(&quot;Ooops, you need to write in a number!&quot;)\n return float(&quot;Inf&quot;)\n\ndef quiz(score=0):\n print(f&quot;Welcome! This is a {QUESTIONS} question quiz!\\n&quot;)\n for question in generate_questions():\n print(question)\n guessed_right = abs(get_guess() - eval(question)) &lt;= MAX_ERROR\n score += 1 if guessed_right else 0\n print(&quot;Correct!&quot; if guessed_right else &quot;Incorrect&quot;, &quot;\\nScore&quot;, score, &quot;\\n&quot;)\n print(f&quot;Your score was {score}/{QUESTIONS} = {round(100*score/QUESTIONS, 2)}&quot;)\n\nif __name__ == &quot;__main__&quot;:\n quiz()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T17:16:32.273", "Id": "519885", "Score": "0", "body": "Overall agree, but what you're calling grammar is not grammar - it's style. Grammar and syntax are loosely interchangeable, and refer to what will or will not parse. Style does not affect whether code will parse, and is more about convention and legibility." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T17:23:33.890", "Id": "519887", "Score": "0", "body": "What I meant is that grammar is to a language what style is to a programming language. As you said it compiles (it is understandable), but breaks convention. Sorry if that was confusing, English is far from my first language." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T18:04:39.997", "Id": "519893", "Score": "0", "body": "@N3buchadnezzar and Toby Speight - I appreciate your candor and honest assessment of the code posted here, as well as the corrections you have recommended. I have seen other newbies post questions and the outcome for those folks was unfortunate to say the least. I am reviewing this now and will look to implement and continue testing and if other questions arise, I will be back. Thanks for your assistance!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T17:11:32.240", "Id": "519970", "Score": "0", "body": "@N3buchadnezzar in reading through your code...most of this makes sense. I appreciate your assistance. The one piece that I'm trying to make sense of - in the def generate_questions function, you have this line:\n\nnum1, num2 = num2, num1\n\nWith regard to the remainder of the function, what exactly is that doing?\n\nThe rest of the function says that we are generating the operator and choose two numbers and we're banning negative numbers - I'm not quite following the rest of the function.\n\nMany thanks for your help!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T17:29:51.323", "Id": "519971", "Score": "1", "body": "@Shane I recommend you trying it out! Try to define for instance `num1, num2 = 1, 2` and then print them `print(num1, num2)`. After these two lines write `num1, num2 = num2, num1` and then print. What happens?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T17:38:54.930", "Id": "519972", "Score": "0", "body": "Further I would strongly advice you to insert print statements everywhere to understand the code, bit by bit and google the unknown functions. What does [`zip`](https://www.geeksforgeeks.org/zip-in-python/) do, what is [`yield`](https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do), or [`eval`](https://stackoverflow.com/questions/9383740/what-does-pythons-eval-do). Try to break it down line by line, ternary by [ternary](https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T17:42:26.973", "Id": "519974", "Score": "1", "body": "Teach them to fish, don't give them the fish. 100%" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T06:37:31.683", "Id": "263308", "ParentId": "263306", "Score": "3" } }, { "body": "<p>What a beautiful exercise - both for you and your child. In brief, and significantly overlapping with the feedback from @N3buchadnezzar:</p>\n<ul>\n<li>Don't repeat the constant 42; centralize it</li>\n<li>Move 20 to a constant</li>\n<li>lower_snake_case for all of your symbols</li>\n<li>Factor out common statements to a single place, such as your score print</li>\n<li>f-strings are more convenient than format calls or multi-argument print calls</li>\n<li>Centralize your question-related I/O into one method (<code>ask_question</code>), and your computation into another (<code>random_calc</code>)</li>\n<li>Use PEP484 type hints</li>\n<li><code>float</code> is not appropriate here; use <code>int</code> instead</li>\n<li>Include a <code>main</code> guard</li>\n<li>You're not actually using <code>OPS</code> for its dictionary features, so just make it a tuple of tuples</li>\n<li>It's a little mean to mark a question incorrect without showing the actual answer. Consider including that.</li>\n</ul>\n<p>Suggested:</p>\n<pre><code>import random\nimport operator\nfrom typing import Tuple\n\nOPS = (\n ('+', operator.add),\n ('-', operator.sub),\n)\nMAX_TERM = 20\n\n\ndef quiz(n: int) -&gt; None:\n print(f'Welcome! This is a {n} question quiz!\\n')\n score = 0\n\n for _ in range(n):\n score += ask_question()\n print('Score', score, '\\n')\n\n print(f'Your score is {score}/{n}')\n\n\ndef ask_question() -&gt; int:\n num1, op, num2, answer = random_calc()\n guess = int(input(\n f'What is {num1} {op} {num2}? '\n ))\n\n if guess == answer:\n print('Correct!')\n return 1\n\n print(f'Incorrect; the answer is {answer}.')\n return 0\n\n\ndef random_calc() -&gt; Tuple[\n int, # First operand\n str, # Operator\n int, # Second operand\n int, # Answer\n]:\n num1 = random.randint(0, MAX_TERM)\n num2 = random.randint(0, MAX_TERM)\n op_name, op = random.choice(OPS)\n answer = op(num1, num2)\n return num1, op_name, num2, answer\n\n\nif __name__ == '__main__':\n quiz(n=5)\n</code></pre>\n<p>Output:</p>\n<pre><code>Welcome! This is a 5 question quiz!\n\nWhat is 5 - 6? -1\nCorrect!\nScore 1 \n\nWhat is 8 + 2? 10\nCorrect!\nScore 2 \n\nWhat is 20 - 6? 14\nCorrect!\nScore 3 \n\nWhat is 4 + 14? 18\nCorrect!\nScore 4 \n\nWhat is 16 - 4? 500\nIncorrect; the answer is 12.\nScore 4 \n\nYour score is 4/5\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T17:56:34.257", "Id": "519889", "Score": "0", "body": "I agree on most of this, but it *might* be useful to keep `OPS` as a `dict` to guarantee the operators have unique names" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T18:03:14.033", "Id": "519891", "Score": "1", "body": "@SaraJ I would agree if the ops are user-defined, but they are not - they're programmer-defined, and so given the simplicity of the data and the low risk I don't see the need." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T18:04:15.220", "Id": "519892", "Score": "1", "body": "@SaraJ Add to that that you'd not want to use a normal dict, but instead some implementation of a frozendict. Here with tuples you get immutability for free." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T18:14:14.020", "Id": "519895", "Score": "1", "body": "True, you do get immutability, but as mentioned you do give up uniqueness, and I don't see much reason to pick one over the other here (both are good of course). But yeah, for simple use of simple data it doesn't matter a whole lot either way" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T17:42:26.023", "Id": "263336", "ParentId": "263306", "Score": "1" } } ]
{ "AcceptedAnswerId": "263308", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T05:08:43.533", "Id": "263306", "Score": "3", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Python Math Quiz" }
263306
<p>This script is my first-ever attempt at writing anything in python. Though I have an electrical engineering background and therefore got a little programming education in college, it was fairly limited and I am definitely no big-time coder, so much of this script may be very rudimentary. I've never touched a JSON file before, and I just installed and configured my first MariaDB database last week, though I do have a little SQL experience with other relational databases. I figured I'd post this here just for general thoughts and suggestions on how I can do better in the future, both with revisions to this script and with python scripting in general.</p> <p>This script reads in the current point forecast for my local gridpoint from the National Weather Service API. It then grabs the forecast quantities that I am most interested in, which mainly mirror the data that I can collect with my Davis Vantage Pro2 weather station (which is writing minute-by-minute values into a different table in this same MariaDB database via a Meteobridge Pro). I will be running this script every couple hours to try to make sure I pick up every forecast run (there are generally around four runs per day, I believe), so the script also checks the database for the existence of forecast data with the same model-run timestamp before it writes everything.</p> <p>The script seems to do what I am after. I have just a little basic checking built-in to make sure I'm staying on the correct forecast period with all of my different parameters, as well as the aforementioned check for the same data already being present. So, beyond that, I'm open to suggestions and guidance on good form and practice in python scripting. This script and the MariaDB are running on a Fedora 34 server with 6 spinning hard drives in RAID5 and a caching enterprise SSD with a Ryzen 9 3950X CPU that is my emby media server, so it was mostly sitting idle when I'm not watching a movie...it needed something to do the rest of the time.</p> <pre><code>import noaa_sdk import json import geojson from datetime import datetime, timedelta from dateutil import tz from array import * from noaa_sdk import NOAA import re import mariadb # Setup Times from_zone = tz.tzutc() to_zone = tz.tzlocal() curr_time = datetime.now() curr_time = curr_time.replace(tzinfo=to_zone) # Make curr_time aware of time zone next_hour = curr_time.replace(second=0, microsecond=0, minute=0) + timedelta(hours=1) # Find the first forecast time that we'll be using later # Initialize intermediate forecast arrays tempi_fcst = [[0,0,0]] dewpi_fcst = [[0,0,0]] relhi_fcst = [[0,0,0]] windi_fcst = [[0,0,0]] wdiri_fcst = [[0,0,0]] propi_fcst = [[0,0,0]] qprfi_fcst = [[0,0,0]] skyci_fcst = [[0,0,0]] # Obtain current NWS forecast data n = NOAA() full_data = n.points_forecast(40.1585, -103.2036, type='forecastGridData') # Determine Forecast Time and Figure out how long this forecast is good for forecast_time = full_data['properties'].get('updateTime')[:19] forecast_time = datetime.strptime(str(forecast_time), '%Y-%m-%dT%H:%M:%S') forecast_time = forecast_time.replace(tzinfo=from_zone) forecast_time = forecast_time.astimezone(to_zone) valid_time = full_data['properties'].get('validTimes')[:19] valid_time = datetime.strptime(str(valid_time), '%Y-%m-%dT%H:%M:%S') valid_time = valid_time.replace(tzinfo=from_zone) valid_time = valid_time.astimezone(to_zone) vd = re.compile(r&quot;(?&lt;=P)(.*?)(?=DT)&quot;) vh = re.compile(r&quot;(?&lt;=DT)(.*?)(?=H)&quot;) valid_days = vd.search(full_data['properties'].get('validTimes')) valid_days = int(valid_days.group()) valid_hours = vh.search(full_data['properties'].get('validTimes')) valid_hours = int(valid_hours.group()) valid_time = valid_time + timedelta(hours=valid_hours,days=valid_days) fdelta = valid_time - next_hour forecast_hours = fdelta.days * 24 + fdelta.seconds // 3600 ####################################################### # Build the Temperature Forecast Array # ####################################################### forecast_period = 0 # First, write into the initial row of the array tempi_fcst[forecast_period][0] = (full_data['properties']['temperature']['values'][forecast_period].get('value') * (9/5)) + 32 # Convert temperature to Fahrenheit and push into array tempi_fcst[forecast_period][1] = full_data['properties']['temperature']['values'][forecast_period].get('validTime')[:19] # Read the UTC time for the current forecast period tempi_fcst[forecast_period][1] = datetime.strptime(str(tempi_fcst[forecast_period][1]), '%Y-%m-%dT%H:%M:%S') # Convert NWS formatted time to python DateTime value tempi_fcst[forecast_period][1] = tempi_fcst[forecast_period][1].replace(tzinfo=from_zone) # Tell the DateTime value that it is in UTC tempi_fcst[forecast_period][1] = tempi_fcst[forecast_period][1].astimezone(to_zone) # Convert the DateTime value to local time zone tempi_fcst[forecast_period][2] = full_data['properties']['temperature']['values'][forecast_period].get('validTime')[28:29] # Push valid hours field into array forecast_period += 1 # Increment period index while forecast_period &lt; (len(full_data['properties']['temperature']['values']) - 1): # Fill in the rest of the array with all of the temperature forecast periods from NWS tempi_fcst.append([0,0,0]) # Append the next row that we're going to write into tempi_fcst[forecast_period][0] = (full_data['properties']['temperature']['values'][forecast_period].get('value') * (9/5)) + 32 tempi_fcst[forecast_period][1] = full_data['properties']['temperature']['values'][forecast_period].get('validTime')[:19] tempi_fcst[forecast_period][1] = datetime.strptime(str(tempi_fcst[forecast_period][1]), '%Y-%m-%dT%H:%M:%S') tempi_fcst[forecast_period][1] = tempi_fcst[forecast_period][1].replace(tzinfo=from_zone) tempi_fcst[forecast_period][1] = tempi_fcst[forecast_period][1].astimezone(to_zone) tempi_fcst[forecast_period][2] = full_data['properties']['temperature']['values'][forecast_period].get('validTime')[28:29] forecast_period += 1 ####################################################### # Build the Dewpoint Forecast Array # ####################################################### forecast_period = 0 dewpi_fcst[forecast_period][0] = (full_data['properties']['dewpoint']['values'][forecast_period].get('value') * (9/5)) + 32 dewpi_fcst[forecast_period][1] = full_data['properties']['dewpoint']['values'][forecast_period].get('validTime')[:19] dewpi_fcst[forecast_period][1] = datetime.strptime(str(dewpi_fcst[forecast_period][1]), '%Y-%m-%dT%H:%M:%S') dewpi_fcst[forecast_period][1] = dewpi_fcst[forecast_period][1].replace(tzinfo=from_zone) dewpi_fcst[forecast_period][1] = dewpi_fcst[forecast_period][1].astimezone(to_zone) dewpi_fcst[forecast_period][2] = full_data['properties']['dewpoint']['values'][forecast_period].get('validTime')[28:29] forecast_period += 1 while forecast_period &lt; (len(full_data['properties']['dewpoint']['values']) - 1): dewpi_fcst.append([0,0,0]) dewpi_fcst[forecast_period][0] = (full_data['properties']['dewpoint']['values'][forecast_period].get('value') * (9/5)) + 32 dewpi_fcst[forecast_period][1] = full_data['properties']['dewpoint']['values'][forecast_period].get('validTime')[:19] dewpi_fcst[forecast_period][1] = datetime.strptime(str(dewpi_fcst[forecast_period][1]), '%Y-%m-%dT%H:%M:%S') dewpi_fcst[forecast_period][1] = dewpi_fcst[forecast_period][1].replace(tzinfo=from_zone) dewpi_fcst[forecast_period][1] = dewpi_fcst[forecast_period][1].astimezone(to_zone) dewpi_fcst[forecast_period][2] = full_data['properties']['dewpoint']['values'][forecast_period].get('validTime')[28:29] forecast_period += 1 ####################################################### # Build the Relative Humidity Forecast Array # ####################################################### forecast_period = 0 relhi_fcst[forecast_period][0] = full_data['properties']['relativeHumidity']['values'][forecast_period].get('value') relhi_fcst[forecast_period][1] = full_data['properties']['relativeHumidity']['values'][forecast_period].get('validTime')[:19] relhi_fcst[forecast_period][1] = datetime.strptime(str(relhi_fcst[forecast_period][1]), '%Y-%m-%dT%H:%M:%S') relhi_fcst[forecast_period][1] = relhi_fcst[forecast_period][1].replace(tzinfo=from_zone) relhi_fcst[forecast_period][1] = relhi_fcst[forecast_period][1].astimezone(to_zone) relhi_fcst[forecast_period][2] = full_data['properties']['relativeHumidity']['values'][forecast_period].get('validTime')[28:29] forecast_period += 1 while forecast_period &lt; (len(full_data['properties']['relativeHumidity']['values']) - 1): relhi_fcst.append([0,0,0]) relhi_fcst[forecast_period][0] = full_data['properties']['relativeHumidity']['values'][forecast_period].get('value') relhi_fcst[forecast_period][1] = full_data['properties']['relativeHumidity']['values'][forecast_period].get('validTime')[:19] relhi_fcst[forecast_period][1] = datetime.strptime(str(relhi_fcst[forecast_period][1]), '%Y-%m-%dT%H:%M:%S') relhi_fcst[forecast_period][1] = relhi_fcst[forecast_period][1].replace(tzinfo=from_zone) relhi_fcst[forecast_period][1] = relhi_fcst[forecast_period][1].astimezone(to_zone) relhi_fcst[forecast_period][2] = full_data['properties']['relativeHumidity']['values'][forecast_period].get('validTime')[28:29] forecast_period += 1 ####################################################### # Build the Wind Speed Forecast Array # ####################################################### forecast_period = 0 windi_fcst[forecast_period][0] = full_data['properties']['windSpeed']['values'][forecast_period].get('value') windi_fcst[forecast_period][1] = full_data['properties']['windSpeed']['values'][forecast_period].get('validTime')[:19] windi_fcst[forecast_period][1] = datetime.strptime(str(windi_fcst[forecast_period][1]), '%Y-%m-%dT%H:%M:%S') windi_fcst[forecast_period][1] = windi_fcst[forecast_period][1].replace(tzinfo=from_zone) windi_fcst[forecast_period][1] = windi_fcst[forecast_period][1].astimezone(to_zone) windi_fcst[forecast_period][2] = full_data['properties']['windSpeed']['values'][forecast_period].get('validTime')[28:29] forecast_period += 1 while forecast_period &lt; (len(full_data['properties']['windSpeed']['values']) - 1): windi_fcst.append([0,0,0]) windi_fcst[forecast_period][0] = full_data['properties']['windSpeed']['values'][forecast_period].get('value') windi_fcst[forecast_period][1] = full_data['properties']['windSpeed']['values'][forecast_period].get('validTime')[:19] windi_fcst[forecast_period][1] = datetime.strptime(str(windi_fcst[forecast_period][1]), '%Y-%m-%dT%H:%M:%S') windi_fcst[forecast_period][1] = windi_fcst[forecast_period][1].replace(tzinfo=from_zone) windi_fcst[forecast_period][1] = windi_fcst[forecast_period][1].astimezone(to_zone) windi_fcst[forecast_period][2] = full_data['properties']['windSpeed']['values'][forecast_period].get('validTime')[28:29] forecast_period += 1 ####################################################### # Build the Wind Direction Forecast Array # ####################################################### forecast_period = 0 wdiri_fcst[forecast_period][0] = full_data['properties']['windDirection']['values'][forecast_period].get('value') wdiri_fcst[forecast_period][1] = full_data['properties']['windDirection']['values'][forecast_period].get('validTime')[:19] wdiri_fcst[forecast_period][1] = datetime.strptime(str(wdiri_fcst[forecast_period][1]), '%Y-%m-%dT%H:%M:%S') wdiri_fcst[forecast_period][1] = wdiri_fcst[forecast_period][1].replace(tzinfo=from_zone) wdiri_fcst[forecast_period][1] = wdiri_fcst[forecast_period][1].astimezone(to_zone) wdiri_fcst[forecast_period][2] = full_data['properties']['windDirection']['values'][forecast_period].get('validTime')[28:29] forecast_period += 1 while forecast_period &lt; (len(full_data['properties']['windDirection']['values']) - 1): wdiri_fcst.append([0,0,0]) wdiri_fcst[forecast_period][0] = full_data['properties']['windDirection']['values'][forecast_period].get('value') wdiri_fcst[forecast_period][1] = full_data['properties']['windDirection']['values'][forecast_period].get('validTime')[:19] wdiri_fcst[forecast_period][1] = datetime.strptime(str(wdiri_fcst[forecast_period][1]), '%Y-%m-%dT%H:%M:%S') wdiri_fcst[forecast_period][1] = wdiri_fcst[forecast_period][1].replace(tzinfo=from_zone) wdiri_fcst[forecast_period][1] = wdiri_fcst[forecast_period][1].astimezone(to_zone) wdiri_fcst[forecast_period][2] = full_data['properties']['windDirection']['values'][forecast_period].get('validTime')[28:29] forecast_period += 1 # Leftover bits from how I was going to do the forecasts, just in case I want to go back and revisit anything here # period = len(wdiri_fcst) - 1 # count = 0 # # while wdiri_fcst[period][1] &gt; curr_time: # count += 1 # period -= 1 # # rows, cols = (count, 3) # wdir_fcst =[] # for i in range(rows): # col = [] # for j in range(cols): # col.append(0) # wdir_fcst.append(col) # # iperiod = period + 1 # period = 0 # # while period &lt;= (count - 1): # wdir_fcst[period][0] = wdiri_fcst[iperiod][0] # wdir_fcst[period][1] = wdiri_fcst[iperiod][1] # wdir_fcst[period][2] = wdiri_fcst[iperiod][2] # period += 1 # iperiod += 1 ####################################################### # Build the probabilityOfPrecipitation Forecast Array # ####################################################### forecast_period = 0 propi_fcst[forecast_period][0] = full_data['properties']['probabilityOfPrecipitation']['values'][forecast_period].get('value') propi_fcst[forecast_period][1] = full_data['properties']['probabilityOfPrecipitation']['values'][forecast_period].get('validTime')[:19] propi_fcst[forecast_period][1] = datetime.strptime(str(propi_fcst[forecast_period][1]), '%Y-%m-%dT%H:%M:%S') propi_fcst[forecast_period][1] = propi_fcst[forecast_period][1].replace(tzinfo=from_zone) propi_fcst[forecast_period][1] = propi_fcst[forecast_period][1].astimezone(to_zone) propi_fcst[forecast_period][2] = full_data['properties']['probabilityOfPrecipitation']['values'][forecast_period].get('validTime')[28:29] forecast_period += 1 while forecast_period &lt; (len(full_data['properties']['probabilityOfPrecipitation']['values']) - 1): propi_fcst.append([0,0,0]) propi_fcst[forecast_period][0] = full_data['properties']['probabilityOfPrecipitation']['values'][forecast_period].get('value') propi_fcst[forecast_period][1] = full_data['properties']['probabilityOfPrecipitation']['values'][forecast_period].get('validTime')[:19] propi_fcst[forecast_period][1] = datetime.strptime(str(propi_fcst[forecast_period][1]), '%Y-%m-%dT%H:%M:%S') propi_fcst[forecast_period][1] = propi_fcst[forecast_period][1].replace(tzinfo=from_zone) propi_fcst[forecast_period][1] = propi_fcst[forecast_period][1].astimezone(to_zone) propi_fcst[forecast_period][2] = full_data['properties']['probabilityOfPrecipitation']['values'][forecast_period].get('validTime')[28:29] forecast_period += 1 ####################################################### # Build the quantitativePrecipitation Forecast Array # ####################################################### forecast_period = 0 qprfi_fcst[forecast_period][0] = full_data['properties']['quantitativePrecipitation']['values'][forecast_period].get('value') qprfi_fcst[forecast_period][1] = full_data['properties']['quantitativePrecipitation']['values'][forecast_period].get('validTime')[:19] qprfi_fcst[forecast_period][1] = datetime.strptime(str(qprfi_fcst[forecast_period][1]), '%Y-%m-%dT%H:%M:%S') qprfi_fcst[forecast_period][1] = qprfi_fcst[forecast_period][1].replace(tzinfo=from_zone) qprfi_fcst[forecast_period][1] = qprfi_fcst[forecast_period][1].astimezone(to_zone) qprfi_fcst[forecast_period][2] = full_data['properties']['quantitativePrecipitation']['values'][forecast_period].get('validTime')[28:29] forecast_period += 1 while forecast_period &lt; (len(full_data['properties']['quantitativePrecipitation']['values']) - 1): qprfi_fcst.append([0,0,0]) qprfi_fcst[forecast_period][0] = full_data['properties']['quantitativePrecipitation']['values'][forecast_period].get('value') qprfi_fcst[forecast_period][1] = full_data['properties']['quantitativePrecipitation']['values'][forecast_period].get('validTime')[:19] qprfi_fcst[forecast_period][1] = datetime.strptime(str(qprfi_fcst[forecast_period][1]), '%Y-%m-%dT%H:%M:%S') qprfi_fcst[forecast_period][1] = qprfi_fcst[forecast_period][1].replace(tzinfo=from_zone) qprfi_fcst[forecast_period][1] = qprfi_fcst[forecast_period][1].astimezone(to_zone) qprfi_fcst[forecast_period][2] = full_data['properties']['quantitativePrecipitation']['values'][forecast_period].get('validTime')[28:29] forecast_period += 1 ####################################################### # Build the Sky Cover Forecast Array # ####################################################### forecast_period = 0 skyci_fcst[forecast_period][0] = full_data['properties']['skyCover']['values'][forecast_period].get('value') skyci_fcst[forecast_period][1] = full_data['properties']['skyCover']['values'][forecast_period].get('validTime')[:19] skyci_fcst[forecast_period][1] = datetime.strptime(str(skyci_fcst[forecast_period][1]), '%Y-%m-%dT%H:%M:%S') skyci_fcst[forecast_period][1] = skyci_fcst[forecast_period][1].replace(tzinfo=from_zone) skyci_fcst[forecast_period][1] = skyci_fcst[forecast_period][1].astimezone(to_zone) skyci_fcst[forecast_period][2] = full_data['properties']['skyCover']['values'][forecast_period].get('validTime')[28:29] forecast_period += 1 while forecast_period &lt; (len(full_data['properties']['skyCover']['values']) - 1): skyci_fcst.append([0,0,0]) skyci_fcst[forecast_period][0] = full_data['properties']['skyCover']['values'][forecast_period].get('value') skyci_fcst[forecast_period][1] = full_data['properties']['skyCover']['values'][forecast_period].get('validTime')[:19] skyci_fcst[forecast_period][1] = datetime.strptime(str(skyci_fcst[forecast_period][1]), '%Y-%m-%dT%H:%M:%S') skyci_fcst[forecast_period][1] = skyci_fcst[forecast_period][1].replace(tzinfo=from_zone) skyci_fcst[forecast_period][1] = skyci_fcst[forecast_period][1].astimezone(to_zone) skyci_fcst[forecast_period][2] = full_data['properties']['skyCover']['values'][forecast_period].get('validTime')[28:29] forecast_period += 1 ####################################################### # Build the master forecast array # ####################################################### rows, cols = (forecast_hours, 9) # One row for every hour of forecast validity beyond the current time, with a column each for the forecast period DateTime and each forecast quantity forecast = [] for i in range(rows): col = [] for j in range(cols): col.append(0) forecast.append(col) # Initialize all of the period indices period = 0 tempi_per = 0 dewpi_per = 0 relhi_per = 0 windi_per = 0 wdiri_per = 0 propi_per = 0 qprfi_per = 0 skyci_per = 0 print(&quot;Forecast Array&quot;) # Print a header for diagnostic purposes while period &lt; (forecast_hours - 1): # Make sure we haven't run out past the end of our forecast validity forecast[period][0] = next_hour + timedelta(hours=period) # Write the current forecast period DateTime into the array, starting with the next hour that will occur after the current time while (tempi_fcst[tempi_per][1] &lt; forecast[period][0]) and (tempi_per &lt; (len(tempi_fcst) - 1)): # Run up the Temperature forecast array's period index until the temperature forecast period is equal to or just higher than the current forecast period tempi_per += 1 if tempi_fcst[tempi_per][1] == forecast[period][0]: # If the Temperature forecast includes a period that coincides with the current forecast period, then use this temperature period forecast[period][1] = '{:6.2f}'.format(tempi_fcst[tempi_per][0]) # Write nicely-formatted values that match the formatting of the database table columns into the big forecast array else: # However, if the Temperature forecast contained a &gt;1 hr interval and jumped past the current forecast period, stay with the previous temperature period for this go-round forecast[period][1] = '{:6.2f}'.format(tempi_fcst[tempi_per - 1][0]) while (dewpi_fcst[dewpi_per][1] &lt; forecast[period][0]) and (dewpi_per &lt; (len(dewpi_fcst) - 1)): # Continue as with Temperature dewpi_per += 1 if dewpi_fcst[dewpi_per][1] == forecast[period][0]: forecast[period][2] = '{:6.2f}'.format(dewpi_fcst[dewpi_per][0]) else: forecast[period][2] = '{:6.2f}'.format(dewpi_fcst[dewpi_per - 1][0]) while (relhi_fcst[relhi_per][1] &lt; forecast[period][0]) and (relhi_per &lt; (len(relhi_fcst) - 1)): relhi_per += 1 if relhi_fcst[relhi_per][1] == forecast[period][0]: forecast[period][3] = '{:3d}'.format(relhi_fcst[relhi_per][0]) else: forecast[period][3] = '{:3d}'.format(relhi_fcst[relhi_per - 1][0]) while (windi_fcst[windi_per][1] &lt; forecast[period][0]) and (windi_per &lt; (len(windi_fcst) - 1)): windi_per += 1 if windi_fcst[windi_per][1] == forecast[period][0]: forecast[period][4] = '{:7.3f}'.format(windi_fcst[windi_per][0]) else: forecast[period][4] = '{:7.3f}'.format(windi_fcst[windi_per - 1][0]) while (wdiri_fcst[wdiri_per][1] &lt; forecast[period][0]) and (wdiri_per &lt; (len(wdiri_fcst) - 1)): wdiri_per += 1 if wdiri_fcst[wdiri_per][1] == forecast[period][0]: forecast[period][5] = '{:3d}'.format(wdiri_fcst[wdiri_per][0]) else: forecast[period][5] = '{:3d}'.format(wdiri_fcst[wdiri_per - 1][0]) while (propi_fcst[propi_per][1] &lt; forecast[period][0]) and (propi_per &lt; (len(propi_fcst) - 1)): propi_per += 1 if propi_fcst[propi_per][1] == forecast[period][0]: forecast[period][6] = '{:3d}'.format(propi_fcst[propi_per][0]) else: forecast[period][6] = '{:3d}'.format(propi_fcst[propi_per - 1][0]) while (qprfi_fcst[qprfi_per][1] &lt; forecast[period][0]) and (qprfi_per &lt; (len(qprfi_fcst) - 1)): qprfi_per += 1 if qprfi_fcst[qprfi_per][1] == forecast[period][0]: forecast[period][7] = '{:6.3f}'.format(qprfi_fcst[qprfi_per][0] / float(qprfi_fcst[qprfi_per][2])) # Quantitative Precip Forecast is usually spread over multiple hours, so divide the forecast amount by the number of valid hours for this period else: forecast[period][7] = '{:6.3f}'.format(qprfi_fcst[qprfi_per - 1][0] / float(qprfi_fcst[qprfi_per - 1][2])) while (skyci_fcst[skyci_per][1] &lt; forecast[period][0]) and (skyci_per &lt; (len(skyci_fcst) - 1)): skyci_per += 1 if skyci_fcst[skyci_per][1] == forecast[period][0]: forecast[period][8] = '{:3d}'.format(skyci_fcst[skyci_per][0]) else: forecast[period][8] = '{:3d}'.format(skyci_fcst[skyci_per - 1][0]) print(&quot;[ &quot; + str(forecast[period][0]) + &quot; , {a:s} , {b:s} , {c:s} , {d:s} , {e:s} , {f:s} , {g:s} , {h:s} ]&quot;.format(a=forecast[period][1], b=forecast[period][2], c=forecast[period][3], d=forecast[period][4], e=forecast[period][5], f=forecast[period][6], g=forecast[period][7], h=forecast[period][8])) # For troubleshooting, print out the row we just made period += 1 # Connect to the database try: conn = mariadb.connect( user=&quot;wx_user&quot;, port=3306, database=&quot;weatherdb&quot; ) except mariadb.Error as e: print(f&quot;Error connecting to MariaDB Platform: {e}&quot;) sys.exit(1) cur = conn.cursor() conn.autocommit = True # Write the current forecast data run into the database if it does not already exist there cur.execute(&quot;SELECT `fcst_period`,`fcst_time` FROM `forecast` WHERE `fcst_time`=?&quot;, (str(forecast_time)[:19],)) # Check to see if the current forecast run is already in the database if cur.fetchall() == []: # If there are no matching results, push the current forecast run into the database period = 0 while period &lt; (forecast_hours - 1): cur.execute(&quot;INSERT INTO `forecast` (`fcst_period`, `temp`, `dewp`, `relh`, `wind`, `wdir`, `prop`, `qprf`, `skyc`, `fcst_ID`, `fcst_time`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'NWS-API', ?)&quot;,(str(forecast[period][0])[:19], forecast[period][1], forecast[period][2], forecast[period][3], forecast[period][4], forecast[period][5], forecast[period][6], forecast[period][7], forecast[period][8], str(forecast_time)[:19])) # This forecast comes from the National Weather Service API, so identify it as such and timestamp everything with the forecast's overall timestamp period += 1 </code></pre> <p>Edit: I should mention that I did snip out the database server address and password. They are in the working version.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T05:20:15.243", "Id": "263307", "Score": "2", "Tags": [ "python", "mysql", "json" ], "Title": "Python script to collect NWS gridpoint forecast data (JSON) and push it into MariaDB" }
263307
<p>Possible improvements I see are take <code>lastdigit_num</code> and implement <code>arr_{lastdigit_num}</code> since <a href="https://brilliant.org/wiki/finding-the-last-digit-of-a-power/#:%7E:text=Finding%20the%20last%20digit%20of%20a%20positive%20integer%20is%20the,division%20by%20n%20n%20n." rel="noreferrer">the math behind this</a> is common for most (<em>integers with cyclicity 4 or 2 common to them</em>) integers and reduces repetitive <code>if</code> statements.</p> <p>For example if <code>num = 23423</code>, then <code>lastdigit_num = 3</code> and <code>arr_{lastdigit_num}</code> is directly linked to 3 rather than having a separate <code>if</code> statement for 3 or any other digit with common cyclicity.</p> <p>But I am not able to implement this in the code.</p> <pre><code>num = int(input(&quot;Enter number: &quot;)) lastdigit_num = int(repr(num)[-1]) exp = int(input(&quot;Enter exponent: &quot;)) lastdigit_exp = int(repr(exp)[-1]) last2digit_exp = 10*int(repr(exp)[-2])+int(repr(exp)[-1]) mod_exp_2_3_7_8 = last2digit_exp % 4 if lastdigit_exp % 2 == 1: mod_exp_4_9 = 1 else: mod_exp_4_9 = 0 arr_2 = [2,4,8,6] arr_3 = [3,9,7,1] arr_4 = [4,6] arr_7 = [7,9,3,1] arr_8 = [8,4,2,6] arr_9 = [9,1] if lastdigit_num == 0: print(f&quot;Last digit of {num}^{exp} is 0.&quot;) elif lastdigit_num == 1: print(f&quot;Last digit of {num}^{exp} is 1.&quot;) elif lastdigit_num == 2: print(f&quot;Last digit of {num}^{exp} is {arr_2[mod_exp_2_3_7_8 - 1]}.&quot;) elif lastdigit_num == 3: print(f&quot;Last digit of {num}^{exp} is {arr_3[mod_exp_2_3_7_8 - 1]}.&quot;) elif lastdigit_num == 4: print(f&quot;Last digit of {num}^{exp} is {arr_4[mod_exp_4_9 - 1]}.&quot;) elif lastdigit_num == 5: print(f&quot;Last digit of {num}^{exp} is 5.&quot;) elif lastdigit_num == 6: print(f&quot;Last digit of {num}^{exp} is 6.&quot;) elif lastdigit_num == 7: print(f&quot;Last digit of {num}^{exp} is {arr_7[mod_exp_2_3_7_8 - 1]}.&quot;) elif lastdigit_num == 8: print(f&quot;Last digit of {num}^{exp} is {arr_8[mod_exp_2_3_7_8 - 1]}.&quot;) elif lastdigit_num == 9: print(f&quot;Last digit of {num}^{exp} is {arr_9[mod_exp_4_9 - 1]}.&quot;) </code></pre>
[]
[ { "body": "<p>There's really no need to convert the inputs to <code>int</code>. We're only using the last digit of <code>a</code> and the last two digits of <code>b</code>. So just check that we don't have any non-digit characters, then convert the last one or two digits to <code>int</code>.</p>\n<p>The code produces incorrect results when <code>b</code> is zero. We should start by testing that:</p>\n<pre><code> if b == 0:\n return 1\n</code></pre>\n<p>Instead of the big <code>if</code>/<code>elif</code> chain, we can simplify the code by making arrays for <em>all</em> our digit sequences, and use <code>a</code> to select which array is used. We could make them all the same length:</p>\n<pre><code>def last_pow_digit(a, b):\n if b == 0:\n return 1\n digits = [\n [ 0, 0, 0, 0 ],\n [ 1, 1, 1, 1 ],\n [ 6, 2, 4, 8 ],\n [ 1, 3, 9, 7 ],\n [ 6, 4, 6, 4 ],\n [ 5, 5, 5, 5 ],\n [ 6, 6, 6, 6 ],\n [ 1, 7, 9, 3 ],\n [ 6, 8, 4, 2 ],\n [ 1, 9, 1, 9 ],\n ]\n return digits[a % 10][b % 4]\n</code></pre>\n<p>Alternatively, the arrays can be different lengths, and we'd use the length to determine the modular reduction of <code>b</code>:</p>\n<pre><code>def last_pow_digit(a, b):\n if b == 0:\n return 1\n digits = [\n [ 0, ],\n [ 1, ],\n [ 6, 2, 4, 8 ],\n [ 1, 3, 9, 7 ],\n [ 6, 4 ],\n [ 5, ],\n [ 6, ],\n [ 1, 7, 9, 3 ],\n [ 6, 8, 4, 2 ],\n [ 1, 9 ],\n ]\n arr = digits[a % 10]\n return arr[b % len(arr)]\n</code></pre>\n<p>I think the first version is simpler, even if it does mean some repetition.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T17:22:53.737", "Id": "519886", "Score": "2", "body": "RE: `if b == 0: return 1` Well *technically* `0^0` is indeterminate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T18:58:17.547", "Id": "519899", "Score": "2", "body": "@RBarryYoung With discrete exponents, \\$0^0\\$ is often [defined](https://en.wikipedia.org/wiki/Zero_to_the_power_of_zero#Discrete_exponents) to be 1. Continuous exponents and complex exponents are different animals, but in this case, the OP is expecting an integer value for `exp`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T20:36:46.080", "Id": "519905", "Score": "1", "body": "Although beware that you may have to implement a tiny bit more logic if you try to generalize to other moduli. For example, when computing the last two digits of 2^n, the sequence does eventually enter a loop (as it must for any modulus), but 2 is not in the loop!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T06:04:47.613", "Id": "519925", "Score": "1", "body": "@RBarryYoung: If you treat `0^0` as undefined behaviour for your program, you're allowed to do whatever you want in that case, including returning 1. I guess the mathematically correct way to handle it would be throwing an exception, though, or returning some kind of NaN." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T08:48:00.713", "Id": "263315", "ParentId": "263312", "Score": "14" } }, { "body": "<p>Why not just use Python's builtin <a href=\"https://docs.python.org/3/library/functions.html#pow\" rel=\"noreferrer\"><code>pow</code></a>? It takes in a third optional argument the modulo, so all you need to get the last digit would be <code>pow(a, b, 10)</code>. You can see <a href=\"https://stackoverflow.com/questions/5246856/how-did-python-implement-the-built-in-function-pow\">here</a> for an explanation of how it works. It is much, much faster to do this in binary.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T04:55:32.447", "Id": "519920", "Score": "1", "body": "wouldn't that be slower?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T05:26:01.500", "Id": "519921", "Score": "3", "body": "I must admit I posted this before analyzing your answer in depth. After timing your answer versus `pow`, the latter still wins for most sensible inputs 5s vs 3s for most sensible inputs. Toby's is faster because yours uses string conversions. I would still, as a general principle, strongly encourage you to use builtins whenever possible. 1) to avoid bugs (yours crashes if exp is a single digit 2) scalability what if you wanted to find the last 3 digits? `pow(a, b, 1000)`. If this is for learning then go ahead, but for production code? builtins." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T07:56:03.173", "Id": "519930", "Score": "0", "body": "this was mainly for learning modular arithmetic but implementing it in code" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T10:41:19.997", "Id": "263321", "ParentId": "263312", "Score": "11" } }, { "body": "<p>Since you stated in a comment that your aim was to learn modular arithmetic, you should certainly use it instead of string operations:</p>\n<pre><code>num = int(input(&quot;Enter number: &quot;))\n\nlastdigit_num = num % 10\n\nexp = int(input(&quot;Enter exponent: &quot;))\n\nlastdigit_exp = exp % 10\nlast2digit_exp = exp % 100\n\n...\n</code></pre>\n<p>This makes your code more readable while reducing unnecessary operations.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T11:35:13.373", "Id": "263361", "ParentId": "263312", "Score": "2" } }, { "body": "<p>As <a href=\"https://codereview.stackexchange.com/a/263321\">N3buchadnezzar notes</a>, Python's built-in <a href=\"https://docs.python.org/3/library/functions.html#pow\" rel=\"noreferrer\"><code>pow</code></a> function already supports modular exponentiation. So, in practice, the correct and idiomatic way to find the last digit of <span class=\"math-container\">\\$a^b\\$</span> for any integers <span class=\"math-container\">\\$a\\$</span> and <span class=\"math-container\">\\$b\\$</span> in Python is:</p>\n<pre class=\"lang-py prettyprint-override\"><code>last_digit = pow(a, b, 10)\n</code></pre>\n<p>If you're doing this as a learning exercise and don't want to use the built-in solution, I would make a bit of a &quot;frame challenge&quot; and recommend that you implement a general <a href=\"https://en.wikipedia.org/wiki/Modular_exponentiation\" rel=\"noreferrer\">modular exponentiation</a> algorithm that works for any modulus, not just 10. Such algorithms actually have practical uses e.g. in cryptography, whereas using string manipulation and hardcoded remainder rules to find the last base-10 digit does not, making it a much more useful pedagogical exercise.</p>\n<hr />\n<p>As this is (presumably) a learning exercise, I would encourage you to come up with your own algorithm and implementation rather than simply adapting an algorithm developed by someone else. Specifically, what you should do is:</p>\n<ol>\n<li><p>Sketch an implementation of an efficient exponentiation algorithm, such as <a href=\"https://en.wikipedia.org/wiki/Exponentiation_by_squaring\" rel=\"noreferrer\">exponentiation by squaring</a>.</p>\n</li>\n<li><p>Modify the algorithm to reduce any intermediate results modulo 10 (or rather modulo <span class=\"math-container\">\\$m\\$</span>, where <span class=\"math-container\">\\$m\\$</span> is an argument to the function) at suitable points so that they cannot grow too large. As a practical goal, you should aim to keep all your intermediate values (excluding the exponent) smaller that <span class=\"math-container\">\\$m^2\\$</span>. (Keeping intermediate values below <span class=\"math-container\">\\$m\\$</span> is also possible, but requires you to implement custom modular addition and multiplication routines. For small values of <span class=\"math-container\">\\$m\\$</span> this is probably not worth doing.)</p>\n</li>\n</ol>\n<p>For step 2, remember that modular reduction distributes over addition and multiplication, in the sense that <span class=\"math-container\">$$(a + b) \\bmod m = ((a \\bmod m) + b) \\bmod m$$</span> and <span class=\"math-container\">$$(a \\times b) \\bmod m = ((a \\bmod m) \\times b) \\bmod m.$$</span> (Or, in Python code, <code>(a + b) % m == ((a % m) + b) % m</code> and <code>(a * b) % m == ((a % m) * b) % m</code>.)</p>\n<p>Thus, if you have an integer variable that you're only going to be multiplying or adding integers to, and you know that you're going to take the remainder modulo <span class=\"math-container\">\\$m\\$</span> of it at the end of your code, you can also safely reduce it modulo <span class=\"math-container\">\\$m\\$</span> at any point during your algorithm without changing the remainder.</p>\n<p>Once you have that algorithm working, feel free to post it here for another round of review. :)</p>\n<hr />\n<p><strong>Ps.</strong> In cases where the exponent may be significantly larger than the modulus, you could also make use of the identity <span class=\"math-container\">$$a^b \\bmod m = a^{b \\bmod \\lambda(m)} \\bmod m,$$</span> where <span class=\"math-container\">\\$\\lambda\\$</span> is the <a href=\"https://en.wikipedia.org/wiki/Carmichael_function\" rel=\"noreferrer\">Carmichael totient function</a>. For example, <span class=\"math-container\">\\$\\lambda(10) = 4\\$</span>, so <span class=\"math-container\">$$a^b \\bmod 10 = a^{b \\bmod 4} \\bmod 10 = (a \\bmod 10)^{b \\bmod 4} \\bmod 10,$$</span> which your original code makes use of.</p>\n<p>Unfortunately computing <span class=\"math-container\">\\$\\lambda(m)\\$</span> for arbitrary large <span class=\"math-container\">\\$m\\$</span> can be quite difficult* — in general, it requires <a href=\"https://en.wikipedia.org/wiki/Integer_factorization\" rel=\"noreferrer\">factoring</a> <span class=\"math-container\">\\$m\\$</span> into a product of prime numbers. There are, however, a number of special cases where calculating <span class=\"math-container\">\\$\\lambda(m)\\$</span> is relatively easy:</p>\n<ul>\n<li>If <span class=\"math-container\">\\$m\\$</span> is prime, <span class=\"math-container\">\\$\\lambda(m) = m-1\\$</span>. <a href=\"https://en.wikipedia.org/wiki/Primality_test\" rel=\"noreferrer\">Determining whether a number is prime</a> is considerably easier than factoring.</li>\n<li>More generally, if <span class=\"math-container\">\\$m = p^k\\$</span> is a power of an odd prime <span class=\"math-container\">\\$p\\$</span>, <span class=\"math-container\">\\$\\lambda(m) = p^{k-1}(p-1)\\$</span>.</li>\n<li>If <span class=\"math-container\">\\$m\\$</span> is a power of 2 and at least 8, <span class=\"math-container\">\\$\\lambda(m) = \\frac m4\\$</span>. (As special cases, <span class=\"math-container\">\\$\\lambda(2) = 1\\$</span> and <span class=\"math-container\">\\$\\lambda(4) = 2\\$</span>.) When <span class=\"math-container\">\\$m\\$</span> is given in binary, testing whether it's a power of 2 is extremely trivial.</li>\n</ul>\n<p>If the prime factorization of <span class=\"math-container\">\\$m\\$</span> is known, then <span class=\"math-container\">\\$\\lambda(m)\\$</span> can be computed based on the rules above and the theorem that if <span class=\"math-container\">\\$a\\$</span> and <span class=\"math-container\">\\$b\\$</span> have no common prime factors, then <span class=\"math-container\">$$\\lambda(ab) = \\operatorname{lcm}(\\lambda(a), \\lambda(b)),$$</span> where <span class=\"math-container\">\\$\\operatorname{lcm}\\$</span> stands for <a href=\"https://en.wikipedia.org/wiki/Least_common_multiple\" rel=\"noreferrer\">least common multiple</a>. For small and/or highly composite <span class=\"math-container\">\\$m\\$</span>, it can be feasible to calculate <span class=\"math-container\">\\$\\lambda(m)\\$</span> by factoring <span class=\"math-container\">\\$m\\$</span> and then applying this formula.</p>\n<hr />\n<p><sup>*) In particular, if you could calculate <span class=\"math-container\">\\$\\lambda\\$</span> efficiently for products of two large primes without knowing those primes, you could break the <a href=\"https://en.wikipedia.org/wiki/RSA_(cryptosystem)\" rel=\"noreferrer\">RSA cryptosystem</a>. So far, however, nobody's managed to figure out an efficient way do that, at least not without using a theoretical quantum computer more advanced than we can currently build.</sup></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T15:34:35.883", "Id": "263372", "ParentId": "263312", "Score": "8" } } ]
{ "AcceptedAnswerId": "263372", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T07:52:12.270", "Id": "263312", "Score": "10", "Tags": [ "python", "python-3.x" ], "Title": "Last digit of any (reasonably large) a^b (Analytically)" }
263312
<p>I just completed my second python project which is a chess game. At the moment I have included a mechanism for pieces to lock onto a square based on the nearest square when moved. And I have introduced a mechanism to take pieces. I haven't yet checked for legal moves but I plan on doing that soon.</p> <p>If anyone could suggest ways I could make the code neater/more effecient that would be greatly appreciated. I've been programming in C++ for around one and a half years so a few things I tried in python that I can do in C++ didn't work which caused me to do some unorthodox methods</p> <p>If you want to run the project here are the images I used as a rar file <a href="https://gofile.io/d/Ss0vPc" rel="nofollow noreferrer">https://gofile.io/d/Ss0vPc</a></p> <pre><code>import pygame import python_math as math whiteC = (200,200,200) blackC = (55, 55, 55) class Coordinates: #convering pixel values to alpha and numerical values that you would see on a chess board # x values a = 0 * 100 b = 1 * 100 c = 2 * 100 d = 3 * 100 e = 4 * 100 f = 5 * 100 g = 6 * 100 h = 7 * 100 i = 8 * 100 j = 9 * 100 k = 10 * 100 l = 11 * 100 m = 12 * 100 n = 13 * 100 # y values one = 7 * 100 two = 6 * 100 three = 5 * 100 four = 4 * 100 five = 3 * 100 six = 2 * 100 seven = 1 * 100 eight = 0 * 100 c = Coordinates whiteTAC = [(c.i, c.eight), (c.j, c.eight) , (c.k, c.eight), (c.l, c.eight), (c.m, c.eight), (c.n, c.eight), (c.i, c.seven), (c.j, c.seven), (c.k, c.seven), (c.l, c.seven), (c.m, c.seven), (c.n, c.seven), (c.i, c.six), (c.j, c.six), (c.k, c.six), (c.l, c.six)] # when we take a piece, these are the coordinates in which the taken piece will go to blackTAC = [(c.i, c.one), (c.j, c.one) , (c.k, c.one), (c.l, c.one), (c.m, c.one), (c.n, c.one), (c.i, c.two), (c.j, c.two), (c.k, c.two), (c.l, c.two) , (c.m, c.two), (c.n, c.two), (c.i, c.three), (c.j, c.three), (c.k, c.three), (c.l, c.three)] def round100bottom(x): return int(math.math.floor(x / 100.0)) * 100 def round100top(x): return int(math.math.ceil(x / 100.0)) * 100 class game_logic: currentMove = &quot;white&quot; wI = 0 #indexs used for moving a piece when its taken away, used for arrays whiteTAC and blackTAC bI = 0 GL = game_logic class Piece: side = None image = None coords = None heldDown = False tempCoords = coords tempBool = False finalRoundOne = 0 finalRoundTwo = 0 justMoved = False def __init__(self, image, coords, side): self.image = pygame.image.load(image) self.coords = coords self.side = side def listenForMovement(self, event): print(self.side) if event.type == pygame.MOUSEBUTTONUP: if self.justMoved: print(&quot;called&quot;) if GL.currentMove == &quot;white&quot;: GL.currentMove = &quot;black&quot; else: GL.currentMove = &quot;white&quot; self.justMoved = False self.heldDown = False self.tempBool = False if ((self.coords[0] - round100bottom(self.coords[0])) &lt; 50): # tests to see which square is the closest by rounding the top and the bottom and seeing which is smallest self.finalRoundOne = round100bottom(self.coords[0]) else: self.finalRoundOne = round100top(self.coords[0]) if ((self.coords[1] - round100bottom(self.coords[1])) &lt; 50): self.finalRoundTwo = round100bottom(self.coords[1]) else: self.finalRoundTwo = round100top(self.coords[1]) self.coords = (self.finalRoundOne, self.finalRoundTwo) TakePiece(self.coords, self.side) if ((event.type == pygame.MOUSEBUTTONDOWN or self.heldDown == True) and pygame.mouse.get_pos()[0] &gt; self.coords[0] and pygame.mouse.get_pos()[0] &lt; self.coords[0] + 100 and pygame.mouse.get_pos()[1] &gt; self.coords[1] and pygame.mouse.get_pos()[1] &lt; self.coords[1] + 100 and GL.currentMove == self.side): self.heldDown = True if self.tempBool != True: self.tempCoords = (pygame.mouse.get_pos()[0] - self.coords[0], pygame.mouse.get_pos()[1] - self.coords[1]) self.tempBool = True self.coords = (pygame.mouse.get_pos()[0] - self.tempCoords[0], pygame.mouse.get_pos()[1] - self.tempCoords[1]) self.justMoved = True class White: king = Piece(r'C:\sprites\wking.png', (c.e, c.one), &quot;white&quot;) queen = Piece(r'C:\sprites\wqueen.png', (c.d, c.one), &quot;white&quot;) bishop1 = Piece(r'C:\sprites\wbishop.png', (c.c, c.one), &quot;white&quot;) bishop2 = Piece(r'C:\sprites\wbishop.png', (c.f, c.one), &quot;white&quot;) knight1 = Piece(r'C:\sprites\wknight.png', (c.b, c.one), &quot;white&quot;) knight2 = Piece(r'C:\sprites\wknight.png', (c.g, c.one), &quot;white&quot;) castle1 = Piece(r'C:\sprites\wcastle.png', (c.a, c.one), &quot;white&quot;) castle2 = Piece(r'C:\sprites\wcastle.png', (c.h, c.one), &quot;white&quot;) pawn1 = Piece(r'C:\sprites\wpawn.png', (c.a, c.two), &quot;white&quot;) pawn2 = Piece(r'C:\sprites\wpawn.png', (c.b, c.two), &quot;white&quot;) pawn3 = Piece(r'C:\sprites\wpawn.png', (c.c, c.two), &quot;white&quot;) pawn4 = Piece(r'C:\sprites\wpawn.png', (c.d, c.two), &quot;white&quot;) pawn5 = Piece(r'C:\sprites\wpawn.png', (c.e, c.two), &quot;white&quot;) pawn6 = Piece(r'C:\sprites\wpawn.png', (c.f, c.two), &quot;white&quot;); pawn7 = Piece(r'C:\sprites\wpawn.png', (c.g, c.two), &quot;white&quot;) pawn8 = Piece(r'C:\sprites\wpawn.png', (c.h, c.two), &quot;white&quot;) class Black: king = Piece(r'C:\sprites\bking.png', (c.e, c.eight), &quot;black&quot;) queen = Piece(r'C:\sprites\bqueen.png', (c.d, c.eight), &quot;black&quot;) bishop1 = Piece(r'C:\sprites\bbishop.png', (c.c, c.eight), &quot;black&quot;) bishop2 = Piece(r'C:\sprites\bbishop.png', (c.f, c.eight), &quot;black&quot;) knight1 = Piece(r'C:\sprites\bknight.png', (c.b, c.eight), &quot;black&quot;) knight2 = Piece(r'C:\sprites\bknight.png', (c.g, c.eight), &quot;black&quot;) castle1 = Piece(r'C:\sprites\bcastle.png', (c.a, c.eight), &quot;black&quot;) castle2 = Piece(r'C:\sprites\bcastle.png', (c.h, c.eight), &quot;black&quot;) pawn1 = Piece(r'C:\sprites\bpawn.png', (c.a, c.seven), &quot;black&quot;) pawn2 = Piece(r'C:\sprites\bpawn.png', (c.b, c.seven), &quot;black&quot;) pawn3 = Piece(r'C:\sprites\bpawn.png', (c.c, c.seven), &quot;black&quot;) pawn4 = Piece(r'C:\sprites\bpawn.png', (c.d, c.seven), &quot;black&quot;) pawn5 = Piece(r'C:\sprites\bpawn.png', (c.e, c.seven), &quot;black&quot;) pawn6 = Piece(r'C:\sprites\bpawn.png', (c.f, c.seven), &quot;black&quot;) pawn7 = Piece(r'C:\sprites\bpawn.png', (c.g, c.seven), &quot;black&quot;) pawn8 = Piece(r'C:\sprites\bpawn.png', (c.h, c.seven), &quot;black&quot;) pygame.init() dis = pygame.display.set_mode((1400, 800)) pygame.display.update() white = White black = Black def draw_pieces(): # dis.blit(white.king.image, white.king.coords) dis.blit(white.pawn1.image, white.pawn1.coords) dis.blit(white.pawn2.image, white.pawn2.coords) dis.blit(white.pawn3.image, white.pawn3.coords) dis.blit(white.pawn4.image, white.pawn4.coords) dis.blit(white.pawn5.image, white.pawn5.coords) dis.blit(white.pawn6.image, white.pawn6.coords) dis.blit(white.pawn7.image, white.pawn7.coords) dis.blit(white.pawn8.image, white.pawn8.coords) dis.blit(white.king.image, white.king.coords) dis.blit(white.queen.image, white.queen.coords) dis.blit(white.bishop1.image, white.bishop1.coords) dis.blit(white.bishop2.image, white.bishop2.coords) dis.blit(white.knight1.image, white.knight1.coords) dis.blit(white.knight2.image, white.knight2.coords) dis.blit(white.castle1.image, white.castle1.coords) dis.blit(white.castle2.image, white.castle2.coords) dis.blit(black.pawn1.image, black.pawn1.coords) dis.blit(black.pawn2.image, black.pawn2.coords) dis.blit(black.pawn3.image, black.pawn3.coords) dis.blit(black.pawn4.image, black.pawn4.coords) dis.blit(black.pawn5.image, black.pawn5.coords) dis.blit(black.pawn6.image, black.pawn6.coords) dis.blit(black.pawn7.image, black.pawn7.coords) dis.blit(black.pawn8.image, black.pawn8.coords) dis.blit(black.king.image, black.king.coords) dis.blit(black.queen.image, black.queen.coords) dis.blit(black.bishop1.image, black.bishop1.coords) dis.blit(black.bishop2.image, black.bishop2.coords) dis.blit(black.knight1.image, black.knight1.coords) dis.blit(black.knight2.image, black.knight2.coords) dis.blit(black.castle1.image, black.castle1.coords) dis.blit(black.castle2.image, black.castle2.coords) for event in pygame.event.get(): white.king.listenForMovement(event) white.queen.listenForMovement(event) white.bishop1.listenForMovement(event) white.bishop2.listenForMovement(event) white.castle1.listenForMovement(event) white.castle2.listenForMovement(event) white.knight1.listenForMovement(event) white.knight2.listenForMovement(event) white.pawn1.listenForMovement(event) white.pawn2.listenForMovement(event) white.pawn3.listenForMovement(event) white.pawn4.listenForMovement(event) white.pawn5.listenForMovement(event) white.pawn6.listenForMovement(event) white.pawn7.listenForMovement(event) white.pawn8.listenForMovement(event) black.king.listenForMovement(event) black.queen.listenForMovement(event) black.bishop1.listenForMovement(event) black.bishop2.listenForMovement(event) black.castle1.listenForMovement(event) black.castle2.listenForMovement(event) black.knight1.listenForMovement(event) black.knight2.listenForMovement(event) black.pawn1.listenForMovement(event) black.pawn2.listenForMovement(event) black.pawn3.listenForMovement(event) black.pawn4.listenForMovement(event) black.pawn5.listenForMovement(event) black.pawn6.listenForMovement(event) black.pawn7.listenForMovement(event) black.pawn8.listenForMovement(event) def TakePiece(coords, side): if side == &quot;black&quot;: if white.king.coords == coords: white.king.coords = whiteTAC[GL.wI] GL.wI += 1 if white.queen.coords == coords: white.queen.coords = whiteTAC[GL.wI] GL.wI += 1 if white.king.coords == coords: white.king.coords = whiteTAC[GL.wI] GL.wI += 1 if white.queen.coords == coords: white.queen.coords = whiteTAC[GL.wI] GL.wI += 1 if white.castle1.coords == coords: white.castle1.coords = whiteTAC[GL.wI] GL.wI += 1 if white.castle2.coords == coords: white.castle2.coords = whiteTAC[GL.wI] GL.wI += 1 if white.knight1.coords == coords: white.knight1.coords = whiteTAC[GL.wI] GL.wI += 1 if white.knight2.coords == coords: white.knight2.coords = whiteTAC[GL.wI] GL.wI += 1 if white.bishop1.coords == coords: white.bishop1.coords = whiteTAC[GL.wI] GL.wI += 1 if white.bishop2.coords == coords: white.bishop2.coords = whiteTAC[GL.wI] GL.wI += 1 if white.pawn1.coords == coords: white.pawn1.coords = whiteTAC[GL.wI] GL.wI += 1 if white.pawn2.coords == coords: white.pawn2.coords = whiteTAC[GL.wI] GL.wI += 1 if white.pawn3.coords == coords: white.pawn3.coords = whiteTAC[GL.wI] GL.wI += 1 if white.pawn4.coords == coords: white.pawn4.coords = whiteTAC[GL.wI] GL.wI += 1 if white.pawn5.coords == coords: white.pawn5.coords = whiteTAC[GL.wI] GL.wI += 1 if white.pawn6.coords == coords: white.pawn6.coords = whiteTAC[GL.wI] GL.wI += 1 if white.pawn7.coords == coords: white.pawn7.coords = whiteTAC[GL.wI] GL.wI += 1 if white.pawn8.coords == coords: white.pawn8.coords = whiteTAC[GL.wI] GL.wI += 1 if side == &quot;white&quot;: if black.king.coords == coords: black.king.coords = blackTAC[GL.bI] GL.bI += 1 if black.queen.coords == coords: black.queen.coords = blackTAC[GL.bI] GL.bI += 1 if black.king.coords == coords: black.king.coords = blackTAC[GL.bI] GL.bI += 1 if black.queen.coords == coords: black.queen.coords = blackTAC[GL.bI] GL.bI += 1 if black.castle1.coords == coords: black.castle1.coords = blackTAC[GL.bI] GL.bI += 1 if black.castle2.coords == coords: black.castle2.coords = blackTAC[GL.bI] GL.bI += 1 if black.knight1.coords == coords: black.knight1.coords = blackTAC[GL.bI] GL.bI += 1 if black.knight2.coords == coords: black.knight2.coords = blackTAC[GL.bI] GL.bI += 1 if black.bishop1.coords == coords: black.bishop1.coords = blackTAC[GL.bI] GL.bI += 1 if black.bishop2.coords == coords: black.bishop2.coords = blackTAC[GL.bI] GL.bI += 1 if black.pawn1.coords == coords: black.pawn1.coords = blackTAC[GL.bI] GL.bI += 1 if black.pawn2.coords == coords: black.pawn2.coords = blackTAC[GL.bI] GL.bI += 1 if black.pawn3.coords == coords: black.pawn3.coords = blackTAC[GL.bI] GL.bI += 1 if black.pawn4.coords == coords: black.pawn4.coords = blackTAC[GL.bI] GL.bI += 1 if black.pawn5.coords == coords: black.pawn5.coords = blackTAC[GL.bI] GL.bI += 1 if black.pawn6.coords == coords: black.pawn6.coords = blackTAC[GL.bI] GL.bI += 1 if black.pawn7.coords == coords: black.pawn7.coords = blackTAC[GL.bI] GL.bI += 1 if black.pawn8.coords == coords: black.pawn8.coords = blackTAC[GL.bI] GL.bI += 1 def draw_background(): pygame.draw.rect(dis, (180, 180, 180), [800, 0, 600, 800]) for i in range(0, 8): for j in range(0, 8): if (i + j) % 2 != 0: pygame.draw.rect(dis, blackC, [i * 100, j * 100, 100, 100 ]) else: pygame.draw.rect(dis, whiteC, [i * 100, j * 100, 100, 100 ]) def main(): while True: draw_background() draw_pieces() pygame.display.update() main() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T08:35:07.373", "Id": "263314", "Score": "3", "Tags": [ "python", "beginner" ], "Title": "Chess using pygame" }
263314
<p>This is the code that joins the list with another one. Also makes use of a static utility to makes use of hashmap for id and name.</p> <p>I've added null checks to safeguard the code with NPE.</p> <p>The key purpose is to make this readable. Could someone help code review this?</p> <pre><code>public List&lt;PGRatingResponse&gt; collatePGRatingsbyVendor(List&lt;PGRatingConfig&gt; pgRatingSansPgname, List&lt;Vendor&gt; vendors) { return pgRatingSansPgname.stream().filter(Objects::nonNull).filter(o1 -&gt; o1.getRating() != null).map(o1 -&gt; { vendors.stream().filter(Objects::nonNull).filter(o2 -&gt; (o2.getVendorId()).equals(o1.getVendorId()) &amp;&amp; o1.getRating() != null &amp;&amp; o1.getVendorId() != null).filter(Objects::nonNull).findAny(); return new PGRatingResponse(o1.getVendorId(), vendors.stream().filter(o -&gt; o.getVendorId() != null &amp;&amp; o.getVendorId().equals(o1.getVendorId())) .findFirst().get().getVendorName(), o1.getRating().stream().filter(Objects::nonNull) .filter(o2 -&gt; o2.getPgId() != null &amp;&amp; o2.getValue() != null) .map(o -&gt; new RatingResponse( LookupTable.pgLookupTable().getOrDefault(o.getPgId() == null ? &quot;5&quot; : o.getPgId(), &quot;Default&quot;), o.getPgId() == null ? &quot;5&quot; : o.getPgId(), o.getValue())) .collect(Collectors.toList())); }).collect(Collectors.toList()); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T11:12:08.820", "Id": "519860", "Score": "0", "body": "Welcome to Code Review, please add an explanation about what the code does." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T12:17:19.830", "Id": "519862", "Score": "0", "body": "Welcome to Code Review! Please [edit] your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!" } ]
[ { "body": "<p>One giant stream with nested streams with nested streams is very difficult to read. Streams are not a hammer, and not all problems are nails. Code should not try to ram things into streams when they make the card harder to read and understand.</p>\n<p>The line breaks here are not where I'd expect them to be, and I think it makes the code harder to read.</p>\n<p>You are filtering on not null in several places. Is it actually possible for the inputs to be null in all those places. Typically null values are not added to java collections objects, for instance. Anyplace where a value couldn't be null, the null check is just confusing.</p>\n<p>Silently ignoring the null values in these places is probably a bug. Without context I can't be sure, but it's very sketchy. Do you really want these null values floating around, with objects containing them being silently ignored?</p>\n<p>The stream of the vendors which ends with <code>findAny()</code> returns a value, but that value is ignored. It has no side effects. That stream does nothing and should be removed.</p>\n<p>Variable names like <code>o</code> and <code>o1</code> are hard to keep track of. Use meaningful variable names like <code>vendor</code>.</p>\n<p>Prefer multiple <code>filter()</code> calls over using <code>&amp;&amp;</code> in a <code>filter()</code>.</p>\n<p>Building a map once and looking up in it is more efficient and easier to read than streaming through a list inside a constructor argument.</p>\n<p>Is &quot;5&quot; the default rating PgId everywhere? If so, why is the value nullable at all? Just assign it to &quot;5&quot; if it isn't assigned.</p>\n<p>It's generally suggested that only the first letter of an acronym in a name is capitalized. So <code>PgRatingResponse</code> would be preferable to <code>PGRatingResponse</code>.</p>\n<p>Building the RatingResponse is complex enough to be extracted into its own method.</p>\n<p>If you made all these changes, your code might look more like:</p>\n<pre><code>public List&lt;PgRatingResponse&gt; collatePgRatingsbyVendor(\n List&lt;PgRatingConfig&gt; pgRatingSansPgname,\n List&lt;Vendor&gt; vendors) {\n\n Map&lt;Long, String&gt; vendorNamesById = vendors.stream()\n .filter(vendor -&gt; vendor.getVendorId() != null)\n .collect(toMap(vendor -&gt; vendor.getVendorId(), vendor -&gt; vendor.getVendorName()));\n\n return pgRatingSansPgname.stream()\n .filter(Objects::nonNull)\n .filter(pgRatingConfig -&gt; pgRatingConfig.getRating() != null)\n .map(pgRatingConfig -&gt;\n new PgRatingResponse(\n pgRatingConfig.getVendorId(),\n vendorNamesById.get(pgRatingConfig.getVendorId()),\n pgRatingConfig.getRating().stream()\n .filter(Objects::nonNull)\n .filter(rating -&gt; rating.getPgId() != null)\n .filter(rating -&gt; rating.getValue() != null)\n .map(rating -&gt; responseFor(rating))\n .collect(Collectors.toList())))\n .collect(Collectors.toList());\n}\n\nprivate RatingResponse responseFor(PgRating rating) {\n // These two variables need better names\n String lookupKey = rating.getPgId() == null ? &quot;5&quot; : rating.getPgId();\n String lookupValue = LookupTable.pgLookupTable().getOrDefault(lookupKey, &quot;Default&quot;);\n return new RatingResponse(lookupValue, lookupKey, rating.getValue());\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T04:21:02.707", "Id": "519919", "Score": "1", "body": "I suggest moving the big lambda `pgRatingConfig -> new PgRatingResponse(...)` into a method, too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T09:24:27.823", "Id": "519936", "Score": "0", "body": "There's no need to cram lots of streams operations into single huge chained expressions, starting with `.stream()` and containing everything up to `.collect()`. Just with any other Java expression, it's quite possible and useful to introduce well-named local variables for intermediate elements like streams or lambdas." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T13:02:12.227", "Id": "263323", "ParentId": "263319", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T10:17:29.760", "Id": "263319", "Score": "1", "Tags": [ "java", "lambda" ], "Title": "How to make this nested lambda expression readable?" }
263319
<p>I am working on some claims data, where I have features such as</p> <p><a href="https://i.stack.imgur.com/RtKbp.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RtKbp.jpg" alt="claims data spreadsheet" /></a></p> <p>The descriptions of the columns are: (A) the year of claim, (B) who's the insuring company (C) whether the vehicle is driven, (D) circumstance code (E) delay in raising claim (F) Vehicle age (G) Damages (H) Savings.</p> <p>Damages and Savings columns are empty: I have to fill the columns damages and savings with the weights/values of each of the (A) to (F) columns. The weights of these columns are given in an another spreadsheet. The other spreadsheet has 2 sheets again (i) is damages values and (ii) is savings values.</p> <p>I have created a simple dictionary comprehension code like this:</p> <p><a href="https://i.stack.imgur.com/Y2O4W.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y2O4W.jpg" alt="Second spreadsheet image" /></a></p> <hr /> <pre><code>import pandas as pd import numpy as np import openpyxl from pathlib import Path damages = 6.5143 savings = -1.6044 year = {} driven = {} vehicle_age = {} insurer = {} code = {} delay = {} my_dic = pd.read_excel(&quot;values111.xlsx&quot;, index_col=None) df = pd.read_csv(&quot;input.csv&quot;) cols = list(df) year = dict(zip(my_dic.year, my_dic.year_values)) driven = dict(zip(my_dic.driven, my_dic.driven_values)) age = dict(zip(my_dic.vehicle_age, my_dic.vehicle_age_values)) insurer = dict(zip(my_dic.insurer, my_dic.insurer_values)) code = dict(zip(my_dic.code, my_dic.code_values)) delay = dict(zip(my_dic.delay, my_dic.delay_values)) list_of_df = df.to_numpy().tolist() #list_of_df = df.to_numpy().tolist() for i in list_of_df: damages = 6.5143 damages = damages + year[i[1]] damages = damages + driven[i[3]] damages = damages + insurer[i[2]] damages = damages + code[i[4]] damages = damages + delay[i[5]] i[7] = damages New_df = pd.DataFrame(list_of_df, columns=cols) (New_df) </code></pre> <hr /> <p>However, I wanted to check if there's a better approach/alternative than this approach. Perhaps a more comprehension-based approach where the <code>for</code> loops can be avoided?</p> <p>I feel it's a little hard coded here, with a lot of indexes (column indexing) approach used. The original dataset has many columns; giving out the indexes can be cumbersome.</p> <p>The spreadsheets of values of the columns where these weights are present have separate sheets of damages and savings. Perhaps this can be included seamlessly without doing the computations two times?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-12T15:57:58.847", "Id": "521317", "Score": "0", "body": "It would be helpful if you could provide your spreadsheet data as csv (comma separated values). Preferably integrated into your post." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T13:11:17.940", "Id": "263324", "Score": "2", "Tags": [ "python", "hash-map", "database", "pandas" ], "Title": "Compute damages and savings for motor insurance claims" }
263324
<h2>Here is my example structure:</h2> <pre><code>. ├── App.jsx ├── index.js └── src └── components ├── Button.jsx └── Header └── Header.jsx </code></pre> <h2>Question:</h2> <ol> <li>Should I name Header.jsx inside Header folder? (I personally prefer this way insteade of <code>Header/index.jsx</code> because I though it would be better to identify in vscode tab.)</li> <li>When It has mobile component, where should I put it and how to name it, for example:</li> </ol> <ul> <li><code>a. components/ButtonMobile.jsx</code></li> <li><code>b. components/Button/ButtonMobile.jsx, components/Button/Button.jsx</code></li> <li><code>c. components/Button/mobile/Button.jsx, components/Button/Button.jsx</code></li> <li><code>d. components/mobile/Button.jsx</code></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T14:55:41.443", "Id": "519870", "Score": "1", "body": "Welcome to the Code Review Community where we review working code you have written and provide suggestions on how to improve that code. I am voting to close this question because it contains no code." } ]
[ { "body": "<h2>This is one of the possibilities I tried:</h2>\n<pre><code>.\n├── App.jsx\n├── index.js\n└── src\n └── components\n ├── Button.jsx\n ├── Drawer\n │ ├── Drawer.jsx\n │ ├── DrawerMobile.jsx\n │ └── components\n │ ├── DrawerTitle.jsx\n │ ├── DrawerMenu.jsx\n │ └── DrawerMenuMobile.jsx\n └── Header\n └── Header.jsx\n</code></pre>\n<ul>\n<li><code>components/Drawer/DrawerMobile.jsx</code> is the root of Drawer component and is mobile version.</li>\n<li><code>components/Drawer/components/DrawerMenuMobile.jsx</code> is a child component of mobile version.</li>\n<li><code>components/Drawer/components/DrawerTitle.jsx</code> is a child component shared both with default and mobile.</li>\n</ul>\n<h2>Some explanation:</h2>\n<p>I name <code>components/Drawer/DrawerMobile.jsx</code> instead of <code>components/mobile/Drawer.jsx</code> because:</p>\n<ul>\n<li><code>DrawerMobile.jsx</code> more easy to identify in vscode tab.</li>\n<li>Avoiding imports name conflict --- <code>{isWide? &lt;Drawer /&gt; : &lt;Drawer /&gt;}</code>.</li>\n<li>Share components inside <code>Drawer/</code>.</li>\n</ul>\n<h2>What's your opinion and explanation? I'm glad to hear.</h2>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T13:56:39.017", "Id": "263326", "ParentId": "263325", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T13:55:51.183", "Id": "263325", "Score": "-1", "Tags": [ "javascript", "react.js", "vue.js" ], "Title": "How do I distinguish the difference in naming and file structure between components and mobile components in React?" }
263325
<p>I do research and compare different numeric models to each other. Therefore, I want to easily switch out the numeric models in my simulations and evaluation code.</p> <p>Some models work in cartesian coordinates, some in cylindrical coordinates. Some don't have a z-coordinate (yet), since they are primarily two-dimensional; some do. Also, the dimensions and orientations of the input and output vectors need to be the same. Obviously, all those differences need to be alleviated. But how do I structure this best? I find it hard to do the change before I understand how the modules would best look like.</p> <p>Here are two models:</p> <pre><code>import numpy as np from scipy.special import kn, iv # Physics Constants MU_0 = 4 * np.pi * 1e-7 # Cable Constants P = 1.862 # length of cable [m] after which we have 360 turn; &quot;Schlaglänge der Leiterwindung&quot; # A = 2.67e-2 # helix radius [m] = 2*A/sqrt(3) # Helgolandkabel A = 65e-3 # helix radius [m] = 2*A/sqrt(3) # 60kV Kabelstück Q = 2 * np.pi * A / P # Constants for the measurement AMPS = 4 # peak current [A] of I * sin(omega * t) R_inner = 139.2e-3 # in m R_outer = 127.1e-2 # in m # Program Constants SIZE = 12 SIZE_Z = 37 ORDER = 5 # ORDER of bessel functions considered FRAMES = 60 # coordinate transformation from cylindrical to cartesian coordinates def coordinate_transform_cy2ca(r, theta, z): x = np.cos(theta) * r y = np.sin(theta) * r return x, y, z # coordinate transformation back def coordinate_transform_ca2cy(x, y, z): r = np.sqrt(np.square(x) + np.square(y)) theta = np.arctan2(x, y) return r, theta, z # vector transformation from cylindrical to cartesian coordinate system def vector_transform_cy2ca(v_r, v_theta, v_z, R, T, Z): x = v_r * np.cos(T) - R * np.sin(T) * v_theta y = v_r * np.sin(T) + R * np.cos(T) * v_theta return x, y, v_z # vector transformation back def vector_transform_ca2cy(v_x, v_y, v_z, X, Y, Z): sq_devisor = np.square(X) + np.square(Y) devisor = np.sqrt(sq_devisor) r = v_x * X / devisor + v_y * Y / devisor theta = v_x * (-Y / sq_devisor) + v_y * X / sq_devisor return r, theta, v_z # calculate vector component r of the magnetic field in cylinder coordinates def calc_b_r(R, T, Z, m, current): # equation 35 m_1 = m m_0 = m - 1 m_2 = m + 1 eta_m = np.abs(m_1 * Q) eta_r_a = eta_m * R / A m_0_term = iv(m_0, eta_m) * kn(m_0, eta_r_a) m_2_term = iv(m_2, eta_m) * kn(m_2, eta_r_a) m_02_sum = m_0_term + m_2_term m_1_term = 2 * m_1 * iv(m_1, eta_m) * kn(m_1, eta_r_a) exp_term = np.exp((0 + 1j) * m_1 * (T - 2 * np.pi * Z / P)) exp_product = 2 * np.pi * R * m_1 * Q / P * exp_term bessel_term = m_1_term + exp_product * m_02_sum b_r = ((0 + 1j) * 3 * MU_0 * current / (4 * np.pi * R)) * bessel_term return b_r # calculate vector component Theta of the magnetic field in cylinder coordinates def calc_b_theta(R, T, Z, m, current): m_1 = m m_0 = m - 1 m_2 = m + 1 eta_m = np.abs(m_1 * Q) eta_r_a = eta_m * R / A exp_term = np.exp((0 + 1j) * m_1 * (T - 2 * np.pi * Z / P)) m_0_term = iv(m_0, eta_m) * kn(m_0, eta_r_a) m_2_term = iv(m_2, eta_m) * kn(m_2, eta_r_a) first_term = (2 * np.pi * m_1 * Q / P) * (m_0_term - m_2_term) mixed_term = (2 * eta_m / A) * iv(m_1, eta_m) * (kn(m_0, eta_r_a) + m_1 * kn(m_1, eta_r_a) / eta_r_a) second_term = mixed_term * exp_term bessel_term = second_term - first_term b_theta = (3 * MU_0 * current / (4 * np.pi)) * bessel_term return b_theta # calculate vector component z of the magnetic field in cylinder coordinates def calc_b_z(R, T, Z, m, current): m_1 = m m_0 = m - 1 m__1 = m - 2 # the subscript &quot;_1&quot; is supposed to indicate A &quot;-1&quot; - its the K_ m-2 in the paper m_2 = m + 1 eta_m = np.abs(m_1 * Q) eta_r_a = eta_m * R / A exp_term = np.exp((0 + 1j) * m_1 * (T - 2 * np.pi * Z / P)) m__1_term = (eta_m / A) * iv(m_0, eta_m) * (m_1 * kn(m_0, eta_r_a) / eta_r_a + kn(m__1, eta_r_a)) # same term as before, just two orders up mirror_term = (eta_m / A) * iv(m_2, eta_m) * (m_1 * kn(m_2, eta_r_a) / eta_r_a + kn(m_1, eta_r_a)) m_0_term = iv(m_0, eta_m) * kn(m_0, eta_r_a) / R # same as before, just two orders up m_2_term = iv(m_2, eta_m) * kn(m_2, eta_r_a) / R m_02_term = (iv(m_0, eta_m) * kn(m_0, eta_r_a) - iv(m_2, eta_m) * kn(m_2, eta_r_a)) * m_1 / R bessel_term = m_0_term + m__1_term - m__1_term - mirror_term - m_02_term b_z = 3 * MU_0 * Q * current / (4 * np.pi) * bessel_term * exp_term return b_z def main(): r = np.arange(R_inner, R_outer, (R_outer - R_inner) / 1) # SIZE) theta = np.arange(0, 2 * np.pi, 2 * np.pi / SIZE) z = np.arange(0, P, P / SIZE_Z) R, T, Z = np.meshgrid(r, theta, z) # these are the orders of the bessel functions # m is the index of the bessel funktion. ms is the list of indices ms = np.arange(int(-ORDER / 3) * 3 - 2, ORDER, 3) m_num = len(ms) # create the result_b_r = np.zeros([FRAMES, R.shape[0], R.shape[1], R.shape[2]]).astype(np.complex_) result_b_theta = np.zeros([FRAMES, T.shape[0], T.shape[1], T.shape[2]]).astype(np.complex_) result_b_z = np.zeros([FRAMES, Z.shape[0], Z.shape[1], Z.shape[2]]).astype(np.complex_) for frame in range(FRAMES): print(frame) #################### here the magnetic field for one time step for all the points in the mesh is calculated current = AMPS * np.exp(1j * frame * 2 * np.pi / FRAMES) b_r = np.zeros([m_num, R.shape[0], R.shape[1], R.shape[2]]).astype(np.complex_) b_theta = np.zeros([m_num, T.shape[0], T.shape[1], T.shape[2]]).astype(np.complex_) b_z = np.zeros([m_num, Z.shape[0], Z.shape[1], Z.shape[2]]).astype(np.complex_) # iterate over the indices of the bessel function, add them up later for i, m in enumerate(ms): b_r[i] = calc_b_r(R, T, Z, m, current) b_theta[i] = calc_b_theta(R, T, Z, m, current) b_z[i] = calc_b_z(R, T, Z, m, current) # this adds up the different parts resulting from the different orders of the bessel functions result_b_r[frame] = np.sum(b_r, axis=0) result_b_theta[frame] = np.sum(b_theta, axis=0) result_b_z[frame] = np.sum(b_z, axis=0) ##################### now the calculation for one point in time for all the indices of the bessel functions is complete # coordinate transform cylindrical to cartesian coordinates b_x, b_y, b_z = vector_transform_cy2ca(result_b_r, result_b_theta, result_b_z, R, T, Z) X, Y, Z = coordinate_transform_cy2ca(R, T, Z) # combine field vectors into one matrix result_b = np.array([b_x, b_y, b_z]) if __name__ == '__main__': main() </code></pre> <p>This is a model in 2D.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np from matplotlib import rc from typing import List, Pattern, Union, Tuple # rc('text', usetex=True) CURRENT_PEAK = 4.0 MU_0 = 4 * np.pi * 1e-7 CONDUCTOR_DISTANCE = 0.065 HELIX_RADIUS = CONDUCTOR_DISTANCE / np.sqrt(3) LENGTH_OF_LAY = 1.862 Q = 2 * np.pi * HELIX_RADIUS / LENGTH_OF_LAY # this expresses the cable specific relation between length of lay and # conductor distance. for parallel conductors it is infinit, for strongly twisted ones it is small. It is A metric # for how much magnetic field can leave the cable. POINTS: np.ndarray = np.array( [[7.0, 0], [13.7, 0], [20.2, 0], [27.7, 0], [37, 0], [44.1, 0], [51.5, 0], [61.2, 0], [72, 0], [84.9, 0], [97, 0], [117.1, 0]]) * 1e-2 POINTS += np.array([10.0, 0.0]) * 1e-2 # radius of the pipe DIPOL_POINT = np.array([0, 0]) def magnetic_dipol_field_in_point(dipol_coordinates, dipol_vector, point_coordinates): direction_vector = (point_coordinates - dipol_coordinates) direction_unit_vector = (direction_vector.T / np.linalg.norm(direction_vector, axis=1).T).T # print(np.linalg.norm(direction_vector, axis=1)) dot = dipol_vector.T * direction_unit_vector r = np.linalg.norm(direction_vector, axis=1) zähler = (3 * direction_unit_vector * dot - dipol_vector).T # * ( np.exp(-Q*.089*r) / 1.55) nenner = np.power(np.linalg.norm(direction_vector, axis=1), 2.0) b_vector = (MU_0 / (4 * np.pi)) * zähler / nenner return b_vector.T def main(): fig, ax = plt.subplots() circle = plt.Circle((0, 0), radius=2.3, facecolor=&quot;none&quot;, linewidth=2, edgecolor='lightblue', alpha=0.3, label=r&quot;outer diameter of cable&quot;) plt.gca().add_artist(circle) dipol_vectors = np.array([1, 0]) dipol_vectors = dipol_vectors / np.linalg.norm(dipol_vectors, axis=0) # print(&quot;dipol_vectors: &quot;,dipol_vectors) dipol_vectors = dipol_vectors * CURRENT_PEAK * (CONDUCTOR_DISTANCE * np.sqrt(3) / 2) * 2 # res = np.zeros_like(POINTS) res = magnetic_dipol_field_in_point(DIPOL_POINT.T, dipol_vectors, POINTS) if __name__ == '__main__': main() </code></pre> <p>I want to learn how to refactor this code into interchangeable modules. I have more models, this is just to illustrate the mess I am coming from, and I look for examples to follow, to unify my codebase.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T16:55:06.693", "Id": "519882", "Score": "0", "body": "This won't run. You haven't defined `DIPOL_POINT` and `POINTS`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T16:56:21.340", "Id": "519883", "Score": "1", "body": "yes, i was cleaning up the code before posting it, and destroyed it while doing so. i need to update the code. - done" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T02:46:35.923", "Id": "519917", "Score": "0", "body": "This is fairly opaque to me. Can you add a description matching up corresponding elements in your two models, and where they exist in the code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T15:34:18.787", "Id": "519964", "Score": "0", "body": "I'm with Reinderien, I started writing an answer, but we'd need a little bit more detail. I understand scientific code is usually a mess ahah, but if you could also clarify what are the inputs and outputs of the code, I believe we could come up with something" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T06:17:54.627", "Id": "520003", "Score": "0", "body": "@IEatBagels, I hear you, and I reworked the first module yesterday and started on the second one. The second one is harder because it is 2D (and needs to be 3D). My challenge is that I need to rethink it, and that takes time. I hope to update the second module today or tomorrow. It gets a lot clearer right away from doing so, and the parallel structures become more visible. If I knew how to pause and unpause a question, I would do so, but I will ping you guys once I am done as a crutch." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T14:04:14.340", "Id": "263327", "Score": "4", "Tags": [ "python", "numpy", "modules" ], "Title": "How to structure and write exchangable calculation models (in python3 modules)?" }
263327
<p>The following code works fine to generate an array of 6 random values (or however many are specified by <code>iterations</code>). I'm wondering if there's a more concise way than using a <code>while</code> loop to achieve the same result.</p> <pre><code>const seedValue = 31; const iterations = 6; let i = 0; const results = []; while (i &lt; iterations) { results.push(seedValue * Math.random()); i++; } console.log(results); </code></pre>
[]
[ { "body": "<p>Probably not the most concise nor efficient, but it is an alternative in a sense that the approach is totally different and shorter than what you provided:</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 seedValue = 31;\nconst iterations = 6;\nconst results = Array(iterations).fill(seedValue).map(v =&gt; v * Math.random())\n\nconsole.log(results)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>The idea comes from other language's <code>range()</code> function, which creates a sequence of values that you can iterate over. JS has no such function, but you can emulate with an array. In this case, I created an empty array of 6 slots, filled them up with the seed value, and transform each by multiplying each by <code>Math.random()</code>.</p>\n<p>If you insist using a loop, consider a <code>for</code> loop instead. This puts the counter's initialization and increment in the same line as the opening, removing the need for separate lines:</p>\n<pre><code>const results = [];\n\nfor (let i = 0; i &lt; iterations; i++) {\n results.push(seedValue * Math.random());\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T15:22:33.837", "Id": "263331", "ParentId": "263330", "Score": "5" } }, { "body": "<p>A simple approach is to use <a href=\"https://tc39.es/ecma262/#sec-array.from\" rel=\"nofollow noreferrer\"><code>Array.from</code></a>. While <code>Array.from</code> is mostly used to create an <a href=\"https://tc39.es/ecma262/#sec-array-objects\" rel=\"nofollow noreferrer\"><code>Array</code></a> from an <a href=\"https://tc39.es/ecma262/#sec-iterable-interface\" rel=\"nofollow noreferrer\"><em>Iterable</em></a> or an <a href=\"https://tc39.es/ecma262/#sec-iterator-interface\" rel=\"nofollow noreferrer\"><em>Iterator</em></a>, it can also be used to create an <code>Array</code> from any <a href=\"https://tc39.es/ecma262/#sec-lengthofarraylike\" rel=\"nofollow noreferrer\"><em>array-like object</em></a>, where an <em>array-like object</em> is simply any object with a <code>length</code> property.</p>\n<p>The second argument to <code>Array.from</code> is a mapping function which produces the elements of the <code>Array</code>.</p>\n<p>So, the whole thing would look something like this:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const seedValue = 31;\nconst iterations = 6;\n\nconst results = Array.from(\n { length: iterations },\n _ =&gt; seedValue * Math.random()\n);\n\nconsole.log(results);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-26T11:14:29.857", "Id": "263483", "ParentId": "263330", "Score": "0" } } ]
{ "AcceptedAnswerId": "263331", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T15:12:59.963", "Id": "263330", "Score": "-1", "Tags": [ "javascript" ], "Title": "concise alternative to a while loop" }
263330
<h1>Create a <code>Time</code> class.</h1> <p><a href="https://www.youtube.com/watch?v=rIE2GAqnFGw" rel="nofollow noreferrer">Time is on my side</a></p> <h2>Specification</h2> <ul> <li><p>Basic attributes: hour, minute, second and day (default is 0), + getters, + setters (using a decorator)</p> </li> <li><p>If you try to initialize an incorrect value of seconds or minutes, i.e. greater than or equal to 60, raise an exception from your own <code>WrongSeconds</code> or<code> WrongMinutes</code> class</p> </li> </ul> <p>Add the following operators:</p> <ul> <li><p><code>+</code>: works as follows - adds hours to hours, minutes to minutes, and so on, e.g. 2 h 30 m 4 s + 6 h 35 m 50 s = 9 h 5 m 54 s (we also return an instance of the Time class), if we exceed 24 h, the day should be 1</p> </li> <li><p>&lt;: Compare first day, hours, then minutes, seconds. Return True / False, e.g. 2 h 40 m 30 s d 0 &lt; 1 h 59 m 30 s d 0 → False, 2 h 40 m 30 s d -1 &lt; 1 h 59 m 30 s d 0 → True</p> </li> <li><p><code>__str__</code>:<code> Time</code> should be displayed as: &quot;20:05:25, day without any changes&quot; (when day = 1, -1 : next / previous day)</p> </li> </ul> <p>Add the function <code>zone</code>, which for a given instance of the<code> Time</code> class returns the appropriate time in another time zone. The argument of the function is the city for which we find the time: Warsaw, London, New York, Tokyo, Syndey, Moscow, Los Angeles. We assume that the default time is GMT.</p> <ul> <li>PEP8</li> <li>DOC</li> <li>tests</li> </ul> <p>And here is the code!</p> <pre><code>class WrongSeconds(Exception): def __str__(self): return &quot;Wrong amount of seconds passed (greater or equal 60)&quot; class WrongMinutes(Exception): def __str__(self): return &quot;Wrong amount of minutes passed (greater or equal 60)&quot; class Time: TIME_ZONES = { &quot;Warsaw&quot;: 2, &quot;London&quot;: 1, &quot;Tokio&quot;: 9, &quot;Sydney&quot;: 10, &quot;Moscow&quot;: 3, &quot;Los angeles&quot;: -7 } def __init__(self, d = 0, h = 0, m = 0, s = 0): self.days = d self.hours = h self.minutes = m self.seconds = s @property def days(self): return self._d @days.setter def days(self, val): self._d = val @property def hours(self): return self._h @hours.setter def hours(self, val): if val &lt; 0: self.days += val//60 val = 24 - abs(val)%24 elif val &gt;= 24: self.days += val//24 val %= 24 self._h = val @property def minutes(self): return self._m @minutes.setter def minutes(self, val): if &quot;_m&quot; not in self.__dict__ and val &gt;= 60: raise WrongMinutes if val &lt; 0: self.hours += val//60 val = 60 - abs(val)%60 elif val &gt;= 60: self.hours += val//60 val %= 60 self._m = val @property def seconds(self): return self._s @seconds.setter def seconds(self, val): if &quot;_s&quot; not in self.__dict__ and val &gt;= 60: raise WrongSeconds if val &lt; 0: self.minutes += val//60 val = 60 - abs(val)%60 elif val &gt;= 60: self.minutes += val//60 val %= 60 self._s = val def strefa(self, city): if city.capitalize() not in self.TIME_ZONES: raise ValueError(f&quot;City {city} not in time zone database&quot;) result_time = self.__class__( self.days, self.hours, self.minutes, self.seconds) result_time.hours += self.TIME_ZONES[city.capitalize()] return str(result_time) def __add__(self, other): assert isinstance(other, self.__class__), f&quot;Cannot add {type(other)} to a time object&quot; result = self.__class__() result.seconds += self.seconds + other.seconds result.minutes += self.minutes + other.minutes result.hours += self.hours + other.hours result.days += self.days + other.days return result def __lt__(self, other): assert isinstance(other, self.__class__), f&quot;Cannot compare {type(other)} with a time object&quot; if self.days &lt; other.days: return True elif self.hours &lt; other.hours: return True elif self.minutes &lt; other.minutes: return True elif self.seconds &lt; other.seconds: return True return False def __str__(self): s = f&quot;{self.hours}:{self.minutes:02}:{self.seconds:02}&quot; if self.days == 0 : return s + &quot;, day without any changes&quot; elif self.days == 1 : return s + &quot;, the next day&quot; elif self.days == -1 : return s + &quot;, previous day&quot; return s + f&quot;, day: {self.days}&quot; # --- TEST CASES --- try: time = Time(m = 60) except Exception as e: print(e.__class__, e, &quot;\n&quot;) time = Time(d = 0, h = 23, m = 59, s = 59) print(time) time.seconds += 1 print(time, &quot;\n&quot;) time1 = Time(h = 3, m = 2, s = 1) time2 = Time(h = 6, m = 5, s = 4) print(time1 + time2, &quot;\n&quot;) print(time1 &lt; time2 ) print(time2 &lt; time1, &quot;\n&quot;) time_gmt = Time(h = 2, m = 0, s = 0) print(time_gmt.strefa(&quot;London&quot;)) print(time_gmt.strefa(&quot;Sydney&quot;)) print(time_gmt.strefa(&quot;Los Angeles&quot;)) print(&quot;------------------------------------&quot;) print(&quot;Comparisons&quot;) t1 = Time(h = 14, m = 4, s = 35) t2 = Time(h = 8, m = 50, s = 25) print(t1 + t2) print(t1) print(t2) print(t1 &lt; t2) </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>&lt;class '__main__.WrongMinutes'&gt; Wrong amount of minutes passed (greater or equal 60) 23:59:59, day without any changes 0:00:00, the next day 9:07:05, day without any changes True False 3:00:00, day without any changes 12:00:00, day without any changes 19:00:00, previous day ------------------------------------ Comparisons 22:55:00, day without any changes 14:04:35, day without any changes 8:50:25, day without any changes True </code></pre> <p>And here is my question, how to get a better solution? Maybe shorter? Maybe get rid of some operations, terms?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T16:19:53.093", "Id": "519877", "Score": "0", "body": "If you can't represent the 61st second of a minute, what's supposed to happen when there's a leap second??" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T16:21:52.917", "Id": "519878", "Score": "0", "body": "um raise a wrongseconds/wrongminutes error i guess" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T16:23:43.627", "Id": "519879", "Score": "0", "body": "That's fine - the code just pretends leap seconds don't exist. I'm poking fun a little, but also pointing out that real date-time code has a lot of awkward real-world stuff to deal with, so better using the libraries than writing your own for actual use." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T16:25:29.887", "Id": "519880", "Score": "1", "body": "Well you know, sometimes (because its a task for school) I also don't see any sense in creating such complicated and thus simple things, but yeah, here we are! :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T19:35:06.277", "Id": "519902", "Score": "0", "body": "One comment is, whenever you are implementing either of the comparison operators, you need to make sure you always implement them all. This would be, `<`, `<=`, `>`, `>=`, `==` and `!=`. Otherwise, the whoever used your `Time` class might run into trouble during comparisons without noticing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-24T09:49:04.290", "Id": "522075", "Score": "0", "body": "Also worth noting that it's probably best to raise a `TypeError` in such methods, rather than using `assert`. `assert` is basically only used for tests/debugging, as you can run python in \"all asserts silenced mode\", which is sometimes done for optimisation purposes. https://stackoverflow.com/questions/1273211/disable-assertions-in-python" } ]
[ { "body": "<p>One small point:</p>\n<p>When we inherit from <code>Exception</code>, we get its (actually, <code>BaseException</code>'s) <code>str()</code> implementation, so we don't need to provide <code>__str__()</code> if we initialise the base class <code>args</code> with the required string:</p>\n<pre><code>class WrongSeconds(Exception):\n def __init__(self):\n self.args = [ &quot;Wrong amount of seconds passed (greater or equal 60)&quot; ]\n</code></pre>\n<hr />\n<p>In the addition, we have these new values:</p>\n<pre><code> result.seconds += self.seconds + other.seconds\n result.minutes += self.minutes + other.minutes\n result.hours += self.hours + other.hours\n result.days += self.days + other.days\n</code></pre>\n<p>I don't see anything that handles overflow of any of these values (e.g. if hours &gt; 24, we need to add a day and subtract 24 of the hours to get the values back into their allowed ranges).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T16:50:48.437", "Id": "263333", "ParentId": "263332", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T16:11:47.293", "Id": "263332", "Score": "2", "Tags": [ "python", "object-oriented", "datetime", "reinventing-the-wheel", "homework" ], "Title": "Create a Time class - OOP in Python" }
263332
<p>If the validation in <code>RestController</code> fails, I need to handle <code>MethodArgumentNotValidException</code> and provide an errorMessage, that contains info about all rejected fields of passed object. If any rejected field has <code>@JsonProperty</code> annotation with non-empty value, then I need to replace field name with this value in errorMessage. What do you think about this implemenation:</p> <p>Dto example:</p> <pre><code>public class Person { @NotEmpty private String name; @JsonProperty(&quot;interests&quot;) @NotNull @NotEmpty private List&lt;String&gt; hobbies; // getters, setters, etc. } </code></pre> <p>Invalid JSON passed to some RestController endpoint in request body:</p> <pre><code> { &quot;name&quot;: &quot;&quot;, &quot;interests&quot;: null } </code></pre> <p>Exception handler:</p> <pre><code>@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity&lt;ApiError&gt; handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { String errorMessage = getRejectedJsonProperties(e).entrySet() .stream() .map(entry -&gt; entry.getKey() + &quot;: &quot; + String.join(&quot;, &quot;, entry.getValue())) .collect(joining(&quot;; &quot;)); return constructResponse(errorMessage, HttpStatus.BAD_REQUEST); } private Map&lt;String, List&lt;String&gt;&gt; getRejectedJsonProperties(MethodArgumentNotValidException e) { Map&lt;String, List&lt;String&gt;&gt; rejectedProps = e.getBindingResult().getFieldErrors().stream() .collect(groupingBy(FieldError::getField, mapping(DefaultMessageSourceResolvable::getDefaultMessage, toList()))); Arrays.stream(e.getParameter().getParameterType().getDeclaredFields()) .filter(f -&gt; rejectedProps.containsKey(f.getName())) .filter(f -&gt; f.isAnnotationPresent(JsonProperty.class) &amp;&amp; !f.getAnnotation(JsonProperty.class).value().isEmpty()) .forEach(f -&gt; rejectedProps.put(f.getAnnotation(JsonProperty.class).value(), rejectedProps.remove(f.getName()))); return rejectedProps; } // constructResponse method } </code></pre> <p>At first in <code>getRejectedJsonProperties()</code> I collect in <code>Map</code> all rejected field names as keys and <code>List</code> of error messages as value (e.g. <code>{name=[must not be empty]; hobbies=[must not be null, must not be empty&quot;]}</code>).</p> <p>Then I take all declared fields of validated object and if field has <code>JsonPropery</code> annotation I replace this entry with new key in <code>rejectedProps</code> map.</p> <p>As a result, the <code>errorMessage</code> in <code>handleMethodArgumentNotValidException()</code>:</p> <pre><code>name: must not be empty; interests: must not be null, must not be empty </code></pre> <p>If you need any clarifications, please let me know and thanks in advance!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T12:41:26.377", "Id": "519942", "Score": "1", "body": "Welcome to the Code Review Community, is the code working as expected? We only review code that is working as expected. Please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask). Right now your question has three votes to close." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T12:46:50.353", "Id": "519945", "Score": "1", "body": "Yes, it works as expected, then it can be closed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T13:01:44.493", "Id": "519947", "Score": "3", "body": "To anyone in the close vote queue, this question was just discussed in the [2nd Monitor](https://chat.stackexchange.com/rooms/8595/the-2nd-monitor) and we don't see any reason why it should be closed. It does need an answer." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T17:11:31.850", "Id": "263334", "Score": "4", "Tags": [ "java", "json", "error-handling", "spring" ], "Title": "Exception handling: using @JsonProperty value to make error message" }
263334
<p>I am learning <code>Rust</code> and I would like to know what is the idiomatic way of writing a function that could run into multiple error types. For instance, in the function <code>get_account_with_creds</code> I am trying to return a struct <code>AccountForResponse</code> if the credentials match. The function could possibly run into a database error, so the <code>Result</code> could be a <code>PoolError</code>. I am using <code>unwrap</code> a few places because the error types are different. How can I improve this? I am also not sure about returning <code>Ok(None)</code></p> <pre><code>pub async fn get_account_with_creds(db: &amp;Db, creds: AccountForLogin) -&gt; Result&lt;Option&lt;AccountForResponse&gt;, PoolError&gt; { let client: Client = db.get().await?; let stmt = client .prepare(&quot;SELECT id, first_name, last_name, email, password from accounts WHERE email = $1&quot;) .await?; let rows = client.query(&amp;stmt, &amp;[&amp;creds.email]).await?; let row = rows.first().unwrap(); let hashed_password: &amp;str = row.get(4); match bcrypt::verify(creds.password, hashed_password).unwrap() { false =&gt; Ok(None), true =&gt; { let account = Some(AccountForResponse { id: Some(row.get(0)), first_name: row.get(1), last_name: row.get(2), email: row.get(3), }); Ok(account) } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T18:54:18.943", "Id": "519898", "Score": "0", "body": "The [anyhow crate](https://crates.io/crates/anyhow) might be what you're looking for." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T19:01:42.837", "Id": "519900", "Score": "0", "body": "Thanks, it seems like it is exactly what I am looking for. But is using `anyhow` the idiomatic way of handling returning multiple error types in Rust? I intend to use it everywhere I face this issue" } ]
[ { "body": "<ul>\n<li><p>If you expect to <em>handle</em> the errors (to recover from them in a way that is specific to which error occurred), or if you're writing a library, then define an <code>enum</code> type which can hold any of the errors might occur. Each enum variant might either contain the original error value (so it can be retrieved), or not (if the original error is purely an implementation detail). The <code>thiserror</code> crate can help you implement <code>Error</code> and <code>From</code> for such enums.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>#[derive(thiserror::Error)]\nenum LoginError {\n Database(#[from] PoolError),\n AccountNotFoundOrIncorrectPassword, // Use this in place of your unwraps\n}\n</code></pre>\n</li>\n<li><p>If you simply want to collect the errors and report/log them, without the <em>code</em> worrying about the differences between different errors (because you don't have a specific plan beyond &quot;log it and/or abort&quot;), then you can use <code>anyhow</code>, or stick to the standard library and use <code>Box&lt;dyn std::error::Error&gt;</code> — there are provided <code>From</code>/<code>Into</code> conversions for it so that the <code>?</code> operator can turn any error that implements <code>std::error::Error</code> into the boxed form.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T21:40:43.803", "Id": "263344", "ParentId": "263338", "Score": "4" } } ]
{ "AcceptedAnswerId": "263344", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T18:42:03.720", "Id": "263338", "Score": "2", "Tags": [ "rust" ], "Title": "Rust returning multiple errors" }
263338
<p>So I'm currently learning about networking between a client and a server and I decided to try to write my own client and server.</p> <p>I implemented a way of receiving data and it goes as follows..</p> <p>The server expects a packet that is structured like this.. <code>[ packetSize(2bytes), [data] ]</code>, so the first two bytes is the entire packet size <code>(size(2bytes) + data(X bytes))</code>.</p> <p>And my implementation receives all the data just fine, I just feel like it could be cleaner, by maybe using a <code>BinaryReader</code> or something similar, the goal here is to maybe get rid of all the <code>Buffer.BlockCopy(..</code> or anything to make it cleaner, maybe even improving it.</p> <pre><code>class Connection { private TcpClient _socket; private int _received; private int _packetSize = -1; private int bufferSize = 1024; private int offset = 0; private byte[] _buffer; private byte[] _packet; private BinaryReader reader; public Connection(TcpClient client) { _buffer = new byte[bufferSize]; _socket = client; reader = new BinaryReader(_socket.GetStream()); Console.WriteLine($&quot;Client connected: {_socket.Client.RemoteEndPoint}&quot;); ProcessPackets(); } public void ProcessPackets() { Task.Run(() =&gt; { /* * Packet Initializer * Receive The PacketSize * Instantiate the Packet byte[], giving it the correct size */ _received = _socket.Client.Receive(_buffer, 0, 2, SocketFlags.None); _packetSize = BitConverter.ToInt16(_buffer, 0); _packet = new byte[_packetSize]; /* Copy over the bytes that represent the size and update the offset. */ Buffer.BlockCopy(_buffer, 0, _packet, 0, _received); offset = _received; /* Append data to the packet while there still is data to receive. */ while (_received &lt; _packetSize) { var delta = _packetSize - _received; if (delta &lt;= bufferSize) { _received += _socket.Client.Receive(_buffer, 0, delta, SocketFlags.None); Buffer.BlockCopy(_buffer, 0, _packet, offset, _received - offset); } else { _received += _socket.Client.Receive(_buffer, 0, bufferSize, SocketFlags.None); Buffer.BlockCopy(_buffer, 0, _packet, offset, _received - offset); } offset += bufferSize; } //Reset the offset. offset = 0; /*junk*/ var data = Encoding.ASCII.GetString(_packet.Skip(2).ToArray()); Console.WriteLine($&quot;Data received: {data}&quot;); }); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T20:28:57.613", "Id": "519904", "Score": "0", "body": "What is `_socket`? Could you provide more code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T20:37:48.300", "Id": "519906", "Score": "0", "body": "@aepot there we go :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-30T00:41:03.610", "Id": "526560", "Score": "0", "body": "Did I answer the question?" } ]
[ { "body": "<p><em>Future note: avoid making Code Review request for not finished yet solution.</em></p>\n<p>Few notes:</p>\n<ul>\n<li>What I'm really missing here: <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/async\" rel=\"nofollow noreferrer\">Asynchronous programming</a></li>\n<li>There's no reason to stay in ASCII, use UTF8 instead. Also ASCII is subset of UTF-8.</li>\n<li>You run receiving packet once and then nothing.</li>\n<li>You aren't return data anywhere, why?</li>\n<li><code>Buffer.BlockCopy</code> is really fast but reading data from network directly to target array would look more efficient.</li>\n<li>Avoid making fields (global variables) for single method. Make locals instead. If you think that declaring primitives e.g. <code>int</code> field once is more efficient than creating it once per loop iteration as local variable, then you're wrong.</li>\n<li>Int16 is signed type. You can double the packet max size just changing it to UInt16.</li>\n<li>There's no sense to store the data length in the received output data because <code>array.Length</code> will contain it.</li>\n</ul>\n<p>Here's my try to play with.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>class Connection\n{\n private readonly TcpClient _client;\n private readonly NetworkStream _stream;\n private readonly Task _task;\n private readonly CancellationTokenSource _cts;\n\n private const int bufferSize = ushort.MaxValue; // 65536\n\n public Connection(TcpClient client)\n {\n _client = client;\n _stream = _client.GetStream();\n _cts = new CancellationTokenSource();\n _task = ReceiveAsync(_cts.Token);\n\n Console.WriteLine($&quot;Client connected: {_client.Client.RemoteEndPoint}&quot;);\n }\n\n public async Task SendAsync(string message)\n {\n byte[] data = Encoding.UTF8.GetBytes(message);\n ushort size = (ushort)data.Length;\n await _stream.WriteAsync(BitConverter.GetBytes(size)).ConfigureAwait(false);\n await _stream.WriteAsync(data).ConfigureAwait(false);\n }\n\n private async Task ReceiveAsync(CancellationToken token)\n {\n byte[] buffer = new byte[bufferSize];\n try\n {\n while (true)\n {\n await _stream.ReadAsync(buffer.AsMemory(0, 2), token).ConfigureAwait(false);\n int size = BitConverter.ToUInt16(buffer, 0);\n int offset = 0;\n\n // normally there will be only one iteration of this loop but\n // ReadAsync doesn't guarantee that 'received' will always match\n // requested bytes amount\n while (offset &lt; size) \n {\n int received = await _stream.ReadAsync(buffer.AsMemory(offset, size - offset), token).ConfigureAwait(false);\n if (received == 0)\n {\n Console.WriteLine($&quot;Client {_client.Client.RemoteEndPoint} disconnected.&quot;);\n return;\n }\n offset += received;\n }\n\n // probably firing an event here would be helpful\n // byte[] output = buffer.AsSpan(0, size).ToArray();\n var data = Encoding.UTF8.GetString(buffer.AsSpan(0, size));\n Console.WriteLine($&quot;Data received: {data}&quot;);\n }\n }\n catch (OperationCanceledException)\n {\n if (_client.Connected)\n {\n _stream.Close();\n Console.WriteLine($&quot;Connection to {_client.Client.RemoteEndPoint} closed.&quot;);\n }\n }\n catch (Exception ex)\n {\n // Test the class a lot with closing the connection on both sides\n // I'm not sure how it will behave because I didn't test it\n Console.WriteLine($&quot;{ex.GetType().Name}: {ex.Message}&quot;);\n throw;\n }\n }\n\n public void Close()\n {\n _cts.Cancel();\n _task.Wait();\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T22:15:22.533", "Id": "263347", "ParentId": "263339", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T19:57:08.117", "Id": "263339", "Score": "1", "Tags": [ "c#", "networking", "tcp" ], "Title": "How to continiously read data from a NetworkStream" }
263339
<p>So far I have this:</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 rand = (min, max) =&gt; Math.floor(Math.random() * (max - min + 1) + min) // rule: // if an even number of nodes are touching // the center node, then flip // else skip. // rule: // for the start nodes (top row), // they are randomly turned on and off. const cellularAutomaton = [ [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], ] const update = () =&gt; { let int = rand(0, 7) let row = cellularAutomaton[0] row[int] = row[int] ? 0 : 1 // now, how to update the remaining rows? for (let i = 1, n = cellularAutomaton.length; i &lt; n; i++) { row = cellularAutomaton[i] for (let k = 0, m = row.length; k &lt; m; k++) { let neighbors = surrounding(i, k) let count = sum(neighbors) if (even(count)) { row[k] = row[k] == 1 ? 0 : 1 } } } } const even = value =&gt; value % 2 == 0 const sum = neighbors =&gt; { let sum = 0 let u = 0 while (u &lt; 3) { let v = 0 while (v &lt; 3) { let value = neighbors[u][v] if (value != null) { sum += value } v++ } u++ } return sum } const surrounding = (row, column) =&gt; { let prevRow = cellularAutomaton[row - 1] let nextRow = cellularAutomaton[row + 1] let left = cellularAutomaton[row][column - 1] let right = cellularAutomaton[row][column + 1] let neighbors = [] if (prevRow) { let a = prevRow[column - 1] let b = prevRow[column] let c = prevRow[column + 1] neighbors.push([a, b, c]) } else { neighbors.push([null, null, null]) } neighbors.push([left, null, right]) if (nextRow) { let a = nextRow[column - 1] let b = nextRow[column] let c = nextRow[column + 1] neighbors.push([a, b, c]) } else { neighbors.push([null, null, null]) } return neighbors } let i = 0 const watch = () =&gt; { i++ if (i == 100) { clearInterval(interval) } } const render = () =&gt; { let out = [] let a = '■' let b = '□' for (let i = 0, n = cellularAutomaton.length; i &lt; n; i++) { row = cellularAutomaton[i] let outrow = [] for (let k = 0, m = row.length; k &lt; m; k++) { let value = row[k] if (value) { outrow.push(a) } else { outrow.push(b) } } out.push(outrow.join(' ')) out.push('\n') } console.clear() console.log(out.join('')) } const draw = () =&gt; { update() watch() render() } const interval = setInterval(draw, 1000)</code></pre> </div> </div> </p> <p>Am I doing this correctly? I have never seen an implementation of cellular automata and so don't know if there is a more efficient way of accomplishing it. Please let me know how to improve this. What can be done differently or more effectively? In particular, finding the neighbors I'm not sure if I've done that well. Also, what do 2D cellular automata typically do on the edges? Do they wrap them to the other side? So everything has the same number of neighbors? I'm not sure exactly how the theory maps to code, and if in theory the neighbors number is the same for every box.</p> <p>Note: I have in this CA a random &quot;seed&quot; in the first row to initialize values. That is by design, I want to &quot;play a beat to the automaton&quot; essentially, and this random function seed is just a pretend beat (without getting too fancy for this post).</p> <p>As a side note, if you have any suggestions on inspiration on the types of rules that can be created, please leave a comment, I would like to build arbitrary CAs and not sure where to start.</p>
[]
[ { "body": "<h3>Correctness</h3>\n<p>First of all, your algorithm doesn't seem to implement the lattice state update correctly: as soon as you update the state of one cell, the neighbor counts of any adjacent cells will change. Usually this isn't supposed to happen: most CA are defined so that, conceptually, every cell changes state at the same instant.</p>\n<p>This means that, when updating the lattice, you'll need some way to remember what the neighborhood of each cell looked like <em>before</em> you started updating them. There are several possible ways to do this (some of which I'll mention further down), but one common solution is <strong>double buffering</strong>.</p>\n<p>Basically, what that means is that you maintain <em>two copies</em> of the cell state array: one that contains the states of the cells on the current time step, and another one that will contain the states of the cells on the next time step. In your update loop, you read from the current array and write to the next-generation array. Once you're done, just swap the arrays and start over.</p>\n<h3>Edge cases</h3>\n<p>Again, there are plenty of options for handling cells at the edges, and you can pick whichever one you want:</p>\n<ol>\n<li><p>Just assume that any cells outside the array always stay in some fixed state (e.g. state 0).</p>\n</li>\n<li><p>Wrap the edges around, so that the bottom row is adjacent to the top row, and the rightmost column is adjacent to the leftmost.</p>\n</li>\n<li><p>Expand the array as the cells spread, so that the pattern evolves as if it's on an infinite lattice with no edges.</p>\n</li>\n<li><p>Do something else. Really, whatever you want. Maybe make the edges into mirrors, so that each edge cell counts as one of its own neighbors. Or update the edge cells according to some external input. Or something.</p>\n</li>\n</ol>\n<p>Options 2 and 3 above have the advantage that the cellular automaton will locally behave the same way at all points, making the edges invisible. Most other options will tend to result in unusual behavior near the edges, either because the cells beyond the edge don't obey the same CA rule as the cells inside the lattice or because the cell adjacency graph looks different near the edges.</p>\n<p>Option 3 does have some obvious performance concerns, especially if the CA rule you're using tends to feature rapidly spreading patterns of cells. Thus, options 1 and 2 are probably the most popular ones for simple CA implementations.</p>\n<h3>Efficiency</h3>\n<p>OK, this is a <em>deep</em> rabbit hole. For a brief glimpse of how deep, take a look at <a href=\"https://codereview.stackexchange.com/questions/42718/optimize-conways-game-of-life/42790#42790\">my earlier answer on optimizing cellular automata in Java</a>. And that doesn't even get into any <em>really</em> advanced optimization techniques.</p>\n<p>Here's a few quick general things to keep in mind:</p>\n<ul>\n<li><p>Optimize for the general case, not for (literal) edge cases. In particular, consider handling the edges of the lattice in a separate update loop so that you can remove any edge-handling conditionals from your main update loop.</p>\n</li>\n<li><p>Precalculate everything you can. If you can save even one nanosecond per cell in your main update loop by spending 10,000 times as much time precalculating stuff outside the loop, that's worth it as soon as your lattice is bigger than 100 × 100 cells.</p>\n</li>\n<li><p>Try to avoid updating cells that you don't need to. I've given some concrete suggestions for that at the end of the earlier answer linked above, but one option is to maintain a list of cells that have just changed and only updating those cells and their neighbors on the next time step. (Or, alternatively, also include the neighbors of any cells that have changed in the list so that it directly includes every cell that may need updating next time.)</p>\n<p>Note that the performance gain from doing this will depend a lot on the CA rule, and may sometimes be negative. For rules where most cells change only rarely, this optimization can be a huge gain. For rules where most cells change nearly all the time, you're better off just updating every cell in a well optimized loop.</p>\n</li>\n<li><p>Precalculate and store the neighbor counts. This optimization is specific to &quot;totalistic&quot; rules where the next state of each cell only depends on its own state and the number of active neighbor cells. In that case, instead of counting the active neighbors of each cell on each time step, you can store the count in the state array alongside the state of the cell itself and, whenever a cell changes state, increment or decrement the neighbor counts of any adjacent cells.</p>\n</li>\n</ul>\n<p>The last two optimizations above can also be used to eliminate the need for double buffering. Basically, instead of reading from one array and writing to another, an alternative way to ensure that cell state updates happen &quot;simultaneously&quot; is to queue them up in a list and then, once you've determined which cells actually need to change, loop though the list and actually update the cells. Again, see the linked earlier answer for an example.</p>\n<h3>JavaScript specific tips</h3>\n<p>Since you're using JS, here's a couple of specific things to consider:</p>\n<ul>\n<li><p>Instead of using <code>setInterval()</code> for scheduling your timesteps, consider moving all the heavy computation into a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers\" rel=\"nofollow noreferrer\">web worker</a> thread. That way your page will remain responsive even if the updates end up consuming more CPU time than expected.</p>\n</li>\n<li><p>Instead of using classic JS arrays, consider using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray\" rel=\"nofollow noreferrer\">typed arrays</a> instead. They're more compact and likely faster than classic arrays, and they work really well for transferring data to and from web workers, too.</p>\n</li>\n<li><p>If you really want to optimize your inner update loop, you could always try rewriting it in <a href=\"https://developer.mozilla.org/en-US/docs/WebAssembly\" rel=\"nofollow noreferrer\">WebAssembly</a>. But that kind of micro-optimization should really only be done after all other practical optimization options have been used.</p>\n</li>\n</ul>\n<p>Finally, perhaps the most efficient optimization might be to rewrite your CA simulation as a <a href=\"https://developer.mozilla.org/en-US/docs/Games/Techniques/3D_on_the_web/GLSL_Shaders\" rel=\"nofollow noreferrer\">WebGL fragment shader</a> instead of JS code. That way it could run on the GPU, which is a lot better suited for this kind of computation than the CPU. You could also use shaders both for the actual CA state update and for rendering the resulting lattice to the screen, if that's what you want to do.</p>\n<p>I've never done this myself, so I have no specific tips to give, but WebGL shaders are certainly capable of this, and much more. (See e.g. <a href=\"https://www.shadertoy.com\" rel=\"nofollow noreferrer\">Shadertoy</a> for some examples.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T11:16:42.367", "Id": "519938", "Score": "1", "body": "Reading and writing to typed arrays is slower (noticeably for large arrays) unless from same type (or internal 32Bit number to Int32Array) because read and writes to and from typed arrays require a type coercion phase." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T14:26:41.897", "Id": "519959", "Score": "0", "body": "@Blindman67: That's a good point. I was assuming that we'd be manipulating everything as integers and that the type coercion should be relatively fast, but that's certainly something that one should test and benchmark." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T10:48:29.313", "Id": "263359", "ParentId": "263340", "Score": "2" } }, { "body": "<h2>Review</h2>\n<ul>\n<li><p>Use semicolons</p>\n</li>\n<li><p>Use 0 based indexing. Your <code>rand</code> function does not need the <code>+ 1</code></p>\n</li>\n<li><p>Use <code>const</code> for values that do not change. For example in function <code>surrounding</code> all variables can be constants <code>prevRow</code>, <code>nextRow</code>, <code>left</code>, <code>right</code>, <code>neighbors</code>, <code>a</code>, <code>b</code>, and <code>c</code></p>\n</li>\n<li><p>In performat code avoid conditional statements and expressions, when possible.</p>\n<p>You have the line <code>row[k] = row[k] == 1 ? 0 : 1</code> The value of row[k] will only ever be 1 or 0. The ternary is slower than adding 1 and bitwise AND 1. The line <code>row[k] = (row[k] + 1) &amp; 1;</code> will flip the value between 0 and 1</p>\n</li>\n</ul>\n<h2>Game of Life</h2>\n<h3>Updating</h3>\n<p>In the game of life there are two states, the previous state and the new state. You are mixing the two by writing the new board state into the same array as you read the previous board state.</p>\n<p>This means that the birth and death of cell to the left and in the row above will be incorrectly counted.</p>\n<p>The correct method is to double buffer the board state.</p>\n<p>Two arrays, one holds the previous state of the cells and one the new state. Each tick of the game of life you swap the two arrays.</p>\n<p>Count neighbors cells from previous state and update the current state. Render the new state and swap the buffers, The current state becomes the previous, and the old previous state is used to set the next new state.</p>\n<p>See rewrite</p>\n<h3>Edges</h3>\n<p>There are as many strategies for edges as you may wish to imagine.</p>\n<p>There is no right or wrong method. The original Game of Life I believe was imagined on an infinite board thus edges are not considered.</p>\n<p>Using edge warps (use cell on opposite edge) would most closely match an infinite board.</p>\n<p>If you use bounded edges then cells outside the grid are configured to a state that does not generate or kill cells on the edge.</p>\n<h3>Performance</h3>\n<ul>\n<li><p>Array indexing has a little overhead, reducing the number of times you index into an array will reduce this overhead.</p>\n<p>Rather than use a 2D array you can use a 1D array and reduce array indexing.</p>\n</li>\n<li><p>Your method of counting neighbors i s horrifically inefficient. You create 3 new arrays, then iterate each, testing for not <code>null</code> to count living cells.</p>\n<p>You need only count the state of the cells, there is no need to create a copy of each cell. See Rewrite</p>\n<p>The example uses two lookup arrays to provide offsets to neighbor cells. The board array is a 1D array and only cells at the edge need to compute the cell index from x and y coordinates.</p>\n</li>\n<li><p>The console is not a very fast method of displaying data. In this case you can use a canvas bitmap and write cells directly to pixels. See rewrite.</p>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>The rewrite implements a <a href=\"https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life\" rel=\"nofollow noreferrer\">Conway's Game of Life</a> 160 by 160 cells displaying the result in a canvas element.</p>\n<p><strong>Notes</strong></p>\n<ul>\n<li><p>It is written to be performant, however it can be a lot faster (using single thread JS can do million + cells) but the code starts to get very complicated due to the optimizations.</p>\n</li>\n<li><p>Edge cells are handled differently than the rest and use the value on the opposite edge to count as neighbors.</p>\n</li>\n<li><p>The update function returns a count of living cells. This is used to reset the game when all cells are dead.</p>\n</li>\n<li><p><strong>Special Note</strong> Count optimization</p>\n<p>When counting neighbors the loops exits when the neighbor count equals 4 as the rule set has the same outcome for counts 4,5,6,7,8 so there is no point counting above 4.</p>\n<p>If you change the rule sets you may have to remove the optimization.</p>\n<p>Additionally there are other early exits from the counting loop.</p>\n</li>\n</ul>\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>\"use strict\";\n\nconst RESET_TIME = 1000; // in millisecond\nconst TICK_TIME = 32; // in millisecond\nconst SIZE = 160; // in cells\n\n// Cell rules\nconst DIE = -1, BIRTH = 1, NO_CHANGE = 0;\n\n// RULES index of items is neighbor count. \n// 5 Items as rules for count 4,5,6,7,8 have same outcome\n// First rule set for dead cells, second for live cells\nconst RULES = [\n [NO_CHANGE, NO_CHANGE, NO_CHANGE, BIRTH, NO_CHANGE],\n [DIE, DIE, NO_CHANGE, NO_CHANGE, DIE]\n];\n// MAX_COUNT max living neighbors to count\nconst MAX_COUNT = RULES[0].length - 1;\n\n// next two arrays are offsets to neighbors as 1D and 2D coords\nconst NEIGHBOR_OFFSETS = [\n -SIZE - 1, -SIZE, -SIZE + 1,\n -1, 1,\n SIZE - 1, SIZE, SIZE + 1\n];\nconst EDGE_OFFSETS = [ // as coord pairs, x, y for cells at edge\n -1, -1, 0, -1, 1, -1,\n -1, 0, 1, 0,\n -1, 1, 0, 1, 1, 1\n];\n\n// double buffered board state\nvar BOARDS = [new Array(SIZE * SIZE).fill(0), new Array(SIZE * SIZE).fill(0)];\nvar currentState = 0;\n\n// canvas for display\nconst display = Object.assign(document.createElement(\"canvas\"), {width: SIZE, height: SIZE});\ndisplay.ctx = display.getContext(\"2d\");\ndisplay.pixels = display.ctx.getImageData(0, 0, SIZE, SIZE);\ndisplay.buf32 = new Uint32Array(display.pixels.data.buffer);\nconst PIXELS = [0, 0xFF000000]; // Uint32 pixel value NOTE channel order ABGR\n // eg 0xFF000000 is black 0xFF0000FF is red\ndocument.body.appendChild(display);\ndisplay.addEventListener(\"click\", randomize); // click to restart\n\n// start game\nrandomize();\ntick();\n\n\nfunction randomize(density = 0.1) {\n const b = BOARDS[currentState % 2];\n var i = b.length;\n while (i--) { b[i] = Math.random() &lt; density ? 1 : 0 }\n render();\n}\nfunction render() {\n const b = BOARDS[currentState % 2], d32 = display.buf32;\n var i = b.length;\n while (i--) { d32[i] = PIXELS[b[i]] }\n display.ctx.putImageData(display.pixels, 0, 0);\n}\nfunction update() { \n var x, y = SIZE, idx = SIZE * SIZE - 1, count, k, total = 0;\n\n // Aliases for various constants and references to keep code line sizes short. \n const ps = BOARDS[currentState % 2]; // prev state\n const ns = BOARDS[(currentState + 1) % 2]; // new state\n const NO = NEIGHBOR_OFFSETS, EO = EDGE_OFFSETS, S = SIZE, S1 = SIZE - 1;\n while (y--) {\n x = SIZE;\n while (x--) {\n count = 0;\n if (x === 0 || x === S1 || y === 0 || y === S1) {\n k = 0;\n while (k &lt; EO.length &amp;&amp; count &lt; MAX_COUNT) {\n const idxMod = (x + S + EO[k]) % S + ((y + S + EO[k + 1]) % S) * S;\n count += ps[idxMod];\n k += 2;\n }\n } else {\n k = 0;\n while (k &lt; NO.length &amp;&amp; count &lt; MAX_COUNT) { count += ps[idx + NO[k++]] }\n }\n const useRule = RULES[ps[idx]][count];\n if (useRule === DIE) { ns[idx] = 0 }\n else if (useRule === BIRTH) { ns[idx] = 1 }\n else { ns[idx] = ps[idx] }\n total += ns[idx];\n idx --;\n } \n }\n return total;\n}\n\nfunction tick() {\n const living = update();\n currentState++;\n render();\n if (living) { \n setTimeout(tick, TICK_TIME);\n } else {\n randomize();\n setTimeout(tick, RESET_TIME);\n }\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>canvas {\n width: 640px;\n height: 640px;\n image-rendering: pixelated;\n border: 1px solid black;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Click canvas to reset</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T12:46:31.100", "Id": "263364", "ParentId": "263340", "Score": "2" } } ]
{ "AcceptedAnswerId": "263364", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T20:05:10.303", "Id": "263340", "Score": "3", "Tags": [ "javascript", "performance", "ecmascript-6", "cellular-automata" ], "Title": "How to implement a 2D Cellular Automaton in JavaScript?" }
263340
<p>This code represents logic used to retry failed calls to a crypto exchange:</p> <pre><code>let retries = [ TimeSpan.FromSeconds(1.) TimeSpan.FromSeconds(3.) TimeSpan.FromSeconds(5.) TimeSpan.FromSeconds(10.) TimeSpan.FromSeconds(30.) ] let rec retryAsync (retryAttempts: TimeSpan list) (request: unit -&gt; Async&lt;Result&lt;'a, ExchangeError&gt;&gt;) : Async&lt;Result&lt;'a, ExchangeError&gt;&gt; = async { let! r = request() match r with | Result.Ok x -&gt; return Result.Ok x | Result.Error e -&gt; match e with | ExchangeError.HttpError _ | ExchangeError.ServiceUnavailable | ExchangeError.InvalidTimestamp -&gt; match retryAttempts with | [] -&gt; return Result.Error e | h::t -&gt; Thread.Sleep(h) return! retryAsync t request | _ -&gt; return Result.Error e } </code></pre> <p>The logic is as follow: There are a bunch of functions that return Async&lt;Result&lt;'a, ExchangeError&gt;&gt; and perform various external operations.</p> <p>I am wrapping them in this code where results that return ok will be passed through, and results that return error will go through some more scrutiny. Some errors trigger a retry (HttpError, ServiceUnavailable and InvalidTimestamp) since they are transient errors which are not linked to the request itself. Other errors are not going through a retry and are passed through directly.</p> <p>I would like to know if this could be expressed in a more concise / &quot;understandable right away by a 3rd party&quot; way.</p> <p>It can be used that way:</p> <pre><code>// cancel orders let cancelOrdersAsync (exchange: IExchange) instrument (orderIds: string list) : Async&lt;Result&lt;unit, ExchangeError&gt;&gt; = exchange.CancelOrdersAsync(instrument, orderIds) // cancel orders and retry let cancelOrdersRetryAsync (exchange: IExchange) instrument (orderIds: string list) = retryAsync retries (fun _ -&gt; cancelOrdersAsync exchange instrument orderIds) </code></pre> <p>as an extra question: could this be made as a curried function where I'd just have something like <em>retryAsync retries cancelOrders</em></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T23:05:51.687", "Id": "519912", "Score": "1", "body": "I don't have enough to add to make this a full answer, but as a beginner to `f#` I find this code easily understandable without your explanation. If your goal is to make this understandable to someone who doesn't know even basic `f#`, then I would issue a frame challenge to say that's not really a desirable goal." } ]
[ { "body": "<p>It looks understandable to me, here's a couple possible improvements:</p>\n<p><code>retryInterval</code> is more informative than <code>retries</code> (you could also specify that these are the defaults):</p>\n<pre class=\"lang-fs prettyprint-override\"><code>let defaultRetryIntervals =\n [\n TimeSpan.FromSeconds(1.)\n TimeSpan.FromSeconds(3.)\n TimeSpan.FromSeconds(5.)\n TimeSpan.FromSeconds(10.)\n TimeSpan.FromSeconds(30.)\n ]\n</code></pre>\n<p><code>retryAsync</code> could be made a little more general, while also clarifying what exactly it's meant to handle (just the retry logic) - we can also reduce a match nesting level:</p>\n<pre class=\"lang-fs prettyprint-override\"><code>let rec retry&lt;'a&gt;\n (shouldRetry: 'a -&gt; bool)\n (retryIntervals: TimeSpan list)\n (request: unit -&gt; Async&lt;'a&gt;)\n : Async&lt;'a&gt;\n =\n async {\n let! result = request()\n match shouldRetry result, retryIntervals with\n | true, head::rest -&gt;\n Thread.Sleep(head)\n return! retry shouldRetry rest request\n | false, _\n | _, [] -&gt;\n return result\n }\n</code></pre>\n<p>And the equivalent to your <code>retryAsync</code> becomes:</p>\n<pre class=\"lang-fs prettyprint-override\"><code>let shouldRetryExchange =\n function\n | Result.Error (ExchangeError.HttpError _)\n | Result.Error ExchangeError.ServiceUnavailable\n | Result.Error ExchangeError.InvalidTimestamp -&gt;\n true\n | _ -&gt;\n false\n\nlet retryExchange&lt;'ok&gt; = retry&lt;Result&lt;'ok,_&gt;&gt; shouldRetryExchange\n</code></pre>\n<blockquote>\n<p>as an extra question: could this be made as a curried function where I'd just have something like retryAsync retries cancelOrders</p>\n</blockquote>\n<p><a href=\"https://stackoverflow.com/a/8379346\">Here's</a> an answer from Tomas Petricek on that. You'd need to create (tupled) single-argument versions of your api functions:</p>\n<pre class=\"lang-fs prettyprint-override\"><code>let cancelOrdersAsync'\n (\n exchange: IExchange,\n instrument,\n orderIds: string list\n ) =\n cancelOrdersAsync exchange instrument orderIds\n</code></pre>\n<p>and then modify <code>retry</code> to get a curried <code>cancelOrdersRetryAsync</code>:</p>\n<pre class=\"lang-fs prettyprint-override\"><code>let rec retryArg&lt;'a, 'arg&gt;\n (shouldRetry: 'a -&gt; bool)\n (retryIntervals: TimeSpan list)\n (request: 'arg -&gt; Async&lt;'a&gt;)\n arg\n : Async&lt;'a&gt;\n =\n async {\n let! result = request arg\n ... same as before ...\n }\n\nlet cancelOrdersRetryAsync =\n retryArg shouldRetryExchange defaultRetryIntervals cancelOrdersAsync'\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-22T22:47:27.513", "Id": "264298", "ParentId": "263341", "Score": "2" } } ]
{ "AcceptedAnswerId": "264298", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T20:07:09.873", "Id": "263341", "Score": "2", "Tags": [ "f#" ], "Title": "Retrying failed calls to a crypto exchange" }
263341
<p>I have created <a href="https://pastebin.com/r3Ak50nA" rel="nofollow noreferrer">a rust program</a> to create <a href="https://mail.tm" rel="nofollow noreferrer">https://mail.tm</a> accounts, but I think there are things I could have done better. Are there things I can do to improve performance? Are there any unnecessary things I have done? I am new to rust, please give examples of what you mean when you suggest improvements :) Thank you.</p> <pre class="lang-rust prettyprint-override"><code>use json; use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use reqwest; use reqwest::header::{HeaderMap, HeaderValue, ACCEPT, CONTENT_TYPE}; use std::thread; use std::time::Duration; use std::{collections::HashMap, io, iter, vec::Vec}; fn gen_address() -&gt; Vec&lt;String&gt; { let mut rng = thread_rng(); let address: String = iter::repeat(()) .map(|()| rng.sample(Alphanumeric)) .map(char::from) .take(10) .collect(); let password: String = iter::repeat(()) .map(|()| rng.sample(Alphanumeric)) .map(char::from) .take(5) .collect(); let body = reqwest::blocking::get(&quot;https://api.mail.tm/domains&quot;) .unwrap() .text() .unwrap(); let domains = json::parse(&amp;body).expect(&quot;Failed to parse domain json.&quot;); let domain = domains[&quot;hydra:member&quot;][0][&quot;domain&quot;].to_string(); let email = format!(&quot;{}@{}&quot;, &amp;address, &amp;domain); vec![email, password] } fn gen_email() -&gt; Vec&lt;String&gt; { let client = reqwest::blocking::Client::new(); let address_info = gen_address(); let address = &amp;address_info[0]; let password = &amp;address_info[1]; let mut data = HashMap::new(); data.insert(&quot;address&quot;, &amp;address); data.insert(&quot;password&quot;, &amp;password); let mut headers = HeaderMap::new(); headers.insert(ACCEPT, HeaderValue::from_static(&quot;application/ld+json&quot;)); headers.insert( CONTENT_TYPE, HeaderValue::from_static(&quot;application/ld+json&quot;), ); let res = client .post(&quot;https://api.mail.tm/accounts&quot;) .headers(headers) .json(&amp;data) .send() .expect(&quot;Error while attempting to create acconut.&quot;); vec![ res.status().to_string(), address.to_string(), password.to_string(), ] } fn main() { fn get_amount() -&gt; i32 { let mut amount = String::new(); loop { println!(&quot;How many emails do you want?&quot;); io::stdin() .read_line(&amp;mut amount) .expect(&quot;Failed to read line.&quot;); let _amount: i32 = match amount.trim().parse() { Ok(num) =&gt; return num, Err(_) =&gt; { println!(&quot;Please enter a number.&quot;); continue; } }; } } let amount = get_amount(); let handle = thread::spawn(move || { let mut handles = vec![]; for _gen in 0..amount { thread::sleep(Duration::from_secs_f32(0.5)); let handle = thread::spawn(|| { let maildata = gen_email(); println!( &quot;Status: {}, Address: {}, Password: {}&quot;, maildata[0], maildata[1], maildata[2] ); }); handles.push(handle); } handles.into_iter().for_each(|h| h.join().unwrap()); }); handle.join().unwrap(); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T20:18:16.923", "Id": "263343", "Score": "2", "Tags": [ "multithreading", "rust", "concurrency", "networking" ], "Title": "Rust program to create mail.tm accounts" }
263343
<p>While learning about python tkinter, I decided to make a digital clock:</p> <pre><code>from datetime import datetime import tkinter as tk from threading import Thread import time class clock(): def __init__(self): self.display = tk.Tk() def start(self): def get(): self.display.geometry(&quot;215x62&quot;) self.display.title(&quot;Clock&quot;) while True: try: now = datetime.now() current_time = now.strftime(&quot;%H:%M %p&quot;) lbl = tk.Label(self.display, text=str(current_time), background = 'black', font = (&quot;Helvetica&quot;, 37), foreground = 'red') lbl.place(x=0, y=0) time.sleep(0.1) except: break receive_thread = Thread(target=get) receive_thread.start() self.display.mainloop() clock = clock() clock.start() </code></pre> <p>Is there any way to make this clock better?</p> <p>Any comments, answers, or steps in the right direction would be appreciated.</p>
[]
[ { "body": "<p>To start, it's crucial that you stop creating a brand new label ten times a second. Just modify the existing one. Also, this is so simple that a class is not called for. Move as much as possible away from your thread, into your setup routine. Finally, your use of <code>%H</code> is likely incorrect given that you also include <code>%p</code>; you probably want <code>%I</code> for a 12-hour clock.</p>\n<p>This all suggests:</p>\n<pre><code>from datetime import datetime\nimport tkinter as tk\nfrom threading import Thread\nfrom time import sleep\n\n\ndef main():\n display = tk.Tk()\n display.geometry('215x62')\n display.title('Clock')\n\n lbl = tk.Label(\n display,\n background='black',\n font=('Helvetica', 37),\n foreground='red',\n )\n lbl.place(x=0, y=0)\n\n def get():\n while True:\n now = datetime.now()\n lbl.config(text=now.strftime('%I:%M %p'))\n sleep(0.1)\n\n receive_thread = Thread(target=get)\n receive_thread.start()\n display.mainloop()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>Ten times a second is overkill, and you can safely make this much sleepier. Do not make a thread at all; use an <code>after()</code> timer, and calculate when exactly the clock should tick:</p>\n<pre><code>from datetime import datetime\nimport tkinter as tk\nfrom time import time\n\n\ndef main() -&gt; None:\n display = tk.Tk()\n display.geometry('215x62')\n display.title('Clock')\n\n lbl = tk.Label(\n display,\n background='black',\n font=('Helvetica', 37),\n foreground='red',\n )\n lbl.place(x=0, y=0)\n\n def tick() -&gt; None:\n now = datetime.now()\n lbl.config(text=now.strftime('%I:%M %p'))\n\n until_next = round(\n 1000 * (60 - time()%60)\n )\n display.after(ms=until_next, func=tick)\n\n tick()\n display.mainloop()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T02:35:34.167", "Id": "519915", "Score": "0", "body": "Reiderien always displaying his beautiful codes. " }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T02:47:04.373", "Id": "519918", "Score": "0", "body": "@ArnonDePaula thank you <3" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T08:56:56.610", "Id": "519935", "Score": "0", "body": "Won't your second code run into stack size limitations after 1000 seconds, since each invocation of `tick` starts a new one?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T12:28:17.603", "Id": "519941", "Score": "1", "body": "@Graphier I don't think so. `after` is asynchronous. It's not going to recurse - this is telling tk to use the event loop and schedule a callback for a later time." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T23:35:52.057", "Id": "263348", "ParentId": "263346", "Score": "8" } } ]
{ "AcceptedAnswerId": "263348", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-22T21:43:26.403", "Id": "263346", "Score": "7", "Tags": [ "python", "tkinter", "timer" ], "Title": "Digital clock with Python Tkinter" }
263346
<p>All this does is safely and reliably opens, writes to, and closes the file. Yet there are so many <code>goto</code>s and the code is quite verbose. I am not even sure that all of what I am doing is necessary.</p> <pre><code>int WriteConfig(void) { FILE *ConfigFile; RetryOpen: if (!(ConfigFile = fopen(Config, &quot;w&quot;))) { if (errno == EINTR) goto RetryOpen; else goto Err; } RetryWrite: if (fwrite(&amp;Conf, sizeof(struct Config), 1, ConfigFile) &lt; 1) { if (errno == EINTR) goto RetryWrite; if (fclose(ConfigFile)) goto Error; goto Err; } if (fclose(ConfigFile)) goto Error; return 0; Err: AlertFuncErrno; return errno; Error: AlertFuncErrno; exit(errno); } </code></pre> <p><code>AlertFuncErrno</code> is a macro that expands to a function call that notifies the user of the error (including <code>strerror(errno)</code>). <code>Config</code> is a global <code>char *</code> that contains a path to the config file. <code>Conf</code> is a global variable of type <code>struct Config</code>. Am I doing too much here? What action would be appropriate when library functions fail? Should I <code>fflush</code> prior to close, so that if there is a write error it will be caught there? Keep in mind I am attempting to create portable code.</p>
[]
[ { "body": "<p>The identifiers are highly confusing - we have <code>Conf</code>, <code>Config</code>, <code>struct Config</code> and <code>ConfigFile</code>. I can't tell without re-reading the code what each one means. We also have two labels whose difference is hard to deduce from their names.</p>\n<p>Why are we passing <code>Conf</code> and <code>Config</code> in globals? That makes the function very inflexible. If we pass them as arguments, that lets us write any configuration to any file. Even better would be to pass an open <code>FILE*</code>, which would enable testing without using filesystem (by passing the write end of a pipe).</p>\n<p>We test whether writing failed completely (<code>fwrite() &lt; 1</code>), but seem not to care whether the data were partially written. So we should also test <code>fwrite() &lt; sizeof Conf</code>, and in that case write again, to output the remaining part. Perhaps</p>\n<pre><code>const char *start = (const char*)&amp;Conf;\nsize_t len = sizeof Conf;\nwhile (len &gt; 0) {\n errno = 0;\n size_t written = fwrite(start, 1, len, ConfigFile);\n if (!written &amp;&amp; errno != EINTR) {\n goto Error;\n }\n start += written;\n len -= written;\n}\n</code></pre>\n<p>Note that we're now using <code>while</code> to form a loop, rather than <code>goto</code>. It's much better to use the C loop structures than <code>goto</code>, which is easy to get wrong in many ways. Similarly, we can re-write the <code>fopen()</code> loop with <code>while</code> rather than <code>goto</code>.</p>\n<p>This handling looks strange:</p>\n<pre><code>Err:\n AlertFuncErrno;\n return errno;\nError:\n AlertFuncErrno;\n exit(errno);\n</code></pre>\n<p>In the first case, we both emit a user message (convention says that the macro should be called <code>ALERT_FUNC_ERRNO</code> so we can immediately see it's a macro) <em>and</em> return the error indication to the caller. The caller is in a better position to know whether the error message is required or it can take alternative action without bothering the user.</p>\n<p>The second case is very disturbing; not only has the user's config not been saved, but now we exit, <em>losing the only copy of the config</em> (in the process's memory). That's exactly the situation where we would want to fall back to writing to some other file so that the data are safe!</p>\n<p>Neither of the error cases make any attempt to close the file, so the function leaks resources if the file is successfully opened but returns without saving.</p>\n<hr />\n<p>Having looked at the code in some detail, there's some more fundamental issues:</p>\n<ul>\n<li><p>We seem to be overwriting a single file starting from the beginning. If something goes wrong, not only have we failed to save from memory to file, but we've also lost the original contents of the file! We really need to ensure that the original contents are backed up, and only remove the backup when our data are safely stashed.</p>\n</li>\n<li><p>It's very difficult to change <code>struct Config</code> without causing problems when reading and writing with different versions of the program. And there's no evident way for us to know whether we have read a different version than we expected, in which case the contents may well be meaningless (perhaps there's a version field at the beginning of the struct, but since you've not shown that, I'm assuming the worst).</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T18:26:39.557", "Id": "519979", "Score": "1", "body": "`fwrite()` is not specified to to set `errno` so testing it in `if (!written && errno != EINTR)` in unclear. If some implementation _does_ set `errno`, then `errno = 0` prior to the loop makes sense to not exit due to a prior `errno`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T19:55:33.963", "Id": "519991", "Score": "0", "body": "Oops, yeah, I just copied that logic from the original without questioning." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T23:59:31.410", "Id": "519998", "Score": "0", "body": "@chux-ReinstateMonica Sure about that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T01:50:45.810", "Id": "520000", "Score": "0", "body": "@user244080 Yes, per the C specification, fwrite() is not specified to set errno. Are you thinking of something else?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T04:14:43.950", "Id": "520001", "Score": "0", "body": "@chux-ReinstateMonica I saw on the `fwrite()` manpage that `fwrite()` will set errno" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T06:44:23.100", "Id": "520004", "Score": "1", "body": "@user244080, the man page describes the implementation you are using, rather than the C standard. If you target only the one platform, then you can rely on that, but for a portable program, you can depend only on what the standard requires of implementations (modulo platform bugs, which should be reported, ideally with a fix)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T06:53:36.333", "Id": "520005", "Score": "0", "body": "Also if fwrite fails, is the file position unspecified?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T06:59:29.517", "Id": "520007", "Score": "0", "body": "https://pubs.opengroup.org/onlinepubs/000095399/functions/fread.html Is that implementation specific?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T07:08:38.760", "Id": "520010", "Score": "1", "body": "That document applies only to POSIX platforms, and says \"⌦and `errno` shall be set to indicate the error. ⌫\" - note that those [advisory information markers](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap01.html#tag_01_07_01), ⌦ and ⌫, indicate that \"__The functionality described is _optional_. The functionality described is also an extension to the ISO C standard.__\" So even on POSIX systems, you can't depend on `errno` being set. And other implementations of C exist (notably DOS and Windows if you have sufficient misfortune to find you have users in the Microsoft world)." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T08:07:44.383", "Id": "263355", "ParentId": "263350", "Score": "2" } } ]
{ "AcceptedAnswerId": "263355", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T03:53:47.317", "Id": "263350", "Score": "1", "Tags": [ "performance", "c", "error-handling", "portability" ], "Title": "Open, writing to, and closing a configuration file, and error checking the process in C" }
263350
<p>I want to share a little app I made that logs tracks I play on Spotify (running in the background on my <a href="https://www.digitalocean.com/" rel="nofollow noreferrer">DigitalOcean</a> droplet server). It uses <a href="https://spotipy.readthedocs.io/en/2.18.0/" rel="nofollow noreferrer">Spotipy</a>, a lightweight Python library for the Spotify Web API. With Spotipy you get full access to all of the music data provided by the Spotify platform.</p> <p>Any suggestions for improvements are welcome.</p> <p><code>my_spotify_logger.py</code></p> <pre><code>from dataclasses import dataclass, asdict import time import datetime from pathlib import Path import json from decouple import config import spotipy from spotipy.oauth2 import SpotifyOAuth TRACK_LOGFILE= Path('logs/track_log.json') TIME_DELAY = 5 SCOPE = 'user-read-currently-playing' SPOTIFY_CLIENT_ID = config('SPOTIFY_CLIENT_ID') SPOTIFY_CLIENT_SECRET = config('SPOTIFY_CLIENT_SECRET') SPOTIFY_REDIRECT_URI = config('SPOTIFY_REDIRECT_URI') spotify_authorization = SpotifyOAuth( SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET, SPOTIFY_REDIRECT_URI, scope=SCOPE, ) spotify = spotipy.Spotify(auth_manager=spotify_authorization) @dataclass class TrackRecord(): played_at: str name: str id: int artist: str def as_dict(self): return asdict(self) def read_track_logfile(): with open(TRACK_LOGFILE, 'r') as json_file: return json.load(json_file) def update_track_logfile(tracks_log): with open(TRACK_LOGFILE, 'w') as json_file: json.dump(tracks_log, json_file) def print_track(track): print(f'{track.played_at}, id: {track.id}\n' f'artist: {track.artist}, {track.name}') def main(): tracks_log = read_track_logfile() track_id = None while True: new_track = spotify.current_user_playing_track() valid_track = ( new_track and new_track['item'] and track_id != new_track['item']['id'] ) if valid_track: track_id = new_track['item']['id'] track_record = TrackRecord( played_at=datetime.datetime.now().strftime(&quot;%Y-%B-%d %H:%M:%S&quot;), id=track_id, artist=new_track['item']['artists'][0]['name'], name=new_track['item']['name'], ) print_track(track_record) tracks_log['tracks'].append(track_record.as_dict()) update_track_logfile(tracks_log) time.sleep(TIME_DELAY) if __name__ == '__main__': main() </code></pre> <p>Using <code>decouple</code> you need to define your secret credentials in a <code>.env</code> file. Credentials you can get at <a href="https://developer.spotify.com/documentation/general/guides/authorization-guide/" rel="nofollow noreferrer">Spotify</a>.</p> <p>Requirements: python 3.8+</p> <pre><code>certifi==2021.5.30 chardet==4.0.0 idna==2.10 python-decouple==3.4 requests==2.25.1 six==1.16.0 spotipy==2.18.0 urllib3==1.26.5 </code></pre> <p>Before first time use, you need to initialize your <code>track_log.json</code> as</p> <pre><code>{&quot;tracks&quot;: []} </code></pre> <p>Finally a nice little app to query json files (in Linux) is <code>jq</code> (<code>sudo apt install jq</code>). For example to see the last 3 tracks played.</p> <pre><code>&gt;jq &quot;.tracks[-3:]&quot; ./logs/track_log.json </code></pre> <pre><code>[ { &quot;played_at&quot;: &quot;2021-June-23 07:37:17&quot;, &quot;name&quot;: &quot;Blitzkrieg Bop - 2001 Remastered Version&quot;, &quot;id&quot;: &quot;33iQW2OneB0oNh2NfrAzqW&quot;, &quot;artist&quot;: &quot;Ramones&quot; }, { &quot;played_at&quot;: &quot;2021-June-23 07:39:28&quot;, &quot;name&quot;: &quot;Should I Stay or Should I Go - Remastered&quot;, &quot;id&quot;: &quot;3v8PlUFGQQDBIk1J86waCo&quot;, &quot;artist&quot;: &quot;The Clash&quot; }, { &quot;played_at&quot;: &quot;2021-June-23 07:42:40&quot;, &quot;name&quot;: &quot;Trash&quot;, &quot;id&quot;: &quot;2OQS3xvoKKSayJMJT8dVuZ&quot;, &quot;artist&quot;: &quot;New York Dolls&quot; } ] </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T07:30:49.463", "Id": "263354", "Score": "1", "Tags": [ "python", "spotipy" ], "Title": "Spotify logger for tracks played" }
263354
<p>This script solves a simple problem:</p> <p>Input two strings differ one character or zero characters in length, return true if the following conditions are met:</p> <p>1, They must start with same character and end with same character.</p> <p>2, One string can be obtained by changing one character or zero characters in the middle of the other string (neither at the start nor end), here changing means replacing and inserting.</p> <p>I have Google searched for several hours to find a solution and it was futile just as usual, I can't ask on stackoverflow.com because I am currently blocked from asking there because my questions are prone to be closed.</p> <p>So after about half an hour I came up with a solution of my own:</p> <pre class="lang-py prettyprint-override"><code>def fuzzymatch(str1, str2): if abs(len(str1) - len(str2)) &lt;= 1 and (str1[0], str1[-1]) == (str2[0], str2[-1]): longer = max(str1, str2, key=len) shorter = (str1 + str2).replace(longer, '') same = sum(''.join(longer[:i + 1]) in shorter for i in range(len(shorter))) if ''.join(longer[same + 1:]) in shorter: same += len(''.join(longer[same + 1:])) if abs(same - len(shorter)) &lt;= 1 and len(str1) == len(str2): return True elif abs(same - len(longer)) &lt;= 1: return True return False </code></pre> <p>I have tested it and confirmed its correctness:</p> <pre class="lang-py prettyprint-override"><code>In [2]: fuzzymatch('sample', 'ample') Out[2]: False In [3]: fuzzymatch('sample', 'sample') Out[3]: True In [4]: fuzzymatch('sample', 'sampley') Out[4]: False In [5]: fuzzymatch('sample', 'samply') Out[5]: False In [6]: fuzzymatch('sample', 'sammple') Out[6]: True In [7]: fuzzymatch('sample', 'sammmple') Out[7]: False In [8]: fuzzymatch('sample', 'simple') Out[8]: True In [9]: fuzzymatch('sample', 'siimple') Out[9]: False </code></pre> <p>I know my approach is not very clean, that's why I am asking here, I want to know, what is a better approach, that gives the same result, is more efficient and with less complexity?</p>
[]
[ { "body": "<p>It would be good to include a docstring explaining the parameters and expected result. Best of all would be to include the unit-tests in <code>doctest</code> format:</p>\n<pre><code>def fuzzymatch(str1, str2):\n &quot;&quot;&quot;\n Returns True if the two strings differ by only one letter (addition,\n removal or change) and that letter is not the first or last.\n &gt;&gt;&gt; fuzzymatch('sample', 'ample')\n False\n\n &gt;&gt;&gt; fuzzymatch('sample', 'sample')\n True\n\n &gt;&gt;&gt; fuzzymatch('sample', 'sampley')\n False\n\n &gt;&gt;&gt; fuzzymatch('sample', 'samply')\n False\n\n &gt;&gt;&gt; fuzzymatch('sample', 'sammple')\n True\n\n &gt;&gt;&gt; fuzzymatch('sample', 'sammmple')\n False\n\n &gt;&gt;&gt; fuzzymatch('sample', 'simple')\n True\n\n &gt;&gt;&gt; fuzzymatch('sample', 'siimple')\n False\n &quot;&quot;&quot;\n</code></pre>\n<p>Now we can auto-test the function:</p>\n<pre><code>if __name__ == &quot;__main__&quot;:\n import doctest\n doctest.testmod()\n</code></pre>\n<p>And we can add some more tests (for example, empty strings should return a value, rather than throwing an exception as they do right now).</p>\n<hr />\n<p>It's often easier to deal with the simplest returns first, rather than having a long indented block where the reader is holding the condition in their head.</p>\n<pre><code>if str1[0] != str2[0] or str1[-1] != str2[-1]:\n return False\n</code></pre>\n<p>And we can simplify the longer/shorter stuff by simply swapping to make <code>str1</code> always the longest:</p>\n<pre><code>if len(str1) &lt; len(str2):\n str1, str2 = str2, str1\n</code></pre>\n<p>That is less work than concatenating the two and then finding and removing one of them.</p>\n<p>This is a really inefficient way of finding the common suffix:</p>\n<blockquote>\n<pre><code>same = sum(''.join(str1[:i + 1]) in str2 for i in range(len(str2)))\n</code></pre>\n</blockquote>\n<p>String <code>in</code> string is a search, but we don't need a search, as we know where we expect to find the match. As well as inefficient, it's also obscure, since we have <code>str.endswith()</code> and <code>str.startswith()</code> at our disposal. A simpler version is</p>\n<pre><code>if len(str1) &lt; len(str2):\n str1, str2 = str2, str1\n\n# str1 is at least as long as str2 now\nif len(str1) &gt; len(str2) + 1:\n return False\n\nfor i in range(1, len(str2) - 1):\n if str2.startswith(str1[:i]) and str2.endswith(str1[i+1:]):\n return True\n\nreturn False\n</code></pre>\n<p>We're still copying string slices around. To make it more efficient, we can look at a character at a time, and for this, I would create a helper function:</p>\n<pre><code>import itertools\n\ndef prefix_count(str1, str2):\n &quot;&quot;&quot;\n Length of longest common prefix of str1 and str2\n\n &gt;&gt;&gt; prefix_count('', '')\n 0\n\n &gt;&gt;&gt; prefix_count('a', '')\n 0\n\n &gt;&gt;&gt; prefix_count('a', 'b')\n 0\n\n &gt;&gt;&gt; prefix_count('ab', 'aa')\n 1\n\n &gt;&gt;&gt; prefix_count('aa', 'aa')\n 2\n\n &quot;&quot;&quot;\n return sum(1 for _ in itertools.takewhile(lambda x: x[0]==x[1], zip(str1, str2)))\n</code></pre>\n<p>We can now use that to find the common prefix forwards and backwards, and see if their length indicates that they meet with no more than 1 character of separation:</p>\n<pre><code>if len(str1) &lt; len(str2):\n str1, str2 = str2, str1\n\n# str1 is at least as long as str2 now\nif len(str1) &gt; len(str2) + 1:\n return False\n\nif not str2 or str1[0] != str2[0] or str1[-1] != str2[-1]:\n return False\n\nreturn prefix_count(str1, str2) + prefix_count(str1[::-1], str2[::-1]) + 1 &gt;= len(str1)\n</code></pre>\n<hr />\n<h1>Final modified version</h1>\n<pre><code>import itertools\n\ndef prefix_count(str1, str2):\n &quot;&quot;&quot;\n Length of longest common prefix of str1 and str2\n\n &gt;&gt;&gt; prefix_count('', '')\n 0\n\n &gt;&gt;&gt; prefix_count('a', '')\n 0\n\n &gt;&gt;&gt; prefix_count('a', 'b')\n 0\n\n &gt;&gt;&gt; prefix_count('ab', 'aa')\n 1\n\n &gt;&gt;&gt; prefix_count('abc', 'aac')\n 1\n\n &gt;&gt;&gt; prefix_count('aa', 'aa')\n 2\n\n &quot;&quot;&quot;\n return sum(1 for _ in itertools.takewhile(lambda x: x[0]==x[1], zip(str1, str2)))\n\n\ndef fuzzymatch(str1, str2):\n &quot;&quot;&quot;\n Returns True if the two strings differ by only one letter (addition,\n removal or change) and that letter is not the first or last.\n\n &gt;&gt;&gt; fuzzymatch('', '')\n False\n\n &gt;&gt;&gt; fuzzymatch('', 'a')\n False\n\n &gt;&gt;&gt; fuzzymatch('aba', 'abca')\n True\n\n &gt;&gt;&gt; fuzzymatch('aba', 'acba')\n True\n\n &gt;&gt;&gt; fuzzymatch('acba', 'adba')\n True\n\n &gt;&gt;&gt; fuzzymatch('sample', 'ample')\n False\n\n &gt;&gt;&gt; fuzzymatch('sample', 'sample')\n True\n\n &gt;&gt;&gt; fuzzymatch('sample', 'sampley')\n False\n\n &gt;&gt;&gt; fuzzymatch('sample', 'samply')\n False\n\n &gt;&gt;&gt; fuzzymatch('sample', 'sammple')\n True\n\n &gt;&gt;&gt; fuzzymatch('sample', 'sammmple')\n False\n\n &gt;&gt;&gt; fuzzymatch('sample', 'simple')\n True\n\n &gt;&gt;&gt; fuzzymatch('sample', 'siimple')\n False\n\n &gt;&gt;&gt; fuzzymatch('aabaa', 'aaaaaa')\n False\n &quot;&quot;&quot;\n\n if len(str1) &lt; len(str2):\n str1, str2 = str2, str1\n\n # str1 is at least as long as str2 now\n if len(str1) &gt; len(str2) + 1:\n return False\n\n if not str2 or str1[0] != str2[0] or str1[-1] != str2[-1]:\n return False\n\n return prefix_count(str1, str2) + prefix_count(str1[::-1], str2[::-1]) + 1 &gt;= len(str1)\n\n\nif __name__ == &quot;__main__&quot;:\n import doctest\n doctest.testmod()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T21:39:08.737", "Id": "519994", "Score": "1", "body": "I wonder if adding, `if str1 == str2: return True` would help with speed? I assume at least in cases where the strings are _frequently_ equal, it should help more than it hurts (and it makes it a little more easy to read)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T06:55:15.587", "Id": "520006", "Score": "0", "body": "I admit I haven't done any benchmarking; I certainly encourage those with an interest to do so, and to post as answers any improvements they find. Of course, it's difficult to benchmark without a good set of representative inputs, and we haven't been given that. :(" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T09:59:34.570", "Id": "263358", "ParentId": "263356", "Score": "6" } } ]
{ "AcceptedAnswerId": "263358", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T08:44:05.360", "Id": "263356", "Score": "6", "Tags": [ "python", "performance", "beginner", "python-3.x" ], "Title": "Python: determine whether one string can be obtained by changing one character in the middle of another string" }
263356
<p>This is a follow-up of my last question over <a href="https://codereview.stackexchange.com/q/262883/242934">here</a>.</p> <p>Following @Reinderien's <a href="https://codereview.stackexchange.com/a/263305/242934">suggestion</a> in that previous post, I've managed to furnish my web-scraper code as follows:</p> <h1>fudan.py</h1> <pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass, asdict from itertools import count from typing import Dict, Iterable, Tuple, List from bs4 import BeautifulSoup from requests import Session, get from datetime import date, datetime import json import os import re @dataclass class Link: caption: str url: str clicks: int replies: int added: date @classmethod def from_row(cls, props: Dict[str, str], url: str) -&gt; 'Link': clicks, replies = props['点击/回复'].split('/') # Skip number=int(props['编号']) - this only has meaning within one page return cls( caption=props['资源标题'], url=url, clicks=int(clicks), replies=int(replies), added=datetime.strptime(props['添加时间'], '%Y/%m/%d').date().isoformat(), ) def __str__(self): return f'{self.added} {self.url} {self.caption}' # @dataclass # class Result: # author: str # title: str # date: date # download: str # publication: str # url: str # @classmethod # def from_metadata(cls, metadata: Dict) -&gt; 'Result': # author = metadata['author'] # title = metadata['title'] # date = metadata['date'] # download = metadata['download'] # publication = &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot; # url = metadata['url'] # def __str__(self) -&gt; str: # return( # f&quot;\n作者 {self.author}&quot; # f&quot;\n標題 {self.title}&quot; # f&quot;\n發佈日期 {self.date}&quot; # f&quot;\n下載連結 {self.download}&quot; # f&quot;\n發表平台 {self.publication}&quot; # f&quot;\n訪問網頁 {self.url}&quot; # ) def get_primary_result(): path = os.path.join(os.getcwd(), 'primary_search_result.json') with open(path, &quot;r&quot;) as f: data = f.read() data = data.replace('\n][\n',',') primary_rslt = json.loads(data) return primary_rslt def get_article(): primary_rslt = get_primary_result() captions_list = [item['caption'] for item in primary_rslt] base_url = 'http://www.gwz.fudan.edu.cn' url_list = [base_url + item['url'] for item in primary_rslt] date_list = [item['added'] for item in primary_rslt] for i, url in enumerate(url_list): with get(url) as resp: resp.raise_for_status() doc = BeautifulSoup(resp.text, 'html.parser') content = doc.select_one('span.ny_font_content') category = doc.select('#_top td a')[1].text if category == '学者文库': try: author, title = captions_list[i].split(&quot;:&quot;) except: author = None title = captions_list[i] if author == &quot;網摘&quot;: author = None title = captions_list[i] date = date_list[i] dl_tag = content.find_all('a', {&quot;href&quot; : re.compile(&quot;/?(lunwen/|articles/up/).+&quot;)})[0] download = dl_tag['href'] download = download.replace(&quot;\r&quot;,&quot;&quot;).replace(&quot;\n&quot;, &quot;&quot;).strip() if download == &quot;#_edn1&quot;: download = None elif download[0] != &quot;/&quot;: download = &quot;/&quot; + download yield { &quot;author&quot;: author, &quot;title&quot;: title, &quot;date&quot;: date, &quot;url&quot;: url, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: download} def get_page(session: Session, query: str, page: int) -&gt; Tuple[List[Link], int]: with session.get( 'http://www.gwz.fudan.edu.cn/Web/Search', params={ 's': query, 'page': page, }, ) as resp: resp.raise_for_status() doc = BeautifulSoup(resp.text, 'html.parser') table = doc.select_one('#tab table') heads = [h.text for h in table.select('tr.cap td')] links = [] for row in table.find_all('tr', class_=''): cells = [td.text for td in row.find_all('td')] links.append(Link.from_row( props=dict(zip(heads, cells)), url=row.find('a')['href'], )) page_td = doc.select_one('#tab table:nth-child(2) td') n_pages = int(page_td.text.rsplit('/', 1)[1]) return links, n_pages def remove_json_if_exist(filename): json_file = filename + &quot;.json&quot; filePath = os.path.join(os.getcwd(), json_file) if os.path.exists(filePath): os.remove(filePath) def get_all_links(session: Session, query: str) -&gt; Iterable[Link]: for page in count(1): links, n_pages = get_page(session, query, page) print(f'{page}/{n_pages}') yield from links with open('primary_search_result.json', 'a') as file: json.dump([asdict(link) for link in links], file, ensure_ascii=False, indent=4) if page &gt;= n_pages: break def search(keyword): remove_json_if_exist('primary_search_result') with Session() as session: for link in get_all_links(session, keyword): print(link) print() def compile_search_result(): print(&quot;Articles Retrieved:&quot;) remove_json_if_exist('fudan_search_result') rslt = get_article() for item in rslt: with open('fudan_search_result.json', 'a') as file: json.dump(item, file, ensure_ascii=False, indent=4) print(item) def main(): search('尹至') compile_search_result() if __name__ == '__main__': main() </code></pre> <p>The code above has the added functionality of looping through the list of urls from the primary search results to yield the metadata of individual articles published on the website.</p> <hr /> <h1>Output:</h1> <pre class="lang-json prettyprint-override"><code>{ &quot;author&quot;: &quot;許文獻&quot;, &quot;title&quot;: &quot;重讀清華〈厚父〉簡釋字懸想一則&quot;, &quot;date&quot;: &quot;2018-08-30&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/4286&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1936重讀清華〈厚父〉簡釋字懸想一則.docx&quot; }{ &quot;author&quot;: &quot;雷燮仁&quot;, &quot;title&quot;: &quot;談《尚書》中表勉義的幾組字&quot;, &quot;date&quot;: &quot;2017-10-31&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/3152&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1861雷燮仁:談《尚書》中表勉義的幾組字.doc&quot; }{ &quot;author&quot;: &quot;雷燮仁&quot;, &quot;title&quot;: &quot;誤“埶”為“執”及相關問題考辨&quot;, &quot;date&quot;: &quot;2017-10-31&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/3146&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1855雷燮仁:誤“埶”為“執”及相關問題考辨.doc&quot; }{ &quot;author&quot;: &quot;蘇建洲&quot;, &quot;title&quot;: &quot;楚系文字“祟”字構形補說兼論相關問題&quot;, &quot;date&quot;: &quot;2017-01-15&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/2969&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1731蘇建洲:楚系文字“祟”字構形補說兼論相關問題.doc&quot; }{ &quot;author&quot;: &quot;王寧&quot;, &quot;title&quot;: &quot;《周易》“童蒙”解&quot;, &quot;date&quot;: &quot;2016-03-30&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/2767&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1623王寧:《周易》“童蒙”解.doc&quot; }{ &quot;author&quot;: &quot;王寧&quot;, &quot;title&quot;: &quot;北大漢簡《蒼頡篇》讀札(下)&quot;, &quot;date&quot;: &quot;2016-03-07&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/2747&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1618王寧:北大漢簡《蒼頡篇》讀札(下).doc&quot; }{ &quot;author&quot;: &quot;王寧&quot;, &quot;title&quot;: &quot;讀《殷高宗問於三壽》散札&quot;, &quot;date&quot;: &quot;2015-05-17&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/2525&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1479王寧:讀《殷高宗問於三壽》散札.doc&quot; }{ &quot;author&quot;: &quot;高月&quot;, &quot;title&quot;: &quot;《漢書·藝文志·諸子略》之道家補&quot;, &quot;date&quot;: &quot;2015-05-09&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/2516&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1474高月:《漢書·藝文志·諸子略》之道家補.doc&quot; }{ &quot;author&quot;: &quot;陳劍&quot;, &quot;title&quot;: &quot;《清華簡(伍)》與舊說互證兩則&quot;, &quot;date&quot;: &quot;2015-04-14&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/2494&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1454陳劍:《清華簡(伍)》與舊說互證兩則.doc&quot; }{ &quot;author&quot;: &quot;王寧&quot;, &quot;title&quot;: &quot;上博二《容成氏》湯伐桀記載辨析&quot;, &quot;date&quot;: &quot;2015-03-11&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/2464&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1433王寧:上博二《容成氏》湯伐桀記載辨析.doc&quot; }{ &quot;author&quot;: &quot;王寧&quot;, &quot;title&quot;: &quot;上博二《容成氏》“南藻氏”相關問題考論&quot;, &quot;date&quot;: &quot;2015-03-01&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/2455&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1425王寧:上博二《容成氏》“南藻氏”相關問題考論.doc&quot; }{ &quot;author&quot;: &quot;張崇禮&quot;, &quot;title&quot;: &quot;清華簡《尹誥》考釋&quot;, &quot;date&quot;: &quot;2014-12-17&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/2400&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1387張崇禮:清華簡《尹誥》考釋.doc&quot; }{ &quot;author&quot;: &quot;王寧&quot;, &quot;title&quot;: &quot;《清華簡〈尹誥〉獻疑》之疑&quot;, &quot;date&quot;: &quot;2014-06-23&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/2298&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1337王寧:《清華簡〈尹誥〉獻疑》之疑.doc&quot; }{ &quot;author&quot;: &quot;孫合肥&quot;, &quot;title&quot;: &quot;清華簡《筮法》札記一則&quot;, &quot;date&quot;: &quot;2014-01-25&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/2222&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1300孫合肥:清華簡《筮法》札記一則.doc&quot; }{ &quot;author&quot;: &quot;陸離&quot;, &quot;title&quot;: &quot;清華簡《別卦》讀“解”之字試說&quot;, &quot;date&quot;: &quot;2014-01-08&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/2208&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1292陸離:清華簡《別卦》讀“解”之字試說.doc&quot; }{ &quot;author&quot;: &quot;王寧&quot;, &quot;title&quot;: &quot;清華簡《尹至》《赤鳩之集湯之屋》對讀一則&quot;, &quot;date&quot;: &quot;2013-11-28&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/2183&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1276王寧:清華簡《尹至》《赤鳩之集湯之屋》對讀一則.doc&quot; }{ &quot;author&quot;: &quot;呂廟軍&quot;, &quot;title&quot;: &quot;“出土文獻與中國古代文明”國際學術研討會綜述&quot;, &quot;date&quot;: &quot;2013-10-22&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/2145&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1254呂廟軍:“出土文獻與中國古代文明”國際學術研討會綜述.doc&quot; }{ &quot;author&quot;: &quot;王挺斌&quot;, &quot;title&quot;: &quot;清華簡《尹誥》“遠邦歸志”考&quot;, &quot;date&quot;: &quot;2013-06-30&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/2082&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1218王挺斌:清华简《尹诰》“远邦归志”考.doc&quot; }{ &quot;author&quot;: &quot;高中華&quot;, &quot;title&quot;: &quot;《清華簡》(壹)校讀四則&quot;, &quot;date&quot;: &quot;2013-06-08&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/2069&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1208高中华:《清华简》(壹)校读四则.doc&quot; }{ &quot;author&quot;: &quot;陳民鎮&quot;, &quot;title&quot;: &quot;清華簡《說命上》首句試解&quot;, &quot;date&quot;: &quot;2013-01-21&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/2003&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1169陳民鎮:清華簡《說命上》首句試解.doc&quot; }{ &quot;author&quot;: &quot;劉剛&quot;, &quot;title&quot;: &quot;清華叁《良臣》為具有晉系文字風格的抄本補證&quot;, &quot;date&quot;: &quot;2013-01-17&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/2002&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1168劉剛:清華叁《良臣》為具有晉系文字風格的抄本補證.doc&quot; }{ &quot;author&quot;: &quot;陳劍&quot;, &quot;title&quot;: &quot;簡談《繫年》的“ ”和楚簡部分“ ”字當釋讀爲“捷””&quot;, &quot;date&quot;: &quot;2013-01-16&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1996&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1167陳劍:簡談《繫年》的“ ”和楚簡部分“ ”字當釋讀爲“捷”.doc&quot; }{ &quot;author&quot;: &quot;韓祖倫&quot;, &quot;title&quot;: &quot;利用楚簡文字釋讀古璽文字四例&quot;, &quot;date&quot;: &quot;2012-06-05&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1884&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1086韩祖伦:利用楚简文字释读古玺文字四例.doc&quot; }{ &quot;author&quot;: &quot;蘇建洲&quot;, &quot;title&quot;: &quot;楚竹書的“罝”字&quot;, &quot;date&quot;: &quot;2012-04-13&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1844&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1057蘇建洲:楚竹書的“罝”字.doc&quot; }{ &quot;author&quot;: &quot;苗豐&quot;, &quot;title&quot;: &quot;卜辭“中录”補證&quot;, &quot;date&quot;: &quot;2012-03-25&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1809&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1049苗豐:卜辭“中录”補證.doc&quot; }{ &quot;author&quot;: &quot;張世超&quot;, &quot;title&quot;: &quot;佔畢脞說(八)&quot;, &quot;date&quot;: &quot;2012-03-09&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1800&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1040張世超:佔畢脞說(八).doc&quot; }{ &quot;author&quot;: &quot;張世超&quot;, &quot;title&quot;: &quot;佔畢脞說(三、四)&quot;, &quot;date&quot;: &quot;2012-02-23&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1787&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1029張世超:佔畢脞說(三、四).doc&quot; }{ &quot;author&quot;: &quot;張崇禮&quot;, &quot;title&quot;: &quot;釋清華簡《尹至》的“瓚”字&quot;, &quot;date&quot;: &quot;2011-12-23&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1748&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/1001張崇禮:釋清華簡《尹至》的“瓚”字.doc&quot; }{ &quot;author&quot;: &quot;陳民鎮&quot;, &quot;title&quot;: &quot;清華簡《楚居》集釋&quot;, &quot;date&quot;: &quot;2011-09-23&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1663&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/0951陳民鎮:清華簡《楚居》集釋.doc&quot; }{ &quot;author&quot;: &quot;胡凱&quot;, &quot;title&quot;: &quot;清華簡《祭公之顧命》集釋&quot;, &quot;date&quot;: &quot;2011-09-23&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1662&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/0950胡凱:清華簡《祭公之顧命》集釋.doc&quot; }{ &quot;author&quot;: &quot;汪亞洲&quot;, &quot;title&quot;: &quot;清華簡《皇門》集釋&quot;, &quot;date&quot;: &quot;2011-09-23&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1660&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/0949汪亞洲:清華簡《皇門》集釋.doc&quot; }{ &quot;author&quot;: &quot;陳民鎮、胡凱&quot;, &quot;title&quot;: &quot;清華簡《金縢》集釋&quot;, &quot;date&quot;: &quot;2011-09-20&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1658&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/0947陳民鎮、胡凱:清華簡《金縢》集釋.doc&quot; }{ &quot;author&quot;: &quot;顏偉明、陳民鎮&quot;, &quot;title&quot;: &quot;清華簡《耆夜》集釋&quot;, &quot;date&quot;: &quot;2011-09-20&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1657&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/0946顏偉明、陳民鎮:清華簡《耆夜》集釋.doc&quot; }{ &quot;author&quot;: &quot;胡凱、陳民鎮&quot;, &quot;title&quot;: &quot;清華簡《保訓》集釋&quot;, &quot;date&quot;: &quot;2011-09-19&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1654&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/0943陳民鎮、胡凱:清華簡《保訓》集釋.doc&quot; }{ &quot;author&quot;: &quot;禚孝文&quot;, &quot;title&quot;: &quot;清華簡《程寤》集釋&quot;, &quot;date&quot;: &quot;2011-09-17&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1653&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/0942禚孝文:清華簡《程寤》集释.doc&quot; }{ &quot;author&quot;: &quot;陳民鎮&quot;, &quot;title&quot;: &quot;清華簡《尹誥》集釋&quot;, &quot;date&quot;: &quot;2011-09-12&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1648&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/0938陳民鎮:清華簡《尹誥》集釋.doc&quot; }{ &quot;author&quot;: &quot;陳民鎮&quot;, &quot;title&quot;: &quot;清華簡《尹至》集釋&quot;, &quot;date&quot;: &quot;2011-09-12&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1647&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/0937陳民鎮:清華簡《尹至》集釋.doc&quot; }{ &quot;author&quot;: &quot;汪亞洲、陳民鎮&quot;, &quot;title&quot;: &quot;清華簡研究論著目錄簡編&quot;, &quot;date&quot;: &quot;2011-09-12&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1646&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/0936汪亞洲、陳民鎮:清華簡研究論著目錄簡編.doc&quot; }{ &quot;author&quot;: &quot;劉信芳&quot;, &quot;title&quot;: &quot;清華藏簡(壹)試讀&quot;, &quot;date&quot;: &quot;2011-09-09&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1643&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/0934劉信芳:清華藏簡(壹)試讀.doc&quot; }{ &quot;author&quot;: &quot;鄧少平&quot;, &quot;title&quot;: &quot;清華簡研究論著目錄(2008.12—2011.8)&quot;, &quot;date&quot;: &quot;2011-08-30&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1631&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/0928鄧少平:清華簡研究論著目錄.doc&quot; }{ &quot;author&quot;: &quot;汪亞洲&quot;, &quot;title&quot;: &quot;清華簡《尹至》“亡典”說&quot;, &quot;date&quot;: &quot;2011-06-17&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1556&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/lunwen/0882汪亞洲:清華簡《尹至》“亡典”說.doc&quot; }{ &quot;author&quot;: null, &quot;title&quot;: &quot;網摘:2011年3月&quot;, &quot;date&quot;: &quot;2011-05-02&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1485&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/articles/up/0855網摘:2011年3月.doc&quot; }{ &quot;author&quot;: &quot;劉光勝&quot;, &quot;title&quot;: &quot;清華簡《耆夜》考論&quot;, &quot;date&quot;: &quot;2011-04-30&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1484&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/articles/up/0854刘光胜:清华简耆夜新探.doc&quot; }{ &quot;author&quot;: &quot;劉洪濤&quot;, &quot;title&quot;: &quot;清華簡補釋四則&quot;, &quot;date&quot;: &quot;2011-04-27&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1479&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/articles/up/0851刘洪涛:清华简补释四则.doc&quot; }{ &quot;author&quot;: &quot;蘇建洲&quot;, &quot;title&quot;: &quot;論楚竹書“厇”字構形&quot;, &quot;date&quot;: &quot;2011-04-10&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1459&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/articles/up/0838蘇建洲:論楚竹書“厇”字構形.doc&quot; }{ &quot;author&quot;: null, &quot;title&quot;: &quot;網摘:2011年2月&quot;, &quot;date&quot;: &quot;2011-04-02&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1450&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/articles/up/0830網摘:2011年2月.doc&quot; }{ &quot;author&quot;: &quot;劉波&quot;, &quot;title&quot;: &quot;清華簡《尹至》“僮亡典”補說&quot;, &quot;date&quot;: &quot;2011-03-04&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1421&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/articles/up/0812清華簡《尹至》“僮亡典”補說.doc&quot; }{ &quot;author&quot;: null, &quot;title&quot;: &quot;網摘:2011年1月&quot;, &quot;date&quot;: &quot;2011-03-01&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1417&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/articles/up/0809網摘:2011年1月.doc&quot; }{ &quot;author&quot;: &quot;陳劍&quot;, &quot;title&quot;: &quot;清華簡《皇門》“賏爾”字補說&quot;, &quot;date&quot;: &quot;2011-02-04&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1397&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/articles/up/0803清華簡《皇門》“賏爾”字補說.doc&quot; }{ &quot;author&quot;: &quot;王寧&quot;, &quot;title&quot;: &quot;清華簡《尹至》《尹誥》中的“衆”和“民”&quot;, &quot;date&quot;: &quot;2011-02-04&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1396&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/articles/up/0802清華簡《尹至》《尹誥》中的“衆”與“民”.doc&quot; }{ &quot;author&quot;: null, &quot;title&quot;: &quot;網摘:《清華一》專輯&quot;, &quot;date&quot;: &quot;2011-02-02&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1393&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/articles/up/0799網摘《清華一》專輯.doc&quot; }{ &quot;author&quot;: &quot;王寧&quot;, &quot;title&quot;: &quot;讀清華簡《程寤》偶記一則&quot;, &quot;date&quot;: &quot;2011-01-28&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1389&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/articles/up/0797讀清華簡《程寤》偶記一則.doc&quot; }{ &quot;author&quot;: &quot;蕭旭&quot;, &quot;title&quot;: &quot;清華竹簡《程寤》校補&quot;, &quot;date&quot;: &quot;2011-01-13&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1379&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/articles/up/0793清華竹簡《程寤》校補.doc&quot; }{ &quot;author&quot;: &quot;袁瑩&quot;, &quot;title&quot;: &quot;清華簡《程寤》校讀&quot;, &quot;date&quot;: &quot;2011-01-11&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1376&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/articles/up/0790清華簡《程寤》校讀.doc&quot; }{ &quot;author&quot;: &quot;孫飛燕&quot;, &quot;title&quot;: &quot;試論《尹至》的“至在湯”與《尹誥》的“及湯”&quot;, &quot;date&quot;: &quot;2011-01-10&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1373&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/articles/up/0788試論《尹至》的“至在湯”與《尹誥》的“及湯”.doc&quot; }{ &quot;author&quot;: &quot;蘇建洲&quot;, &quot;title&quot;: &quot;《清華簡》考釋四則&quot;, &quot;date&quot;: &quot;2011-01-09&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1368&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/articles/up/0784《清華簡》考釋四則.doc&quot; }{ &quot;author&quot;: &quot;沈培&quot;, &quot;title&quot;: &quot;清華簡字詞考釋二則&quot;, &quot;date&quot;: &quot;2011-01-09&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1367&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/articles/up/0783清華簡字詞考釋二則.doc&quot; }{ &quot;author&quot;: &quot;讀書會&quot;, &quot;title&quot;: &quot;清華簡《尹至》、《尹誥》研讀札記&quot;, &quot;date&quot;: &quot;2011-01-05&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1352&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/articles/up/0774清華簡《尹至》、《尹誥》研讀札記.doc&quot; }{ &quot;author&quot;: &quot;讀書會&quot;, &quot;title&quot;: &quot;清華簡《耆夜》研讀札記&quot;, &quot;date&quot;: &quot;2011-01-05&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1347&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/articles/up/0773清華簡《耆夜》研讀札記.doc&quot; }{ &quot;author&quot;: &quot;朱曉海&quot;, &quot;title&quot;: &quot;〈尹至〉可能是百篇《尚書》中前所未見的一篇&quot;, &quot;date&quot;: &quot;2010-06-17&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1187&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/articles/up/0692〈尹至〉可能是百篇《尚書》中前所未見的一篇.doc&quot; }{ &quot;author&quot;: null, &quot;title&quot;: &quot;清華九簡研讀札記&quot;, &quot;date&quot;: &quot;2010-05-30&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1166&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/articles/up/0676清華九簡研讀札記.doc&quot; }{ &quot;author&quot;: &quot;蘇建洲&quot;, &quot;title&quot;: &quot;《清華簡九篇綜述》封二所刊《皇門》簡簡釋&quot;, &quot;date&quot;: &quot;2010-05-30&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/1165&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/articles/up/0675《清華簡九篇綜述》封二所刊《皇門》簡簡釋.doc&quot; }{ &quot;author&quot;: &quot;淺野裕一&quot;, &quot;title&quot;: &quot;上博楚簡《柬大王泊旱》之災異思想&quot;, &quot;date&quot;: &quot;2009-09-13&quot;, &quot;url&quot;: &quot;http://www.gwz.fudan.edu.cn/Web/Show/904&quot;, &quot;publication&quot;: &quot;復旦大學出土文獻與古文字研究中心學者文庫&quot;, &quot;download&quot;: &quot;/articles/up/0494上博楚簡《柬大王泊旱》之災異思想.doc&quot; } </code></pre> <h1>Questions:</h1> <p>I originally intended to use another <code>dataclass</code> (as commented out) to extend @Reinderien's answer, but ended up doing the whole thing with functions and dictionaries instead.</p> <p>So my main question would be:</p> <ol> <li>How do we decide whether a <code>dataclass</code> is necessary for a task?</li> <li>Something specific to this part the <code>get_page</code> function in <code>fudan.py</code> above:</li> </ol> <pre class="lang-py prettyprint-override"><code>with session.get( 'http://www.gwz.fudan.edu.cn/Web/Search', params={ 's': query, 'page': page, }, ) as resp: resp.raise_for_status() doc = BeautifulSoup(resp.text, 'html.parser') </code></pre> <p>Why can't (or shouldn't) we just use this instead?</p> <pre class="lang-py prettyprint-override"><code>from requests import get with get('http://www.gwz.fudan.edu.cn/Web/Search?s=' + query) as resp: ... </code></pre> <p>(<em>Points of concern</em>: ① difference between <code>get</code> and <code>session.get</code> ② use of <code>params</code> instead of posting the query directly as part of the url string)</p> <ol start="3"> <li>Any other suggestion to improve my code are also welcome!</li> </ol>
[]
[ { "body": "<ul>\n<li>Distinguish between your Link and Result classes; I've renamed the latter to Article</li>\n<li>Publication is the same for every row so I've omitted it. You can reintroduce it if you really want, but it's strange to have to hard-code a value that's the same for every record in a file.</li>\n<li>Having an intermediate JSON that's saved only to be loaded again is not a good idea. Just operate on values in memory. The traditional thing to do may be to load the entire intermediate data to a list and then iterate over it, but that doesn't scale well in memory. The approach I've shown is wholly iterative and only carries one page at a time in memory.</li>\n<li>Deleting and then opening a file in append mode doesn't make sense. Just open it in normal write mode, and it will truncate and overwrite any existing contents.</li>\n<li>Never bare <code>try/except</code>. In this case since you're looking for a separator, just test for existence of the separator instead of using logic-by-exception.</li>\n<li>You broke the <code>date</code>-typed column that I suggested by storing it as a string. Don't format it to a string until it reaches the edge of your program.</li>\n<li><code>get_all_links</code> is not the right place to save to JSON.</li>\n<li>Your category filter does not need to hard-code an index to a specific anchor. Instead look for <code>#</code> in the <code>href</code>.</li>\n</ul>\n<p>Your specific points of concern:</p>\n<blockquote>\n<p>difference between get and session.get</p>\n</blockquote>\n<p>You already have a session, that you use half of the time - the other half you're doing direct <code>get</code>, which in this context you should avoid. Just use the session. It better expresses your intent to (1) carry around any potential cookies that a browser would, (2) apply common headers if that ever becomes necessary, and (3) share a connection pool.</p>\n<blockquote>\n<p>use of params instead of posting the query directly as part of the url string</p>\n</blockquote>\n<p>The <code>params</code> dict is a more Pythonic way of passing parameters: key-value pairs are manipulated more easily, you can pass in non-string parameters that Requests will coerce to strings for you, and Requests will do all of the necessary encoding and escaping that you shouldn't have to care about yourself.</p>\n<blockquote>\n<p>How do we decide whether a dataclass is necessary for a task?</p>\n</blockquote>\n<p>Nothing is ever &quot;necessary&quot;, but dataclasses are often &quot;well-suited&quot;. Consider if:</p>\n<ul>\n<li>You're using Python 3.7+, which you should be anyway</li>\n<li>You know the attributes of the class and their types, which you should anyway</li>\n<li>The general-purpose constructor <code>__init__</code> would be a trivial assignment of parameters to members</li>\n<li>Any specific-purpose pseudoconstructors can be represented as <code>@classmethod</code>s returning a class instance or instances</li>\n</ul>\n<p>then dataclasses are well-suited.</p>\n<h2>Suggested</h2>\n<pre><code>from dataclasses import dataclass\nfrom itertools import count\nfrom pathlib import Path\nfrom typing import Dict, Iterable, Tuple, List, Optional\nfrom urllib.parse import urljoin\n\nfrom bs4 import BeautifulSoup\nfrom requests import Session\nfrom datetime import date, datetime\n\nimport json\nimport re\n\nBASE_URL = 'http://www.gwz.fudan.edu.cn'\n\n\n@dataclass\nclass Link:\n caption: str\n url: str\n clicks: int\n replies: int\n added: date\n\n @classmethod\n def from_row(cls, props: Dict[str, str], path: str) -&gt; 'Link':\n clicks, replies = props['点击/回复'].split('/')\n # Skip number=int(props['编号']) - this only has meaning within one page\n\n return cls(\n caption=props['资源标题'],\n url=urljoin(BASE_URL, path),\n clicks=int(clicks),\n replies=int(replies),\n added=datetime.strptime(props['添加时间'], '%Y/%m/%d').date(),\n )\n\n def __str__(self):\n return f'{self.added} {self.url} {self.caption}'\n\n def author_title(self) -&gt; Tuple[Optional[str], str]:\n sep = ':' # full-width colon, U+FF1A\n\n if sep not in self.caption:\n return None, self.caption\n\n author, title = self.caption.split(sep, 1)\n author, title = author.strip(), title.strip()\n\n net_digest = '網摘'\n if author == net_digest:\n return None, title\n\n return author, title\n\n\n@dataclass\nclass Article:\n author: Optional[str]\n title: str\n date: date\n download: Optional[str]\n url: str\n\n @classmethod\n def from_link(cls, link: Link, download: str) -&gt; 'Article':\n\n author, title = link.author_title()\n\n download = download.replace(&quot;\\r&quot;, &quot;&quot;).replace(&quot;\\n&quot;, &quot;&quot;).strip()\n if download == '#_edn1':\n download = None\n elif download[0] != '/':\n download = '/' + download\n\n return cls(\n author=author,\n title=title,\n date=link.added,\n download=download,\n url=link.url,\n )\n\n def __str__(self) -&gt; str:\n return(\n f&quot;\\n作者 {self.author}&quot;\n f&quot;\\n標題 {self.title}&quot;\n f&quot;\\n發佈日期 {self.date}&quot;\n f&quot;\\n下載連結 {self.download}&quot;\n f&quot;\\n訪問網頁 {self.url}&quot;\n )\n\n def as_dict(self) -&gt; Dict[str, str]:\n return {\n 'author': self.author,\n 'title': self.title,\n 'date': self.date.isoformat(),\n 'download': self.download,\n 'url': self.url,\n }\n\n\ndef compile_search_results(session: Session, links: Iterable[Link], category_filter: str) -&gt; Iterable[Article]:\n\n for link in links:\n with session.get(link.url) as resp:\n resp.raise_for_status()\n doc = BeautifulSoup(resp.text, 'html.parser')\n\n category = doc.select_one('#_top td a[href=&quot;#&quot;]').text\n if category != category_filter:\n continue\n\n content = doc.select_one('span.ny_font_content')\n dl_tag = content.find(\n 'a', {\n 'href': re.compile(&quot;/?(lunwen/|articles/up/).+&quot;)\n }\n )\n\n yield Article.from_link(link, download=dl_tag['href'])\n\n\ndef get_page(session: Session, query: str, page: int) -&gt; Tuple[List[Link], int]:\n with session.get(\n urljoin(BASE_URL, '/Web/Search'),\n params={\n 's': query,\n 'page': page,\n },\n ) as resp:\n resp.raise_for_status()\n doc = BeautifulSoup(resp.text, 'html.parser')\n\n table = doc.select_one('#tab table')\n heads = [h.text for h in table.select('tr.cap td')]\n links = []\n\n for row in table.find_all('tr', class_=''):\n cells = [td.text for td in row.find_all('td')]\n links.append(Link.from_row(\n props=dict(zip(heads, cells)),\n path=row.find('a')['href'],\n ))\n\n page_td = doc.select_one('#tab table:nth-child(2) td')\n n_pages = int(page_td.text.rsplit('/', 1)[1])\n\n return links, n_pages\n\n\ndef get_all_links(session: Session, query: str) -&gt; Iterable[Link]:\n for page in count(1):\n links, n_pages = get_page(session, query, page)\n print(f'{page}/{n_pages}')\n yield from links\n\n if page &gt;= n_pages:\n break\n\n\ndef save_articles(articles: Iterable[Article], file_prefix: str) -&gt; None:\n file_path = Path(file_prefix).with_suffix('.json')\n\n with file_path.open('w') as file:\n file.write('[\\n')\n first = True\n\n for article in articles:\n if first:\n first = False\n else:\n file.write(',\\n')\n json.dump(article.as_dict(), file, ensure_ascii=False, indent=4)\n\n file.write('\\n]\\n')\n\n\ndef main():\n with Session() as session:\n links = get_all_links(session, query='尹至')\n academic_library = '学者文库'\n articles = compile_search_results(session, links, category_filter=academic_library)\n save_articles(articles, 'fudan_search_result')\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T15:56:58.857", "Id": "263375", "ParentId": "263357", "Score": "2" } } ]
{ "AcceptedAnswerId": "263375", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T08:56:05.610", "Id": "263357", "Score": "4", "Tags": [ "python", "web-scraping" ], "Title": "Use of dataclass when scraping with Requests" }
263357
<p><strong>Problem statement:</strong> I have the following access log, get the count by timestamp(hh:mm) and sort the count based on minute. And write it into the CSV file.</p> <p><code>access.log:</code></p> <pre><code>172.16.0.3 - - [25/Sep/2002:14:04:19 +0200] &quot;GET /api/endpoint HTTP/1.1&quot; 401 80500 &quot;domain&quot; &quot;Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.1) Gecko/20020827&quot; 172.16.0.3 - - [25/Sep/2002:14:04:19 +0200] &quot;GET /api/endpoint HTTP/1.1&quot; 200 80500 &quot;domain&quot; &quot;Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.1) Gecko/20020827&quot; 172.16.0.3 - - [25/Sep/2002:14:04:19 +0200] &quot;GET /api/endpoint HTTP/1.1&quot; 401 80500 &quot;domain&quot; &quot;Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.1) Gecko/20020827&quot; 172.16.1.3 - - [25/Sep/2002:14:04:19 +0200] &quot;GET /api/endpoint HTTP/1.1&quot; 401 80500 &quot;domain&quot; &quot;Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.1) Gecko/20020827&quot; 172.16.1.3 - - [25/Sep/2002:14:05:19 +0200] &quot;GET /api/endpoint HTTP/1.1&quot; 200 80500 &quot;domain&quot; &quot;Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.1) Gecko/20020827&quot; 172.16.1.3 - - [25/Sep/2002:14:05:19 +0200] &quot;GET /api/endpoint HTTP/1.1&quot; 200 80500 &quot;domain&quot; &quot;Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.1) Gecko/20020827&quot; </code></pre> <p>expected output:</p> <pre><code>#cat output.csv: 14:04, 4 14:05, 2 </code></pre> <p><strong>My solution:</strong></p> <pre><code>import re import csv log_list = {} with open('access.log','r') as loglines: for line in loglines: if line != &quot;\n&quot;: re_pattern = '([\d\.?]+) - - \[(.*?)\] &quot;(.*?)&quot; (.*?) (.*?) &quot;(.*?)&quot; &quot;(.*?)&quot;' re_match = re.match(re_pattern, line) timestamp = re_match.groups()[1] hh_mm = timestamp[12:17] if hh_mm in log_list: log_list[hh_mm] += 1 else: log_list[hh_mm] = 1 srtd_list = sorted(log_list.items(), key=lambda i:i[0]) with open('parsed_file.csv','w') as parsed_file: csv_writer = csv.writer(parsed_file) for item in srtd_list: csv_writer.writerow(item) </code></pre> <p><strong>Follow up questions:</strong></p> <ol> <li>Any other efficient way to perform this?</li> <li>How can i improve the book keeping of the count, if the file size is 10GB or if the file is ever growing.</li> <li>Efficient way to do the same for a file which gonna keep rotate hourly.</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T13:17:37.450", "Id": "519953", "Score": "1", "body": "Why is this being done in the first place? There are multiple strange things going on here, including that you're divorcing the time from the date. Is this for some kind of log traffic histogram only paying attention to the time of day?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T17:48:20.260", "Id": "519976", "Score": "0", "body": "yes., that's right! @Reinderien" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T19:54:06.627", "Id": "519990", "Score": "1", "body": "Incorporating advice from an answer into the question violates the question-and-answer nature of this site. You could post improved code as a new question, as an answer, or as a link to an external site - as described in [I improved my code based on the reviews. What next?](/help/someone-answers#help-post-body). I have rolled back the edit, so the answers make sense again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T05:47:29.397", "Id": "520002", "Score": "0", "body": "i see! and noted that point. thanks! @TobySpeight" } ]
[ { "body": "<pre class=\"lang-py prettyprint-override\"><code>log_list = {}\n...\n if hh_mm in log_list:\n log_list[hh_mm] += 1\n else:\n log_list[hh_mm] = 1\n...\n</code></pre>\n<p>This can be replaced with a <code>Counter</code> where unknown keys default to zero.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\n\nlog_list = Counter()\n...\n log_list[hh_mm] += 1\n...\n</code></pre>\n<p><code>re_pattern</code> does not need to be redefined each time through the loop. It should be moved outside of the loop, possibly to the top of the file as a constant (ie, named in all caps: <code>RE_PATTERN</code>), and maybe even compiled using <code>re.compile(…)</code></p>\n<p>There is no point capturing patterns you aren’t using. You just need <code>(…)</code> around the timestamp re pattern.</p>\n<p>From <code>srtd_list</code> on, you can outdent one level. You’ve finished reading the <code>loglines</code>, so you should allow the file to be closed immediately.</p>\n<p>The <code>key=…</code> in <code>sorted(…)</code> is unnecessary, since you are sorting on the guaranteed-unique first element of a tuple.</p>\n<hr />\n<p>You don’t need regex at all to do this. You could write the first part of the code as:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import csv\nfrom collections import Counter\n\nwith open('access.log','r') as loglines:\n log_list = Counter(line.split()[3][13:18]\n for line in loglines\n if line != '\\n')\nsrtd_list = sorted(log_list.items())\n…\n</code></pre>\n<p>This is simultaneously simpler and more cryptic. Comment it well if you use it!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T17:50:15.170", "Id": "519977", "Score": "0", "body": "1. Good suggestion on the collections\n2. `re_pattern` in the loop is not an intended one - will correct it, thanks for highlighting it\n3. Sorted is required, because i need sort it based on `hh:mm`\n4. Regarding regex vs split, will test out which one would be performant and use that. Thanks for the suggestion there too.\n\nAny thoughts on the followup questions? Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T19:25:50.077", "Id": "519985", "Score": "0", "body": "Regarding: \"_3. Sorted is required, because i need sort it based on hh:mm_\". I think you misunderstood me. `srtd_list = sorted(log_list.items(), key=lambda i:i[0])` will behave the same way `srtd_list = sorted(log_list.items())` does, because without a `key=...` argument, it sorts based on the natural ordering of each item, and since the items are dictionary key-value pairs, the first element of each item (the key) is unique, so it ends up sorting based on the dictionary keys, as desired." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T19:37:06.543", "Id": "519988", "Score": "0", "body": "Your CSV file will have, at most 1440 lines in it, regardless of the size of the input log (10GB, 10TB, 10PB, 10EB, 10ZB, 10YB ...) since there are only 24*60 distinct minutes in the day." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T14:39:00.027", "Id": "263370", "ParentId": "263360", "Score": "3" } }, { "body": "<p>Just an idea, but instead of regexes you could use built-in Python libraries for parsing datetimes, for example:</p>\n<pre><code>&gt;&gt;&gt; from datetime import datetime\n&gt;&gt;&gt; d = &quot;25/Sep/2002:14:04:19 +0200&quot;\n&gt;&gt;&gt; datetime.strptime(d, '%d/%b/%Y:%H:%M:%S %z')\ndatetime.datetime(2002, 9, 25, 14, 4, 19, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200)))\n</code></pre>\n<p>This code will parse your timestamp into a <strong>timezone-aware</strong> datetime. This approach could be interesting in case you want to be able to parse different formats, or you have varying time zones in your logs. Without a timezone, timestamps are meaningless unless you are operating against a known, stable location, but <strong>daylight saving time</strong> could come into play.</p>\n<p>Maybe you can ignore the timezone in your use case, depending on how the log was produced. Or not.</p>\n<p>Also, this could offer better performance than regex but I haven't tested it.</p>\n<p>It's obvious that this is a webserver log, and it's rather common to see bash scripts being used for that kind of purpose. A combination of <code>grep</code>, <code>cut</code> and <code>uniq -c</code> could get the job done in 10 lines or less I think.</p>\n<p>Now if you are interested in computing live statistics by constantly monitoring the file, you need to implement some sort of bash <code>tail</code> feature. In Python this could be done using <code>process.popen</code> and then you read from the stream line by line, and increment your counters accordingly (I could post some sample code if you're interested).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T20:58:00.073", "Id": "263386", "ParentId": "263360", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T11:01:14.770", "Id": "263360", "Score": "3", "Tags": [ "python" ], "Title": "Parsing log file and returning timestamp ordered output" }
263360
<p>For a job in company I had to do a code assignment. My assignment performs all the required tasks needed to be done. But after one month the company provided me a feedback and said that <strong>we have reviewed your exercise, very sorry for the delay. Unfortunately, while working, the structure and readability of the code are not sufficient, and we will not be proceeding further with your application at this time</strong>. The assignment was not to make a big application with a lot of modules. I am not able to figure out how can I improve it. Below is the assignment and my code, please review it and provide me your suggestions. Thanks</p> <p><a href="https://i.stack.imgur.com/iDWEm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iDWEm.jpg" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/HpVcl.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HpVcl.jpg" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/AOfAO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AOfAO.jpg" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/5PCII.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5PCII.jpg" alt="enter image description here" /></a></p> <pre><code> import SwiftUI struct ContentView : View { @State private var selectedBlocks = [[String:Int]]() @State private var scoreArray = [[String:Int]]() @State private var finalScore = &quot;&quot; @State private var isUserInteractionDisabled = false private let emptyNeighborScore = 10 private let filledNeighborScore = 5 private let intialBlockScore = 5 private let numberOfColumns = 5 private let numberOfRows = 5 private var resultLength = 10 private var columns: [GridItem] { Array(repeating: .init(.adaptive(minimum: 60)), count: numberOfColumns) } var body: some View { HStack(spacing: 0){ Text(&quot;Score: \(finalScore )&quot;) }.frame(height: 100) ScrollView(.vertical, showsIndicators: false) { ForEach(0..&lt;numberOfRows) { rowIndex in LazyVGrid(columns: columns, spacing: 20) { ForEach(0..&lt;numberOfColumns) { columnIndex in let cellIndex: [String:Int] = [&quot;rowIndex&quot;:rowIndex, &quot;columnIndex&quot;:columnIndex ] let results = self.scoreArray.filter { $0[&quot;rowIndex&quot;] == rowIndex &amp;&amp; $0[&quot;columnIndex&quot;] == columnIndex } Button(action: { self.updateSelectBlock(rowIndex:rowIndex, columnIndex:columnIndex) // &lt;- on tap update selection }) { Text(results.count&gt;0 ? &quot;\(results[0][&quot;score&quot;] ?? 0 )&quot; : &quot; &quot;) } .frame(width:50) .border(Color.black, width: 2) .background(self.selectedBlocks.contains(cellIndex) ? Color.blue : Color.white) } .buttonStyle(PlainButtonStyle()) } } }.disabled(isUserInteractionDisabled) } func updateSelectBlock(rowIndex:Int, columnIndex:Int) { isUserInteractionDisabled = true var cellIndex: [String:Int] = [&quot;rowIndex&quot;:rowIndex, &quot;columnIndex&quot;:columnIndex ] if(!self.selectedBlocks.contains(cellIndex) &amp;&amp; self.selectedBlocks.count &lt; resultLength) { self.selectedBlocks.append(cellIndex) } else { return } if(rowIndex &lt; numberOfRows-1) { let rowDifference = (numberOfRows - rowIndex - 2) var currentRowIndex = rowIndex var hasNeigbhor = false var count = 0 _ = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true){ t in if count == (rowDifference) { t.invalidate() isUserInteractionDisabled = false } count += 1 let bottomNeighborCheck = checkNeigbhor(rowIndex:currentRowIndex+1, columnIndex:columnIndex) let horizontalNeigborsCheck = checkHorizontalNeigbhors(rowIndex:currentRowIndex, columnIndex:columnIndex) let activeNeighborsCheck = horizontalNeigborsCheck || bottomNeighborCheck if(!activeNeighborsCheck) { if let index = self.selectedBlocks.firstIndex(of: cellIndex) { self.selectedBlocks.remove(at: index) } currentRowIndex = currentRowIndex + 1 cellIndex = [&quot;rowIndex&quot;:currentRowIndex, &quot;columnIndex&quot;:columnIndex] if(!self.selectedBlocks.contains(cellIndex)) { self.selectedBlocks.append(cellIndex) } } else { if(!self.selectedBlocks.contains(cellIndex) &amp;&amp; hasNeigbhor == false) { if let index = self.selectedBlocks.firstIndex(of: cellIndex) { self.selectedBlocks.remove(at: index) } hasNeigbhor = true self.selectedBlocks.append(cellIndex) } } showScore(checkActiveNeighbors:activeNeighborsCheck, currentRowIndex:currentRowIndex) } } } func checkNeigbhor(rowIndex:Int, columnIndex:Int) -&gt; Bool { let leftNeighborIndex : [String:Int] = [&quot;rowIndex&quot;:rowIndex, &quot;columnIndex&quot;:columnIndex] return self.selectedBlocks.contains(leftNeighborIndex) ? true :false } func checkHorizontalNeigbhors(rowIndex:Int, columnIndex:Int) -&gt; Bool { let leftNeighborCheck = checkNeigbhor(rowIndex:rowIndex, columnIndex:columnIndex-1) let rightNeighborCheck = checkNeigbhor(rowIndex:rowIndex, columnIndex:columnIndex+1) return leftNeighborCheck &amp;&amp; rightNeighborCheck } func showScore(checkActiveNeighbors:Bool, currentRowIndex:Int) { if( self.selectedBlocks.count == resultLength &amp;&amp; (checkActiveNeighbors || currentRowIndex == numberOfRows-1)) { self.calculateScore() return } } func calculateScore() { for blockIndex in 0..&lt;self.selectedBlocks.count { var score = intialBlockScore var rowIndexOfBlock : Int = self.selectedBlocks[blockIndex][&quot;rowIndex&quot;] ?? 0 let columnIndexOfBlock : Int = self.selectedBlocks[blockIndex][&quot;columnIndex&quot;] ?? 0 if(rowIndexOfBlock &lt; numberOfRows) { let rowDifference = (numberOfRows - rowIndexOfBlock - 1) for n in 0..&lt;rowDifference { let localIndex = rowIndexOfBlock+n let bottomNeighborCheck = checkNeigbhor(rowIndex:localIndex+1, columnIndex:columnIndexOfBlock) if(!bottomNeighborCheck &amp;&amp; localIndex+1&lt;numberOfRows){ let cellIndex = [&quot;rowIndex&quot;:localIndex+1, &quot;columnIndex&quot;:columnIndexOfBlock, &quot;score&quot;:emptyNeighborScore] if(!self.scoreArray.contains(cellIndex)) { self.scoreArray.append(cellIndex) } } else if (bottomNeighborCheck &amp;&amp; rowIndexOfBlock+1&lt;numberOfRows) { score = score + filledNeighborScore } } let cellIndex = [&quot;rowIndex&quot;:rowIndexOfBlock, &quot;columnIndex&quot;:columnIndexOfBlock, &quot;score&quot;:score] if(!self.scoreArray.contains(cellIndex)) { self.scoreArray.append(cellIndex) } rowIndexOfBlock = rowIndexOfBlock + 1 } calculateFinalScore() } } func calculateFinalScore() { var totalScore = 0 for inde in 0..&lt;self.scoreArray.count { let blockScore : Int = self.scoreArray[inde][&quot;score&quot;] ?? 0 totalScore = totalScore+blockScore } finalScore = &quot; \(totalScore )&quot; } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-25T02:56:09.300", "Id": "520073", "Score": "0", "body": "The over arching issue I see is a lack of separation of concerns. You have game logic in your view." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-09T06:40:32.133", "Id": "525135", "Score": "1", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." } ]
[ { "body": "<p>First there's some low hanging fruit. Perpetual use of <code>self.</code> when not needed. Use of parens when not needed. Inconsistent formatting (sometimes you put a space before the open brace, sometimes you don't. Sometimes you put code after a close brace on the same line, sometimes you don't.)</p>\n<p>These seem like minor things I'm sure and the compiler doesn't care at all, but it's a sign of sloppy thinking, rushed code, or someone who just doesn't care. You want it to look like you care, didn't do a rush job and think clearly.</p>\n<p>That single, random comment in the code that does nothing but point out the obvious is a red flag as well. If you are going to put comments in, they should explain why you did what you did, not describe what the code is doing. Anybody who can read Swift will know what the code is doing, but they won't know why you did it unless you tell them.</p>\n<p>The super multi-purpose <code>scoreArray = [[String: Int]]()</code> is an odd choice. It looks like each <code>[String: Int]</code> represents something that has a <code>rowIndex</code> and <code>columnIndex</code> and a <code>score</code>. Maybe use a struct for that instead of a Dictionary.</p>\n<p>And as Alexander said in the comments, the lack of separation between logic and view is the biggest problem. As the code sits, it's impossible to test.</p>\n<p>Some examples, if I was reviewing this code, I would want to see a function that takes in a board state and returns a score. I would want to see a function that takes a board state and a coordinate and returns a Bool indicating whether a block at that location would need to drop. Others like that as well. I would want to see a type that represents the BoardState (maybe even called <code>BoardState</code>)</p>\n<p>Even if you didn't write tests, even if you weren't tasked to write tests, your code should be testable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-08T22:37:42.470", "Id": "265863", "ParentId": "263363", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T12:45:11.217", "Id": "263363", "Score": "3", "Tags": [ "swift", "ios", "swiftui" ], "Title": "Structure and readability of the code in swift ios" }
263363
<p>I'm currently writing a game of life with small extra features but I ran into a problem - in my first try i decided to use simple list of Cell objects:</p> <pre><code>class Cell: def __init__(self, x, y, is_alive): self.is_alive = is_alive self.x = x self.y = y self.will_be_alive = False self.neighbours = 0 def kill(self): self.will_be_alive = False def revive(self): self.will_be_alive = True def iterate(self): self.is_alive = self.will_be_alive </code></pre> <p>but now I'm using different approach:</p> <pre><code>class Cells: def __init__(self, width, height): self.current_states = [[False for i in range(width)] for j in range(height)] self.next_states = [[False for i in range(width)] for j in range(height)] self.neighbours = [[0 for i in range(width)] for j in range(height)] </code></pre> <p>as you can see, instead of list of objects it's now object with lists. I expected my program to run slightly faster, but it's totally opposite - it's 20 fps less. I think, that problem may be in iterate method in second way:</p> <pre><code>def next_state(cells): for i, row in enumerate(cells.current_states): for j, cell in enumerate(row): if cells.neighbours[i][j] &gt; 0: count_state(cells, j, i) elif cells.neighbours[i][j] == 0 and cells.current_states[i][j]: cells.next_states[i][j] = False for i, row in enumerate(cells.current_states): for j, cell in enumerate(row): neigh_iterate(cells, j, i) def count_state(cells, x, y): nei = neighboors(cells.current_states, x, y) if (nei &gt; 3 or nei &lt; 2) and cells.current_states[y][x]: cells.next_states[y][x] = False elif nei == 3 and not cells.current_states[y][x]: cells.next_states[y][x] = True def neigh_iterate(cells, x, y): prev = cells.current_states[y][x] iterate(cells, x, y) if cells.current_states[y][x] != prev: if cells.current_states[y][x]: add_neighbour(cells.neighbours, x, y, 1) else: add_neighbour(cells.neighbours, x, y, -1) def neighboors(current_states, x, y): how_many = -1 if current_states[y][x] else 0 for i in range(-1, 2): for j in range(-1, 2): if current_states[(y + i) % BOARD_HEIGHT][(x + j) % BOARD_WIDTH]: how_many += 1 return how_many def iterate(cells, x, y): cells.current_states[y][x] = cells.next_states[y][x] </code></pre> <p>Do you have any ideas guys?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T15:14:56.350", "Id": "519963", "Score": "0", "body": "What do you mean by \"20 fps less\"? Are you recreating an array every frame? There are several possible causes starting with some Python implementation details and up to CPU cache. I have 2 recommendations: 1. don't assume something being faster for you code - check it. 2. Read about data-driven development." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T17:04:24.680", "Id": "519969", "Score": "0", "body": "I've already profiled code with cProfile. Despite the smaller number of calls to iterating functions, they last over 120ms longer in second approach. App dropped from average 62 to 41-42 frames, so it's over 33% waste of performance." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T14:11:46.213", "Id": "263367", "Score": "2", "Tags": [ "python", "pygame", "game-of-life" ], "Title": "One data object instead of array of objects - why is it slower?" }
263367
<p>This is a follow-up of my question over <a href="https://codereview.stackexchange.com/q/262883/242934">here</a>.</p> <p>I have been working on my web-scraping techniques by trying out different approaches and rewriting code for a handful of online databases.</p> <p>I've recently seen for myself that <code>requests</code> is definitely way more efficient than <code>selenium</code>, as demonstrated by the scripts below. <code>requests</code> retrieved far more data in a much shorter time than <code>selenium</code>.</p> <p>Differences in output is (most likely) due to application of the search keyword in content (<code>按文章內容</code>) filter on the website with <code>selenium</code>.</p> <p>Another popular web-scraping framework in Python is <a href="https://scrapy.org" rel="nofollow noreferrer">Scrapy</a>.</p> <h1>Questions:</h1> <ol> <li>How would the code look like with that method?</li> <li>How does <code>Scrapy</code> compare to the other two above?</li> <li>Assuming a developer has equivalent high-level proficiency for each method, how does he/she decide when to use which method for a given task? In other words, what are the factors determining the method that is most suited to the task?</li> <li>Any suggestions to improve on the existing code are also welcome!</li> </ol> <hr /> <h1>wuhan.py</h1> <h2>By Requests:</h2> <pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass, asdict from itertools import count from typing import Dict, Iterable, Tuple, List from bs4 import BeautifulSoup from requests import post from datetime import date, datetime import json import os import re @dataclass class Result: author: str title: str date: date url: str publication: str = &quot;武漢大學簡帛網&quot; @classmethod def from_metadata(cls, metadata: Dict) -&gt; 'Result': author, title = metadata['caption'].split(':') published_date = date.isoformat(datetime.strptime(metadata['date'], '%y/%m/%d')) url = 'http://www.bsm.org.cn/' + metadata['url'] return cls( author = author, title = title, date = published_date, url = url ) def __str__(self): return ( f'作者    {self.author}' f'\n標題 {self.title}' f'\n發表時間 {self.date}' f'\n文章連結 {self.url}' f'\n發表平台 {self.publication}' ) def submit_query(keyword: str): query = {&quot;searchword&quot;: keyword} with post('http://www.bsm.org.cn/pages.php?pagename=search', query) as resp: resp.raise_for_status() doc = BeautifulSoup(resp.text, 'html.parser') content = doc.find('div', class_='record_list_main') rows = content.select('ul') for row in rows: if len(row.findAll('li')) != 2: print() print(row.text) print() else: captions_tag, date_tag = row.findAll('li') caption_anchors = captions_tag.findAll('a') category, caption = [item.text for item in caption_anchors] url = caption_anchors[1]['href'] date = re.sub(&quot;[()]&quot;, &quot;&quot;, date_tag.text) yield { &quot;category&quot;: category, &quot;caption&quot;: caption, &quot;date&quot;: date, &quot;url&quot;: url} def remove_json_if_exists(filename): json_file = filename + &quot;.json&quot; filePath = os.path.join(os.getcwd(), json_file) if os.path.exists(filePath): os.remove(filePath) def search(query: str): remove_json_if_exists('wuhan_search_result') rslt = submit_query(query) for metadata in rslt: article = Result.from_metadata(metadata) print(article) print() with open('wuhan_search_result.json', 'a') as file: json.dump(asdict(article), file, ensure_ascii=False, indent=4) def main(): search('尹至') if __name__ == '__main__': main() </code></pre> <h3>Output:</h3> <pre class="lang-json prettyprint-override"><code>{ &quot;author&quot;: &quot;楊 坤 &quot;, &quot;title&quot;: &quot;說清華竹書《尹至》“白[夕彔]”&quot;, &quot;date&quot;: &quot;2015-12-28&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=2408&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;馬文增 &quot;, &quot;title&quot;: &quot;清華簡《尹至》新釋、注解、白話譯文&quot;, &quot;date&quot;: &quot;2015-06-01&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=2246&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;楊 坤 &quot;, &quot;title&quot;: &quot;跋清華竹書《尹至》&quot;, &quot;date&quot;: &quot;2013-09-16&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1902&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;王 寧 &quot;, &quot;title&quot;: &quot;清華簡《尹至》“勞”字臆解&quot;, &quot;date&quot;: &quot;2012-07-31&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1724&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;沈亞丹、王云飛 &quot;, &quot;title&quot;: &quot;清華簡《尹至》、《尹誥》集釋&quot;, &quot;date&quot;: &quot;2011-09-27&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1556&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;邢 文 &quot;, &quot;title&quot;: &quot;談清華簡《尹至》的“動亡典,夏有祥”&quot;, &quot;date&quot;: &quot;2011-03-25&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1423&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;黃懷信 &quot;, &quot;title&quot;: &quot;清華簡《尹至》補釋&quot;, &quot;date&quot;: &quot;2011-03-17&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1416&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;王 寧 &quot;, &quot;title&quot;: &quot;清華簡《尹至》釋證四例&quot;, &quot;date&quot;: &quot;2011-02-21&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1403&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;黃人二、趙思木 &quot;, &quot;title&quot;: &quot;清華簡《尹至》餘釋&quot;, &quot;date&quot;: &quot;2011-01-12&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1385&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;黃人二、趙思木 &quot;, &quot;title&quot;: &quot;清華簡《尹至》補釋&quot;, &quot;date&quot;: &quot;2011-01-11&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1383&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;趙平安、王挺斌 &quot;, &quot;title&quot;: &quot;論清華簡的文獻學價值&quot;, &quot;date&quot;: &quot;2019-05-07&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=3361&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;王 寧 &quot;, &quot;title&quot;: &quot;清華簡七《子犯子餘》文字釋讀二則&quot;, &quot;date&quot;: &quot;2017-05-03&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=2798&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;王 寧 &quot;, &quot;title&quot;: &quot;清華簡《說命》補釋五則&quot;, &quot;date&quot;: &quot;2016-02-19&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=2472&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;楊 坤 &quot;, &quot;title&quot;: &quot;說清華竹書《尹至》“白[夕彔]”&quot;, &quot;date&quot;: &quot;2015-12-28&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=2408&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;龐壯城 &quot;, &quot;title&quot;: &quot;北大漢簡《節》考釋零箋&quot;, &quot;date&quot;: &quot;2015-11-25&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=2374&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;馬文增 &quot;, &quot;title&quot;: &quot;清華簡《尹誥》新釋、簡注、白話譯文&quot;, &quot;date&quot;: &quot;2015-06-08&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=2256&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;馬文增 &quot;, &quot;title&quot;: &quot;據“清華簡”看關於伊尹的訛傳與誤解&quot;, &quot;date&quot;: &quot;2015-06-04&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=2250&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;馬文增 &quot;, &quot;title&quot;: &quot;清華簡《尹至》新釋、注解、白話譯文&quot;, &quot;date&quot;: &quot;2015-06-01&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=2246&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;王 寧 &quot;, &quot;title&quot;: &quot;上博二《容成氏》戎遂、鬲山氏、鳴條考&quot;, &quot;date&quot;: &quot;2015-02-27&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=2162&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;潘 潤 &quot;, &quot;title&quot;: &quot;從清華簡《繫年》看戴氏取宋的開始時間及其歷史意義&quot;, &quot;date&quot;: &quot;2014-12-06&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=2106&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;王 寧 &quot;, &quot;title&quot;: &quot;釋郭店簡《老子》乙中的“劬”&quot;, &quot;date&quot;: &quot;2014-11-12&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=2102&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;許名瑲 &quot;, &quot;title&quot;: &quot;戰國簡帛總括範圍副詞“畢”、“率”探究&quot;, &quot;date&quot;: &quot;2013-12-28&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1971&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;許名瑲 &quot;, &quot;title&quot;: &quot;戰國簡帛總括範圍副詞“咸”探究&quot;, &quot;date&quot;: &quot;2013-12-17&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1965&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;許名瑲 &quot;, &quot;title&quot;: &quot;戰國簡帛總括範圍副詞“皆”探究&quot;, &quot;date&quot;: &quot;2013-11-27&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1957&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;楊 坤 &quot;, &quot;title&quot;: &quot;跋清華竹書《尹至》&quot;, &quot;date&quot;: &quot;2013-09-16&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1902&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;黃庭頎 &quot;, &quot;title&quot;: &quot;論古文字材料所見之「伊尹」稱號&quot;, &quot;date&quot;: &quot;2013-07-15&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1866&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;肖芸曉 &quot;, &quot;title&quot;: &quot;試論清華竹書伊尹三篇的關聯&quot;, &quot;date&quot;: &quot;2013-03-07&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1834&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;楊 博 &quot;, &quot;title&quot;: &quot;簡述楚系簡帛典籍的史料分類&quot;, &quot;date&quot;: &quot;2013-01-17&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1819&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;王 寧 &quot;, &quot;title&quot;: &quot;清華簡《尹至》“勞”字臆解&quot;, &quot;date&quot;: &quot;2012-07-31&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1724&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;申 超 &quot;, &quot;title&quot;: &quot;清華簡《尹誥》“我克協我友,今惟民遠邦歸志”試說&quot;, &quot;date&quot;: &quot;2012-04-20&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1672&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;張 峰 &quot;, &quot;title&quot;: &quot;《清華簡〈程寤〉》中的“思”&quot;, &quot;date&quot;: &quot;2011-11-11&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1576&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;王玉蛟 &quot;, &quot;title&quot;: &quot;淺論《清華簡(一)》中的“于”和“於”&quot;, &quot;date&quot;: &quot;2011-11-03&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1574&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;王玉蛟 &quot;, &quot;title&quot;: &quot;《清華簡大學藏戰國竹簡(壹)》人稱代詞研究&quot;, &quot;date&quot;: &quot;2011-11-02&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1573&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;黃尚明 &quot;, &quot;title&quot;: &quot;從楚簡證“《詩》、《書》、執禮”的“執”應讀爲“埶”&quot;, &quot;date&quot;: &quot;2011-10-14&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1563&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;沈亞丹、王云飛 &quot;, &quot;title&quot;: &quot;清華簡《尹至》、《尹誥》集釋&quot;, &quot;date&quot;: &quot;2011-09-27&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1556&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;李燁、田佳鷺 &quot;, &quot;title&quot;: &quot;“清華簡(壹)”中的“厥”和“其”&quot;, &quot;date&quot;: &quot;2011-06-17&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1495&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;邢 文 &quot;, &quot;title&quot;: &quot;談清華簡《尹至》的“動亡典,夏有祥”&quot;, &quot;date&quot;: &quot;2011-03-25&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1423&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;黃懷信 &quot;, &quot;title&quot;: &quot;清華簡《尹至》補釋&quot;, &quot;date&quot;: &quot;2011-03-17&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1416&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;王 寧 &quot;, &quot;title&quot;: &quot;清華簡《尹至》釋證四例&quot;, &quot;date&quot;: &quot;2011-02-21&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1403&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;黃人二、趙思木 &quot;, &quot;title&quot;: &quot;讀《清華大學藏戰國竹簡(壹)》..&quot;, &quot;date&quot;: &quot;2011-02-17&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1402&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;曹方向 &quot;, &quot;title&quot;: &quot;記清華簡第一冊九篇竹書的若干書寫情況&quot;, &quot;date&quot;: &quot;2011-01-31&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1396&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;黃 杰 &quot;, &quot;title&quot;: &quot;清華簡《程寤》筆記一則&quot;, &quot;date&quot;: &quot;2011-01-12&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1387&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;黃人二、趙思木 &quot;, &quot;title&quot;: &quot;清華簡《尹至》補釋&quot;, &quot;date&quot;: &quot;2011-01-11&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1383&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;宋華强 &quot;, &quot;title&quot;: &quot;清華簡校讀散札&quot;, &quot;date&quot;: &quot;2011-01-10&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1380&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;黃 杰 &quot;, &quot;title&quot;: &quot;讀清華簡筆記(二)&quot;, &quot;date&quot;: &quot;2011-01-09&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1376&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;黃人二、趙思木 &quot;, &quot;title&quot;: &quot;讀《清華大學藏戰國竹簡(壹)》..&quot;, &quot;date&quot;: &quot;2011-01-09&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1375&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;曹方向 &quot;, &quot;title&quot;: &quot;清華大學藏戰國竹簡《尹誥》篇補議一則&quot;, &quot;date&quot;: &quot;2011-01-08&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1373&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;何有祖 &quot;, &quot;title&quot;: &quot;清華大學藏簡讀札(一)&quot;, &quot;date&quot;: &quot;2011-01-08&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1372&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; }{ &quot;author&quot;: &quot;黃人二、趙思木 &quot;, &quot;title&quot;: &quot;讀《清華大學藏戰國竹簡》書後(..&quot;, &quot;date&quot;: &quot;2011-01-07&quot;, &quot;url&quot;: &quot;http://www.bsm.org.cn/show_article.php?id=1368&quot;, &quot;publication&quot;: &quot;武漢大學簡帛網&quot; } </code></pre> <hr /> <h2>By Selenium:</h2> <pre class="lang-py prettyprint-override"><code>from contextlib import contextmanager from dataclasses import dataclass, replace from datetime import datetime, date from pathlib import Path from typing import Iterable, Optional, ContextManager import re import time # pip install proxy.py import proxy from proxy.http.exception import HttpRequestRejected from proxy.http.parser import HttpParser from proxy.http.proxy import HttpProxyBasePlugin from selenium.common.exceptions import ( NoSuchElementException, StaleElementReferenceException, TimeoutException, WebDriverException, ) from selenium.webdriver import Firefox, FirefoxProfile from selenium.webdriver.common.by import By from selenium.webdriver.common.proxy import ProxyType from selenium.webdriver.remote.webdriver import WebDriver from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait @dataclass class PrimaryResult: caption: str date: date link: str @classmethod def from_row(cls, row: WebElement) -&gt; 'PrimaryResult': caption_elems, date_elems = row.find_elements_by_tag_name('li') captions = caption_elems.find_elements_by_tag_name('a')[1] date_elems = re.sub(&quot;[()]&quot;, &quot;&quot;, date_elems.text) published_date = date.isoformat(datetime.strptime(date_elems, '%y/%m/%d')) return cls( caption = captions.text, date = published_date, link = captions.get_attribute('href') ) def __str__(self): return ( f'標題 {self.caption}' f'\n發表時間 {self.date}' f'\n文章連結 {self.link}' ) class MainPage: def __init__(self, driver: WebDriver): self.driver = driver def select_dropdown_item(self): driver = self.driver driver.find_element_by_xpath(&quot;//form/li[2]/select/option[text()='按文章內容']&quot;).click() def submit_search(self, keyword: str) -&gt; None: wait = WebDriverWait(self.driver, 100) search = wait.until( EC.presence_of_element_located((By.ID, 'searchword')) ) search.send_keys(keyword) search.submit() def get_element_and_stop_page(self, *locator) -&gt; WebElement: ignored_exceptions = (NoSuchElementException, StaleElementReferenceException) wait = WebDriverWait(self.driver, 30, ignored_exceptions=ignored_exceptions) elm = wait.until(EC.presence_of_element_located(locator)) self.driver.execute_script(&quot;window.stop();&quot;) return elm def next_page(self) -&gt; None: try: link = self.get_element_and_stop_page(By.LINK_TEXT, &quot;下页&quot;) except: print(&quot;No button with 「下页」 found.&quot;) return try: link.click() print(&quot;Navigating to Next Page&quot;) except (TimeoutException, WebDriverException): print(&quot;Last page reached&quot;) # @contextmanager # def wait_for_new_window(self): # driver = self.driver # handles_before = driver.window_handles # yield # WebDriverWait(driver, 10).until( # lambda driver: len(handles_before) != len(driver.window_handles)) def switch_tabs(self): driver = self.driver print(&quot;Current Window:&quot;) print(driver.title) print() p = driver.current_window_handle chwd = driver.window_handles time.sleep(3) &quot;&quot;&quot; I am not quite sure how to use `wait.until...` in this context, so I make do with `time.sleep(3)` before switching windows. &quot;&quot;&quot; driver.switch_to.window(chwd[1]) print(&quot;New Window:&quot;) print(driver.title) print() class SearchResults: def __init__(self, driver: WebDriver): self.driver = driver def get_structured_elements(self): rows = self.driver.find_elements_by_xpath('//div[5]/div[2]/div/ul[position() &gt; 1]') # caption_links = self.driver.find_elements_by_xpath('//div[5]/div[2]/div/ul/li[1]/a[2]') # if : # for i, row in enumerate(rows): # if &quot;發表的文章有&quot; not in row.text: # pass # else: # slice = i+1 # rows = rows[slice:] for row in rows: yield PrimaryResult.from_row(row) # class ContentFilterPlugin(HttpProxyBasePlugin): # HOST_WHITELIST = { # b'ocsp.digicert.com', # b'ocsp.sca1b.amazontrust.com', # b'big5.oversea.cnki.net', # b'gwz.fudan.edu.cn' # } # def handle_client_request(self, request: HttpParser) -&gt; Optional[HttpParser]: # host = request.host or request.header(b'Host') # if host not in self.HOST_WHITELIST: # raise HttpRequestRejected(403) # if any( # suffix in request.path # for suffix in ( # b'png', b'ico', b'jpg', b'gif', b'css', # ) # ): # raise HttpRequestRejected(403) # return request # def before_upstream_connection(self, request): # return super().before_upstream_connection(request) # def handle_upstream_chunk(self, chunk): # return super().handle_upstream_chunk(chunk) # def on_upstream_connection_close(self): # pass # @contextmanager # def run_driver() -&gt; ContextManager[WebDriver]: # prox_type = ProxyType.MANUAL['ff_value'] # prox_host = '127.0.0.1' # prox_port = 8889 # profile = FirefoxProfile() # profile.set_preference('network.proxy.type', prox_type) # profile.set_preference('network.proxy.http', prox_host) # profile.set_preference('network.proxy.ssl', prox_host) # profile.set_preference('network.proxy.http_port', prox_port) # profile.set_preference('network.proxy.ssl_port', prox_port) # profile.update_preferences() # plugin = f'{Path(__file__).stem}.{ContentFilterPlugin.__name__}' # with proxy.start(( # '--hostname', prox_host, # '--port', str(prox_port), # '--plugins', plugin, # )), Firefox(profile) as driver: # yield driver def search(keyword) -&gt; None: with Firefox() as driver: driver.get('http://www.bsm.org.cn/index.php') page = MainPage(driver) page.select_dropdown_item() page.submit_search(keyword) time.sleep(5) page.switch_tabs() primary_result_page = SearchResults(driver) primary_results = primary_result_page.get_structured_elements() for result in primary_results: print(result) print() if __name__ == '__main__': search('尹至') </code></pre> <h3>Output:</h3> <pre><code>Current Window: 簡帛網-武漢大學簡帛研究中心 New Window: 簡帛網》搜索 標題 趙平安、王挺斌 :論清華簡的文獻學價值 發表時間 2019-05-07 文章連結 http://www.bsm.org.cn/show_article.php?id=3361 標題 王 寧 :清華簡七《子犯子餘》文字釋讀二則 發表時間 2017-05-03 文章連結 http://www.bsm.org.cn/show_article.php?id=2798 標題 王 寧 :清華簡《說命》補釋五則 發表時間 2016-02-19 文章連結 http://www.bsm.org.cn/show_article.php?id=2472 標題 楊 坤 :說清華竹書《尹至》“白[夕彔]” 發表時間 2015-12-28 文章連結 http://www.bsm.org.cn/show_article.php?id=2408 標題 龐壯城 :北大漢簡《節》考釋零箋 發表時間 2015-11-25 文章連結 http://www.bsm.org.cn/show_article.php?id=2374 標題 馬文增 :清華簡《尹誥》新釋、簡注、白話譯文 發表時間 2015-06-08 文章連結 http://www.bsm.org.cn/show_article.php?id=2256 標題 馬文增 :據“清華簡”看關於伊尹的訛傳與誤解 發表時間 2015-06-04 文章連結 http://www.bsm.org.cn/show_article.php?id=2250 標題 馬文增 :清華簡《尹至》新釋、注解、白話譯文 發表時間 2015-06-01 文章連結 http://www.bsm.org.cn/show_article.php?id=2246 標題 王 寧 :上博二《容成氏》戎遂、鬲山氏、鳴條考 發表時間 2015-02-27 文章連結 http://www.bsm.org.cn/show_article.php?id=2162 標題 潘 潤 :從清華簡《繫年》看戴氏取宋的開始時間及其歷史意義 發表時間 2014-12-06 文章連結 http://www.bsm.org.cn/show_article.php?id=2106 標題 王 寧 :釋郭店簡《老子》乙中的“劬” 發表時間 2014-11-12 文章連結 http://www.bsm.org.cn/show_article.php?id=2102 標題 許名瑲 :戰國簡帛總括範圍副詞“畢”、“率”探究 發表時間 2013-12-28 文章連結 http://www.bsm.org.cn/show_article.php?id=1971 標題 許名瑲 :戰國簡帛總括範圍副詞“咸”探究 發表時間 2013-12-17 文章連結 http://www.bsm.org.cn/show_article.php?id=1965 標題 許名瑲 :戰國簡帛總括範圍副詞“皆”探究 發表時間 2013-11-27 文章連結 http://www.bsm.org.cn/show_article.php?id=1957 標題 楊 坤 :跋清華竹書《尹至》 發表時間 2013-09-16 文章連結 http://www.bsm.org.cn/show_article.php?id=1902 標題 黃庭頎 :論古文字材料所見之「伊尹」稱號 發表時間 2013-07-15 文章連結 http://www.bsm.org.cn/show_article.php?id=1866 標題 肖芸曉 :試論清華竹書伊尹三篇的關聯 發表時間 2013-03-07 文章連結 http://www.bsm.org.cn/show_article.php?id=1834 標題 楊 博 :簡述楚系簡帛典籍的史料分類 發表時間 2013-01-17 文章連結 http://www.bsm.org.cn/show_article.php?id=1819 標題 王 寧 :清華簡《尹至》“勞”字臆解 發表時間 2012-07-31 文章連結 http://www.bsm.org.cn/show_article.php?id=1724 標題 申 超 :清華簡《尹誥》“我克協我友,今惟民遠邦歸志”試說 發表時間 2012-04-20 文章連結 http://www.bsm.org.cn/show_article.php?id=1672 標題 張 峰 :《清華簡〈程寤〉》中的“思” 發表時間 2011-11-11 文章連結 http://www.bsm.org.cn/show_article.php?id=1576 標題 王玉蛟 :淺論《清華簡(一)》中的“于”和“於” 發表時間 2011-11-03 文章連結 http://www.bsm.org.cn/show_article.php?id=1574 標題 王玉蛟 :《清華簡大學藏戰國竹簡(壹)》人稱代詞研究 發表時間 2011-11-02 文章連結 http://www.bsm.org.cn/show_article.php?id=1573 標題 黃尚明 :從楚簡證“《詩》、《書》、執禮”的“執”應讀爲“埶” 發表時間 2011-10-14 文章連結 http://www.bsm.org.cn/show_article.php?id=1563 標題 沈亞丹、王云飛 :清華簡《尹至》、《尹誥》集釋 發表時間 2011-09-27 文章連結 http://www.bsm.org.cn/show_article.php?id=1556 標題 李燁、田佳鷺 :“清華簡(壹)”中的“厥”和“其” 發表時間 2011-06-17 文章連結 http://www.bsm.org.cn/show_article.php?id=1495 標題 邢 文 :談清華簡《尹至》的“動亡典,夏有祥” 發表時間 2011-03-25 文章連結 http://www.bsm.org.cn/show_article.php?id=1423 標題 黃懷信 :清華簡《尹至》補釋 發表時間 2011-03-17 文章連結 http://www.bsm.org.cn/show_article.php?id=1416 標題 王 寧 :清華簡《尹至》釋證四例 發表時間 2011-02-21 文章連結 http://www.bsm.org.cn/show_article.php?id=1403 標題 黃人二、趙思木 :讀《清華大學藏戰國竹簡(壹)》.. 發表時間 2011-02-17 文章連結 http://www.bsm.org.cn/show_article.php?id=1402 標題 曹方向 :記清華簡第一冊九篇竹書的若干書寫情況 發表時間 2011-01-31 文章連結 http://www.bsm.org.cn/show_article.php?id=1396 標題 黃 杰 :清華簡《程寤》筆記一則 發表時間 2011-01-12 文章連結 http://www.bsm.org.cn/show_article.php?id=1387 標題 黃人二、趙思木 :清華簡《尹至》補釋 發表時間 2011-01-11 文章連結 http://www.bsm.org.cn/show_article.php?id=1383 標題 宋華强 :清華簡校讀散札 發表時間 2011-01-10 文章連結 http://www.bsm.org.cn/show_article.php?id=1380 標題 黃 杰 :讀清華簡筆記(二) 發表時間 2011-01-09 文章連結 http://www.bsm.org.cn/show_article.php?id=1376 標題 黃人二、趙思木 :讀《清華大學藏戰國竹簡(壹)》.. 發表時間 2011-01-09 文章連結 http://www.bsm.org.cn/show_article.php?id=1375 標題 曹方向 :清華大學藏戰國竹簡《尹誥》篇補議一則 發表時間 2011-01-08 文章連結 http://www.bsm.org.cn/show_article.php?id=1373 標題 何有祖 :清華大學藏簡讀札(一) 發表時間 2011-01-08 文章連結 http://www.bsm.org.cn/show_article.php?id=1372 標題 黃人二、趙思木 :讀《清華大學藏戰國竹簡》書後(.. 發表時間 2011-01-07 文章連結 http://www.bsm.org.cn/show_article.php?id=1368 </code></pre> <hr />
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T15:39:36.507", "Id": "263373", "Score": "2", "Tags": [ "python", "web-scraping" ], "Title": "requests vs selenium vs scrapy" }
263373
<p>I've found pretty simple problem on <a href="https://www.youtube.com/watch?v=N92w4e-hrA4" rel="nofollow noreferrer">Numberphiles channel</a>: suppose we have a recursive function <span class="math-container">$$ \begin{equation} \begin{split} f_0 &amp;= Z ^ 2+ C \\ f_i &amp;= f_{i-1}^2 + C \; | \; i = 1 \dots \end{split} \end{equation} $$</span></p> <p>What values of <span class="math-container">\$ Z \$</span> and <span class="math-container">\$ C \$</span> should be <span class="math-container">\$ |\{ f_i | \; i=0..5\}| = 6 \; \cap \; f_5 = Z \$</span> so that firs 6 elements of the sequence are unique, except last the one which should be equal to the initial <span class="math-container">\$ Z \$</span>. In this case, lets say that initial pair <span class="math-container">\$ Z, C \$</span> forms a cycle of length 6.</p> <p>As you may notices, there is no solution in integer numbers <span class="math-container">\$ Z, C \in \mathbf{ℤ} \$</span>, but there may be solution in rational numbers.</p> <p>So, the final question I'm trying to answer: is there initial pair of rational numbers that forms a cycle of length 6 and which numerator and denominator doesn't exceeds 100 by module <span class="math-container">$$ Z = \frac{a}{b}, \; C = \frac{c}{d} \\ |a,c| \le 100 ,\; 0 \lt b,d \le 100 \\ a, b, c, d \in \mathbf{ℤ} $$</span></p> <pre class="lang-hs prettyprint-override"><code>import Control.Monad (liftM2) import Data.List import Data.Maybe import Data.Ratio import System.IO -- Returns list of unique normalized fractions where -- |numerator| &lt;= abs -- 0 &lt; denominator &lt;= abs genRange :: Integral a =&gt; a -&gt; [Ratio a] genRange abs = map head $ group $ sort $ liftM2 (%) numerator denominator where numerator = [(-abs)..abs] denominator = [1..abs] -- Returns list of initial values (Z, C) initials :: Integral a =&gt; a -&gt; [(Ratio a, Ratio a)] initials abs = liftM2 (,) zs cs where zs = genRange abs cs = filter (&lt;0) zs -- Returns sequence of values of fi, i=[1..] f :: Integral a =&gt; Ratio a -&gt; Ratio a -&gt; [Ratio a] f z c = [zn] ++ (f zn c) where zn = z ^ 2 + c -- Returns `Just pair`, if it forms a cycle of specified length hasCircleF :: (Integral a) =&gt; Int -&gt; (Ratio a, Ratio a) -&gt; Maybe (Ratio a, Ratio a) hasCircleF len pair | endsWith == z &amp;&amp; amountUnique == 6 = Just pair | otherwise = Nothing where (z, c) = pair circle = take len $ (f z c) endsWith = last $ circle amountUnique = length $ group $ sort circle collectMatches :: Integral a =&gt; [(Ratio a, Ratio a)] collectMatches = mapMaybe (hasCircleF 6) (initials 100) main :: IO () main = mapM_ (putStrLn . show) collectMatches </code></pre> <p>Currently, it takes half an hour on my machine.</p>
[]
[ { "body": "<p>By inspection, we can eliminate <span class=\"math-container\">\\$a = 0\\$</span> from the search, since that would result in <span class=\"math-container\">\\$f_i = C\\$</span> which yields a cycle of length 1.</p>\n<p>Since you are computing <span class=\"math-container\">\\$Z^2\\$</span>, we can immediately see <span class=\"math-container\">\\$f_0(\\frac{a}{b}) = f_0(\\frac{-a}{b})\\$</span> for any value of <span class=\"math-container\">\\$a \\gt 0\\$</span>, and the same sequence of values results. So instead of searching <span class=\"math-container\">\\$a &lt; 0\\$</span>, we can limit our sequence generation to <span class=\"math-container\">\\$a &gt; 0\\$</span>, and instead check <span class=\"math-container\">\\$f_5 = \\pm Z\\$</span> to account for the negative range. This cuts the search space in half, so should reduce your running time to just 15 minutes on your machine.</p>\n<hr />\n<p>For clarity, consider searching for a cycle length=3.</p>\n<p>At some point, your testing: <span class=\"math-container\">\\$a=1, b=4, c=-29, d=16\\$</span>, or <span class=\"math-container\">\\$|Z| = \\frac{1}{4}, C = \\frac{-29}{16}\\$</span> and discover:</p>\n<p><span class=\"math-container\">$$f_0 = -7/4$$</span>\n<span class=\"math-container\">$$f_1 = 5/4$$</span>\n<span class=\"math-container\">$$f_2 = -1/4$$</span></p>\n<p>Since <span class=\"math-container\">\\$|f_2| = |Z|\\$</span>, we've discovered a solution, but we haven't identified what the solution is yet.</p>\n<p>If <span class=\"math-container\">\\$f_2 \\gt 0\\$</span>, then <span class=\"math-container\">\\$Z = \\frac{a}{b}, C = \\frac{c}{d}\\$</span> is the solution.</p>\n<p>If <span class=\"math-container\">\\$f_2 \\lt 0\\$</span>, then <span class=\"math-container\">\\$Z = \\frac{-a}{b}, C = \\frac{c}{d}\\$</span> is the solution.</p>\n<p>Therefore, the solution actually is <span class=\"math-container\">\\$Z = \\frac{-1}{4}, C = \\frac{-29}{16}\\$</span></p>\n<p>This same process applies to your cycle=6 search, effectively testing <span class=\"math-container\">\\$a,b,c,d\\$</span> and <span class=\"math-container\">\\$-a,b,c,d\\$</span> simultaneously, and therefore cutting the search space in half.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T22:06:29.890", "Id": "519995", "Score": "0", "body": "All fractions are normalized, it is enough to filter denominators = 1. Z^2 removes sign, that is right, but it doesn't mean that sequence started from negative Z can not finish with itself. Can you prove that for any Z and C if circle started from Z of length N exists, then it exists for sequence started from -Z of same length?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T22:12:26.703", "Id": "519997", "Score": "0", "body": "If \\$f_5(\\frac{a}{b}) = \\frac{-a}{b}\\$, then \\$f_5(\\frac{-a}{b}) = \\frac{-a}{b}\\$ is the required solution, so all you need to find is an \\$a > 0\\$ such that \\$|f_5| = Z\\$." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T21:56:34.580", "Id": "263387", "ParentId": "263374", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T15:41:28.947", "Id": "263374", "Score": "1", "Tags": [ "performance", "haskell", "mathematics" ], "Title": "Find circles for `f(z, c) = z ^ 2 + c` of length 6 in rational numbers" }
263374
<p>I am working on a project, neurodecode, which uses a logger based on the <code>logging</code> library. As I am not very familiar with logging, I don't know how to further improve this aspect of the project.</p> <p>The project is constructed as:</p> <pre><code>neurodecode |_ __init__.py |_ logger.py |_ folder1 |_ script1.py |_ script2.py ... </code></pre> <p>The <code>logger.py</code> contains: (I removed the docstring to compact the code).</p> <pre><code>import sys import logging LOG_LEVELS = { 'DEBUG': logging.DEBUG, 'INFO': logging.INFO, 'WARNING': logging.WARNING, 'ERROR': logging.ERROR } def init_logger(logger, verbosity='INFO'): if not logger.hasHandlers(): logger.setLevel(verbosity) add_logger_handler(logger, sys.stdout, verbosity=verbosity) def add_logger_handler(logger, stream, verbosity='INFO'): c_handler = logging.StreamHandler(stream) c_handler.setFormatter(neurodecodeFormatter()) logger.addHandler(c_handler) set_log_level(logger, verbosity, -1) return logger def set_log_level(logger, verbosity, handler_id=0): logger.handlers[handler_id].level = LOG_LEVELS[verbosity] class neurodecodeFormatter(logging.Formatter): # Format string syntax for the different Log levels fmt_debug = &quot;[%(module)s:%(funcName)s:%(lineno)d] DEBUG: %(message)s (%(asctime)s)&quot; fmt_info = &quot;[%(module)s.%(funcName)s] %(message)s&quot; fmt_warning = &quot;[%(module)s.%(funcName)s] WARNING: %(message)s&quot; fmt_error = &quot;[%(module)s:%(funcName)s:%(lineno)d] ERROR: %(message)s&quot; def __init__(self, fmt='%(levelno)s: %(message)s'): super().__init__(fmt) def format(self, record): if record.levelno == LOG_LEVELS['DEBUG']: self._fmt = self.fmt_debug elif record.levelno == LOG_LEVELS['INFO']: self._fmt = self.fmt_info elif record.levelno == LOG_LEVELS['WARNING']: self._fmt = self.fmt_warning elif record.levelno &gt;= LOG_LEVELS['ERROR']: self._fmt = self.fmt_error self._style = logging.PercentStyle(self._fmt) return logging.Formatter.format(self, record) </code></pre> <p>And the <code>__init__.py</code> contains:</p> <pre><code>import logging from .logger import init_logger # set loggers logging.getLogger('matplotlib').setLevel(logging.ERROR) logger = logging.getLogger('neurodecode') logger.propagate = False init_logger(logger, verbosity='INFO') </code></pre> <p>First, do you see any improvements which could be made to those 2 parts? Maybe I could add <code>from .logger import set_log_level</code> to the <code>__init__.py</code> to be able to set the log level as <code>neurodecode.set_log_level()</code>.</p> <p>Second, in the different subfolders and scripts, I am using the logger as:</p> <pre><code>from pathlib import Path from .. import logger # relative import vary depending on the script class Foo: def __init__(self, param1, param2): self.param1 = str(param1) logger.info(f'Param1 set as {self.param1}') param2 = Foo._check_param2(param2) def method_to_do_stuff(self, n): try: # do stuff x = 2/n except Exception as error: logger.error('Something didn't work..') raise error @staticmethod def _check_param2(param2): # let's imagine it's a path -&gt; pathlib param2 = Path(param2) if not param2.exists(): logger.error('The path to param2 was not found') raise IOError </code></pre> <p>In this dummy example above, which sums up well most of my use case of the logger, I feel like I am not using it correctly. Shouldn't the logger catch the exception and the message attached directly, e.g. with <code>raise IOError('The path to param2 was not found')</code>?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-27T18:56:58.957", "Id": "520245", "Score": "0", "body": "See also https://stackoverflow.com/a/68154386/313768" } ]
[ { "body": "<p>Part of your interface accepts strings as levels, and you have a string-level mapping. Why? There are standard symbols available from the logging library for anyone to use. There is no advantage to passing around stringly-typed levels, and in fact the standard levels being integral is a feature. It's entirely possible for a user to want to pass in a level integer that does not have an entry in your map and it should still behave well. So I would suggest dropping your <code>LOG_LEVELS</code> entirely, accepting <code>verbosity: int</code> (for which you should have a type hint), and replacing this:</p>\n<pre><code> if record.levelno == LOG_LEVELS['DEBUG']:\n self._fmt = self.fmt_debug\n elif record.levelno == LOG_LEVELS['INFO']:\n self._fmt = self.fmt_info\n elif record.levelno == LOG_LEVELS['WARNING']:\n self._fmt = self.fmt_warning\n elif record.levelno &gt;= LOG_LEVELS['ERROR']:\n self._fmt = self.fmt_error\n</code></pre>\n<p>with something that respects ranges instead, i.e.</p>\n<pre><code>if record.levelno &lt;= logging.DEBUG:\n self._fmt = self.fmt_debug\nelif record.levelno &lt;= logging.INFO:\n self._fmt = self.fmt_info\nelif record.levelno &lt;= logging.WARNING:\n self._fmt = self.fmt_warning\nelse:\n self._fmt = self.fmt_error\n</code></pre>\n<p>That said, there are other problems with the above:</p>\n<ul>\n<li><code>neurodecodeFormatter</code> should be <code>NeurodecodeFormatter</code> by PEP8</li>\n<li>Rather than baking in <code>DEBUG: </code> etc. in your format string, just use <code>%(levelname)</code></li>\n<li><code>logging.Formatter.format(self, record)</code> should use <code>super()</code></li>\n<li>I question setting <code>self._fmt</code> and relying on it not to change while the super's implementation of <code>format()</code> uses it. I realize that's how the <a href=\"https://stackoverflow.com/a/14859558/313768\">accepted answer on SO does it</a>, but don't trust everything you read on SO. This introduces a concurrency vulnerability where two threaded calls to the same formatter will have unpredictable results - which <code>_fmt</code> assignment will win? You could either add a lock and keep doing what you're doing, which is not awesome; or you could keep surrogate formatter instances - one for every level - and call into them while avoiding mutating your own instance or theirs. I would recommend the latter.</li>\n</ul>\n<p>I recommend changing</p>\n<pre><code> try:\n # do stuff\n x = 2/n\n except Exception as error:\n logger.error('Something didn't work..')\n raise error\n</code></pre>\n<p>to</p>\n<pre><code> try:\n # do stuff\n x = 2/n\n except Exception:\n logger.error(&quot;Something didn't work..&quot;, exc_info=True)\n raise\n</code></pre>\n<p>There's no need to keep a reference to the exception at all; and you should be <a href=\"https://docs.python.org/3.8/library/logging.html#logging.debug\" rel=\"nofollow noreferrer\">including the stack trace</a>. Also your quote syntax was wrong.</p>\n<blockquote>\n<p>Shouldn't the logger catch the exception</p>\n</blockquote>\n<p>Absolutely not. Loggers are not for exception catching; they're for exception logging.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-27T18:05:14.580", "Id": "263521", "ParentId": "263376", "Score": "4" } } ]
{ "AcceptedAnswerId": "263521", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T16:10:37.363", "Id": "263376", "Score": "4", "Tags": [ "python", "python-3.x", "logging" ], "Title": "Improvements to logger and how to correctly use it" }
263376
<p>I made simple scripting language (interpreter) in C and now, I want to make my code better.</p> <p>Here is my code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #define TRUE (1 == 1) #define FALSE (1 == 0) #define FUNCTION_NAME_COUNT 2 #define FUNCTION_ARG_FUNCTION_NAME_COUNT 1 #define MAX_FUNCTION_NAME_LENGTH 247 #define MAX_FUNCTION_ARG_LENGTH 127 #define MAX_STRING_LENGTH 2048 char *itoa(int value, char *str, int base) { char *output; char *ptr; char *low; if (base &lt; 2 | base &gt; 36) { *str = '\0'; return str; } output = ptr = str; if (value &lt; 0 &amp; base == 10) { *ptr++ = '-'; } low = ptr; do { *ptr++ = &quot;zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz&quot;[35 + value % base]; value /= base; } while (value); *ptr-- = '\0'; while (low &lt; ptr) { char tmp = *low; *low++ = *ptr; *ptr-- = tmp; } return output; } char *strr(char *str, char *output, int x, int y) { int i; for (i = x + 1; i &lt; y; i++) { output[i - (x + 1)] = str[i]; } return output; } char *equstr(char *str, char *output) { int i = 0; while (str[i]) { output[i] = str[i]; i++; } return output; } void clear_str(char *str) { int i = 0; while (str[i]) { str[i] = '\0'; i++; } } int is_string(char *str) { if (str[0] == '&quot;' &amp; str[strlen(str) - 1] == '&quot;') { return TRUE; } else { return FALSE; } } int is_sint(char *str) { int i = 0; while (str[i]) { if (str[i] &gt;= '0' &amp; str[i] &lt;= '9') { return TRUE; } else { return FALSE; break; } } } void lang_prints(char *s) { char output[MAX_STRING_LENGTH] = &quot;\0&quot;; if (is_string(s)) { strr(s, output, 0, strlen(s) - 1); printf(&quot;%s\n&quot;, output); } } void lang_printi(int i) { printf(&quot;%d\n&quot;, i); } char *lang_arg_lens(char *s) { char *output = malloc(MAX_STRING_LENGTH); if (is_string(s)) { itoa(strlen(s) - 2, output, 10); return output; } } int main() { int i, j; char function_names[FUNCTION_NAME_COUNT][MAX_FUNCTION_NAME_LENGTH] = { &quot;prints&quot;, &quot;printi&quot; }; char function_arg_function_names[FUNCTION_ARG_FUNCTION_NAME_COUNT][MAX_FUNCTION_NAME_LENGTH] = { &quot;lens&quot; }; char input[MAX_STRING_LENGTH]; char function_name[MAX_FUNCTION_NAME_LENGTH] = &quot;\0&quot;; char function_arg[MAX_FUNCTION_ARG_LENGTH] = &quot;\0&quot;; char tmp_function_arg[MAX_FUNCTION_ARG_LENGTH] = &quot;\0&quot;; char function_arg_function_name[MAX_FUNCTION_NAME_LENGTH] = &quot;\0&quot;; char old_function_arg[MAX_FUNCTION_ARG_LENGTH] = &quot;\0&quot;; printf(&quot;&gt; &quot;); scanf(&quot;%s&quot;, input); for (i = 0; i &lt; FUNCTION_NAME_COUNT; i++) { clear_str(function_name); strr(input, function_name, -1, strlen(function_names[i])); strr(input, function_arg, strlen(function_names[i]), strlen(input) - 1); if (strcmp(function_name, function_names[i]) == FALSE) { if (input[strlen(function_name)] == '(' &amp; input[strlen(function_name) + strlen(function_arg) + 1] == ')') { for (j = 0; j &lt; FUNCTION_ARG_FUNCTION_NAME_COUNT; j++) { if (strcmp(old_function_arg, &quot;\0&quot;) == FALSE) { equstr(function_arg, old_function_arg); } clear_str(function_arg); clear_str(function_arg_function_name); strr(function_arg, function_arg_function_name, -1, strlen(function_arg_function_names[j])); strr(old_function_arg, function_arg, strlen(function_arg_function_names[j]), strlen(old_function_arg) - 1); strr(old_function_arg, function_arg_function_name, -1, strlen(function_arg_function_names[j])); if (strcmp(function_arg_function_name, function_arg_function_names[j]) == FALSE) { if (old_function_arg[strlen(function_arg_function_name)] == '(' &amp; old_function_arg[strlen(function_arg_function_name) + strlen(function_arg) + 1] == ')') { switch (j) { case 0: equstr(function_arg, tmp_function_arg); clear_str(function_arg); equstr(lang_arg_lens(tmp_function_arg), function_arg); break; } } } else { clear_str(function_arg); equstr(old_function_arg, function_arg); } } switch (i) { case 0: lang_prints(function_arg); break; case 1: if (is_sint(function_arg)) { lang_printi(atoi(function_arg)); } break; } } } } } </code></pre> <p>Here is the <a href="https://github.com/ArianKG/KGScript" rel="noreferrer">GitHub</a> repository of my scripting language.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T18:30:31.213", "Id": "519980", "Score": "2", "body": "Curious, why `#define TRUE (1 == 1)` instead of `true` from `<stdbool.h>`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T18:52:00.857", "Id": "519982", "Score": "1", "body": "@chux-ReinstateMonica Well, the latter is tied to a true boolean type. Whether that is good (proper type), bad (ABI), or doesn't matter..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T18:54:18.440", "Id": "519983", "Score": "8", "body": "A sample of the language being parsed would greatly improve this question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T12:21:12.743", "Id": "520025", "Score": "0", "body": "It would be helpful if you mention which C standard is targeted by your code. This matters stuff like stdbool.h." } ]
[ { "body": "<p><strong>Potential bug</strong></p>\n<p><code>str[strlen(str) - 1]</code> is <em>undefined behavior</em> when <code>str[0] == 0</code>. Instead use a <em>logical</em> AND.</p>\n<pre><code>// if (str[0] == '&quot;' &amp; str[strlen(str) - 1] == '&quot;') \nif (str[0] == '&quot;' &amp;&amp; str[strlen(str) - 1] == '&quot;')\n</code></pre>\n<p>Note <code>is_string(&quot;\\&quot;&quot;)</code> returns true.</p>\n<p><strong>Potential bug</strong></p>\n<p><code>int is_sint(char *str)</code> has no return value when <code>str[0] == 0</code>.</p>\n<p>Code is strange as it has a <code>while</code> loop but never iterates a second time.</p>\n<p><code>is_sint(&quot;-123&quot;)</code> returns false.</p>\n<p><strong>Design asymmetry</strong></p>\n<p><code>if (value &lt; 0 &amp; base == 10)</code> makes for base 10 a <em>special</em> case. Suggest <code>if (value &lt; 0)</code> instead and then make a companion <code>uitoa(unsigned value, char *str, int base)</code> for a sign-less version.</p>\n<p><strong>Consider <code>const</code> and <code>restrict</code></strong></p>\n<p>Both <code>const</code> (source does not changed) and <code>restrict</code> (referenced data only affected via this pointer) can make for faster code and wider application.</p>\n<p>Example:</p>\n<pre><code>// char *equstr(char *str, char *output)\nchar *equstr(const char * restrict str, char * restrict output)\n</code></pre>\n<p><strong>Use <code>stdbool.h</code></strong></p>\n<p>Rather than make up <code>TRUE/FASLE</code>, use <code>bool, true, false</code>.</p>\n<p><strong>Tighten up array initializations</strong></p>\n<p><code>\\0</code> not needed.</p>\n<pre><code>// char output[MAX_STRING_LENGTH] = &quot;\\0&quot;;\nchar output[MAX_STRING_LENGTH] = &quot;&quot;;\n</code></pre>\n<p><strong>Avoid buffer overflow</strong></p>\n<p><code>scanf(&quot;%s&quot;, input);</code> is worse than <code>gets()</code>. Use a <em>width</em> or research <code>fgets()</code>.</p>\n<p><strong>Use size</strong></p>\n<p><code>char *itoa(int value, char *str, int base)</code> belongs to the era when memory was expensive. Make more robust and safe string functions and pass in a <em>size</em> to avoid buffer overrun.</p>\n<p>I'd re-order with destination parameters on the left and use another name as <code>itoa()</code> is likely to collide with other code bases.</p>\n<pre><code>// char *itoa(int value, char *str, int base)\nchar *my_itoa(size_t str_size, char *str, int value, int base)\n</code></pre>\n<p><strong>Pedantic: Large string support</strong></p>\n<p><code>strr(char *str, char *output, int x, int y)</code> relies on the length of a string not exceeding <code>INT_MAX</code>. The length of a string may approach the potentially much larger <code>SIZE_MAX</code>.</p>\n<p>Does not apply with this <code>main()</code>, but consider code re-use.</p>\n<p><strong><code>|</code> vs. <code>||</code></strong></p>\n<p><code>if (base &lt; 2 || base &gt; 36)</code> is more idiomatic than <code>if (base &lt; 2 | base &gt; 36)</code>, yet makes no functional difference here.</p>\n<p><strong>Perhaps a shorter 0-9a-z string?</strong></p>\n<p>Include the usual suspects.</p>\n<pre><code>// Enough room INT_MIN as a binary string.\n#define MY_ITOA_BUF_SIZE (sizeof(int) * CHAR_BIT + 2)\n#define MY_ITOA_BASE_MIN 2\n#define MY_ITOA_BASE_MAX 36\n\n// Negative values result in a string beginning with a '-' for all bases\n//\nchar* my_itoa(size_t n, char *s, int i, int base) {\n char buf[MY_ITOA_BUF_SIZE];\n char *p = &amp;buf[sizeof buf - 1];\n assert(base &gt;= MY_ITOA_BASE_MIN &amp;&amp; base &lt;= MY_ITOA_BASE_MAX);\n\n *p = '\\0';\n int value = i &lt; 0 ? i : -i; // negative absolute value\n do {\n div_t qr = div(value, base);\n *(--p) = &quot;0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;[-qr.rem];\n value = qr.quot;\n } while (value);\n\n if (i &lt; 0) {\n *(--p) = '-';\n }\n\n size_t n_used = (size_t) (&amp;buf[sizeof buf] - p);\n // If not enough room\n if (n_used &gt; n) {\n if (n &gt; 0) {\n *s = '\\0';\n }\n return NULL;\n }\n return memcpy(s, p, n_used);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T16:18:10.197", "Id": "520043", "Score": "0", "body": "Perhaps you could mention `sscanf` and `sscanf_s` (C11 and up) explicitly in your point about `scanf`?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T18:51:59.677", "Id": "263381", "ParentId": "263377", "Score": "5" } }, { "body": "<h1><code>is_string</code></h1>\n<pre><code>int is_string(char *str)\n{\n return str[0] == '&quot;' &amp;&amp; str[strlen(str) - 1] == '&quot;';\n}\n</code></pre>\n<p>Instead of returning <code>TRUE</code> or <code>FALSE</code> (as mentioned in another answer, use <code>true</code> and <code>false</code>), simply return the expression as it resolves to a boolean value anyway. It makes your code shorter and easier to scan through.</p>\n<h1><code>is_sint</code></h1>\n<pre><code>int is_sint(char *str)\n{\n return str[0] &gt;= '0' &amp;&amp; str[0] &lt;= '9';\n}\n</code></pre>\n<p>Since the <code>while</code> loop doesn't iterate a second time, and <code>i</code> is never incremented, so we only need to evaluate the expression once, and not in the loop. Uses the same logic as above.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T20:05:35.580", "Id": "263382", "ParentId": "263377", "Score": "2" } }, { "body": "<h3>Boolean type</h3>\n<p>If you really want / need a boolean type, use <code>&lt;stdbool.h&gt;</code>. If you don't, just use an <code>int</code> as much prior code enshrines.<br />\nBut for the love of all, don't define your own <code>TRUE</code>. Remember that only null and zero are falsey, all else being truthy. Defining a constant invites comparison against it, which violates this convention imbued into the language itself.<br />\nDefining <code>FALSE</code> while also worrying at least won't lead to compiling code which is logically wrong. But that is all it has going for itself.</p>\n<h3>Boolean logic</h3>\n<p>If you have a boolean value to return, return it directly, don't branch on it and return literals. Unless you are paid by LoC, it's a pointless obfuscation.</p>\n<p>Unless you have a good reason, use boolean operators for boolean logic. Avoiding the short-circuiting is rarely important enough to use bitwise operators instead. And if you use it, remember it doesn't short-curcuit.</p>\n<h3>Dead code</h3>\n<p>Eliminate dead code to avoid confusing or irritating readers.<br />\nAfter <code>break</code>, <code>return</code>, and the like, additional code in the block without intervening jump-label (in general, <code>goto</code> is to be avoided, as you do) or <code>case</code>-label is unreachable.</p>\n<h3>Initialize on declaration</h3>\n<p>Unless you want to run under strict C89, (just about) all compilers support mixing declarations and statements, and if you ask for any optimization, the result is generally the same.\nEnhancing readability and just about eliminating the chance for a whole class of bugs for no cost is a bargain, right?</p>\n<p>See &quot;<a href=\"//stackoverflow.com/questions/27729930/is-declaration-of-variables-expensive\">Is declaration of variables expensive?</a>&quot;.</p>\n<h3>Help finding bugs</h3>\n<p>If <code>base</code> to <code>itoa()</code> is out-of-range, that is a programming-error which should be found and fixed in development, never to be seen in release-mode. <code>assert()</code> is designed for that.</p>\n<p>If you really want, you might kill the program in release too, trading efficiency for defense in depth, but don't ever silently swallow the error. Doing so makes debugging a nightmare.</p>\n<h3>Be <code>const</code>-correct</h3>\n<p>Doing so enables the compiler to help you find bugs, and makes functions more self-documenting.</p>\n<h3>Use <code>restrict</code> where appropriate</h3>\n<p>Doing so allows the compiler to assume memory is not aliased, eliminating potential dependencies and increasing efficiency, in addition to making functions more self-documenting.</p>\n<h3>Line-length</h3>\n<p>Long lines are hard to read, especially if they lead to wrapping by the editor or horizontal scrolling.<br />\n172 is really a bit much, below 80 would be best.</p>\n<p>String-literals are easily wrapped, as consecutive ones are merged by the compiler.</p>\n<h3>What is a string</h3>\n<p>A string is a sequence of non-nul elements including and terminated by the first nul element. <code>str@@</code>-functions are expected to handle strings, though there are infamous exceptions.</p>\n<h3>Single source of truth</h3>\n<p>The outer dimension of an array is sized according to the initializer if omitted. And you can get it back using <code>(sizeof *array / sizeof array)</code>.</p>\n<p>Unless there is a good reason to do otherwise, instead of an array of arrays of fixed length for storing string-literals, consider an array of pointers. It might be more efficient, and eliminates the forced fixed length.</p>\n<h3><code>switch</code> and single label</h3>\n<p>An if-statements seems much more appropriate, as it is simpler.</p>\n<h3>Appropriate types</h3>\n<p><code>size_t</code> is the designated type for object-sizes and array-indices. Unless you have a compelling reason, use it.</p>\n<h3>String length</h3>\n<p>Don't blindly assume strings are a minimum number of characters long. Empty strings exist, and out-of-bounds access is generally <em>Undefined Behavior</em>.</p>\n<h3>Additional comments for specific code</h3>\n<ol>\n<li><p>Why should <code>itoa()</code> only supply the minus-sign if the base is 10?<br />\nThat doesn't seem to make any sense.</p>\n</li>\n<li><p><code>strr()</code> is just bad.</p>\n<ul>\n<li>It looks more like a <code>mem</code>-function, as it doesn't treat the input as a string, nor outputs a string.</li>\n<li><code>r</code> for <code>reverse</code> is very cryptic. Just spell it out.</li>\n<li>Copying elements x to y both exclusive is a very surprising contract. If you don't use a single length-parameter as expected (the caller can adjust the source-pointer appropriately), I would expect the first to be inclusive.</li>\n</ul>\n</li>\n<li><p><code>equstr()</code> is also an acquired taste.</p>\n<ul>\n<li>It is not quite a string-function as it doesn't terminate the target.</li>\n<li>It really threw me for a loop that it modifies one argument, instead of comparing them, with the semantics of <code>!strcmp(a, b)</code>.</li>\n</ul>\n</li>\n<li><p><code>clear_str()</code></p>\n<ul>\n<li>nulling out all of a strings elements is rarely needed. Generally, just truncating it by setting the first element to zero is sufficient.</li>\n</ul>\n</li>\n<li><p><code>is_string()</code></p>\n<p>Are you sure anything starting with and ending with <code>&quot;</code> is a string according to your grammar?</p>\n<ul>\n<li>What about embedded <code>&quot;</code>?</li>\n<li>What about the length one string <code>&quot;\\&quot;&quot;</code>?</li>\n<li>What about escape-sequences?</li>\n</ul>\n</li>\n<li><p><code>is_sint()</code></p>\n<ul>\n<li>Ramp up the warning level. Your compiler should warn about the path without <code>return</code>-statement.</li>\n<li>Are you sure only the first character should be tested?</li>\n<li>Are you sure a signed integer must not be negative?</li>\n</ul>\n<p>When fixing that, don't screw up the empty string.</p>\n</li>\n<li><p><code>lang_arg_lens()</code></p>\n<ul>\n<li>Where is the dynamic memory allocated freed again?</li>\n<li><code>MAX_STRING_LENGTH</code> seems wasteful.</li>\n</ul>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T20:18:24.000", "Id": "263383", "ParentId": "263377", "Score": "3" } } ]
{ "AcceptedAnswerId": "263381", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T16:12:02.997", "Id": "263377", "Score": "5", "Tags": [ "c", "interpreter" ], "Title": "Simple scripting language (interpreter) in C" }
263377
<p>I have created <code>calculateMinimumAmount</code> to calculate the minimum buy/sell amount that exchange will allow the spot order to be placed based on the current price.</p> <p>The exchange I used (FTT) does not limit the minimum order amount by value (like Binance needed at least 10 USD per order) but by a token amount.</p> <p>For example: BTC is at <code>33,000 USD</code> so the minimum amount will be <code>0.0001 BTC</code> or <code>3.33 USD</code></p> <p>I can't find how they calculate the minimum order or what is this calculation called. So I guess:</p> <ul> <li>The minimum order value must greater than <code>1</code> but less than <code>10</code> USD</li> <li>(in conditions format) <code>value &gt; 1 &amp;&amp; value &lt; 10</code></li> </ul> <pre><code>const calculateMinimumAmount = (currentPrice: number) =&gt; { // Calculate amount that can be buy/sell with 10 USD const amountFor10 = 10 / currentPrice; // Round to first non-zero decimals digit - e.g. '0.000113112' -&gt; '0.0001' // https://stackoverflow.com/a/23887837/7405706 const decimalPlaces = Math.abs( Math.floor(Math.log(amountFor10) / Math.log(10)) ); // Modified from the linked answer to just only first non-zero digit let minimumAmount = amountFor10.toFixed(decimalPlaces); // Replace last character with 1 - e.g. '0.00003' -&gt; '0.00001' const replaceIndex = minimumAmount.length - 1; minimumAmount = minimumAmount.substring(0, replaceIndex) + '1' + minimumAmount.substring(replaceIndex + 1); const resultAmount = parseFloat(minimumAmount); return Math.min(resultAmount, 1); // Only the smallest amount }; </code></pre> <p>Here's the result - which I have verified the result in the exchange that all of them are correct</p> <pre><code>calculateMinimumAmount(33000); // BTC -&gt; 0.0001 calculateMinimumAmount(1983); // ETH -&gt; 0.001 calculateMinimumAmount(300); // BNB -&gt; 0.01 calculateMinimumAmount(128); // LTC -&gt; 0.01 calculateMinimumAmount(26.586); // FTT -&gt; 0.1 calculateMinimumAmount(2.939); // SRM -&gt; 1 calculateMinimumAmount(1.01); // USDT -&gt; 1 calculateMinimumAmount(1); // Ideal USDT -&gt; 1 calculateMinimumAmount(0.232857); // DOGE -&gt; 1 </code></pre> <p>I don't think this is not the best way to calculate it. Because it has string manipulation involved (which shouldn't present in a calculation, right?)</p> <hr /> <p><strong>Update:</strong></p> <p>I looked at the result and just figured out the relation of price digits and result in decimal places. So here's the updated version.</p> <p>I see that 5 digits will output 4 decimal places. So I count the digits and convert them into decimals. Much simpler.</p> <pre><code>const calculateMinimumAmount = (currentPrice: number) =&gt; { // Digits of currentPrice - e.g. 10000 -&gt; 5 digits // https://stackoverflow.com/a/14879700/7405706 const intDigits = (Math.log(currentPrice) * Math.LOG10E + 1) | 0; // Convert to the lowest amount in the digits - e.g. 33000 -&gt; 10000 const roundedInteger = 10 ** intDigits; // Covert to decimals - e.g. 10000 -&gt; 0.0001 const minimumAmount = 1 / (roundedInteger / 10); return Math.min(1, minimumAmount); // Only the smallest amount }; </code></pre> <p>But again, I'm not sure this is the best way to calculate this.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T17:46:03.230", "Id": "263380", "Score": "0", "Tags": [ "javascript", "algorithm", "typescript" ], "Title": "Calculate minimum buy/sell amount that exchange will allow the order to be placed based on current price" }
263380
<p>So I've just started teaching myself C++ a few weeks ago and I've decided to work on an implementation of Tic Tac Toe, using the command line. The program allows a human to play against a bot, which simply selects a random location on the board. I'm requesting a review because I'm not sure about a few things that I've done in the program, including the use of pointers, arrays, random number generator, and the general structure. I'm also not by any means an experienced programmer, hence the request for a general review. I strongly appreciate any advice. Thanks.</p> <pre><code>#include &lt;iostream&gt; #include &lt;stdlib.h&gt; using namespace std; #define row 3 #define col 3 void printBoard(char board[row][col]); void setBoard(char board[row][col]); void getInput(char board[row][col], int *rowInput, int *colInput); int bot(char board[row][col]); int game(char board[row][col]); int checkAvailable(char board[row][col], int rowInput, int colInput); int checkWinner(char board[row][col]); int main() { char board[row][col]; game(board); } int game(char board[row][col]) { int rowInput, colInput; setBoard(board); printBoard(board); // game loop while(checkWinner(board) == 0) { getInput(board, &amp;rowInput, &amp;colInput); printBoard(board); if (checkWinner(board) == 1) {cout &lt;&lt; &quot;X Wins!\n&quot;; break;} bot(board); printBoard(board); if (checkWinner(board) == -1) {cout &lt;&lt; &quot;O Wins!\n&quot;; break;} } return 0; } void printBoard(char board[row][col]) { // print board cout &lt;&lt; &quot;\n&quot;; for (int i = 0; i &lt; row; i++) { for (int j = 0; j &lt; col; j++) { cout &lt;&lt; board[i][j] &lt;&lt; &quot; &quot;; } cout &lt;&lt; &quot;\n&quot;; } } void setBoard(char board[row][col]) { // reset board for (int i = 0; i &lt; row; i++) { for (int j = 0; j &lt; col; j++) { board[i][j] = '0'; } } } int bot(char board[row][col]) { // bot playing against human int random = rand() % 9; int botRow = random/3; int botCol = random - botRow * 3; if(checkAvailable(board, botRow, botCol) == 1) { board[botRow][botCol] = 'O'; return 0; } else { bot(board); return 0; } } void getInput(char board[row][col], int *rowInput, int *colInput) { // get input from user (row and column) cout &lt;&lt; &quot;Enter row: &quot;; cin &gt;&gt; *rowInput; (*rowInput)--; cout &lt;&lt; &quot;Enter column: &quot;; cin &gt;&gt; *colInput; (*colInput)--; if(checkAvailable(board, *rowInput, *colInput) == -1) { getInput(board, rowInput, colInput); } else { board[*rowInput][*colInput] = 'X'; } } int checkAvailable(char board[row][col], int rowInput, int colInput) { // check if square is available if (board[rowInput][colInput] == '0') {return 1;} else {return -1;} return 0; } int checkWinner(char board[row][col]) { // check if there has been a winner // rows for (int i = 0; i &lt; row; i++) { if (board[i][0] == 'X' &amp;&amp; board[i][1] == 'X' &amp;&amp; board[i][2] == 'X') {return 1;} if (board[i][0] == 'O' &amp;&amp; board[i][1] == 'O' &amp;&amp; board[i][2] == 'O') {return -1;} } // columns for (int i = 0; i &lt; row; i++) { if (board[0][i] == 'X' &amp;&amp; board[1][i] == 'X' &amp;&amp; board[2][i] == 'X') {return 1;} if (board[0][i] == 'O' &amp;&amp; board[1][i] == 'O' &amp;&amp; board[2][i] == 'O') {return -1;} } // diagonals if (board[0][0] == 'X' &amp;&amp; board[1][1] == 'X' &amp;&amp; board[2][2] == 'X') {return 1;} if (board[0][0] == 'O' &amp;&amp; board[1][1] == 'O' &amp;&amp; board[2][2] == 'O') {return -1;} if (board[2][0] == 'X' &amp;&amp; board[1][1] == 'X' &amp;&amp; board[0][2] == 'X') {return 1;} if (board[2][0] == 'O' &amp;&amp; board[1][1] == 'O' &amp;&amp; board[0][2] == 'O') {return -1;} return 0; } </code></pre>
[]
[ { "body": "<h1>General Observations</h1>\n<h2>The Good</h2>\n<p>No global variables!<br />\nNice consistent indentation.<br />\nGood use of functions.</p>\n<h2>Could be Better</h2>\n<p>The code looks too much like C and not enough like C++. There is no use of C++ container classes such as <a href=\"https://en.cppreference.com/w/cpp/container/array\" rel=\"nofollow noreferrer\">std::array</a> or <a href=\"https://en.cppreference.com/w/cpp/container/vector\" rel=\"nofollow noreferrer\">std::vector</a>. This would allow you to use iterators rather than raw pointers.</p>\n<p>The bot could be smarter. I would start by taking the center cell if the human didn't take it first.</p>\n<h1>Avoid <code>using namespace std;</code></h1>\n<p>If you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifier<code>cout</code> you may override within your own classes, and you may override the operator <code>&lt;&lt;</code> in your own classes as well. This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow question</a> discusses this in more detail.</p>\n<h1>Constants in C++</h1>\n<p>The preferred method for constants in C++ is to use a <a href=\"https://en.cppreference.com/w/cpp/language/constexpr\" rel=\"nofollow noreferrer\">constexpr</a> variable rather than a <code>#define</code>.</p>\n<pre><code>constexpr int row = 3;\nconstexpr int col = 3;\n</code></pre>\n<p><code>#define</code> is still used in <code>#if CONSTANT #endif</code>.</p>\n<h1>Code Organization</h1>\n<p>Function prototypes are very useful in large programs that contain multiple source files, and that case they will be in header files. In a single file program like this it is better to put the <code>main()</code> function at the bottom of the file and all the functions that get used in the proper order above <code>main()</code>. Keep in mind that every line of code written is another line of code where a bug can crawl into the code.</p>\n<h1>Always Initialize Variables</h1>\n<p>In the <code>game()</code> function the variables <code>rowInput</code> and <code>colInput</code> are declared but they are not initialized. C++ does not do default initialization of variables and this can lead to use of undefined variables. Always initialize variables when they are declared. Declare and initialize one variable per line to make the code easier to maintain.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T07:32:17.970", "Id": "520013", "Score": "0", "body": "Taking the centre cell is exactly the wrong thing to do if the only play made so far is in a corner. The human will then take the opposite corner, and then always has the threat of taking a third corner and creating two positions to defend." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T22:10:01.853", "Id": "263388", "ParentId": "263385", "Score": "3" } } ]
{ "AcceptedAnswerId": "263388", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-23T20:57:23.893", "Id": "263385", "Score": "3", "Tags": [ "c++", "beginner", "tic-tac-toe" ], "Title": "A TicTacToe command line game in c++" }
263385
<p>I'm writing a (compile-time-)fixed-width unsigned big integer. To implement subtraction, a subtract-with-borrow primitive is required. When efficient platform-specific implementation isn't available (e.g. x86_64's <code>_subborrow_u64</code> intrinsic), it needs to be implemented in Standard C++.</p> <p>I've been able to come up with the following implementation:</p> <pre><code>#include &lt;stdint.h&gt; inline auto subtract_with_borrow( uint64_t&amp; result, uint64_t left, uint64_t right, uint64_t borrow /* only 0 or 1 */) -&gt; uint64_t /* borrow */ { result = left - right - borrow; return (left &lt; right) | ((left == right) &amp; borrow); } </code></pre> <p>However, I suspect it might be suboptimal since it requires roughly twice as many operations as add-with-carry (don't review it):</p> <pre><code>inline auto add_with_carry( uint64_t&amp; result, uint64_t left, uint64_t right, uint64_t carry /* only 0 or 1 */) -&gt; uint64_t /* carry */ { result = left + right; uint64_t next_carry = result &lt; left; result += carry; return next_carry; } </code></pre> <p>I intuitively expect a certain symmetry to exist here. Can <code>subtract_with_borrow</code> be simplified further? Or is my intuition wrong and this is indeed the optimal implementation?</p> <p>And no, the compiler optimization doesn't manage to magically transform it into a better version.</p>
[]
[ { "body": "<p>Your intuition is correct, but the issue is that your add_with_carry lacks the carry propagation in subtract_with_borrow.</p>\n<p>That's a general observation - if the new code looks more complicated than the old code, you should also consider that the old code lacked something.</p>\n<p>Consider the call add_with_carray(0,2^64-1,1):</p>\n<pre><code> result=0+(2^64-1); // 2^64-1\n next_carry=(2^64-1)&lt;0; // False\n result+=1; // causing result=0; due to overflow\n return next_carry; // 0\n</code></pre>\n<p>In general you should test such routines for carry=0,1 and left, right close to 0 and 2^64-1</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T08:11:05.247", "Id": "263396", "ParentId": "263389", "Score": "3" } }, { "body": "<p>Prefer to use the C++ <code>&lt;cstdint&gt;</code> header that puts identifiers in the correct namespace, rather than the deprecated C-compatibility header. This is particularly important in header files, as these affect every translation unit that uses them.</p>\n<blockquote>\n<pre><code> uint64_t carry /* only 0 or 1 */)\n</code></pre>\n</blockquote>\n<p>I dislike that comment style. Because the comment is almost, but not quite, at the end of line, it's very easy to miss the <code>)</code> hiding there, and mis-parse.</p>\n<p>If <code>carry</code> can only be 0 or 1, does it really make sense to pass as a 64-bit type? Certainly the bitwise arithmetic to create the carry-out is unlikely to create better code than plain logic <code>&amp;&amp;</code> and <code>||</code> (any decent compiler can avoid unnecessary jumps because none of the operands have side-effects).</p>\n<p>The test cases seem to have missed an important case in <code>add_with_carry()</code> (I know you said not to review that, but it's relevant for the subtract function):</p>\n<pre><code>#include &lt;gtest/gtest.h&gt;\n\nTEST(add_with_carry, ci_causes_co)\n{\n uint64_t small = 0;\n uint64_t big = ~small;\n uint64_t result;\n EXPECT_EQ(add_with_carry(result, small, big, 0), 0);\n EXPECT_EQ(result, big);\n EXPECT_EQ(add_with_carry(result, small, big, 1), 1);\n EXPECT_EQ(result, 0);\n}\n</code></pre>\n<p>The corresponding test of subtraction succeeds:</p>\n<pre><code>TEST(subtract_with_borrow, ci_causes_co)\n{\n uint64_t small = 0;\n uint64_t big = ~small;\n uint64_t result;\n EXPECT_EQ(subtract_with_borrow(result, 0, 0, 0), 0);\n EXPECT_EQ(result, 0);\n EXPECT_EQ(subtract_with_borrow(result, 0, 0, 1), 1);\n EXPECT_EQ(result, big);\n}\n</code></pre>\n<p>So the two functions are not directly comparable. It's a shame you didn't include the tests for review - given that you've missed probably the most important boundary case, then the testing may well be deficient in other ways too.</p>\n<p>To make the tests pass, I needed to make the logic of the two functions equivalent to each other:</p>\n<pre><code>static\nauto subtract_with_borrow(uint64_t&amp; result,\n uint64_t left, uint64_t right,\n bool borrow)\n{\n result = left - right - borrow;\n return left &lt; right || left == right &amp;&amp; borrow;\n}\n\nstatic\nauto add_with_carry(uint64_t&amp; result,\n uint64_t left, uint64_t right,\n bool carry)\n{\n result = left + right + carry;\n return left &gt; ~right || left == ~right &amp;&amp; carry;\n}\n</code></pre>\n<p>Now that both tests pass, the corresponding assembly outputs look very similar to each other.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T11:49:35.853", "Id": "520020", "Score": "2", "body": "I disagree about `<cstdint>`. I believe that `[u]intN_t` should've been fundamental types like `int`, and the fact that they are implemented as typedefs is a historical mistake. When considered like that, putting them into `std` doesn't make much sense." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T12:12:34.763", "Id": "520024", "Score": "0", "body": "You are correct about my `add_with_carry` being broken, of course. But I believe an implementation exactly symmetric with `subtract_with_borrow` would be `result = left + right + carry; return result < left || result == left && carry;`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T12:49:50.030", "Id": "520026", "Score": "1", "body": "You could do it that way, and change `subtract_with_borrow` to match. It's arguably better to not use `result` in computing the return value, though, as that allows more parallelism in a superscalar CPU." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T12:50:18.090", "Id": "520027", "Score": "0", "body": "I'm not convinced that _optional_ types could, never mind should, have been fundamental!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T11:34:21.233", "Id": "263402", "ParentId": "263389", "Score": "2" } } ]
{ "AcceptedAnswerId": "263396", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T01:18:08.347", "Id": "263389", "Score": "1", "Tags": [ "c++", "performance", "algorithm", "integer", "c++20" ], "Title": "Unsigned 64bit subtract-with-borrow in Standard C++" }
263389
<p>This code scrapes <a href="http://www.oddsportal.com" rel="nofollow noreferrer">www.oddsportal.com</a> for all the URLs provided in the code and appends it to a dataframe.</p> <p>I am not very well versed with iterative logic hence I am finding it difficult to improvise on it.</p> <p>Code:</p> <pre><code>import pandas as pd from selenium import webdriver from bs4 import BeautifulSoup as bs browser = webdriver.Chrome() class GameData: def __init__(self): self.date = [] self.time = [] self.game = [] self.score = [] self.home_odds = [] self.draw_odds = [] self.away_odds = [] self.country = [] self.league = [] def parse_data(url): browser.get(url) df = pd.read_html(browser.page_source, header=0)[0] html = browser.page_source soup = bs(html, &quot;lxml&quot;) cont = soup.find('div', {'id': 'wrap'}) content = cont.find('div', {'id': 'col-content'}) content = content.find('table', {'class': 'table-main'}, {'id': 'tournamentTable'}) main = content.find('th', {'class': 'first2 tl'}) if main is None: return None count = main.findAll('a') country = count[1].text league = count[2].text game_data = GameData() game_date = None for row in df.itertuples(): if not isinstance(row[1], str): continue elif ':' not in row[1]: game_date = row[1].split('-')[0] continue game_data.date.append(game_date) game_data.time.append(row[1]) game_data.game.append(row[2]) game_data.score.append(row[3]) game_data.home_odds.append(row[4]) game_data.draw_odds.append(row[5]) game_data.away_odds.append(row[6]) game_data.country.append(country) game_data.league.append(league) return game_data urls = { &quot;https://www.oddsportal.com/soccer/england/premier-league/results/#/page/1&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league/results/#/page/2&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league/results/#/page/3&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league/results/#/page/4&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league/results/#/page/5&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league/results/#/page/6&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league/results/#/page/7&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league/results/#/page/8&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league/results/#/page/9&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league-2019-2020/results/#/page/1&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league-2019-2020/results/#/page/2&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league-2019-2020/results/#/page/3&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league-2019-2020/results/#/page/4&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league-2019-2020/results/#/page/5&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league-2019-2020/results/#/page/6&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league-2019-2020/results/#/page/7&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league-2019-2020/results/#/page/8&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league-2019-2020/results/#/page/9&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league-2018-2019/results/#/page/1&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league-2018-2019/results/#/page/2&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league-2018-2019/results/#/page/3&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league-2018-2019/results/#/page/4&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league-2018-2019/results/#/page/5&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league-2018-2019/results/#/page/6&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league-2018-2019/results/#/page/7&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league-2018-2019/results/#/page/8&quot;, &quot;https://www.oddsportal.com/soccer/england/premier-league-2018-2019/results/#/page/9&quot;, } if __name__ == '__main__': results = None for url in urls: game_data = parse_data(url) if game_data is None: continue result = pd.DataFrame(game_data.__dict__) if results is None: results = result else: results = results.append(result, ignore_index=True) print(results) | | date | time | game | score | home_odds | draw_odds | away_odds | country | league | |-----|-------------|--------|----------------------------------|---------|-------------|-------------|-------------|-----------|--------------------------| | 0 | 12 May 2019 | 14:00 | Brighton - Manchester City | 1:4 | 14.95 | 7.75 | 1.2 | England | Premier League 2018/2019 | | 1 | 12 May 2019 | 14:00 | Burnley - Arsenal | 1:3 | 2.54 | 3.65 | 2.75 | England | Premier League 2018/2019 | | 2 | 12 May 2019 | 14:00 | Crystal Palace - Bournemouth | 5:3 | 1.77 | 4.32 | 4.22 | England | Premier League 2018/2019 | | 3 | 12 May 2019 | 14:00 | Fulham - Newcastle | 0:4 | 2.45 | 3.55 | 2.92 | England | Premier League 2018/2019 | | 4 | 12 May 2019 | 14:00 | Leicester - Chelsea | 0:0 | 2.41 | 3.65 | 2.91 | England | Premier League 2018/2019 | | 5 | 12 May 2019 | 14:00 | Liverpool - Wolves | 2:0 | 1.31 | 5.84 | 10.08 | England | Premier League 2018/2019 | | 6 | 12 May 2019 | 14:00 | Manchester Utd - Cardiff | 0:2 | 1.3 | 6.09 | 9.78 | England | Premier League 2018/2019 | </code></pre> <p>As you can see the URLs can be optimised to run through all pages in that league/branch</p> <p><a href="https://i.stack.imgur.com/qW3LL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qW3LL.png" alt="Inspect element" /></a></p> <p>How can I optimise this code to iteratively run for every page?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T12:55:51.130", "Id": "520028", "Score": "2", "body": "Asking for this code to be reviewed is fine, but asking for net new features to be added is off topic" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T15:52:24.713", "Id": "520039", "Score": "0", "body": "Also this code actually just won't run. You have what appear to be string literals that are unquoted. Also you haven't shown your imports." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T22:28:03.720", "Id": "520061", "Score": "0", "body": "@PyNoob https://codereview.stackexchange.com/questions/263433/scraping-oddsportal-with-requests-only" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T22:57:16.503", "Id": "520062", "Score": "0", "body": "@Reinderien I am not asking for new features to be built. Apologies if it feels that way. I thought my question explained otherwise." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T23:56:01.823", "Id": "520063", "Score": "0", "body": "@Reinderien Yep, apologies, I agree the code did not have imports. I have edited the code. I have also posted an example output. Thanks a ton. Please help to optimise it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-25T00:38:55.840", "Id": "520069", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/126837/discussion-between-pynoob-and-reinderien)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-25T00:54:05.397", "Id": "520070", "Score": "0", "body": "@Reinderien I have edited the title. Is is satisfactory?" } ]
[ { "body": "<ul>\n<li>It seems that <code>GameData</code> is meant to house multiple games, with lists for each attribute. You should re-represent this as a list of <code>GameData</code> instances where each instance has a scalar for each attribute and not a list.</li>\n<li>Using Selenium is not out of the question, here, but Requests will be faster. However, to do this you need to perform reverse engineering to understand some of the silly things that the web page designers did, like a character substitution cipher on odds figures.</li>\n<li>Why are you using Pandas? If it's only for printing data, there's no need for it.</li>\n<li>First realize that <code>urls</code> is a set, where you want a sequence instead. You should be restructuring your code to accept a sport, country, year range and page range, and generating those URLs as part of the routine.</li>\n</ul>\n<p>A suggested scraping program for these data exists here: <a href=\"https://codereview.stackexchange.com/questions/263433/scraping-oddsportal-with-requests-only\">Scraping OddsPortal with requests only</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-25T14:02:35.960", "Id": "263454", "ParentId": "263390", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T05:07:09.590", "Id": "263390", "Score": "-1", "Tags": [ "python", "performance", "iterator", "beautifulsoup" ], "Title": "Scraping odds portal with beautiful soup" }
263390
<p>This project is the natural extension to <a href="https://codereview.stackexchange.com/questions/263265/c20-coroutine-generator">my attempt to make a templated<code>generator</code> coroutine</a>. This time, I tried what I called a &quot;<code>task</code>&quot; (may be not the real term for this) : it generates a value or not, and is recursively awaitable. It can call other coroutines which each pause will also pause the main coroutine. It was really difficult to implement recursion, and I wonder if there is a better option, like one bundled with coroutine support directly. My first attempt was to make a variable <code>innerCoroutine</code> but I think it suffers from performances issues because when there is, like 100 coroutines on the stack, each call will recursively try to found the most inner coroutine, and with this method each <code>resume()</code> call is 0(1). I tested with unit cases, so there was many trials until all tests passes so it may be a bit complicated. I wonder if is it okay, especially from the point of view of undefined behavior and memory leaks.</p> <p>When I started learning C++ coroutines, I found them overly unnecessary complicated, but I think I begin to figure out they are not that complicated, and highly powerful and customizable, at least I hope.</p> <p><a href="https://godbolt.org/z/Wf78bq3Eo" rel="nofollow noreferrer">Godbolt link</a></p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;coroutine&gt; #include &lt;optional&gt; #include &lt;cassert&gt; #include &lt;memory&gt; #include &lt;vector&gt; #include &lt;iostream&gt; struct promise_type_vars { using stack = std::vector&lt;std::coroutine_handle&lt;&gt;&gt;; std::shared_ptr&lt;stack&gt; stack_; }; template&lt;typename self&gt; struct promise_type_base : promise_type_vars { using promise_type = typename self::promise_type; std::suspend_always initial_suspend() { return {}; } std::suspend_always final_suspend() noexcept { return {}; } [[noreturn]] void unhandled_exception() { throw; } self get_return_object() { return {std::coroutine_handle&lt;promise_type&gt;::from_promise(static_cast&lt;promise_type&amp;&gt;(*this))}; } }; template&lt;typename T&gt; struct add_reference { using type = T&amp;; }; template&lt;&gt; struct add_reference&lt;void&gt; { using type = void; }; template&lt;typename T&gt; using add_reference_t = typename add_reference&lt;T&gt;::type; template&lt;typename T = void&gt; class task { static constexpr bool is_void = std::is_same_v&lt;T, void&gt;; public: struct promise_type_nonvoid : promise_type_base&lt;task&gt; { std::optional&lt;T&gt; t_; void return_value(T t) { t_ = std::move(t); this-&gt;stack_-&gt;pop_back(); } }; struct promise_type_void : promise_type_base&lt;task&gt; { void return_void() { this-&gt;stack_-&gt;pop_back(); } }; struct promise_type : std::conditional_t&lt;is_void, promise_type_void, promise_type_nonvoid&gt; { using stack = promise_type_vars::stack; }; private: std::coroutine_handle&lt;promise_type&gt; h_; public: task(std::coroutine_handle&lt;promise_type&gt; h) : h_(h) { h_.promise().stack_ = std::make_shared&lt;typename promise_type::stack&gt;(); h_.promise().stack_-&gt;push_back(h_); } task(const task&amp;) = delete; task&amp; operator=(const task&amp;) = delete; task(task&amp;&amp; other) { swap(h_, other.h_); } task&amp; operator=(task&amp;&amp; other) { swap(h_, other.h_); return *this; } ~task() { if(h_) { h_.destroy(); h_ = {}; } } bool is_resumable() const { return h_ &amp;&amp; !h_.done(); } bool operator()() { return resume(); } auto&amp; stack() const { return *h_.promise().stack_; } bool resume() { assert(is_resumable()); auto&amp; s = *h_.promise().stack_; auto back = s.back(); back.resume(); //execute suspended point // at this point, back and s.back() could be different if(back.done()) { if(s.size() &gt; 0) { // Not root, execute co_await return expression resume(); } else { if constexpr(!is_void) { assert(h_.promise().t_ &amp;&amp; &quot;Should return a value to caller&quot;); } } } return is_resumable(); } // Make co_await'able (allow recursion and inner task as part of the parent task) ------------------------ bool await_ready() const { return false; } template&lt;typename X&gt; bool await_suspend(std::coroutine_handle&lt;X&gt;&amp; p) { // --- stack push h_.promise().stack_ = p.promise().stack_; p.promise().stack_-&gt;push_back(h_); // --- h_(); // never wait an inner function whether initially or finally (initially managed here) if(!h_.done()) { // the inner coroutine has at least one suspend point return true; } else { return false; // don't wait if the coroutine is already ended (coroutine is NOOP) } } T await_resume() { if constexpr(!is_void) { assert(h_.promise().t_ &amp;&amp; &quot;Should return a value in a co_wait expression&quot;); return get(); } } add_reference_t&lt;T&gt; get() { if constexpr(!is_void) { return h_.promise().t_.value(); } } }; task&lt;double&gt; one() { std::cout &lt;&lt; &quot;one takes a coffee&quot; &lt;&lt; std::endl; co_await std::suspend_always{}; co_return 1; } task&lt;&gt; noop() { std::cout &lt;&lt; &quot;the noop does something&quot; &lt;&lt; std::endl; co_return; } task&lt;short&gt; two() { co_return co_await one() + co_await one(); } task&lt;int&gt; foo() { int i = 0; i += co_await one(); std::cout &lt;&lt; &quot;foo just run one()&quot; &lt;&lt; std::endl; i += co_await two(); std::cout &lt;&lt; &quot;foo just run two()&quot; &lt;&lt; std::endl; std::cout &lt;&lt; &quot;foo makes a pause after his work&quot; &lt;&lt; std::endl; co_await std::suspend_always{}; co_await noop(); co_return i; } int main() { auto handle = foo(); for(int i = 1; handle(); ++i) { std::cout &lt;&lt; i &lt;&lt; &quot;. hi from main&quot; &lt;&lt; std::endl; } std::cout &lt;&lt; &quot;Result: &quot; &lt;&lt; handle.get() &lt;&lt; std::endl; return 0; } </code></pre> <p>Output :</p> <pre><code>one takes a coffee 1. hi from main foo just run one() one takes a coffee 2. hi from main one takes a coffee 3. hi from main foo just run two() foo makes a pause after his work 4. hi from main the noop does something Result: 3 </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T05:31:31.313", "Id": "263391", "Score": "3", "Tags": [ "c++", "c++20" ], "Title": "C++20 Coroutine Task" }
263391
<p>I am trying to implement a shopping cart using redux-saga. The following code is working fine. But it does not look right to me. I am mutating the cart whenever I am adding the product. Let me know if I can improve the code. If this is the case.</p> <pre><code>import { takeEvery, put } from 'redux-saga/effects'; import * as actions from '../action/saga.js'; function* cart(action) { const { product, onSuccess, onError } = action.payload; let cart = []; if (typeof window !== 'undefined') { if (localStorage.getItem('cart')) { cart = JSON.parse(localStorage.getItem('cart')); } const duplicate = cart.find( (item) =&gt; item._id === product._id ); if (!duplicate) { cart.push({ ...product, count: 1, }); } else { cart = cart.map((item) =&gt; item._id === product._id ? { ...item, count: item.count + 1 } : item ); } localStorage.setItem('cart', JSON.stringify(cart)); } try { if (onSuccess) yield put({ type: onSuccess, payload: { cart: cart }, }); } catch (error) { if (onError) yield put({ type: onError, payload: error.message }); } } export function* watchCart() { yield takeEvery(actions.sagaCartCallBegan.type, cart); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T07:48:08.577", "Id": "263394", "Score": "0", "Tags": [ "javascript", "react.js", "redux" ], "Title": "Mutating the shopping cart using redux-saga" }
263394
<p>I have two lists, I need to make another list with the same elements than the other lists. But elements on this list need the next sequence.</p> <blockquote> <p>list1[0], list2[0], list1[1], list2[1], ... and so on</p> </blockquote> <p>for that, I made this code.</p> <pre><code>List&lt;string&gt; list1 = new List&lt;string&gt; { &quot;rabbit&quot;, &quot;dog&quot;, &quot;cat&quot;, &quot;shark&quot; }; List&lt;string&gt; list2 = new List&lt;string&gt; { &quot;red&quot;, &quot;blue&quot;, &quot;green&quot;, &quot;black&quot; }; var mixStuff = list1.Zip(list2, (c, a) =&gt; new { colors = c, animals = a }); List&lt;string&gt; newThings = new List&lt;string&gt;(); foreach(var mix in mixStuff) { newThings.Add(mix.colors); newThings.Add(mix.animals); } </code></pre> <p>I wonder if is there any way to do this better/cleaner. Thanks!</p>
[]
[ { "body": "<p>The simplest solution I can think of</p>\n<pre><code>var interleavingMergedLists = list1\n .Zip(list2, (lhs, rhs) =&gt; new[] {lhs, rhs})\n .SelectMany(l =&gt; l)\n .ToList(); \n</code></pre>\n<ol>\n<li>Rather than creating a new anonymous object / ValueTuple instead create an array.</li>\n<li>Then you can flatten that array with the <code>SelectMany</code></li>\n<li>And finally you can materialize your query with <code>ToList</code></li>\n</ol>\n<hr />\n<p>Please note that this works fine only if both lists have the same size.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T16:23:38.337", "Id": "520045", "Score": "1", "body": "Sorry for the delayed response, I wasn't at home. Thanks a lot for your reply!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T11:55:39.020", "Id": "263404", "ParentId": "263397", "Score": "3" } }, { "body": "<p>This is a great opportunity to write your own extension method to merge <code>IEnumerable</code>s</p>\n<pre><code>\npublic static class EnumerableMergeExtension\n{\n public static IEnumerable&lt;TSource&gt; Merge&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; first, IEnumerable&lt;TSource&gt; second)\n {\n if (first is null) throw new ArgumentNullException(nameof(first));\n if (second is null) throw new ArgumentNullException(nameof(second));\n \n return MergeIterator(first, second);\n }\n \n private static IEnumerable&lt;TSource&gt; MergeIterator&lt;TSource&gt;(IEnumerable&lt;TSource&gt; first, IEnumerable&lt;TSource&gt; second)\n {\n using var firstEnumerator = first.GetEnumerator();\n using var secondEnumerator = second.GetEnumerator();\n \n var firstHasNext = firstEnumerator.MoveNext();\n var secondHasNext = secondEnumerator.MoveNext();\n do\n {\n if (firstHasNext)\n {\n yield return firstEnumerator.Current;\n firstHasNext = firstEnumerator.MoveNext();\n }\n if (secondHasNext)\n {\n yield return secondEnumerator.Current;\n secondHasNext = secondEnumerator.MoveNext();\n }\n }\n while (firstHasNext || secondHasNext);\n }\n}\n \n</code></pre>\n<p>By manually advancing the enumerators you can handle enumerables of different lengths, even empty enumerables.\nThe function is split in two to ensure eager parameter validation and lazy enumeration.</p>\n<p>It's also possible to extend <code>Merge</code> to handle any number of enumerables without having to chain <code>Zip</code></p>\n<pre><code>\npublic static class EnumerableMergeExtension\n{\n public static IEnumerable&lt;TSource&gt; Merge&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; first, params IEnumerable&lt;TSource&gt;[] rest)\n {\n if (first is null) throw new ArgumentNullException(nameof(first));\n if (rest is null) throw new ArgumentNullException(nameof(rest));\n \n var enumerables = new IEnumerable&lt;TSource&gt;[rest.Length + 1];\n enumerables[0] = first;\n for(int i = 0; i &lt; rest.Length; i++)\n {\n enumerables[i+1] = rest[i] ?? throw new ArgumentNullException(string.Format(&quot;{0}[{1}]&quot;, nameof(rest), i));\n }\n \n return MergeIterator(enumerables);\n }\n \n private static IEnumerable&lt;TSource&gt; MergeIterator&lt;TSource&gt;(IEnumerable&lt;TSource&gt;[] sources)\n {\n var enumerators = new IEnumerator&lt;TSource&gt;[sources.Length];\n try\n {\n for(int i = 0; i &lt; sources.Length; i++)\n {\n enumerators[i] = sources[i].GetEnumerator();\n }\n \n var hasNexts = new bool[enumerators.Length];\n \n bool MoveNexts()\n {\n var anyHasNext = false;\n for (int i = 0; i &lt; enumerators.Length; i++)\n {\n anyHasNext |= hasNexts[i] = enumerators[i].MoveNext();\n }\n return anyHasNext;\n }\n \n while(MoveNexts())\n {\n for (int i = 0; i &lt; enumerators.Length; i++)\n {\n if(hasNexts[i])\n {\n yield return enumerators[i].Current;\n }\n }\n }\n }\n finally\n {\n foreach (var enumerator in enumerators)\n {\n enumerator?.Dispose();\n }\n }\n }\n}\n\n</code></pre>\n<p>And now you can merge an additional list</p>\n<pre><code>\nList&lt;string&gt; list1 = new List&lt;string&gt; { &quot;rabbit&quot;, &quot;dog&quot;, &quot;cat&quot;, &quot;shark&quot; };\nList&lt;string&gt; list2 = new List&lt;string&gt; { &quot;red&quot;, &quot;blue&quot;, &quot;green&quot;, &quot;black&quot; };\nList&lt;string&gt; list3 = new List&lt;string&gt; { &quot;tiny&quot;, &quot;medium&quot;, &quot;small&quot;, &quot;huge&quot;, &quot;none&quot; };\n\n//rabbit, red, dog, blue, cat, green, shark, black\nConsole.WriteLine(string.Join(&quot;, &quot;, list1.Merge(list2)));\n//rabbit, red, tiny, dog, blue, medium, cat, green, small, shark, black, huge, none\nConsole.WriteLine(string.Join(&quot;, &quot;, list1.Merge(list2, list3)));\n\n\n</code></pre>\n<p>Next you could add additional overloads with selectors and so on.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-25T12:08:21.663", "Id": "263451", "ParentId": "263397", "Score": "4" } } ]
{ "AcceptedAnswerId": "263451", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T08:22:23.277", "Id": "263397", "Score": "1", "Tags": [ "c#" ], "Title": "Combine elements of two lists into another list" }
263397
<p>These are the scripts I wrote to generate valid ngrams, the output will be filtered manually then used in Markov chain style pseudoword generation.</p> <p>You will need <strike>PowerShell 7</strike> and <a href="https://www.ibiblio.org/webster/" rel="nofollow noreferrer">gcide_xml</a> to make these scripts work.</p> <p>I wanted to find an English corpus/dictionary library for Python, and didn't find one with enough number of words, but I found gcide instead.</p> <p>The xml files in are broken, at least I can't view them in Firefox, though I found the entries can be extracted using this regex: <code>(?&lt;=&lt;ent&gt;)(\w*)(?=&lt;/ent&gt;)</code>.</p> <p>The entries are in 26 xml files with names match <code>gcide_\w\.xml</code>, I don't like the idea of using <code>os.walk()</code> with <code>for</code> loop to get the needed files, then opening reading processing and closing these 26 files in another for loop, so I used a PowerShell one-liner to get the job done, though if there is a Python library that can do this in one-loop I'd happily use that instead of PowerShell.</p> <p>The entries may contain duplicates (homographs), invalid words (acronyms, especially ones with only consonants, words starting with numbers, roman numerals and other nonsense), and most entries are in Titlecase, while some are in lowercase, and the roman numerals are always in lowercase, so I preprocessed the entries.</p> <p><strike>I then used two other scripts to generate a list of potential candidates and pre-eliminated some.</p> <p>Then I used another script to count the occurrences of each candidates in the entries (how many words in the list of words contain the candidates) to further eliminate invalid ngrams.</strike></p> <p>I then used another script to pull the ngrams directly from the words</p> <p>By order of execution and importation, the scripts are:</p> <h2>getdict.py</h2> <pre class="lang-py prettyprint-override"><code>import re from itertools import chain from pathlib import Path from string import ascii_lowercase folder = Path(r'D:\corpus\gcide_xml-0.51').rglob('*') xml_files = [i for i in folder if re.search('gcide_\w.xml', str(i))] words = [re.findall(&quot;(?&lt;=&lt;ent&gt;)(\w*)(?=&lt;/ent&gt;)&quot;, i.read_text()) for i in xml_files] words = sorted(set(chain(*words))) LETTERS = set(ascii_lowercase) VOWELS = set('aeiouy') CONSONANTS = LETTERS - VOWELS words = [i for i in words if not re.match('^[cdilmvx]+$', i) and not re.search('\d', i)] words = set(i.lower() for i in words) words = [i for i in words if not set(i).issubset(CONSONANTS)] words = sorted(words) Path('D:/corpus/gcide_dict.txt').write_text('\n'.join(words)) </code></pre> <h2>validngrams.py</h2> <pre class="lang-py prettyprint-override"><code>import json import re from collections import Counter from collections import defaultdict from pathlib import Path def process(obj): obj = obj.most_common() obj = [(k, v) for k, v in obj if v &gt;= 20] return dict(sorted(obj, key=lambda x: (-x[1], x[0]))) words = Path('D:/corpus/gcide_dict.txt').read_text().splitlines() cngrams = Counter() for w in words: slices = set() for i in range(1, len(w) + 1): for j in range(i): slices.update(re.findall('\w{%s}' % i, w[j:])) for k in slices: cngrams[k] += 1 cngrams = process(cngrams) validngrams = defaultdict(lambda: defaultdict(dict)) for k, v in cngrams.items(): validngrams[k[0]]['%sgrams' % len(k)].update({k: v}) validngrams = {k: v for k, v in sorted(validngrams.items())} Path('D:/corpus/validngrams.json').write_text(json.dumps(validngrams, indent=4)) </code></pre> <p>I want to ask about possible improvements on code style, structure, and performance, especially performance of the last script, it took about 20 minutes on my machine with Intel Core i5-4430 on PtIpython to get the count of occurrences of each candidate, I have tried list comprehension and of course nested for loops to achieve this, but none of them are much more performant than the <code>map()</code> method, and of course I have Google searched for a better method, and found nothing better than list comprehension.</p> <p>How can the formatting, code style, structure, readability and most importantly, performance of my scripts be improved?</p> <p>The last script desperately needs boost in performance. What are some libraries that can make the process of finding how many strings in list A contain a string from list B for each string in list B significantly faster?</p> <hr /> <p>Update:</p> <p>Uploaded <a href="https://drive.google.com/file/d/1kF-sK_RpcpIO3jxOUnJvnlctdaDRLI9o/view?usp=sharing" rel="nofollow noreferrer">gcide_dict.txt</a> to Google Drive as per request.</p> <p>And I have found a faster way to get the count of ngrams, and updated the code.</p> <p>In my testing, the <code>map()</code> way:</p> <pre class="lang-py prettyprint-override"><code>validngrams = list(map(lambda x: (sum(x in i for i in words), x), ngrams)) </code></pre> <p>Takes a grand total of 1395 seconds on my machine:</p> <pre class="lang-py prettyprint-override"><code>In [82]: %time validngrams = list(map(lambda x: (sum(x in i for i in words), x), ngrams)) Wall time: 23min 15s </code></pre> <p>Whereas the <code>Counter()</code> way takes only 1040 seconds:</p> <pre class="lang-py prettyprint-override"><code>In [48]: %time validngrams = Counter(i for i in ngrams for j in words if i in j) Wall time: 17min 20s </code></pre> <p>It saves 355 seconds, and is 25.45 percent faster.</p> <p>Though I am still looking for a way to make it down to about 12 minutes.</p> <hr /> <p>Update:</p> <p>Found a Python 3 way to get the absolute paths of all files inside a directory and its subdirectories, without using <code>os.walk()</code>, the dinosaur from Python 2.</p> <p>Using <code>pathlib</code>, listing files recursively can be done in simply by the <code>.rglob()</code> method of <code>Path()</code> class, instead of using a for loop like <code>os.walk()</code>.</p> <p>And with <code>pathlib</code>, reading the contents of multiple files can be simply done by loop through their <code>Path</code>s and call the <code>read_text()</code> method, instead of multiple <code>with open()</code> blocks.</p> <p>The updated code eliminated the need of PowerShell and is tremendously faster than PowerShell, I edited the corresponding code above.</p> <hr /> <h2>Update</h2> <p>I was thinking, instead of generating possible ngrams and verifying them, I could just directly get the ngrams from the words themselves by splitting the words using regex, and since <code>re.findall()</code> does not find combinations that whose index of first letter modulo the length of the combination is not zero, I used steps to find all combinations.</p> <p>And then, because there might be duplicates, I used a set to eliminate the duplicates.</p> <p>And of course, the results contain combinations that are unpronounceable by themselves and require linguistical analysis to filter out invalid ones, but the job of finding them is done.</p> <p>And this approach is tremendously faster than the last one, it only takes about 9 seconds on PtIpython.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T13:34:57.433", "Id": "520030", "Score": "0", "body": "Sharing the `gcide_dict.txt` might be useful to the reviewers" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-26T20:10:22.330", "Id": "520198", "Score": "0", "body": "Look at implementing `validngrams.py` using a [Suffix Tree](https://en.wikipedia.org/wiki/Suffix_tree). Store the strings in a tree and then search the tree for the ngrams." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-02T05:36:58.987", "Id": "527735", "Score": "0", "body": "Can you write a docstring at the top of each file, which clearly states what input the file takes, and what it outputs? This is good code review itself but it's also likely to get you a code review." } ]
[ { "body": "<h1>document parts of a program</h1>\n<p>It's good to document things in general, but it's especially important to document a data pipeline consisting of several process steps. Clearly label what each file is, and what each program takes in and outputs. For example:</p>\n<pre><code>gcide/*.xml: An english dictionary of words, in XML format. One file per dictionary letter.\ngetdict.py: Takes in the gcide english dictionary as multiple XML files (gcide/*.xml). Outputs a list of legitimate-looking words (gcide_dict.txt).\ngcide_dict.txt: An english dictionary, one word per line in sorted order.\nvalidngrams.py: Takes in a wordlist (gcide_dict.txt). Outputs n-grams found in that dictionary as JSON (validngrams.json). \nvalidngrams.json: Ngram data, as JSON. The JSON dictionary maps each ngram found to a count.\n\nRecommended pipeline:\n Download GCIDE_XML to D:\\corpus\\gcide_xml-0.51\n Run python getdict.py\n Run python validngrams.py\n The output will be in D:/corpus/validngrams.json\n</code></pre>\n<p>I couldn't figure out what a &quot;valid&quot; vs an &quot;invalid&quot; ngram. I think a &quot;valid&quot; ngram is one that appears at least 20 times?</p>\n<p>Your JSON format is a 4-layer nested dictionary: <code>first letter -&gt; #grams -&gt; ngram -&gt; count</code>. Document this and give a few sample lines. A more natural format (at least it seems to me) is <code>#grams -&gt; ngram -&gt; count</code>. Also, it's useful to add total counts, so you can calculate frequency. Because you omit low-frequency 2-grams, the sum of all 2-gram counts beginning with &quot;A&quot; is not the same as the 1-gram count for &quot;A&quot;.</p>\n<h1>misunderstanding ngrams</h1>\n<p>An n-gram is a series of characters that appears in an english text, typically with a frequency/count. For example, you could have a table of 2-grams: the frequency with which every pair of characters appears in English text.</p>\n<p>I'm not sure it's best to mix together 1-grams, 2-grams, 3-grams and so on into a huge list. I'd probably write them to separate files. You most likely only want to use one at a time when you're using them anyway.</p>\n<p>It probably makes no sense to use a wordlist as your corpus--this won't let you generate anything realistic-looking. You need the frequency data. You want to know that &quot;the&quot; is very common, and you may want spaces in your input. That said, go ahead and play around with the wordlist if you like.</p>\n<p>Also you want some pre-calculated, Google <a href=\"https://storage.googleapis.com/books/ngrams/books/datasetsv3.html\" rel=\"nofollow noreferrer\">produced some</a> with its million books project as the corpus, which I think are relatively good.</p>\n<h2>performance</h2>\n<p>I couldn't test getdict.py, but for me validngrams.py takes about 10 seconds to run on <a href=\"https://en.wikipedia.org/wiki/Words_(Unix)\" rel=\"nofollow noreferrer\">/usr/share/dict/words</a> (wikipedia links an example wordlist).</p>\n<p>I'm not sure what you were doing before, but that seems fast enough to me now. It's best practice on Code Review not to update your program before it's reviewed--adding update notes is a little better, but not much. If you want to improve this further, I'd start by identifying which sections are slow. You're using <code>%time</code> which is a good sign.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-02T06:21:50.133", "Id": "267616", "ParentId": "263399", "Score": "1" } } ]
{ "AcceptedAnswerId": "267616", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T10:38:40.277", "Id": "263399", "Score": "4", "Tags": [ "python", "performance", "beginner", "python-3.x" ], "Title": "Python scripts that generate valid ngrams for use in pseudoword generation" }
263399
<p>I've tried to make a little library in C++, to gather all useful and necessary functions. I wrote the code(in one file, to make it more portable). Unfortunately, it works on Windows only.</p> <pre><code>#pragma once #ifndef NEWCPP #define NEWCPP #include &lt;iostream&gt; #include &lt;windows.h&gt; #include &lt;string&gt; #include &lt;ctype.h&gt; #include &lt;stdio.h&gt; #include &lt;fstream&gt; #include &lt;cctype&gt; #include &lt;algorithm&gt; #include &lt;time.h&gt; #include &lt;sstream&gt; #include &lt;sys/stat.h&gt; #include &lt;vector&gt; #include &lt;stdexcept&gt; #include &lt;cstdarg&gt; using namespace std; HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); namespace newcppPrivate { void Init() { srand(time(0)); } const int fileInitializeStartTime = (int)time(0); #define STARTTIME fileInitializeStartTime #define PRESSTIMESLEEP 10 } using namespace newcppPrivate; namespace COLORS { #define CLASSIC (-1) //WORD #define INVISIBLEBLACK 0 #define BLUE 1 #define GREEN 2 #define LIGHTBLUE 3 #define RED 4 #define PURPLE 5 #define YELLOW 6 #define WHITE 7 #define GREY 8 #define LIGHTBLUE 9 #define LIGHTGREEN 10 #define CYAN 11 #define LIGHTRED 12 #define PINK 13 #define LIGHTYELLOW 14 #define WHITE2 15 } using namespace COLORS; #ifdef _WIN32 #include &lt;io.h&gt; #define access _access_s #else #include &lt;unistd.h&gt; #endif //Gives true if folder exist. bool DirExist(const string&amp; path) { struct stat buffer; return (stat(path.c_str(), &amp;buffer) == 0); //return PathFileExists(path.c_str()); } //Returns string converted to wstring. wstring StringToWString(const string s) { std::wstring wsTmp(s.begin(), s.end()); return wsTmp; } LPCWSTR s2ws(const std::string&amp; s) { int len; int slength = (int)s.length() + 1; len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); wchar_t* buf = new wchar_t[len]; MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len); std::wstring r(buf); delete[] buf; //return r; std::wstring stemp = s2ws(s); return stemp.c_str(); } //Returns string converted to LPSTR LPSTR StrToLPSTR(string s) { return const_cast &lt;char*&gt; (s.c_str()); } //Returns true if given char is number bool isCharNumber(char c) { return isdigit(c); } //Deleting all given chars from string and returns it. string DeleteAllChars(string s, char c) { s.erase(std::remove(s.begin(), s.end(), c), s.end()); return s; } //Deleting chars from first parameter that are in second. string DeleteAllChars(string s, string chars) { for (int i = 0; i &lt; chars.length(); i++) s = DeleteAllChars(s, chars[i]); return s; } //Replacing string in text to another string. //Usage: //ReplaceAll(string(&quot;The main string&quot;), string(&quot; &quot;), string(&quot;-&quot;)) //Returns: //&quot;The-main-string&quot; string ReplaceAll(std::string str, const std::string&amp; from, const std::string&amp; to) { size_t start_pos = 0; while ((start_pos = str.find(from, start_pos)) != std::string::npos) { str.replace(start_pos, from.length(), to); start_pos += to.length(); // Handles case where 'to' is a substring of 'from' } return str; } //Returns a chracter table length. int CharacterTableLength() { //return int(char(0) - 1); char a = 'a' + 1; int counter = 1; while (a != 'a') { a++; counter++; } return counter; } //Returns string to uppercase string UpperString(string s) { transform(s.begin(), s.end(), s.begin(), ::toupper); return s; } template &lt;typename T&gt; string NumberToString(T pNumber) { ostringstream oOStrStream; oOStrStream &lt;&lt; pNumber; return oOStrStream.str(); } //Returns true if element is part of array. template &lt;class element, class container&gt; bool PartOfArray(element elem, container array, int arraySize=0) { if (!arraySize) arraySize = sizeof(array) / sizeof(array[0]); for (int i = 0; i &lt; arraySize; i++) if (elem == array[i]) return true; return false; } //Returns true if __access_s function returns 0 (~file exists) bool FileExists(const std::string&amp; Filename) { return _access(Filename.c_str(), 0) == 0; } //Changing console text color. For changing it back, ChangeColor(COLORS::CLASSIC) or SetDefaultColor void ChangeColor(int color = CLASSIC) { SetConsoleTextAttribute(hConsole, color); } //Setting standart color void SetDefaultColor() { SetConsoleTextAttribute(hConsole, CLASSIC); } //Writes each symbol in string with function Sleep void Write(string s, int maxTime=100) { if (maxTime &lt;= 0) maxTime = 1; //Previous version was without it //srand(time(0)); for (int i = 0; i &lt; s.length(); i++) { cout &lt;&lt; s[i]; Sleep(rand() % maxTime); //WARNING: Slowing down. } } //Writes string in setted color with Sleep. void Print(string s, int color=CLASSIC, int maxT=1, int colorAfter=CLASSIC) { ChangeColor(color); //WARNING: Calling SetConsoleTextAttribute insead should speed up. Write(s, maxT); //Slows down output. ChangeColor(colorAfter); } //Simulating user press void Press(BYTE key, int sleepTime=PRESSTIMESLEEP) { keybd_event(key, 0, 0, 0); Sleep(sleepTime); keybd_event(key, 0, KEYEVENTF_KEYUP, 0); } //Simulating 2 presses void DoublePress(BYTE key, BYTE key2, int sleepTime=PRESSTIMESLEEP) { keybd_event(key, 0, 0, 0); keybd_event(key2, 0, 0, 0); Sleep(sleepTime); keybd_event(key, 0, KEYEVENTF_KEYUP, 0); keybd_event(key2, 0, KEYEVENTF_KEYUP, 0); } template&lt;class T&gt; T Random(T min = 0, T max = 10000) { max -= min; T res = rand() % (max+1); return res + min; } //Class for bruteforcing. class BruteForce { private: const char pzc = 1; const char pnc = 0; public: string res = &quot;&quot;; //Bruteforce guess //Give next string guess string GiveNextGuess() { PlusPlus(); return res; } string CurrentGuess() { return res; } //Setting start length of brute-force string. Can be given as normal(parameter 2 but s is maybe ['', '']) void SetStartLength(int l) { if (l &lt;= 0) throw std::invalid_argument(&quot;Received incorrect value.&quot;); res.clear(); for (int i = 0; i &lt; l; i++) res += pzc; } void PlusPlus() { int a = 0; while (true) { if (a &gt; res.length()) { res += pzc; break; } else if (res[a] == pnc) { res[a] = pzc; a++; } else { res[a]++; break; } } } }; namespace sortfunctions { template&lt;class T&gt; vector&lt;T&gt; GnomeSort(vector&lt;T&gt; arr, bool (*compare)(T, T)) { const int s = arr.size(); for (int i = 1; i &lt; s; i++) { if (compare(arr[i], arr[i - 1])) { T helper = arr[i]; arr[i] = arr[i - 1]; arr[i - 1] = helper; if (i != 1) i -= 2; } } return arr; } template&lt;class T&gt; vector&lt;T&gt; BubbleSort(vector&lt;T&gt; arr, bool (*compare)(T, T)) { const int s = arr.size(); for (int i = 0; i &lt; s; i++) { for (int k = i + 1; k &lt; s; k++) { if (compare(arr[i], arr[k])) { T helper = arr[i]; arr[i] = arr[k]; arr[k] = helper; } } } return arr; } } //Returns junk. Should return last value somewhere in program used. Needs to give any string. template&lt;class T&gt; const int GetJunk(T r = 10) { if (r != r) return 0; } #endif </code></pre> <h2>Questions:</h2> <ol> <li>Can it be done in other way? For example, I can write code in multiple files, but then compile into one .lib file? If so, how to install it then?</li> <li>Any code review suggestions?</li> </ol> <hr> <h3>Some notes</h3> <p><code>CharacterTableLength</code> - is function that should return number of all symbols installed on the computer. For example, if on computer installed 3 languages, this function should return number of special and 3 languages symbols.</p> <p>I specially wrote variable names without '_'. I really dont like this style, I use Camel case instead.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T13:43:59.333", "Id": "520032", "Score": "4", "body": "`GnomeSort` and `BubbleSort` are useful and necessary on Windows? Glad I never had to write anything for that platform!" } ]
[ { "body": "<h1>General Observations</h1>\n<blockquote>\n<p>Can it be done in other way? For example, I can write code in multiple files, but then compile into one .lib file? If so, how to install it then?</p>\n</blockquote>\n<p>Generally it is best to put functions into C++ source files and have header files that provide the interfaces (function prototypes and constants). A library can contain multiple source files, how to do this depends on whether it is a static library or a dynamic library. Putting functions into a header file means that if a function is modified everything needs to be recompiled. If only the function prototype is in the header file then generally to fix a bug means recompiling one file and re-linking the program or library.</p>\n<p>Please compile using all the warning messages you can. It helps find possible bugs. I compile with more warning messages than you apparently do and this is what I see when I compile:</p>\n<pre><code>Build started...\n1&gt;------ Build started: Project: myLittleLib, Configuration: Debug Win32 ------\n1&gt;myLittleLib.cpp\n1&gt;C:\\Users\\PaulC\\Documents\\ProjectsNfwsi\\CodeReview\\myLittleLib\\myLittleLib\\myCppLib.h(28,19): warning C4244: 'argument': conversion from 'time_t' to 'unsigned int', possible loss of data\n1&gt;C:\\Users\\PaulC\\Documents\\ProjectsNfwsi\\CodeReview\\myLittleLib\\myLittleLib\\myCppLib.h(49,1): warning C4005: 'LIGHTBLUE': macro redefinition\n1&gt;C:\\Users\\PaulC\\Documents\\ProjectsNfwsi\\CodeReview\\myLittleLib\\myLittleLib\\myCppLib.h(43): message : see previous definition of 'LIGHTBLUE'\n1&gt;C:\\Users\\PaulC\\Documents\\ProjectsNfwsi\\CodeReview\\myLittleLib\\myLittleLib\\myCppLib.h(110,23): warning C4018: '&lt;': signed/unsigned mismatch\n1&gt;C:\\Users\\PaulC\\Documents\\ProjectsNfwsi\\CodeReview\\myLittleLib\\myLittleLib\\myCppLib.h(186,23): warning C4018: '&lt;': signed/unsigned mismatch\n1&gt;C:\\Users\\PaulC\\Documents\\ProjectsNfwsi\\CodeReview\\myLittleLib\\myLittleLib\\myCppLib.h(253,19): warning C4018: '&gt;': signed/unsigned mismatch\n1&gt;C:\\Users\\PaulC\\Documents\\ProjectsNfwsi\\CodeReview\\myLittleLib\\myLittleLib\\myCppLib.h(90): warning C4717: 's2ws': recursive on all control paths, function will cause runtime stack overflow\n1&gt;myLittleLib.vcxproj -&gt; C:\\Users\\PaulC\\Documents\\ProjectsNfwsi\\CodeReview\\myLittleLib\\Debug\\myLittleLib.exe\n1&gt;Done building project &quot;myLittleLib.vcxproj&quot;.\n========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========\n</code></pre>\n<p>I'm using Visual Studio 2019 Professional</p>\n<h1>Include Guards</h1>\n<p>I'm assuming this library is a header file because of the include guards. In C++ use either <code>#pragma once</code> or <code>#ifndef</code> but you don't need both. I prefer <code>#ifndef</code> because it may be more portable, not all C++ compilers support <code>#pragma once</code> but it is widely supported.</p>\n<h1>Avoid <code>using namespace std;</code></h1>\n<p>If you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifier<code>cout</code> you may override within your own classes, and you may override the operator <code>&lt;&lt;</code> in your own classes as well. This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow question</a> discusses this in more detail.</p>\n<p>This code is abusing <code>using namespace ANYNAMESPACE;</code></p>\n<p>Never put <code>using namespace std;</code> in a header file.</p>\n<h1>Use Enum Types</h1>\n<p>Rather than using a lot of <code>#defines</code> which are frowned on in C++, there are 2 ways to create constants. One is to use <a href=\"https://en.cppreference.com/w/cpp/language/constexpr\" rel=\"noreferrer\">constexpr</a>, the other is using an <a href=\"https://en.cppreference.com/w/cpp/language/enum\" rel=\"noreferrer\">enum type</a>. When more than 2 or 3 constants are being defined an enum is a better way to do this. The link I provided shows an example of a color enum, however, this is what the current code could look like:</p>\n<pre><code> enum MyCOLORS\n {\n BLUE,\n GREEN,\n RED,\n PURPLE,\n YELLOW,\n WHITE,\n GREY,\n LIGHTBLUE,\n LIGHTGREEN,\n CYAN,\n LIGHTRED,\n PINK,\n LIGHTYELLOW,\n WHITE2\n };\n</code></pre>\n<p>Please note that in the code under review LIGHTBLUE is defined twice which should be reported by the compiler.</p>\n<h1>Type Mismatch in <code>for</code> Loops</h1>\n<p>Container classes such as <code>std::string</code> and <code>wstring</code> return the type <code>size_t</code> from the <code>length</code> or <code>size</code> member. The type <code>size_t</code> varies from compiler to compiler but it is always <code>unsigned</code>, in many cases it is either <code>unsigned int</code> or <code>unsigned long</code>. One of the possible reasons for this is to prevent negative indexes when using the variable as an index into the container.</p>\n<pre><code>string DeleteAllChars(string s, string chars) {\n for (size_t i = 0; i &lt; chars.length(); i++)\n s = DeleteAllChars(s, chars[i]);\n return s;\n}\n</code></pre>\n<p>Negative indexes can have bad side affects and cause exceptions.</p>\n<h1>Reinventing the Wheel</h1>\n<p>There is no good reason for this function</p>\n<pre><code>bool isCharNumber(char c) {\n return isdigit(c);\n}\n</code></pre>\n<p>The function <code>isdigit()</code> is well known and well documented, why replace it with an unknown, undocumented function?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-25T19:15:16.457", "Id": "520139", "Score": "0", "body": "Also, raw `char` to a character-function? The UB." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T17:58:49.277", "Id": "263420", "ParentId": "263400", "Score": "7" } }, { "body": "<ol>\n<li>Your <code>s2ws()</code> function is a recursive function with no base condition. Presumably, it's from <a href=\"https://stackoverflow.com/questions/27220/how-to-convert-stdstring-to-lpcwstr-in-c-unicode\">here</a>? Notice where the closing braces are placed. It's also invoking undefined behavior because it's returning a pointer to memory that will be deallocated once the function returns.\nSame with <code>StrToLPSTR()</code> and <code>NumberToString()</code> functions.</li>\n</ol>\n<hr />\n<ol start=\"2\">\n<li><code>#define</code>s are not bound by namespace. The <code>COLORS</code> namespace is literally empty at the time of compilation. The compiler isn't throwing a compile error because you've used <code>using namespace COLORS;</code>.</li>\n</ol>\n<hr />\n<ol start=\"3\">\n<li>As mentioned above, use <code>constexpr</code> to define constants.</li>\n</ol>\n<hr />\n<ol start=\"4\">\n<li>If you're using C++17, you used should <code>std::filesystem</code> instead of relying on specific OS calls. It has the benefit of being portable.</li>\n</ol>\n<hr />\n<ol start=\"5\">\n<li>If you're using C++17, you should generally use <code>std::string_view</code> instead of <code>const std::string&amp;</code>.</li>\n</ol>\n<hr />\n<ol start=\"6\">\n<li>You can use <code>std::to_string</code> instead of using <code>std::stringstream</code> in the <code>NumberToString()</code> function.</li>\n</ol>\n<p>Right now, the function can accept any type. The constrain them to numeric types, you can use <code>static_assert</code> to do a compile time check. Using the <code>type_traits</code> library, you can do</p>\n<p><code>static_assert(is_integral_v&lt;T&gt; &amp;&amp; is_floating_point_v&lt;T&gt;, &quot;only numeric types allowed&quot;!);</code></p>\n<p>This will now throw an error if you pass in any other type other than numeric types.</p>\n<hr />\n<ol start=\"7\">\n<li><code>PartOfArray</code> contains a bug. What if someone passes a C-style array and doesn't pass the size?</li>\n</ol>\n<pre><code>int arr[] = {1, 2, 3};\nbool inArray = PartOfArray(3, arr);\nstd::cout &lt;&lt; std::boolalpha &lt;&lt; inArray; // prints false;\n</code></pre>\n<hr />\n<ol start=\"8\">\n<li>Use <code>&lt;chrono&gt;</code> library instead of <code>&lt;time.h&gt;</code>. Use <code>&lt;random&gt;</code> library instead of <code>rand()</code></li>\n</ol>\n<hr />\n<ol start=\"9\">\n<li>The <code>PlusPlus()</code> method invokes undefined behavior because of an out-of-bounds memory access. Hint: what happens when <code>a=0</code> and <code>res=&quot;&quot;</code>?</li>\n</ol>\n<hr />\n<ol start=\"10\">\n<li>Some are the comments are redundant. Code should be as self-documenting as possible. <code>Returns true if function returns 0</code> doesn't add anything that I can't figure out by looking at the code.</li>\n</ol>\n<hr />\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-25T02:59:17.010", "Id": "263440", "ParentId": "263400", "Score": "3" } }, { "body": "<p>I'm not sure how your file is meant to be used. It appears to be set up like a header file, but nothing in it is <code>inline</code> so it can only appear in one translation unit. From your comments, I suspect you have only, thus far, written programs that consist of a single CPP file.</p>\n<p>If you want a header-only library, global variables and functions must be marked <code>inline</code>. But you need to learn how to make a project that consists of multiple CPP files linked together, and how to use libraries. Libraries can include third-party code, not just reusable components of your own, so it's something you really need to learn!</p>\n<p>As for the specific code...</p>\n<pre><code>namespace COLORS {\n #define CLASSIC (-1) //WORD\n\n #define INVISIBLEBLACK 0\n\n #define BLUE 1\n #define GREEN 2\n #define LIGHTBLUE 3\n #define RED 4\n #define PURPLE 5\n #define YELLOW 6\n #define WHITE 7\n #define GREY 8\n #define LIGHTBLUE 9\n #define LIGHTGREEN 10\n #define CYAN 11\n #define LIGHTRED 12\n #define PINK 13\n #define LIGHTYELLOW 14\n #define WHITE2 15\n }\n using namespace COLORS;\n</code></pre>\n<p>The <code>namespace</code> doesn't do anything since the <code>#define</code> does not respect namespaces at all. It is one of the top issues that you should not use <code>#define</code> anyway, so change this to an enumerated type — a classic style <code>enum</code> will still let you use the enumeration names where an <code>int</code> is expected, if that is your intended use.</p>\n<p>Also, defining a namespace and then immediately <code>using</code> it is a feature that's automated by using <code>inline</code>. (This is a different use of the same keyword mentioned above).</p>\n<p><code>#ifdef _WIN32</code><br />\nWell, you are including &quot;Windows.h&quot; at the top, so you are already committed to Windows for this file.</p>\n<pre><code>//Returns string converted to LPSTR\n LPSTR StrToLPSTR(string s) {\n return const_cast &lt;char*&gt; (s.c_str());\n }\n</code></pre>\n<p>Major bug! You are passing <code>s</code> <em>by value</em>, so <code>s.c_str()</code> will return a pointer to the buffer (or internal SSO area) that is <em>destroyed</em> when <code>s</code> goes out of scope, which is when the function returns.</p>\n<p>You also should not be casting away the const. Don't do this. If you need a non-const nul-terminated C-style string, make sure you produce one that can be written to.</p>\n<pre><code>//Returns true if given char is number\n bool isCharNumber(char c) {\n return isdigit(c);\n }\n</code></pre>\n<p>Why??? This adds nothing over the standard function. If you are intentionally taking care of the legacy <code>int</code> parameter issue, overload it using the <strong>same name</strong>.</p>\n<pre><code>//Deleting chars from first parameter that are in second.\n string DeleteAllChars(string s, string chars) {\n for (int i = 0; i &lt; chars.length(); i++)\n s = DeleteAllChars(s, chars[i]);\n return s;\n }\n</code></pre>\n<p>You are passing the second parameter, <code>chars</code>, <em>by value</em> which is not appropriate. Do you understand that this deep-copies the entire string? If it will not be modified, what is the point of that?<br />\nIt's very inefficient, deleting all occurrences of one character at a time, recopying the whole string object each time.<br />\nUse <code>std::remove_if</code> followed by <code>erase</code> (look up &quot;delete/erase idiom&quot;). <strong>In general</strong>, become familiar with the standard library and other libraries in your project.</p>\n<pre><code>//Returns a chracter table length.\n int CharacterTableLength() {\n //return int(char(0) - 1);\n char a = 'a' + 1;\n int counter = 1;\n while (a != 'a') {\n a++;\n counter++;\n }\n\n return counter;\n }\n</code></pre>\n<p>I don't even understand what this is supposed to do. It doesn't take any parameters or refer to any global names, so what &quot;chracter[sic] table&quot; are you talking about? It looks like it increments a <code>char</code> value until it wraps around, thus (if that were legal) telling you the number of possible values in a <code>char</code>. If you don't want to just assume it's 256, use <code>numeric_limits&lt;unsigned char&gt;::max()+1</code>.<br />\nBut this code is actually exhibiting <em>Undefined Behavior</em> as you are not allowed to wrap-around a signed number. The optimizer will look at the condition in your <code>while</code> loop and say &quot;Oh, that's always false&quot; and replace your code with an infinite loop, or delete it altogether.</p>\n<blockquote>\n<p>function that should return number of all symbols installed on the computer. For example, if on computer installed 3 languages, this function should return number of special and 3 languages symbols.</p>\n</blockquote>\n<p>No, it increments a <code>char</code> which has nothing to do with what languages are installed, or which of those <code>char</code> values has a legal code point assigned to it. It just works as a small (8 bit) integer, having nothing to do with the Locale or selected font or anything.</p>\n<pre><code>template &lt;typename T&gt;\n string NumberToString(T pNumber) {\n ostringstream oOStrStream;\n oOStrStream &lt;&lt; pNumber;\n return oOStrStream.str();\n }\n</code></pre>\n<p>That is just a slow re-implementation of <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/to_string\" rel=\"nofollow noreferrer\"><code>std::to_string</code></a>. What's wrong with <code>to_string</code>?</p>\n<pre><code>//Returns true if element is part of array.\n template &lt;class element, class container&gt;\n bool PartOfArray(element elem, container array, int arraySize=0) {\n if (!arraySize) arraySize = sizeof(array) / sizeof(array[0]);\n \n for (int i = 0; i &lt; arraySize; i++)\n if (elem == array[i])\n return true;\n\n return false;\n }\n</code></pre>\n<p>Ugh, don't use the old C <code>sizeof</code> trick to determine array sizes. It's brittle and will give the wrong answer if you end up giving it a parameter that's already decayed into a pointer.</p>\n<p>Don't use the legacy <code>for</code> loop with index numbers when the range-based <code>for</code> will do.</p>\n<p>But, your code, even though <code>container</code> is templated, only works with bare C style arrays, not with containers in general. And you are just reproducing existing standard functions anyway!</p>\n<p>Just see if <code>std::count</code> is non-zero, or (more efficient since it can quit when it finds the first match) if <code>std::find</code> returns something other than the <code>end</code>.</p>\n<p>Even writing out the logic (not using library function) with the previous tips would make it work with <em>any</em> container, such as <code>vector</code>, not just plain C arrays:</p>\n<pre><code> template &lt;typename element, typename container&gt;\n bool PartOfArray(element elem, container array) {\n for (const auto&amp; val : array)\n if (elem == elem) return true;\n return false;\n }\n</code></pre>\n<p>Oh, I noticed you are passing <code>container array</code> <em>by value</em>. If you actually called this with an array, it will have decayed to a pointer in the parameter! So remember what I said about the <code>sizeof</code> trick being easy to silently get wrong? <code>sizeof (array)</code> actually returns the size of a single pointer, nothing to do with the original array.</p>\n<p>Look at <a href=\"https://godbolt.org/z/94n4s5z5K\" rel=\"nofollow noreferrer\">Compiler Explorer</a>:\nIf the optional 3rd parameter is not given, it is replace with the value <code>2</code> even though the array size is <code>2089</code>. You can see why in the signature reported in the assembly view: <code>int, int*, int</code>. See, the &quot;array&quot; is actually passed as a pointer to the first element.</p>\n<p><strong>Had you tested your code, you would have noticed that it did not work at all</strong>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-25T19:18:48.553", "Id": "520141", "Score": "0", "body": "That isn't really a \"legacy `int` parameter issue\". Allowed arguments are all values of type `unsigned char` and `EOF`. Anything else is UB." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-25T19:21:44.733", "Id": "520142", "Score": "0", "body": "`sizeof container` is a compilation-error. `sizeof (container)` would be the same as `sizeof array`, and pretty useless if the argument passed is a native array." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-28T13:51:41.240", "Id": "520291", "Score": "0", "body": "@Deduplicator corrected. Interesting that the template argument deduction gives the decayed type when the parameter is `container x` (with no `&`). I'll have to review the rules for that. By \"legacy 'int' parameter\" I meant that the function, inherited from C (thus \"Legacy\"), takes an `int` and doesn't work with normal `char` which is signed. Using it correctly requires casting, or better yet making your own wrapper that takes `char`. Using it correctly requires extra work, thus it's an \"issue\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-28T19:47:02.080", "Id": "520336", "Score": "0", "body": "That is not in any way surprising. A function cannot have an argument of type array. If it looks like it does, that really is a pointer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-25T15:49:57.313", "Id": "263460", "ParentId": "263400", "Score": "4" } } ]
{ "AcceptedAnswerId": "263420", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T10:57:36.437", "Id": "263400", "Score": "5", "Tags": [ "c++", "beginner", "windows", "library" ], "Title": "My little C++ library for comfortable programming" }
263400
<p>This is a simple practice problem. The task is to write a function <code>getLR</code> that receives an <code>Integral</code>, <code>n</code>, and returns a list representation (LR) of <code>n</code>. For example: <code>73847 -&gt; [7,3,8,4,7]</code>. Negative numbers return the LR of the absolute value, for example: <code>-837 -&gt; [8,3,7]</code>. In the following code I use three helper functions <code>getAbs</code>, <code>getI</code> and <code>getList</code>:</p> <pre><code>getLR :: (Integral a) =&gt; a -&gt; [a] getLR n = if n==0 then [0] else getAbs n getAbs :: (Integral a) =&gt; a -&gt; [a] getAbs n = if n&gt;=0 then getI n n 0 else getI (-n) (-n) 0 -- Computes the length of an Integer and stores it in i, for example 321 has length 3, 9999 has length 4. getI :: (Integral a) =&gt; a -&gt; a -&gt; a -&gt; [a] getI n m i = if m==0 then getList n [] (i-1) else getI n (m`div`10) (i+1) -- Constructs the LR recursively. getList :: (Integral a) =&gt; a -&gt; [a] -&gt; a -&gt; [a] getList n ns i = if n==0 then ns else getList (n-10^i*(n`div`(10^i))) (ns++[n`div`(10^i)]) (i-1) </code></pre> <p>The code works correctly. My specific concerns are readability and simplicity of the code. If you have any suggestions how to make the code more readable or more simple I'd be happy to receive your feedback. If you find any problems besides readability and simplicity: don't hesitate to point them out as well.</p>
[]
[ { "body": "<p>I'm not a Haskell programmer, but let me just point out a few things here.</p>\n<p>First, expressions such as <code>(n-10^i*(n`div`(10^i)))</code> look quite cluttered. One thing you can do is just put a space between each operator and its operands, and with longer expressions, you can extract pieces and bind them to names to make it easier to understand what's going on. For example, you use <code>10^i</code> multiple times. Perhaps you could use <code>let fac = 10 ^ i in...</code> to make it clearer what's happening.</p>\n<p>Second, the names of these methods are a bit unclear. <code>getAbs</code> seems like it would return the absolute value instead of returning the list representation of a number's absolute value. Honestly, I would inline it as part of <code>getLR</code>. <code>getLR</code>'s meaning isn't immediately clear, and I think <code>listRepr</code> or simply <code>digits</code> is a clearer name for it. Similarly, <code>getI</code> doesn't tell you what it does unless you read the comment above it. I would suggest using <code>where</code> to &quot;hide&quot; it, along with <code>getList</code>.</p>\n<p>However, I think your implementation is a little complicated. All you need is to build up a list of digits, starting at the last digit, by using <code>x `mod` 10</code> to get the next digit and <code>x `div` 10</code> to get the rest of the number. Here's a solution that I find much simpler:</p>\n<pre><code>digits :: (Integral a) =&gt; a -&gt; [a]\ndigits 0 = [0]\ndigits n = go (abs n) [] where\n go 0 digs = digs\n go x digs = go (x `div` 10) (x `mod` 10 : digs)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T14:05:58.303", "Id": "263409", "ParentId": "263401", "Score": "3" } }, { "body": "<p>Interestingly enough, this can be solved with no math at all. The things to know are:</p>\n<ol>\n<li><code>show</code> turns an <code>Int</code> into a <code>String</code></li>\n<li>A <code>String</code> is internally actually <code>[Char]</code>, so you can <code>map</code> to and from strings as you would lists.</li>\n<li><code>read</code> converts a <code>String</code> to the datatype it represents (but does not work with <code>Char</code>s)</li>\n</ol>\n<p>Putting those together, the steps to turn an integer into a list of integers is:</p>\n<ol>\n<li><code>show</code> it</li>\n<li>Turn each character in the string into a string itself</li>\n<li><code>map</code> a function with the signature <code>String -&gt; Int</code></li>\n</ol>\n<pre class=\"lang-hs prettyprint-override\"><code>digits :: Int -&gt; [Int]\ndigits = map (read :: String -&gt; Int) . map (:[]) . show\n</code></pre>\n<p>Running in a repl:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>&gt; let digits = map (read :: String -&gt; Int) . map (:[]) . show\n&gt; digits 73487\n=&gt; [7,3,4,8,7]\n</code></pre>\n<p><strong>Update to make it work for both Ints and Integers</strong></p>\n<pre class=\"lang-hs prettyprint-override\"><code>digits :: (Integral a, Show a, Read a) =&gt; a -&gt; [a]\ndigits = map (read . (:[])) . show\n</code></pre>\n<p>Running in a repl:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>&gt; digits :: (Integral a, Show a, Read a) =&gt; a -&gt; [a]\n digits = map (read . (:[])) . show\n\n&gt; digits (12345::Int)\n=&gt; [1,2,3,4,5]\n&gt; digits (12345::Integer)\n=&gt; [1,2,3,4,5]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-29T11:00:06.000", "Id": "520376", "Score": "0", "body": "nice solution. however it seems to only work when `digits` receives `Int`. when passing the type `Integer` it doesn't seem to work, i.e. can you make it work with `digits :: Integer -> [Integer]`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-29T14:21:36.610", "Id": "520392", "Score": "0", "body": "Not at first pass, but I'll give it another go later!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-30T02:04:03.933", "Id": "520450", "Score": "0", "body": "@MoritzWolff Okay, it took me a while but it ended up being way easier than I thought... Just needed a different type signature." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-30T07:14:47.750", "Id": "520454", "Score": "1", "body": "This is nice for some cases, but less general than OP's solution. Not only does it not work for types that don't implement `Show` and `Read`, but it also makes assumptions about `show` and `read` that don't hold in general. For an example of the latter, look at `Identity Int` (where `Identity` is from `Data.Functor.Identity`) - `getLR (Identity 123)` is `[Identity 1, Identity 2, Identity 3]`, but `digits (Identity 123)` fails to produce a value" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-01T22:13:35.470", "Id": "520610", "Score": "0", "body": "This looks like a good, concise approach too, but you might want to tack on `. abs` at the end of the `digits` function so that it works with negative numbers" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-01T22:29:30.330", "Id": "520612", "Score": "0", "body": "It's a concise approach, and I do like it otherwise I wouldn't have posted it, but I hesitate to call it *good* as it uses twice the memory of the accepted answer on longer integers." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-28T16:55:17.667", "Id": "263558", "ParentId": "263401", "Score": "2" } } ]
{ "AcceptedAnswerId": "263409", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T11:04:29.470", "Id": "263401", "Score": "3", "Tags": [ "haskell", "recursion", "functional-programming" ], "Title": "Haskell Function to get the List representation of an Integral" }
263401
<p>Any help with my code. I think it's kind of hard code where I want to extract links from a page and download them.</p> <p>It's going to scrape some links from websites (but the <code>Scraper</code> function that I've written is hardcode) and download the videos if they exist and I'm sure it's not good at all and it's more of a smell code.</p> <h2>Code</h2> <pre><code>import requests import subprocess import getpass import time from bs4 import BeautifulSoup as bs # import argparse # Add Command Line Arguments to a Python Script (switch_flag) def Login(url, login_route, username, password): headers = { 'User-Agent': '', 'origin': url, 'referer': url + login_route, } request_session = requests.session() csrf_token = request_session.get(url).cookies['csrftoken'] login_payload = { 'hidden_username': username, 'password': password, 'csrfmiddlewaretoken': csrf_token } login_request = request_session.post( url + login_route, headers=headers, data=login_payload) if login_request.status_code == 200: msg = f'\nYou have logged in successfully {login_request.status_code}' else: msg = f'\nError {login_request.status_code}' print(msg) def get_user_input(): url = input('URL: ') username = getpass.getpass('USERNAME: ') password = getpass.getpass('PASSWORD: ') login_route = input('LOGIN_ROUTE: ') return Login(url, login_route, username, password) def Scraper(page_url): headers = { '' } page = requests.get( page_url, headers=headers, ) soup = bs(page.text, &quot;html.parser&quot;) URL_List = [] link_count = 0 for a_tag in soup.select('a[href^=&quot;/course/&quot;]'): links = &quot;https://maktabkhooneh.org&quot; + a_tag[&quot;href&quot;] URL_List.append(links) link_count += 1 return URL_List def Donwloader(url_list): URL_List = Scraper(url_list) download_count = 0 try: for links in URL_List: command = f'youtube-dl {links}' result = subprocess.call(command, shell=True) if result == 0: download_count += 1 except KeyboardInterrupt: print('Paused ;)') return f'\n{download_count} file(s) have been downloaded' if __name__ == '__main__': page_url = input('Please enter the page URL: ') Login_permission = input('Login required Website [Y], [N]? ') if Login_permission == 'y' or Login_permission == 'Y': get_user_input() list_len = len(Scraper(page_url)) Download_Permission = input( f'\n{list_len} link(s) have been extracted. Do you want to DOWNLOAD them [Y], [N]? ') Scraper(page_url) if Download_Permission == 'y' or Download_Permission == 'Y': Donwloader(page_url) else: print('\nProcess has been canceled ;)') </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T16:46:08.787", "Id": "520047", "Score": "0", "body": "What is an example of a page URL that this can accept?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T17:31:04.820", "Id": "520052", "Score": "0", "body": "For example, https://maktabkhooneh.org/course/%D8%A2%D9%85%D9%88%D8%B2%D8%B4-%D8%B1%D8%A7%DB%8C%DA%AF%D8%A7%D9%86-Pandas-mk1214/%D9%81%D8%B5%D9%84-1-%D8%A2%D9%85%D9%88%D8%B2%D8%B4-Pandas-ch4004/%D9%88%DB%8C%D8%AF%DB%8C%D9%88-%D9%85%D9%82%D8%AF%D9%85%D9%87/" } ]
[ { "body": "<p>A few suggestions.</p>\n<p>It's good that you are using a <strong>session</strong> but you are not using it properly. The idea is to reuse the session across your code to increase efficiency while crawling sites. It is used in the login routine but in the Scraper routine you are using a plain requests.get(). So you are not actually taking advantage of requests.session.</p>\n<p>You should actually set a <strong>user agent</strong> in your headers. Not having one, or using the default value (something like: python-requests/2.25.1) makes it obvious that you are <strong>bot</strong>. Thus, your script may have trouble crawling some sites. I would suggest that you spoof the user agent to match a regular browser. It doesn't cost anything.</p>\n<p>You are using F-strings in your code but sometimes concatenation using the + sign. For more consistency I suggest that you use F-strings only.</p>\n<p>I would try to refactor your set of function as a class. Below is a quick attempt, it is not complete and meant for demonstration purposes. I have set a few headers in particular a spoofed user agent (Firefox). It is enough to do it once at the session level, since every request (get, post) that uses the session inherits from these parameters. So you don't have to repeat yourself. But you can still pass extra headers on a case by case basis, this is what is being done in the login route where we want to pass a referer for example.</p>\n<p>I tried to add a bit of abstraction by creating a function to retrieve a single page. Then I would design another function to actually parse it using BS4 etc.</p>\n<p>I also added some basic error handling at the application level, plus some logging on console, you can easily add logging to a file if desired (useful for troubleshooting).</p>\n<p>You might want to use a configuration file to store URLs and other settings to avoid the hassle of typing in values. Using getpass is fine if you don't want to store credentials or other sensitive information.</p>\n<p>PS: a discussion about using <code>shell=True</code> with subprocess: <a href=\"https://stackoverflow.com/q/3172470/6843158\">Actual meaning of 'shell=True' in subprocess</a>. In short I don't think you need it, it may even be detrimental from a security point of view.</p>\n<p>Since you are scraping a third-party site, the HTML should be considered as unsafe, unsanitized, untrusted user input.</p>\n<p>And if the call fails (return code != 0), don't stay silent but <strong>log</strong> this event. All you have to do is to take advantage of the logger already available and do something like:</p>\n<pre><code> if result == 0:\n download_count += 1\n else:\n self.logger.warning(f&quot;Failed to execute command: {command} - Return code: {result}&quot;)\n</code></pre>\n<p>Then at least you have a trace of the things that go wrong during the process.</p>\n<p>Maybe that's the thing that is missing in your script: traceability. It's good to print some messages here and there, to show what the script is doing and at what stage it currently is. Especially when it's expected that execution will take a while, you want to be able to track progress. The logging module is there for you, use it and abuse it.</p>\n<hr />\n<p>Misc: in Scraper, you increment <code>link_count</code> but you could just use <code>len(URL_List)</code> instead. No need for another variable.</p>\n<hr />\n<p>PS: it would make sense to move the class to a standalone file, so that it can be reused and there is better separation. Just import it like another module. Then the main script will be smaller and more manageable.</p>\n<hr />\n<h2>Class skeleton</h2>\n<pre><code>import sys\nimport logging\nimport requests\nimport getpass\n\nfrom bs4 import BeautifulSoup as bs\n\n\nclass Downloader:\n\n def __init__(self, logger=None):\n # set up logging\n self.logger = logger or logging.getLogger(__name__)\n self.logger.debug(&quot;Initialize class Downloader&quot;)\n\n # init session\n self.session = requests.session()\n\n # add some standard headers and spoof user agent\n self.session.headers.update({\n &quot;User-Agent&quot;: &quot;Mozilla/5.0 (X11; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0&quot;,\n &quot;Accept&quot;: &quot;text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8&quot;,\n &quot;Accept-Language&quot;: &quot;en-US,en;q=0.5&quot;\n })\n self.logger.debug(f&quot;Session headers: {self.session.headers}&quot;)\n\n def fetch_page(self, url: str, headers: None):\n &quot;&quot;&quot;Fetch a single page and return request results - some extra headers may be provided\n &quot;&quot;&quot;\n self.logger.debug(f&quot;Fetching page: {url}&quot;)\n return self.session.get(url=url, headers=headers)\n\n def login(self, url: str, csrf_token: str, username: str, password: str, headers: None):\n &quot;&quot;&quot;Log in to website - some extra headers may be provided\n &quot;&quot;&quot;\n self.logger.debug(f&quot;Logging in with user: {username}&quot;)\n login_payload = {\n 'hidden_username': username,\n 'password': password,\n 'csrfmiddlewaretoken': csrf_token\n }\n return self.session.post(url=url, data=login_payload, headers=headers)\n\n\ndef main():\n\n try:\n # set up simple logging to console\n logging.getLogger().setLevel(logging.NOTSET)\n\n logger = logging.getLogger(__name__)\n\n # Add stdout handler, with level DEBUG\n console = logging.StreamHandler(sys.stdout)\n console.setLevel(logging.DEBUG)\n formatter = logging.Formatter(\n '%(asctime)s - %(levelname)s - %(message)s',\n datefmt=&quot;%Y-%m-%d %H:%M:%S&quot;\n )\n console.setFormatter(formatter)\n logger.addHandler(console)\n\n # get URL and credentials\n url = input('URL: ')\n login_route = input('LOGIN_ROUTE: ')\n username = getpass.getpass('USERNAME: ')\n password = getpass.getpass('PASSWORD: ')\n\n # start crawling\n downloader = Downloader(logger=logger)\n page = downloader.fetch_page(url=url)\n if page.status_code == 200:\n # fetch the CSRF token - return None if not found\n csrf_token = page.cookies.get('csrftoken')\n if csrf_token is None:\n raise Exception(&quot;Failed to obtain the CSRF token&quot;)\n else:\n logger.debug(f&quot;Got CSRF token: {csrf_token}&quot;)\n\n # proceed to login - add some extra headers on top of the session headers\n login_headers = {\n 'origin': url,\n 'referer': url + login_route,\n }\n login_request = downloader.login(\n url=login_route, csrf_token=csrf_token, username=username, password=password,\n headers=login_headers\n )\n if login_request.status_code == 200:\n logger.debug(f&quot;You have logged in successfully - status code: {page.status_code}&quot;)\n else:\n raise Exception(f&quot;Failed to login - status code: {login_request.status_code}&quot;)\n\n # TODO: loop on links and retrieve videos\n else:\n raise Exception(f&quot;Failed to fetch URL: {url} - status code: {page.status_code}&quot;)\n\n\n # Ctrl-C\n except KeyboardInterrupt:\n logger.warning(&quot;Shutdown requested (KeyboardInterrupt)...&quot;)\n sys.exit(0)\n\n except Exception:\n logger.error(&quot;Exception occured&quot;, exc_info=True)\n sys.exit(1)\n finally:\n logger.debug(&quot;Application shutting down&quot;)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-25T05:26:37.663", "Id": "520076", "Score": "0", "body": "thank you so much. But how can I pass the login part in case the site is not login required?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T20:56:38.597", "Id": "263428", "ParentId": "263403", "Score": "1" } } ]
{ "AcceptedAnswerId": "263428", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-24T11:40:02.000", "Id": "263403", "Score": "2", "Tags": [ "python", "web-scraping" ], "Title": "Simple Scraper_Downloader based on Youtube-dl" }
263403