body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I have the below code that takes the sql data and exports it to xml or csv. The xml is processing at good speed but my csv sometimes takes 1 hour depending on how many data rows it exports. My question is my code effective writing the csv or it can be improved for speed? Has around 40 columns and x rows which can be over 10k. </p>
<pre><code>public static void SqlExtract(this string queryStatement, string xFilePath, string fileName)
{
string connectionString = @"Data Source=ipaddress; Initial Catalog=name; User ID=username; Password=password";
using (SqlConnection _con = new SqlConnection(connectionString))
{
using (SqlCommand _cmd = new SqlCommand(queryStatement, _con))
{
using (SqlDataAdapter _dap = new SqlDataAdapter(_cmd))
{
if (fileName == "item1" || fileName == "item2" || fileName == "item3")
{
DataSet ds = new DataSet("FItem");
_con.Open();
_dap.Fill(ds);
_con.Close();
FileStream fs = new FileStream(xFilePath, FileMode.Create, FileAccess.Write, FileShare.None);
StreamWriter writer = new StreamWriter(fs, Encoding.UTF8);
ds.WriteXml(writer, XmlWriteMode.IgnoreSchema);
fs.Close();
StringWriter sw = new StringWriter();
ds.WriteXml(sw, XmlWriteMode.IgnoreSchema);
string OutputXML = sw.ToString();
OutputXML = OutputXML.Replace("Table", "Item");
System.IO.File.WriteAllText(xFilePath, OutputXML);
}
else
{
DataTable table1 = new DataTable("Table1");
_con.Open();
_dap.Fill(table1);
_con.Close();
string exportCSV = string.Empty;
foreach (DataRow row in table1.Rows)
{
int i = 1;
foreach (DataColumn column in table1.Columns)
{
if (row[1].ToString() == "002" && i > 41 || row[1].ToString() == "END" && i > 4)
{
//do nothing
}
else
{
if (i > 1)
{
exportCSV += ";";
}
exportCSV += row[column.ColumnName].ToString();
}
i++;
}
exportCSV += "\r\n";
}
//Write CSV
File.WriteAllText(xFilePath, exportCSV.ToString());
}
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T00:36:14.890",
"Id": "466516",
"Score": "0",
"body": "also, you may look into turning this into async Task(), utilizing \"await _con.OpenAsync().ConfigureAwait(false);\" and \" _cmd.ExecuteReaderAsync\""
}
] |
[
{
"body": "<p>Your biggest problem targeting performance is the use of string concatenation by using <code>exportCSV +=</code>. Each time such a line will be executed a new string object will be created which takes time. </p>\n\n<p>By using a <code>StringBuilder</code> like so </p>\n\n<pre><code>StringBuilder exportCSV = new StringBuilder(1024);\nforeach (DataRow row in table1.Rows)\n{\n int i = 1;\n foreach (DataColumn column in table1.Columns)\n {\n if (row[1].ToString() == \"002\" && i > 41 || row[1].ToString() == \"END\" && i > 4)\n {\n //do nothing\n }\n else\n {\n if (i > 1)\n {\n exportCSV.Append(\";\");\n }\n exportCSV.Append(row[column.ColumnName].ToString());\n }\n i++;\n }\n exportCSV.AppendLine();\n}\n</code></pre>\n\n<p>the performance will get a lot better. </p>\n\n<hr>\n\n<p>The xml-part should be rewritten like so </p>\n\n<pre><code>DataSet ds = new DataSet(\"FItem\");\n_con.Open();\n_dap.Fill(ds);\n_con.Close();\n\nStringWriter sw = new StringWriter();\nds.WriteXml(sw, XmlWriteMode.IgnoreSchema);\nstring outputXML = sw.ToString().Replace(\"Table\", \"Item\");\nSystem.IO.File.WriteAllText(xFilePath, OutputXML);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T11:37:35.243",
"Id": "466421",
"Score": "0",
"body": "thanks so much for the info it greatly improved performance now it’s like under a minute. Learn something new today thanks a lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T11:58:27.300",
"Id": "466423",
"Score": "0",
"body": "Do you have any tips for improving speed on the xml part?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T12:34:31.147",
"Id": "466427",
"Score": "0",
"body": "sorry what do you mean I’m writing it twice? If I leave one or the other I will not be able to access the xml I’ll get an error failed to parse document."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T12:40:50.110",
"Id": "466429",
"Score": "0",
"body": "You are using `StreamWriter` to write to a `FileStream` and later on you use a `StringWriter` and use the content of it to call `File.WriteAllText()` which overwrites the formerly written file. See: https://docs.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=netframework-4.8"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T12:42:48.980",
"Id": "466430",
"Score": "0",
"body": "I need to do that to replace the tag name as when I start to write first time the tag is “table” default I think but I need it to be “Item”"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T12:47:02.697",
"Id": "466432",
"Score": "0",
"body": "if I comment that out the size of the file is 0 also I get an error when I try to open the file “failed to parse document “. I think it needs to be encoded with utf8."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T12:59:52.473",
"Id": "466434",
"Score": "0",
"body": "I read the link you sent and commented out the StreamWriter but I didn’t do anything to FileStream which was causing the issue. Now everything works thanks for your help. Much appreciated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T13:03:35.020",
"Id": "466435",
"Score": "0",
"body": "Updated answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T13:05:12.877",
"Id": "466436",
"Score": "0",
"body": "exactly that’s what I have thanks a lot."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T10:54:32.837",
"Id": "237827",
"ParentId": "237826",
"Score": "4"
}
},
{
"body": "<p>Some quick remarks:</p>\n\n<ul>\n<li><p>Don't start variable names with underscores unless they're class-wide <code>private</code> ones.</p></li>\n<li><p>Local variables should be camelCased. <code>OutputXML</code> doesn't follow that rule.</p></li>\n<li><p>Split your code into smaller methods that don't intermix data retrieval and file writing. Your method does multiple things, depending on some (odd) logic. Even its name doesn't make sense: it's called <code>SqlExtract</code> yet it generates CSV or XML files depending on seemingly arbitrary conditions.</p></li>\n<li><p>Don't hardcode your connection string. Put it in a .config file and <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.configuration.configurationmanager.connectionstrings?view=netframework-4.8\" rel=\"nofollow noreferrer\">access it via the ConfigurationManager</a>.</p></li>\n<li><p>Why do <code>_con.Open();</code> and <code>_con.Close();</code>? The <code>using</code> takes care of this.</p></li>\n<li><p>Don't loop through <code>table1.Rows</code>. Instead have a method that transforms a <code>DataRow row</code> into a csv line and use that to construct a <code>IEnumerable<T></code>, which you then can use in combination with <code>string.Join()</code>. Something like <code>var csvContents = string.Join(Environment.NewLine, table1.Rows.Cast<DataRow>().Select(x => DataRowToCsvLine(x)));</code>. That's one line (instead of 20) which expresses far better what your code does (and yes, the <code>DataRowToCsvLine</code> method is also a couple of lines, but it doesn't pollute the main logic).</p></li>\n<li><p><code>row[1].ToString() == \"END\"</code>: are you sure it is always going to be <code>\"END\"</code>? Or is it possible it can be <code>\"end\"</code>? Consider using <code>string.Equals()</code> instead, which allows for case insensitive comparisons. Same for <code>fileName == \"item1\"</code> etc.</p></li>\n<li><p>Properly dispose of <code>StringWriter</code> with a <code>using</code> block. Example: <a href=\"https://social.msdn.microsoft.com/Forums/vstudio/en-US/7d949d5c-a41c-4dc7-bbcb-429761f851d1/is-calling-flush-and-close-necesary-for-stringwriter-and-xmltextwriter?forum=netfxbcl\" rel=\"nofollow noreferrer\">https://social.msdn.microsoft.com/Forums/vstudio/en-US/7d949d5c-a41c-4dc7-bbcb-429761f851d1/is-calling-flush-and-close-necesary-for-stringwriter-and-xmltextwriter?forum=netfxbcl</a></p></li>\n</ul>\n\n<p>None of the above might improve the speed of your code, but it will make it much more maintainable and consistent.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T12:36:29.027",
"Id": "466428",
"Score": "0",
"body": "Thanks for the tips I will amend this mistakes. The last par of the comments I can guarantee that END will be upper case. Same as with the item name."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T12:02:33.577",
"Id": "237831",
"ParentId": "237826",
"Score": "5"
}
},
{
"body": "<p>Something along these lines:\nwhere your \"entry point\" is extension method <strong>DataTable.SqlToFile()</strong> (see DoWork below as a usage example). \nI'd suggest breaking your main logic of \"serializing\" datatable as xml/csv into separate methods - <strong>SqlToFile</strong> (saves \"serialized\" datatable into a file), <strong>SqlExtract</strong> (extracts datatable rows as xml or csv), and 2 separate methods <strong>SqlAsXML()</strong> and <strong>SqlAsCSV()</strong> to get xml and csv strings respectively.\nTo serialize into xml, I'm using GetXML() ( or you can use WriteXML() as you did). And to serialize into csv, by using StringBuilder() and iterating in Rows, \"saving\" each row as comma-delimited string.</p>\n\n<p>In addition, data access logic is implemented as its own class.</p>\n\n<pre><code>public static class SQLExtensions\n{\n public static bool SqlToFile(this System.Data.DataTable dt, string xFilePath, string fileName)\n {\n try\n {\n string result = dt.SqlExtract(fileName);\n System.IO.File.WriteAllText(xFilePath, result);\n return true;\n }\n catch (System.IO.IOException ex)\n {\n return false;\n }\n catch (Exception ex)\n {\n return false;\n }\n }\n\n public static string SqlExtract(this System.Data.DataTable dt, string fileName)\n {\n string result = String.Empty;\n var xmlfiles = new[] { \"item1\", \"item2\", \"item3\" };\n if (xmlfiles.Contains(fileName))\n {\n result = dt.SqlAsXML(fileName);\n }\n else\n {\n string delimiter = \";\";\n result = dt.FilterData().SqlAsCSV(delimiter);\n }\n return result;\n }\n\n public static string SqlAsXML(this System.Data.DataTable dt, string fileName)\n {\n var ds = new System.Data.DataSet();\n ds.Tables.Add(dt);\n string xml = ds.GetXml();\n return xml;\n }\n #region CSV related\n public static IEnumerable<System.Data.DataRow> FilterData(this System.Data.DataTable dtIns)\n {\n var list = dtIns\n .Rows.Cast<System.Data.DataRow>()\n .Where(\n r => !((r[1].ToString() == \"002\" && dtIns.Rows.IndexOf(r) > 41) || (r[1].ToString() == \"END\" && dtIns.Rows.IndexOf(r) > 4))\n )\n ;\n return list;\n }\n public static string SqlAsCSV(this System.Data.DataTable dt, string delimiter = \",\")\n {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < dt.Rows.Count - 1; i++)\n {\n System.Data.DataRow dr = dt.Rows[i];\n sb.AppendLine(dr.RowDataAsCSV(delimiter));\n }\n return sb.ToString();\n }\n public static string SqlAsCSV(this IEnumerable<System.Data.DataRow> rows, string delimiter = \",\")\n {\n StringBuilder sb = new StringBuilder();\n foreach (var row in rows)\n {\n sb.AppendLine(row.RowDataAsCSV(delimiter));\n }\n return sb.ToString();\n }\n public static string RowDataAsCSV(this System.Data.DataRow row, string delimiter = \",\")\n {\n string rowdata = String.Join(delimiter, row.ItemArray.Select(f => f.ToString()));\n return rowdata;\n }\n #endregion\n}\n\npublic class DataAccess\n{\n public async Task< System.Data.DataTable> DataAsync(string connectionInfo, string commandSQL)\n {\n System.Data.DataTable dt = new System.Data.DataTable(\"data\");\n\n using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionInfo))\n {\n try\n {\n await connection.OpenAsync().ConfigureAwait(false);\n }\n catch (InvalidOperationException ex)\n {\n return null;\n }\n catch (System.Data.SqlClient.SqlException ex)\n {\n return null;\n }\n using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(commandSQL, connection))\n {\n using (var r = await command.ExecuteReaderAsync(System.Data.CommandBehavior.SequentialAccess).ConfigureAwait(false))\n {\n dt.Load(r);\n }\n }\n connection.Close();\n }\n\n return dt;\n }\n}\n\npublic class MainMainMain\n{\n public async Task DoWork(string commandSQL, string xFilePath, string fileName)\n {\n string connectionString = @\"Data Source=ipaddress; Initial Catalog=name; User ID=username; Password=password\";\n var da = new DataAccess();\n var dt = await da.DataAsync(connectionString, commandSQL ).ConfigureAwait(false);\n if (dt != null)\n {\n bool converted = dt.SqlToFile(xFilePath, fileName);\n }\n else\n {\n //oh-ho\n }\n }\n}\n</code></pre>\n\n<ul>\n<li>furthermore, you could add common interface, and have AsXML and AsCSV as implmentations.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T14:30:37.583",
"Id": "466579",
"Score": "0",
"body": "Could you add why you made the changes you did? Its not much help to the OP if you just modify there code without an explanation for why they should change that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T15:11:06.053",
"Id": "466590",
"Score": "1",
"body": "good point, will do"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T15:51:59.637",
"Id": "466599",
"Score": "0",
"body": "@yob Can you let me know if I do this changes will this increase performance? At the moment with all changes made from OP It takes for 10k rows around 2 min which is not bad considering it originally took around 15 mins for csv. Are you able to provide more info why this is more better approach? Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T16:17:53.110",
"Id": "466601",
"Score": "0",
"body": "@QuickSilver, - i tried export to csv from selecting 8 columns and 2 columns from table containing 49700 rows. timings were ~23 sec and ~13 seconds."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T16:19:24.140",
"Id": "466602",
"Score": "0",
"body": "@yob thanks I’ll give it a try"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T16:21:14.623",
"Id": "466603",
"Score": "0",
"body": "@QuickSilver - 2 points, - 1) check if data \"extraction\" is a \"bottleneck\", 2) and remove \"if (row[1].ToString() == \"002\" && i > 41 || row[1].ToString() == \"END\" && i > 4)\" from within the loop, and instead use DataView with RowFilter"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T16:54:46.210",
"Id": "466610",
"Score": "0",
"body": "@yob are you able to update your answer to include this changes so other people can read through and understand everything. Also I wanted to ask how to exclude the column name from the extract in your version as it’s getting generated on the file. Also I can see at the very end of the column it’s just printing “;” because each second row will have less columns than the first so I want to only generate if there is data in the column and not have blank spaces so every second row will have 14 columns less that the first row and I need to avoid writing this. The last row is short as well 5 cols."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T19:16:20.657",
"Id": "466620",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/104899/discussion-between-yob-and-quicksilver)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T13:39:10.307",
"Id": "237904",
"ParentId": "237826",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "237827",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T10:37:11.617",
"Id": "237826",
"Score": "3",
"Tags": [
"c#",
"performance",
"sql-server"
],
"Title": "Export sql data to xml and csv"
}
|
237826
|
<pre><code> public class EmployeeDBHandler
{
public List<Employee> GetEmployees()
{
List<Employee> empList = new List<Employee>();
string sqlConnstr = Utils.GetDBConnection();
SqlConnection sqlConn = new SqlConnection(sqlConnstr);
SqlCommand sqlCmd = new SqlCommand("GetAllEmployee", sqlConn);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlConn.Open();
using (SqlDataReader reader = sqlCmd.ExecuteReader())
{
while (reader.Read())
{
var emp = new Employee()
{
EId = (int)(reader["EmpID"]),
FirstName = Convert.ToString(reader["FirstName"]),
LastName = Convert.ToString(reader["LastName"])
};
empList.Add(emp);
}
}
return empList;
}
public List<Employee> FetchEmployee(int empid)
{
List<Employee> empList = new List<Employee>();
string sqlConnstr = Utils.GetDBConnection();
SqlConnection sqlConn = new SqlConnection(sqlConnstr);
SqlCommand sqlCmd = new SqlCommand("usp_FetchEmployeeDetails", sqlConn);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("@EmpID", empid);
sqlConn.Open();
using (SqlDataReader reader = sqlCmd.ExecuteReader())
{
while (reader.Read())
{
var emp = new Employee()
{
EId = (int)(reader["EmpID"]),
FirstName = (reader["FirstName"].ToString()),
LastName = (reader["LastName"].ToString())
};
empList.Add(emp);
}
}
return empList;
}
public void AddEmployeeInfo(string firstname, string lastname)
{
string sqlConnstr = Utils.GetDBConnection();
SqlConnection sqlConn = new SqlConnection(sqlConnstr);
SqlCommand sqlCmd = new SqlCommand("AddEmployee", sqlConn);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("@FirstName", firstname);
sqlCmd.Parameters.AddWithValue("@LastName", lastname);
sqlConn.Open();
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
public void UpdateEmployee(int empid,string firstname, string lastname)
{
string sqlConnstr = Utils.GetDBConnection();
SqlConnection sqlConn = new SqlConnection(sqlConnstr);
SqlCommand sqlCmd = new SqlCommand("usp_UpdateEmployeeDetails", sqlConn);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("@EmpID", empid);
sqlCmd.Parameters.AddWithValue("@FirstName", firstname);
sqlCmd.Parameters.AddWithValue("@LastName", lastname);
sqlConn.Open();
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
public void DeleteEmployee(int empid)
{
string sqlConnstr = Utils.GetDBConnection();
SqlConnection sqlConn = new SqlConnection(sqlConnstr);
SqlCommand sqlCmd = new SqlCommand("usp_DeleteEmployeeDetails", sqlConn);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("@EmpID",empid);
sqlConn.Open();
sqlCmd.ExecuteNonQuery();
sqlConn.Close();
}
}
</code></pre>
<p>I'm try to build a 3-tier arch. but I feel these code can be improvised so please review my above Data Access Layer code and give suggestions and corrections, if any, to improvise my code.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T11:38:33.333",
"Id": "466422",
"Score": "5",
"body": "This is riddled with outdated and downright bad practices. Throw it all away and [use Dapper](https://dapper-tutorial.net/) instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T11:41:40.760",
"Id": "466707",
"Score": "0",
"body": "@BCdotWEB Thanks for the suggestion.. minimal code and neat..It's Dapper."
}
] |
[
{
"body": "<p>something along these lines</p>\n\n<pre><code>public static class DTExtensions\n{\n public static List<T> ToList<T>(this System.Data.DataTable dt) where T : new()\n {\n var obj = dt.Rows.OfType<System.Data.DataRow>().Select(dr => dr.ToObject<T>()).ToList();\n return obj;\n }\n public static T ToObject<T>(this System.Data.DataRow dataRow) where T : new()\n {\n T item = new T();\n var itemType = item.GetType();\n foreach (System.Data.DataColumn column in dataRow.Table.Columns)\n {\n System.Reflection.PropertyInfo property = itemType.GetProperty(column.ColumnName);\n\n if (property != null && dataRow[column] != DBNull.Value)\n {\n var result = Convert.ChangeType(dataRow[column], property.PropertyType);\n property.SetValue(item, result, null);\n }\n }\n\n return item;\n }\n}\n\n\npublic class DataHandler\n{\n private readonly string _ConnectionInfo = String.Empty;\n public DataHandler(string connectioninfo)\n {\n _ConnectionInfo = connectioninfo;\n }\n\n public async Task<System.Data.DataTable> DataAsync( string commandSQL, IEnumerable<System.Data.SqlClient.SqlParameter> listParameter=null)\n {\n System.Data.DataTable dt = new System.Data.DataTable(\"data\");\n\n using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(_ConnectionInfo))\n {\n try\n {\n await connection.OpenAsync().ConfigureAwait(false);\n }\n catch (InvalidOperationException ex)\n {\n return null;\n }\n catch (System.Data.SqlClient.SqlException ex)\n {\n return null;\n }\n using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(commandSQL, connection))\n {\n command.CommandType = System.Data.CommandType.StoredProcedure;\n if (listParameter != null && listParameter.Any())\n {\n command.Parameters.AddRange(listParameter.Where(p => p != null).ToArray());\n }\n using (var r = await command.ExecuteReaderAsync(System.Data.CommandBehavior.SequentialAccess).ConfigureAwait(false))\n {\n dt.Load(r);\n }\n command.Parameters.Clear();\n }\n connection.Close();\n }\n\n return dt;\n }\n}\n\npublic sealed class Employee\n{\n public string EmpID { get; set; }\n public string FirstName { get; set; }\n public string LastName { get; set; }\n}\n\npublic class EmployeeDBHandler\n{\n private readonly DataHandler _DataHandler;\n public EmployeeDBHandler(DataHandler datahandler)\n {\n _DataHandler = datahandler ?? throw new System.ArgumentNullException(\"datahandler\");\n }\n\n public async Task<List<Employee>> GetEmployees()\n {\n System.Data.DataTable dt = await _DataHandler.DataAsync(\"GetAllEmployee\").ConfigureAwait(false);\n if (dt != null)\n {\n //OR look into using yeild\n //yield return employee\n //OR\n var list = dt.ToList<Employee>();\n return list;\n }\n return null;\n }\n\n public async Task<List<Employee>> FetchEmployee(int empid)\n {\n List<Employee> empList = new List<Employee>();\n var parameters = new List<System.Data.SqlClient.SqlParameter> { new SqlParameter(\"@EmpID\", empid) };\n System.Data.DataTable dt = await _DataHandler.DataAsync(\"usp_FetchEmployeeDetails\", parameters).ConfigureAwait(false);\n if (dt != null && dt.Rows.Count>0)\n {\n var list = dt.ToList<Employee>();\n return list;\n }\n return null;\n }\n}\n\n// main program:\npublic class MainProgram\n{\n public void DoSomeWork()\n {\n string sqlConnstr = @\"Data Source=<...>; Initial Catalog=<...>; User ID=username; Password=password\"; //Utils.GetDBConnection();\n var dbHandler = new DataHandler(sqlConnstr);\n var employeeHandler = new EmployeeDBHandler(dbHandler);\n\n var employees = employeeHandler.GetEmployees();\n if (employees != null)\n {\n //.....\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T11:44:32.643",
"Id": "466708",
"Score": "1",
"body": "Thanks for your effort. Could you edit your code by adding some comments which will give me more understanding on the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T13:46:31.330",
"Id": "469766",
"Score": "1",
"body": "-1 This provides NO review at all, just a bunch of code without an explanation on what it does improve and no rationale for any change."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T13:57:39.937",
"Id": "469768",
"Score": "0",
"body": "this provides \"give suggestions and corrections\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T15:17:41.370",
"Id": "469787",
"Score": "1",
"body": "@yob No, it doesn't. It's just a bunch of code, with no suggestion nor correction of anything. You should explain the rationale for the suggested code and how it improves the original code. A code review is all about explaining possible improvements, not just \"use this instead\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-21T22:32:19.747",
"Id": "497462",
"Score": "1",
"body": "This is not a code review."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T13:59:39.353",
"Id": "237907",
"ParentId": "237828",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T10:55:06.433",
"Id": "237828",
"Score": "3",
"Tags": [
"c#",
"ado.net"
],
"Title": "Improvements to data access layer"
}
|
237828
|
<p>I'm trying to compile stats for college basketball games. I have two inputs:</p>
<p><code>regular_season_boxscore_df</code>: A DataFrame consiststing of regular season boxscores.
It looks like this:</p>
<pre><code>print(regular_season_boxscore_df.head())
Season DayNum WTeamID WScore LTeamID ... LAst LTO LStl LBlk LPF
0 2003 10 1104 68 1328 ... 8 18 9 2 20
1 2003 10 1272 70 1393 ... 7 12 8 6 16
2 2003 11 1266 73 1437 ... 9 12 2 5 23
3 2003 11 1296 56 1457 ... 9 19 4 3 23
4 2003 11 1400 77 1208 ... 12 10 7 1 14
[5 rows x 34 columns]
print(regular_season_boxscore_df.columns)
Index(['Season', 'DayNum', 'WTeamID', 'WScore', 'LTeamID', 'LScore', 'WLoc',
'NumOT', 'WFGM', 'WFGA', 'WFGM3', 'WFGA3', 'WFTM', 'WFTA', 'WOR', 'WDR',
'WAst', 'WTO', 'WStl', 'WBlk', 'WPF', 'LFGM', 'LFGA', 'LFGM3', 'LFGA3',
'LFTM', 'LFTA', 'LOR', 'LDR', 'LAst', 'LTO', 'LStl', 'LBlk', 'LPF'],
dtype='object')
</code></pre>
<p><code>running_team_stats_df</code>: A DataFrame which will contain the running totals for a team's stats for each season. It's filled with zeros and looks like this:</p>
<pre><code>print(running_team_stats_df.head())
season team_id day_num FGA FGM Ast Blk ... FTA FTM NumOT OR PF Stl TO
0 2003 1101 0 0 0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0
1 2003 1102 0 0 0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0
2 2003 1103 0 0 0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0
3 2003 1104 0 0 0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0
4 2003 1105 0 0 0 0.0 0.0 ... 0.0 0.0 0.0 0.0 0.0 0.0 0.0
[5 rows x 17 columns]
print(running_team_stats_df.columns)
Index(['season', 'team_id', 'day_num', 'FGA', 'FGM', 'Ast', 'Blk', 'DR',
'FGA3', 'FGM3', 'FTA', 'FTM', 'NumOT', 'OR', 'PF', 'Stl', 'TO'],
dtype='object')
</code></pre>
<p>(I realize there's a 'Season' vs 'season' and a 'DayNum' vs 'day_num' naming scheme discrepancy. That's one of the first things I want to fix)</p>
<p>On to my code. I want to expand the regular season box score to include a running list of stats for the current season. Currently, the boxscore only lists that games stats for the winning team and losing team. I want to have those teams season stats in there as well. Here's the code I'm using to get that done:</p>
<pre><code>def expand_regular_season(regular_season_boxscore_df, running_team_stats_df):
print('Expanding regular season to add detail...', end='')
# Create expanded boxscore df
regular_season_detail_df = pd.DataFrame(columns = [
'Season', 'DayNum', 'WTeamID', 'WScore', 'LTeamID', 'LScore', 'WLoc', 'NumOT',
'WFGM', 'WFGA', 'WFGM3', 'WFGA3', 'WFTM', 'WFTA', 'WOR', 'WDR',
'WAst', 'WTO', 'WStl', 'WBlk', 'WPF',
'year_WNumOT', 'year_WFGM', 'year_WFGA', 'year_WFGM3', 'year_WFGA3',
'year_WFTM', 'year_WFTA', 'year_WOR',
'year_WDR', 'year_WAst', 'year_WTO', 'year_WStl', 'year_WBlk', 'year_WPF',
'LFGM', 'LFGA', 'LFGM3', 'LFGA3',
'LFTM', 'LFTA', 'LOR', 'LDR', 'LAst', 'LTO', 'LStl', 'LBlk', 'LPF',
'year_LNumOT', 'year_LFGM', 'year_LFGA', 'year_LFGM3', 'year_LFGA3',
'year_LFTM', 'year_LFTA', 'year_LOR',
'year_LDR', 'year_LAst', 'year_LTO', 'year_LStl', 'year_LBlk', 'year_LPF'])
with tqdm(total=len(regular_season_boxscore_df)) as pbar:
for _, row in regular_season_boxscore_df.iterrows():
# Create a condition for easier locating based on the season and the team
win_team_cond = ((running_team_stats_df.season == row.Season) &(running_team_stats_df.team_id == row.WTeamID))
lose_team_cond = ((running_team_stats_df.season == row.Season) & (running_team_stats_df.team_id == row.LTeamID))
# Create a series that pulls the running teams stats prior to the current game
_ds = pd.Series({
'year_WNumOT': running_team_stats_df.loc[win_team_cond, 'NumOT'].values[0],
'year_WFGM' : running_team_stats_df.loc[win_team_cond, 'FGM'].values[0],
'year_WFGA' : running_team_stats_df.loc[win_team_cond, 'FGA'].values[0],
'year_WFGM3' : running_team_stats_df.loc[win_team_cond, 'FGM3'].values[0],
'year_WFGA3' : running_team_stats_df.loc[win_team_cond, 'FGA'].values[0],
'year_WFTM' : running_team_stats_df.loc[win_team_cond, 'FTM'].values[0],
'year_WFTA' : running_team_stats_df.loc[win_team_cond, 'FTA'].values[0],
'year_WOR' : running_team_stats_df.loc[win_team_cond, 'OR'].values[0],
'year_WDR' : running_team_stats_df.loc[win_team_cond, 'DR'].values[0],
'year_WAst' : running_team_stats_df.loc[win_team_cond, 'Ast'].values[0],
'year_WTO' : running_team_stats_df.loc[win_team_cond, 'TO'].values[0],
'year_WStl' : running_team_stats_df.loc[win_team_cond, 'Stl'].values[0],
'year_WBlk' : running_team_stats_df.loc[win_team_cond, 'Blk'].values[0],
'year_WPF' : running_team_stats_df.loc[win_team_cond, 'PF'].values[0],
'year_LNumOT': running_team_stats_df.loc[lose_team_cond, 'NumOT'].values[0],
'year_LFGM' : running_team_stats_df.loc[lose_team_cond, 'FGM'].values[0],
'year_LFGA' : running_team_stats_df.loc[lose_team_cond, 'FGA'].values[0],
'year_LFGM3' : running_team_stats_df.loc[lose_team_cond, 'FGM3'].values[0],
'year_LFGA3' : running_team_stats_df.loc[lose_team_cond, 'FGA'].values[0],
'year_LFTM' : running_team_stats_df.loc[lose_team_cond, 'FTM'].values[0],
'year_LFTA' : running_team_stats_df.loc[lose_team_cond, 'FTA'].values[0],
'year_LOR' : running_team_stats_df.loc[lose_team_cond, 'OR'].values[0],
'year_LDR' : running_team_stats_df.loc[lose_team_cond, 'DR'].values[0],
'year_LAst' : running_team_stats_df.loc[lose_team_cond, 'Ast'].values[0],
'year_LTO' : running_team_stats_df.loc[lose_team_cond, 'TO'].values[0],
'year_LStl' : running_team_stats_df.loc[lose_team_cond, 'Stl'].values[0],
'year_LBlk' : running_team_stats_df.loc[lose_team_cond, 'Blk'].values[0],
'year_LPF' : running_team_stats_df.loc[lose_team_cond, 'PF'].values[0]})
# Create a new row that contains the original box score and the current running stats for the season
regular_season_detail_df = regular_season_detail_df.append(row.append(_ds), ignore_index = True)
# Update the running stats
running_team_stats_df.loc[win_team_cond, 'day_num'] = row['DayNum']
running_team_stats_df.loc[win_team_cond, 'FGA'] += row['WFGA']
running_team_stats_df.loc[win_team_cond, 'FGM'] += row['WFGM']
running_team_stats_df.loc[win_team_cond, 'Ast'] += row['WAst']
running_team_stats_df.loc[win_team_cond, 'Blk'] += row['WBlk']
running_team_stats_df.loc[win_team_cond, 'DR'] += row['WDR']
running_team_stats_df.loc[win_team_cond, 'FGA3'] += row['WFGA3']
running_team_stats_df.loc[win_team_cond, 'FGM3'] += row['WFGM3']
running_team_stats_df.loc[win_team_cond, 'FTA'] += row['WFTA']
running_team_stats_df.loc[win_team_cond, 'FTM'] += row['WFTM']
running_team_stats_df.loc[win_team_cond, 'NumOT'] += row['NumOT']
running_team_stats_df.loc[win_team_cond, 'OR'] += row['WOR']
running_team_stats_df.loc[win_team_cond, 'PF'] += row['WPF']
running_team_stats_df.loc[win_team_cond, 'Stl'] += row['WStl']
running_team_stats_df.loc[win_team_cond, 'TO'] += row['WTO']
running_team_stats_df.loc[lose_team_cond, 'day_num'] = row['DayNum']
running_team_stats_df.loc[lose_team_cond, 'FGA'] += row['LFGA']
running_team_stats_df.loc[lose_team_cond, 'FGM'] += row['LFGM']
running_team_stats_df.loc[lose_team_cond, 'Ast'] += row['LAst']
running_team_stats_df.loc[lose_team_cond, 'Blk'] += row['LBlk']
running_team_stats_df.loc[lose_team_cond, 'DR'] += row['LDR']
running_team_stats_df.loc[lose_team_cond, 'FGA3'] += row['LFGA3']
running_team_stats_df.loc[lose_team_cond, 'FGM3'] += row['LFGM3']
running_team_stats_df.loc[lose_team_cond, 'FTA'] += row['LFTA']
running_team_stats_df.loc[lose_team_cond, 'FTM'] += row['LFTM']
running_team_stats_df.loc[lose_team_cond, 'NumOT'] += row['NumOT']
running_team_stats_df.loc[lose_team_cond, 'OR'] += row['LOR']
running_team_stats_df.loc[lose_team_cond, 'PF'] += row['LPF']
running_team_stats_df.loc[lose_team_cond, 'Stl'] += row['LStl']
running_team_stats_df.loc[lose_team_cond, 'TO'] += row['LTO']
pbar.update()
print('done')
return regular_season_detail_df
</code></pre>
<p>I'm very new to Pandas and I'm sure there's a better way to be using it that doesn't involve iterating through every row. There's 87504 boxscores to get through and it took about four and a half hours to run, so not ideal.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T14:01:11.233",
"Id": "466442",
"Score": "0",
"body": "Welcome to Code Review! – While you question is good, you should change the title of this post to a general description of what the code does. Asking for a better way to something is implied in any code review posts, and is therefore unnecessary. Check out this (https://codereview.stackexchange.com/help/how-to-ask) page for more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T14:07:28.763",
"Id": "466443",
"Score": "0",
"body": "When you say the `running_team_stats_df` is a running total, does this mean that for each team it contains their stats for each day of the season? Are all of your stats additive? Can you share a larger sample of your data, covering each of the changing things (team ID, day_num, etc), for this a link would suffice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T14:11:10.480",
"Id": "466444",
"Score": "0",
"body": "running_team_stats_df contains the current seasonal stats for that team and season. So for example, there will be one unique row for each team for each season (2003 to current). I call it a running total because when I'm iterating through the season, it will be 'up to date' at that time and that way I can add that data to the regular season box score. So the box score wont only have that games stats, it'll have that teams seasons stats as well."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T13:32:33.393",
"Id": "237832",
"Score": "2",
"Tags": [
"python",
"pandas"
],
"Title": "Trying to optimize code that creates a running tally of a team's seasonal stats and adds it to their boxscore"
}
|
237832
|
<p>I am working to a python application for some operational test on a Arista brand Network (more info here: <a href="https://gitlab.com/networkAutomation/pyateos" rel="nofollow noreferrer">https://gitlab.com/networkAutomation/pyateos</a>)</p>
<p>I am the only one doing coding in my team so I do not have much chance to compare myself with someone really knowledgeable that can suggest me a better way to do coding. So far I compare my code with pylint (great way to learn) as well as blogs and community. Would be great if you can have a look and tell me what you think. I am available to any sort of suggestion. Thanks for your time.</p>
<pre><code>#!/usr/bin/env python3
import os
import re
import sys
import time
import json
import argparse
from jsondiff import diff
from pyeapi import load_config
from pyeapi import connect_to
from plugins.acl import acl
from plugins.as_path import as_path
from plugins.bgp_evpn import bgp_evpn
from plugins.bgp_ipv4 import bgp_ipv4
from plugins.interface import interface
from plugins.ip_route import ip_route
from plugins.mlag import mlag
from plugins.ntp import ntp
from plugins.prefix_list import prefix_list
from plugins.route_map import route_map
from plugins.snmp import snmp
from plugins.stp import stp
from plugins.vlan import vlan
from plugins.vrf import vrf
from plugins.vxlan import vxlan
def arguments():
parser = argparse.ArgumentParser(
prog='pyATEOS',
description='''pyATEOS - A simple python application for operational status test on
Arista device. Based on pyATS idea and pyeapi library for API calls.'''
)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
'-B',
'--before',
dest='before',
action='store_true',
help='''write json file containing the test result BEFORE.
To be run BEFORE the config change.
File path example: $PWD/before/ntp/router1_ntp.json'''
)
group.add_argument(
'-A',
'--after',
dest='after',
action='store_true',
help='''write json file containing the test result AFTER.
To be run AFTER the config change.
File path example: $PWD/after/ip_route/router1_ip_route.json'''
)
group.add_argument(
'-C',
'--compare',
dest='compare',
action='store_true',
help='''diff between before and after test files.
File path example: $PWD/diff/snmp/router1_snmp.json'''
)
parser.add_argument(
'-i',
'--inventory',
dest='inventory',
help='specify pyeapi inventory file path'
)
parser.add_argument(
'-n',
'--node',
dest='node',
help='specify inventory node. Multiple values are accepted separated by space',
nargs='+',
required=True
)
parser.add_argument(
'-t',
'--test',
dest='test',
help='run one or more specific test. Multiple values are accepted separated by space',
nargs='+',
required=True
)
parser.add_argument(
'-F',
'--file_name',
dest='file',
help='''provide the 2 filename IDs to compare, separated by space.
BEFORE first, AFTER second. i.e [..] -C -f 1582386835 1582387929''',
nargs='+',
type=int,
)
if parser.parse_args().compare and parser.parse_args().file is None:
parser.error("-C/--compare requires -F/--file_name.")
return parser.parse_args()
def flags(args):
returned_dict = dict()
if args.inventory:
inventory = args.inventory
else:
inventory = 'eos_inventory.ini'
if args.compare:
if args.file:
assert len(args.file) == 2 and (args.file[0] - args.file[1]) < 0, '''
provide the 2 filename IDs to compare, separated by space.
BEFORE first, AFTER second. i.e [..] -C -f 1582386835 1582387929'''
file_name = args.file
else:
file_name = None
returned_dict.update(
inventory=inventory,
node=args.node,
test=args.test,
before=args.before,
after=args.after,
compare=args.compare,
file_name=file_name
)
return returned_dict
class WriteFile():
def __init__(self, test, node, file_name=None):
self.test = test
self.node = node
self.file_name = file_name
self.pwd_before = os.getcwd() + '/before/{}'.format(self.test)
self.pwd_after = os.getcwd() + '/after/{}'.format(self.test)
self.pwd_diff = os.getcwd() + '/diff/{}'.format(self.test)
self.time_file = round(time.time())
def write_before(self, result):
if not os.path.exists(self.pwd_before):
os.makedirs(self.pwd_before)
with open('{0}/{1}_{2}_{3}.json'.format(
self.pwd_before,
self.time_file,
self.test,
self.node
), 'w', encoding='utf-8') as file:
json.dump(result, file, ensure_ascii=False, indent=4)
print('BEFORE file ID for {} test: {}'.format(self.test.upper(), self.time_file))
def write_after(self, result):
if not os.path.exists(self.pwd_after):
os.makedirs(self.pwd_after)
with open('{0}/{1}_{2}_{3}.json'.format(
self.pwd_after,
self.time_file,
self.test,
self.node
), 'w', encoding='utf-8') as file:
json.dump(result, file, ensure_ascii=False, indent=4)
print('AFTER file ID for {} test: {}'.format(self.test.upper(), self.time_file))
def write_diff(self):
if not os.path.exists(self.pwd_diff):
os.makedirs(self.pwd_diff)
def replace(string, substitutions):
substrings = sorted(substitutions, key=len, reverse=True)
regex = re.compile('|'.join(map(re.escape, substrings)))
sub_applied = regex.sub(lambda match: substitutions[match.group(0)], string)
for integer in re.findall(r'\d+:', sub_applied):
sub_applied = sub_applied.replace(integer, f'"{integer[:-1]}":')
return sub_applied
substitutions = {
'\'':'\"',
'insert':'"insert"',
'delete':'"delete"',
'True':'true',
'False':'false',
'(':'[',
')':']',
}
try:
before = open('{0}/{1}_{2}_{3}.json'.format(
self.pwd_before,
self.file_name[0],
self.test,
self.node), 'r')
except FileNotFoundError as error:
print(error)
sys.exit(1)
try:
after = open('{0}/{1}_{2}_{3}.json'.format(
self.pwd_after,
self.file_name[1],
self.test,
self.node), 'r')
except FileNotFoundError as error:
print(error)
sys.exit(1)
json_diff = str(diff(before, after, load=True, syntax='symmetric'))
edit_json_diff = replace(json_diff, substitutions)
diff_file_id = str((self.file_name[0] - self.file_name[1]) * -1)
with open('{0}/{1}_{2}_{3}.json'.format(
self.pwd_diff,
diff_file_id,
self.test,
self.node), 'w', encoding='utf-8') as file:
json.dump(json.loads(edit_json_diff), file, ensure_ascii=False, indent=4)
print('DIFF file ID for {} test: {}'.format(self.test.upper(), diff_file_id))
def bef_aft_com(**kwargs):
test_run = list()
if kwargs:
before = kwargs.get('before')
after = kwargs.get('after')
compare = kwargs.get('compare')
file_name = kwargs.get('file_name')
nodes = kwargs.get('node')
test = kwargs.get('test')
test_all = [
'acl',
'as_path',
'bgp_evpn',
'bgp_ipv4',
'interface',
'ip_route',
'mlag',
'ntp',
'prefix_list',
'route_map',
'snmp',
'stp',
'vlan',
'vrf',
'vxlan'
]
if 'mgmt' in test:
test.remove('mgmt')
test_run.extend(('ntp', 'snmp'))
elif 'routing' in test:
test.remove('routing')
test_run.extend(('bgp_evpn', 'bgp_ipv4', 'ip_route'))
elif 'layer2' in test:
test.remove('layer2')
test_run.extend(('stp', 'vlan', 'vxlan'))
elif 'ctrl' in test:
test.remove('ctrl')
test_run.extend(('acl', 'as_path', 'prefix_list', 'route_map'))
elif 'all' in test:
test.remove('all')
test_run = test_all
test_run.extend(test)
for node in nodes:
for test in list(set(test_run)):
if test not in test_all:
raise ValueError('Test name not valid. Please check the test list available under plugins folder')
else:
if before:
wr_before = WriteFile(test, node)
wr_before.write_before(eval(test)(connect_to(node)).show)
elif after:
wr_after = WriteFile(test, node)
wr_after.write_after(eval(test)(connect_to(node)).show)
elif compare:
wr_diff = WriteFile(test, node, file_name)
wr_diff.write_diff()
def main():
my_flags = flags(arguments())
load_config(my_flags.get('inventory'))
if my_flags.get('test'):
bef_aft_com(**my_flags)
if __name__ == '__main__':
main()
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T13:48:01.677",
"Id": "237833",
"Score": "4",
"Tags": [
"python",
"networking",
"automation"
],
"Title": "python network test application"
}
|
237833
|
<p>I have a code to get most similar element in an array of categories of jobs to another job using <a href="https://colab.research.google.com/github/tensorflow/hub/blob/master/examples/colab/cross_lingual_similarity_with_tf_hub_multilingual_universal_encoder.ipynb#scrollTo=Q8F4LNGFqOiq" rel="nofollow noreferrer">Google's Universal Sentence Encoder</a>. </p>
<pre><code>#@title Setup common imports and functions
import numpy as np
import pandas as pd
import tensorflow.compat.v2 as tf
import tensorflow_hub as hub
from tensorflow_text import SentencepieceTokenizer
import sklearn.metrics.pairwise
from simpleneighbors import SimpleNeighbors
from tqdm import tqdm
from tqdm import trange
def most_similar(embeddings_1, embeddings_2, labels_1, labels_2):
assert (len(embeddings_1) == len(labels_1) and len(embeddings_2) == len(labels_2))
# arccos based text similarity (Yang et al. 2019; Cer et al. 2019)
sim = 1 - np.arccos(sklearn.metrics.pairwise.cosine_similarity(embeddings_1, embeddings_2))/np.pi
embeddings_1_col, embeddings_2_col, sim_col = [], [], []
for i in range(len(embeddings_1)):
for j in range(len(embeddings_2)):
embeddings_1_col.append(labels_1[i])
embeddings_2_col.append(labels_2[j])
sim_col.append(sim[i][j])
df = pd.DataFrame(zip(embeddings_1_col, embeddings_2_col, sim_col),
columns=['embeddings_1', 'embeddings_2', 'sim'])
# return the higest similarity one
category = df['embeddings_1'].iloc[df['sim'].argmax()]
return category
def main():
X = pd.read_csv('X.csv')
y = pd.read_csv('y.csv')
df_rni = pd.read_csv('df.csv').head()
# The 16-language multilingual module is the default but feel free
# to pick others from the list and compare the results.
module_url = 'https://tfhub.dev/google/universal-sentence-encoder-multilingual/3' #@param ['https://tfhub.dev/google/universal-sentence-encoder-multilingual/3', 'https://tfhub.dev/google/universal-sentence-encoder-multilingual-large/3']
model = hub.load(module_url)
def embed_text(input):
return model(input)
# get unique job categories and job of people
job_categories = X.S02Q11_Professional_field.unique()
# turn them to list
job_categories = job_categories.tolist()
# emebedding job categories
references_result = embed_text(job_categories[1:])
for _, row in df_rni.iterrows():
actual_job = row['new_professionactuelle']
# check for nan that can't be embedded
if str(actual_job) != 'nan':
# embedding actual job
target_result = embed_text(actual_job)
# visualize similarity
category = most_similar(references_result, target_result, job_categories[1:], [actual_job])
row['category'] = category
print(category)
else: row['category'] = category
df_rni
if __name__ == "__main__":
main()
</code></pre>
<p>Within <code>most_similar()</code>, in a given loop it returns the element with the highest similarity, whatever the languages. For instance with <code>Chef d'Entreprise</code>:</p>
<pre><code> embeddings_1 embeddings_2 sim
0 Property and construction Chef D'entreprise 0.543505
1 Trade Chef D'entreprise 0.578675
2 Leisure, sport and tourism Chef D'entreprise 0.499804
3 Accountancy, banking and finance Chef D'entreprise 0.529382
4 Creative arts and design Chef D'entreprise 0.537169
5 Charity and voluntary work Chef D'entreprise 0.558755
6 Sales Chef D'entreprise 0.598833
7 Healthcare Chef D'entreprise 0.563151
8 Engineering and manufacturing Chef D'entreprise 0.560561
9 Social care Chef D'entreprise 0.558178
10 Agriculture, farming and environment Chef D'entreprise 0.547525
11 Law Chef D'entreprise 0.545288
12 Other. Please specify: Chef D'entreprise 0.511661
13 Teacher training and education Chef D'entreprise 0.563531
14 Hospitality and events management Chef D'entreprise 0.566105
15 Transport and logistics Chef D'entreprise 0.503070
16 Energy and utilities Chef D'entreprise 0.523951
17 Public services and administration Chef D'entreprise 0.541838
18 Information technology Chef D'entreprise 0.535399
19 Business, consulting and management Chef D'entreprise 0.605267
20 Recruitment and HR Chef D'entreprise 0.621728
21 Law enforcement and security Chef D'entreprise 0.526561
</code></pre>
<h1>Inputs and outputs</h1>
<ul>
<li><p>Inputs:</p>
<ol>
<li><code>X.csv</code> a csv/dataframe of actual jobs that look like this one:</li>
</ol></li>
</ul>
<pre><code> new_professionactuelle
0 Entrepreneur
1 طالبة
...
</code></pre>
<ol start="2">
<li><p><code>df.csv</code> job categories that must include all the following categories:</p>
<pre><code>['Agriculture, farming and environment',
'Accountancy, banking and finance',
'Teacher training and education', 'Leisure, sport and tourism',
'Transport and logistics', 'Information technology',
'Hospitality and events management',
'Business, consulting and management', 'Creative arts and design',
'Trade', 'Law enforcement and security',
'Property and construction', 'Law',
'Engineering and manufacturing', 'Social care',
'Charity and voluntary work', 'Sales',
'Public services and administration', 'Other. Please specify:',
'Healthcare', 'Energy and utilities',
'Marketing, advertising and PR', 'Media and internet',
'Recruitment and HR', 'Science and pharmaceuticals']
</code></pre>
<ul>
<li>Output would be the column in <code>X.csv</code> plus a new column, the most similar job.</li>
</ul></li>
</ol>
<pre><code> new_professionactuelle job category
0 Entrepreneur Accountancy, banking and finance
1 طالبة Law
...
</code></pre>
<h1>Concerns</h1>
<p>it returns <code>Recruitment and HR</code>. I want to reduce this code to its simplest and to make it performant (as I will probably test 90000 jobs). Not considering readability I am worried I can get rid of functions that are actually useful, like the <code>assert</code> one that makes me sure that I have the labels corresponding to the embeddings. However I am sure I can do it simpler.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T14:02:49.793",
"Id": "237838",
"Score": "2",
"Tags": [
"python",
"performance",
"machine-learning"
],
"Title": "Get most similar element in an array of string with another string"
}
|
237838
|
<p>I implemented a simple producer-consumer where producer produces links to fetch and several workers consume those URLs and return write data into response queue. Unfortunately, sometimes API can start responding 400-x errors and in that case we need to sleep each for some time. I have implemented it using a queue where I put not only an url, but also time to sleep in case some error happened.</p>
<pre><code>class Producer(object):
def __init__(self, url_queue, total_urls=15):
self.url_queue = url_queue
self.total_urls = total_urls
async def run(self):
count = 0
choices = ['blah-%s' % i for i in range(15)]
while count < self.total_urls:
await self.url_queue.put(('http://localhost:8080/%s' % choices[count], 0))
count += 1
logging.info("Count: %s", count)
if count % 1000 == 0:
await asyncio.sleep(1)
class DownloadWorker(object):
def __init__(self, url_queue: asyncio.Queue,
response_queue: asyncio.Queue):
self.url_queue = url_queue
self.response_queue = response_queue
self.count = 0
async def run(self):
async with aiohttp.ClientSession() as session:
while True:
url, wait = await self.url_queue.get()
if wait:
logging.info("Sleeping for %s ", wait)
await asyncio.sleep(wait)
async with session.get(url) as resp:
try:
content = await resp.json()
await self.response_queue.put(content)
logging.info("Content %s", content)
except:
self.url_queue.put_nowait((url, 3.))
logging.exception('Error processing message')
finally:
self.url_queue.task_done()
</code></pre>
<p>And here is the code for running producer-worker:</p>
<pre><code> async def worker_pattern(worker_count):
response_queue = asyncio.Queue()
url_queue = asyncio.Queue()
producer = Producer(url_queue)
producers = [
asyncio.create_task(producer.run())
]
consumers = []
for i in range(worker_count):
worker = DownloadWorker(url_queue, response_queue)
consumers.append(asyncio.create_task(
worker.run()
))
await asyncio.gather(*producers)
await url_queue.join()
for c in consumers:
c.cancel()
return response_queue
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T14:09:04.537",
"Id": "237839",
"Score": "2",
"Tags": [
"python",
"producer-consumer"
],
"Title": "Managing exceptions in aiohttp using consumer-producer pattern"
}
|
237839
|
<p>Lets say I have one method, which extracts property name and value:</p>
<pre><code>public TModel Get (Expression<Func<object>> param)
{
using (OracleConnection connection = new OracleConnection(GetConnectionString()))
{
connection.Open();
var propertyName= ((MemberExpression)param.Body).Member.Name;
var value = param.Compile()();
// GetTableName() returns table name of TModel
var query = $"SELECT * FROM {GetTableName()} WHERE {propertyName}='{value}'";
var output = connection.Query<TModel>(query);
connection.Dispose();
return output.FirstOrDefault();
}
}
</code></pre>
<p>and using it as:</p>
<pre><code>var model = Get(() => foo.FirstProperty);
</code></pre>
<p>However, if I want to get name and value from the unknown number of properties, I do this:</p>
<pre><code>public TModel Get(params Expression<Func<object>>[] param)
using (OracleConnection connection = new OracleConnection(GetConnectionString()))
{
connection.Open();
var query = new StringBuilder();
query.Append($"SELECT * FROM {GetTableName()} WHERE ");
for (int i = 0; i < param.Length; i++)
{
var propertyName = ((MemberExpression)param[i].Body).Member.Name;
var value = param[i].Compile()();
query.Append($"{propertyName} = '{value}'");
if (i + 1 < param.Length) query.Append(" AND ");
}
var output = connection.Query<TModel>(query.ToString());
connection.Dispose();
return output.FirstOrDefault();
}
}
</code></pre>
<p>But, implementation looks a bit 'ugly' and verbose:</p>
<pre><code>var model = Get(() => foo.FirstProperty, () => foo.SecondProperty); // and so on
</code></pre>
<p>I could send manualy name of the property + value, however, I would like to keep the implementation as simple as possible and less verbose.</p>
<p>Is there any way to simplify this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T16:09:08.517",
"Id": "466458",
"Score": "2",
"body": "Pseudocode, stub code, **hypothetical code**, obfuscated code, and generic best practices are outside the scope of this site. 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": "2020-02-24T16:13:15.997",
"Id": "466459",
"Score": "0",
"body": "Also, what is even the point of this code? In what scenario do you know so little of your DB that you're trying to guess what fields a table has? Surely you're not building your own ORM? If so: https://lostechies.com/jimmybogard/2012/07/24/dont-write-your-own-orm/ ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T21:45:18.463",
"Id": "466500",
"Score": "0",
"body": "@BCdotWEB This is not hypothetical, obfuscated code and I'm not looking for best practices. Main point of this question is how to simplify method to get name/value pairs of multiple properties. And building a dynamic sql statement is not the same as creating own ORM. Reason behind: I'm using dapper.Contrib extention and Oracle database. However, these two are not very 'friendly', therefore, I have a method which writes sql statement based on the given object and then pass it to the dapper, which does all the ORM job."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T22:43:50.853",
"Id": "466508",
"Score": "0",
"body": "how about passing `object[]` which would be something like `Get(() => new {foo.FirstProperty, foo.SecondProperty})` then just loop over the object array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T00:31:33.127",
"Id": "466515",
"Score": "0",
"body": "aside from other comments, why do you invoke \" connection.Dispose()\" if you're enclosing in \"using\"?"
}
] |
[
{
"body": "<p>If you want to iterate through all of the properties then reflection will help you to do that. You can find more at <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.type.getproperties?view=netframework-4.8\" rel=\"nofollow noreferrer\">MS docs</a>\nSomething like this:</p>\n\n<pre><code>public TModel Get<TParam>(TParam param)\n{\n var allParams = typeof(TParam).GetProperties().Select(p => $\"{p.Name} ='{p.GetValue(param)}'\");\n var condition = string.Join(\" AND \", allParams);\n\n using (OracleConnection connection = new OracleConnection(GetConnectionString()))\n {\n connection.Open();\n\n // GetTableName() returns table name of TModel\n var query = $\"SELECT * FROM {GetTableName()} WHERE {condition}\";\n\n var output = connection.Query<TModel>(query);\n return output.FirstOrDefault();\n }\n}\n</code></pre>\n\n<p>But you have to think how to escape SQL injections. Because the value of <code>query</code> variable in current implementation could have potential vulnerabilities.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T21:31:10.337",
"Id": "238170",
"ParentId": "237841",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T15:30:42.007",
"Id": "237841",
"Score": "1",
"Tags": [
"c#",
".net",
"dapper"
],
"Title": "Getting names/values of multiple properties"
}
|
237841
|
<p>I need to transfer data from one vendor's system to another.</p>
<p>The source vendor has a view that generates data that combines invoice and line-item data into records w/ line-item cardinality:</p>
<pre><code>"Invoice","Date","Line","Description","Price"
"A","2/1/2020","1","something","100"
"A","2/1/2020","2","something else","75"
"B","1/1/2020","1","lorem ipsum","25"
"C","12/15/2020","1","foo bar","10.25"
"C","12/15/2020","2","foo bar","99.99"
</code></pre>
<p>The data needs to be transmitted, however, as a unit that combines the invoice and its line items:</p>
<pre><code><I>
<Invoice>A</Invoice>
<Date>02/01/20</Date>
<Items>
<Item>
<Line>1</Line>
<Description>something</Description>
<Price>100</Price>
</Item>
<Item>
<Line>2</Line>
<Description>something else</Description>
<Price>75</Price>
</Item>
</Items>
</I>
</code></pre>
<p>Towards this end, I've written the following:</p>
<pre><code># create testing data
function Get-Data
{
[PSCustomObject]@{
Invoice = 'A'
Date='2/1/2020'
Line=1
Description = 'something'
Price = 100.0
}
[PSCustomObject]@{
Invoice = 'A'
Date='2/1/2020'
Line=2
Description = 'something else'
Price = 75.0
}
[PSCustomObject]@{
Invoice = 'B'
Date='1/1/2020'
Line=1
Description = 'lorem ipsum'
Price = 25.0
}
[PSCustomObject]@{
Invoice = 'C'
Date='12/15/2020'
Line=1
Description = 'foo bar'
Price = 10.25
}
[PSCustomObject]@{
Invoice = 'C'
Date='12/15/2020'
Line=2
Description = 'foo bar'
Price = 99.99
}
}
# serialize related line items
function ConvertTo-LineItemXml {
[CmdletBinding()]
param (
[Parameter(ValueFromPipelineByPropertyName)]
[int]$Line,
[Parameter(ValueFromPipelineByPropertyName)]
[string]$Description,
[Parameter(ValueFromPipelineByPropertyName)]
[decimal]$Price
)
begin {}
process
{
$xml += "<Item><Line>$Line</Line><Description>$Description</Description><Price>$Price</Price></Item>"
}
end
{
$xml
}
}
# convert data to required Xml message and post
function Send-Invoice {
[CmdletBinding()]
param (
[Parameter(ValueFromPipelineByPropertyName)]
[string]$Invoice,
[Parameter(ValueFromPipelineByPropertyName)]
[datetime]$Date,
[Parameter(ValueFromPipelineByPropertyName)]
[pscustomobject]$Items
)
begin {}
process {
$xml = "<I><Invoice>$Invoice</Invoice><Date>$($Date.ToString('MM/dd/yy'))</Date><Items>"
$xml += $Items | ForEach-Object {
$_ | ConvertTo-LineItemXml
}
$xml += '</Items></I>'
Invoke-WebRequest -Method Post -Uri $Uri -Body $xml -ContentType 'application/xml'
}
end {}
}
# controller
Get-Data |
# group by invoice
Group-Object {$_.Invoice} |
# for each group
ForEach-Object {
# get invoice-specific information from the group's first record
$i = $_.Group | Select-Object -First 1 Invoice, Date
# get the line-item-specific information from the group's records
$li = $_.Group | Select-Object Line, Description, Price
# assign to property
$i | Add-Member -MemberType NoteProperty -Name 'Items' -Value $li
# return structure
$i
} |
Send-Invoice # format as xml and post
</code></pre>
<p>I should probably move <code>ConvertTo-LineItemXml</code> from within <code>Send-Invoice</code> to allow the caller to have more control over the processing.</p>
<p>What other improvements can I make?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T22:37:05.083",
"Id": "466636",
"Score": "0",
"body": "Does `Invoke-WebRequest -Method Post -Uri $Uri -Body $xml -ContentType 'application/xml'` work as expected? I'm asking because body of a _fixed_ `$Uri` would be rewritten with the last `$xml` i.e. invoice C for given input data, and other invoices are lost?"
}
] |
[
{
"body": "<p>You can use <code>XElement</code>.<br/>\nIt is especially useful when constructing XML.</p>\n\n<pre><code>using namespace System.Xml.Linq\nAdd-Type -AssemblyName System.Xml.Linq\n\nGet-Data | Group-Object Invoice | ForEach-Object {\n\n $items = $_.Group | ForEach-Object {\n [XElement]::new('Item', @(\n [XElement]::new('Line', $_.Line)\n [XElement]::new('Description', $_.Description)\n [XElement]::new('Price', $_.Price)))\n }\n\n $xml = [XElement]::new('I', @(\n [XElement]::new(\"Invoice\", $_.Name)\n [XElement]::new(\"Date\", $_.Group[0].Date)\n [XElement]::new('Items', $items)\n )).ToString()\n\n $xml\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T17:40:46.780",
"Id": "238203",
"ParentId": "237842",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T15:40:01.027",
"Id": "237842",
"Score": "3",
"Tags": [
"powershell"
],
"Title": "What's a better way to decrease cardinality when serializing records"
}
|
237842
|
<p>I know that if you are using too many if else statements there is a better way, I hope. Please help me learn, thank you everyone. I tried to think of a better way but just couldnt come up with anything better than this.</p>
<p>data is coming from back end as rows from mysql i.e array of objects</p>
<pre><code><template>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="q-gutter-y-md" style="max-width: 100vw">
<q-card flat bordered>
<q-card-section class="text-dark text-center">
<div class="text-h6">Revenue</div>
</q-card-section>
<q-separator inset/>
<q-card-section>
<q-tabs
v-model="tab"
dense
class="text-grey"
active-color="primary"
indicator-color="primary"
align="justify"
narrow-indicator
>
<q-tab name="by_time" label="By Time" />
<q-tab name="by_sellers" label="By Sellers" />
<q-tab name="by_category" label="By Category" />
<q-tab name="by_product" label="By Product" />
</q-tabs>
<q-separator />
<q-tab-panels v-model="tab" animated>
<q-tab-panel name="by_time">
<q-select filled :options="barTypeSelectOptions" v-model="barTypeModel" ></q-select>
<apexchart :series="timeSeries" :options="chartOptions" :type="barTypeModel" height="300"/>
</q-tab-panel>
<q-tab-panel name="by_sellers">
<q-select filled :options="barTypeSelectOptions" v-model="barTypeModel" ></q-select>
<apexchart :series="timeSeries" :options="chartOptions" :type="barTypeModel" height="300"/>
</q-tab-panel>
<q-tab-panel name="by_category">
<q-select filled :options="barTypeSelectOptions" v-model="barTypeModel" ></q-select>
<apexchart :series="timeSeries" :options="chartOptions" :type="barTypeModel" height="300"/>
</q-tab-panel>
<q-tab-panel name="by_product">
<q-select filled :options="barTypeSelectOptions" v-model="barTypeModel" ></q-select>
<apexchart :series="timeSeries" :options="chartOptions" :type="barTypeModel" height="300"/>
</q-tab-panel>
</q-tab-panels>
</q-card-section>
</q-card>
</div>
</div>
</template>
<script>
// import Bar from './Bar'
// import monthToNumber from '../assets/monthtonumber.js'
// get "delivered" rows, within a given time interval, from 'order_items' table
export default {
components: {
// Bar
},
data () {
return {
reducerResult: {},
chartData: null,
tabCategory: null,
amount: null,
tab: 'by_time',
barTypeSelectOptions: ['bar', 'line'],
barTypeModel: 'bar',
timeSeries: [{
name: 'Sales',
data: []
}],
chartOptions: {
colors: ['#88C996'],
grid: {
show: true,
strokeDashArray: 1,
xaxis: {
lines: {
show: true
}
}
},
title: {
text: 'Column',
align: 'left',
style: {
color: '#FFF'
}
},
fill: {
type: 'solid',
gradient: {
shade: 'dark',
type: 'vertical',
shadeIntensity: 0.9,
inverseColors: false,
opacityFrom: 1,
opacityTo: 0.8,
stops: [0, 50]
}
},
dataLabels: {
enabled: true
},
stroke: {
curve: 'smooth',
width: 1.5
},
xaxis: {
categories: ['Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct'],
labels: {
style: {
colors: '#81C784'
}
}
},
yaxis: {
title: {
text: 'Rupees'
},
labels: {
style: {
color: '#fff'
}
}
},
tooltip: {
y: {
formatter: function (val) {
return val + ' Rupees'
}
}
}
}
}
},
methods: {
async getChartData () {
const userId = JSON.parse(localStorage.getItem('user')).id
this.chartData = await this.$axios.get(`/seller_admin/chart_data_all/${this.tab}?userId=${userId}`)
return this.chartData
},
monthReducer (a, i) {
const newDate = new Date(i.order_creation_date)
const month = newDate.toLocaleString('default', { month: 'long' })
a[month] = (a[month] || 0) + i.price // check if the key already has a value, apparently returns 0
return a
},
sellerReducer (a, i) {
a[i.seller_name] = (a[i.seller_name] || 0) + i.price
return a
},
productReducer (a, i) {
a[i.product_name] = (a[i.product_name] || 0) + i.price
return a
},
categoryReducer (a, i) {
a[i.category_name] = (a[i.category_name] || 0) + i.price
return a
},
updateChart (xaxis, yaxis) {
this.timeSeries = [{
data: yaxis
}]
this.chartOptions = { ...this.chartOptions,
...{ xaxis: {
categories: xaxis
} }
}
},
setTab () {
this.tab = 'by_time'
}
},
watch: {
tab (newv, oldv) {
if (newv === 'by_time') {
this.reducerResult = {}
this.chartData.reduce(this.monthReducer, this.reducerResult)
this.tabCategory = []
this.amount = []
for (const month in this.reducerResult) {
this.amount.push(this.reducerResult[month])
this.tabCategory.push(month)
}
this.updateChart(this.tabCategory, this.amount)
} else if (newv === 'by_sellers') {
this.reducerResult = {}
this.chartData.reduce(this.sellerReducer, this.reducerResult)
this.tabCategory = []
this.amount = []
for (const seller in this.reducerResult) {
this.amount.push(this.reducerResult[seller])
this.tabCategory.push(seller)
}
this.updateChart(this.tabCategory, this.amount)
} else if (newv === 'by_category') {
this.reducerResult = {}
this.chartData.reduce(this.categoryReducer, this.reducerResult)
this.tabCategory = []
this.amount = []
for (const category in this.reducerResult) {
this.amount.push(this.reducerResult[category])
this.tabCategory.push(category)
}
this.updateChart(this.tabCategory, this.amount)
} else {
this.reducerResult = {}
this.chartData.reduce(this.productReducer, this.reducerResult)
this.tabCategory = []
this.amount = []
for (const product in this.reducerResult) {
this.amount.push(this.reducerResult[product])
this.tabCategory.push(product)
}
this.updateChart(this.tabCategory, this.amount)
}
// updatechart garne
}
},
async created () {
await this.getChartData()
this.chartData.reduce(this.monthReducer, this.reducerResult)
this.tabCategory = []
this.amount = []
for (const month in this.reducerResult) {
this.amount.push(this.reducerResult[month])
this.tabCategory.push(month)
}
this.updateChart(this.tabCategory, this.amount)
}
}
</script>
</code></pre>
<p>I also know that if data were formatted properly from backend it would look better in the front. However this is more of a general question as I always end up writing this kind of code.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T16:05:04.700",
"Id": "466456",
"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**](https://CodeReview.Meta.StackExchange.com/q/2436) for guidance on writing good question titles."
}
] |
[
{
"body": "<p>The only difference in your <code>if</code>/<code>else</code>s looks to be the function you pass to <code>this.chartData.reduce</code>. Everything else is the same, so you can create an object of functions indexed by the <code>newv</code>, and look up the appropriate one to pass.</p>\n\n<p>You can also construct an array of values and an array of keys immediately by using <code>Object.keys</code> and <code>Object.values</code>:</p>\n\n<pre><code>tab (newv, oldv) {\n // you could also define this object elsewhere if you wanted\n const reducersByNewv = {\n by_time: this.monthReducer,\n by_sellers: this.sellerReducers,\n by_category: this.categoryReducer,\n by_product: this.productReducer\n };\n this.reducerResult = this.chartData.reduce(reducersByNewv[newv], {});\n this.tabCategory = Object.keys(this.reducerResult);\n this.amount = Object.values(this.reducerResult);\n this.updateChart(this.tabCategory, this.amount);\n // updatechart garne\n}\n</code></pre>\n\n<p>It also looks like you aren't actually using the <code>reducerResult</code>, <code>tabCategory</code>, or <code>amount</code> anywhere else. If that's true, standalone, function-scoped variables would be more appropriate than assigning to the instance:</p>\n\n<pre><code>tab (newv, oldv) {\n const reducersByNewv = {\n by_time: this.monthReducer,\n by_sellers: this.sellerReducers,\n by_category: this.categoryReducer,\n by_product: this.productReducer\n };\n const reducerResult = this.chartData.reduce(reducersByNewv[newv], {});\n const tabCategory = Object.keys(reducerResult);\n const amount = Object.values(reducerResult);\n this.updateChart(tabCategory, amount);\n // updatechart garne\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T03:44:46.223",
"Id": "237845",
"ParentId": "237844",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "237845",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T03:35:31.580",
"Id": "237844",
"Score": "3",
"Tags": [
"javascript",
"vue.js"
],
"Title": "How to make this code for efficient and better looking?"
}
|
237844
|
<p>I haven't been programming for a while, I wanted to do a simple project to warm myself up and get back into the game; I made this simple tool that finds the probabilities of coin toss combinations. Enter a number to get all combinations with that many flips, or enter a string to search for that combination, i.e. <code>H**H</code> would find all combinations starting and ending with heads.</p>
<pre class="lang-rb prettyprint-override"><code>module Every
def every(&block)
arys = map do |ary|
base_ary = eval ary.inspect.split(':')[1] rescue nil
base_ary.nil? ? ary : base_ary
end
longest = arys.max_by(&:count).count
arys.map!.with_index do |ary, i|
cyc = ary * ( longest / ary.count + 1 )
self[i].is_a?(Enumerator) ? cyc[0...longest] : ary
end
arys.transpose.each &block
end
end
class Array
# I didn't have to use this module, but I had written it in the past
# and this seemed like a good place to use it
include Every
end
class CoinToss
attr_accessor :outcomes, :reference, :iterations, :combins, :occrs
def initialize(outcomes = ["H", "T"], reference = gets.chomp.upcase)
@outcomes = outcomes.each &:to_s
if (Integer reference rescue false)
@iterations = reference.to_i
@reference = "*" * @iterations
else
set = @outcomes.join("*")
raise ArgumentError, "Invalid Characters" unless reference =~ /\A[#{set}]+\z/
@reference = reference
@iterations = @reference.length
end
@combins = @outcomes.repeated_permutation(@iterations).to_a
@occrs = 0
ref = [@reference.chars]
# every loop ref is repeated but combins is iterated
[ref.cycle, @combins].every do |r, c|
# replaces `*` in ref with regex string for characters from `outcomes`
@template = r.join.gsub "*", "[#{@outcomes.join}]"
@occrs += 1 unless !(c.join =~ /#{@template}/) # +1 if it matches the template
end
end
def get_combins(match_marker = "~")
@combins.each do |c|
# m is blank if combin doesn't match the template
m = !(c.join =~ /#{@template}/) ? "" : match_marker
line = Array c.join
# skips marker when reference contains only `*`
line << m unless @reference.chars.all? { |r| r == "*" }
puts line.join(" ")
end
end
def get_probability(rationalize = true, match_word = "out of")
puts Rational(occrs, combins.length) if rationalize
puts [@occrs, match_word, @combins.length].join(" ") unless rationalize
end
end
tosses = CoinToss.new
tosses.get_combins
tosses.get_probability(rationalize = false)
tosses.get_probability(rationalize = true)
</code></pre>
<p>Thanks for any advice.</p>
|
[] |
[
{
"body": "<p>Here are some suggestions to your code</p>\n<h2>Every module</h2>\n<p>I had quite a hard time to understand what it does.</p>\n<p>Using eval can be quite dangerous so I would try to avoid it.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>eval ary.inspect.split(':')[1] rescue nil\n</code></pre>\n<p>You used a module to monkey patch the Array class which is sensible. Another, even more safe way to monkey patch could be to use refinements.</p>\n<blockquote>\n<p>Refinements are designed to reduce the impact of monkey patching on other users of the monkey-patched class. Refinements provide a way to extend a class locally.</p>\n</blockquote>\n<p><a href=\"https://docs.ruby-lang.org/en/2.4.0/syntax/refinements_rdoc.html\" rel=\"nofollow noreferrer\">https://docs.ruby-lang.org/en/2.4.0/syntax/refinements_rdoc.html</a></p>\n<p>The safest way of course is to not use monkey patching at all. Maybe something like <code>array.flatten.each</code> could do the trick too?</p>\n<h2>CoinToss</h2>\n<h3>Initialize reference</h3>\n<p>Initializing the reference in your constructor looks quite complicated. Maybe it could get extracted to dedicated classes.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class Reference\n def initialize(input, allowed_characters = [])\n @input = input\n @allowed_characters = allowed_characters\n end\n\n def to_s\n if integer?\n IntegerReference.new(input.to_i)\n else\n StringReference.new(input, allowed_characters)\n end\n end\n\n private\n\n attr_accessor :input, :allowed_characters\n\n def integer?\n Integer(reference)\n rescue\n false\n end\nend\n\nclass IntegerReference\n def initialize(size)\n @size = size\n end\n\n def to_s\n build_string\n end\n\n def valid?\n true\n end\n\n private\n\n attr_accessor :size\n\n def build_string\n "*" * size\n end\nend\n\nclass StringReference\n def initialize(string, allowed_characters = [])\n @string = string\n @allowed_characters = allowed_characters\n end\n\n def to_s\n return string if valid?\n end\n\n def valid?\n string =~ /\\A[#{validation_regex}]+\\z/\n end\n\n private\n\n attr_accessor :string\n\n def validation_regex\n allowed_characters.join("*")\n end\nend\n</code></pre>\n<h1>Use getter</h1>\n<p>You already setup attribute accessors but then fail to use them. Instead of <code>@combins</code> use <code>combins</code>. This has the advantage that you can change the way <code>combins</code> is returned by changing the getter method.</p>\n<h2>Return data instead of puts</h2>\n<p>Return data from your methods instead of using a puts. This has several advantages likes</p>\n<ul>\n<li>Use the classes outside a terminal (e.g. website)</li>\n<li>Easier to test</li>\n</ul>\n<h2>Naming</h2>\n<p>There are only two hard things in computer science ... Try to use speaking names and avoid abbreviations like <code>combins</code>, <code>occrs</code>, <code>r</code>, <code>c</code>. This will help to make your program easier to read and understand.</p>\n<h2>Lazy loading</h2>\n<p>Instead of setting up everything in the controller, use lazy loading and memoization.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def combinations\n @combinations ||= outcomes.repeated_permutation(@iterations).to_a\nend\n\ndef iterations\n @iterations ||= reference.length\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-11T14:45:10.357",
"Id": "243718",
"ParentId": "237847",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T16:10:29.037",
"Id": "237847",
"Score": "2",
"Tags": [
"ruby"
],
"Title": "Ruby coin toss probability tool"
}
|
237847
|
<p>My try:</p>
<pre><code>import base64
from django.core.files.base import ContentFile
def form_valid(self, form):
self.object = form.save(commit=False)
if self.request.POST.get('image_as_base64', None):
format, imgstr = self.request.POST.get('image_as_base64').split(';base64,')
ext = format.split('/')[-1]
data = ContentFile(base64.b64decode(imgstr))
file_name = "'temp_name." + ext
self.object.receipt.save(file_name, data, save=True)
</code></pre>
<p>Do you see any security problems?</p>
<p>The value in the frontend is generated in this way (Vue.js method):</p>
<pre><code> saveMapAsImage() {
this.printPlugin.printMap('A4Portrait page', 'Miles');
self = this;
this.routingMap.on('easyPrint-finished', e => {
var reader = new window.FileReader();
reader.readAsDataURL(e.event); // e.event is a Blob object generated via leaflet-easyPrint
reader.onloadend = function () {
base64data = reader.result;
self.image_as_base64 = base64data;
}
});
}
</code></pre>
<p>HTML</p>
<pre><code><input v-model="image_as_base64" type="hidden" id="id_image_as_base64" name="image_as_base64"/>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T16:38:11.540",
"Id": "466463",
"Score": "2",
"body": "*\"Secure\"* can mean a lot of different things. What is your [threat model](https://en.wikipedia.org/wiki/Threat_model)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T16:38:18.650",
"Id": "466464",
"Score": "1",
"body": "Why are you saving it in base64? It increases the size of the image and usually can't be cached properly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T16:50:13.167",
"Id": "466466",
"Score": "0",
"body": "@EdekiOkoh the output file format is .png, I only get base64 from frontend and save as .png"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T01:08:58.237",
"Id": "466519",
"Score": "0",
"body": "I'm not clear on what you mean by \"secure\". Are you worried that the base64 you get from the frontend will not actually be a .png, but some other kind of data?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T08:51:55.653",
"Id": "466534",
"Score": "0",
"body": "@MJ713 yes, this is one possible problem"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T15:31:04.930",
"Id": "467002",
"Score": "0",
"body": "POST works on binary data as well, right? Why convert in the first place? As for code review, your `form_valid` method does all kinds of things that I would not associate by validating a form. And your `save` function doesn't save."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-04T14:13:07.287",
"Id": "467467",
"Score": "0",
"body": "@MaartenBodewes thanks, so I just should send this blob object instead of converting it to base64 in JavaScript?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-04T14:47:04.183",
"Id": "467471",
"Score": "0",
"body": "Yes, assuming that your Django framework can handle it. But I don't know why it shouldn't."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T16:31:13.063",
"Id": "237848",
"Score": "0",
"Tags": [
"python",
"javascript",
"security",
"django",
"base64"
],
"Title": "How to save image in base64 format as file in secure way?"
}
|
237848
|
<p>We scan the string from left to right finding the unique characters. We also need to find the non unique characters and count them on how many times they appear.
If we can’t find any unique characters, then we return an empty list. </p>
<p>Here’s the code:</p>
<pre><code>def unique_occ(the_str):
res1 = list(the_str)
unique_letter = []
non_unique = []
for i in res1:
#there lies the issue
#as you can see, the loop should take care of the counting.
#But if is this is the first time that the letters appears
#, well there is an issue.
if i not in unique_letter:
unique_letter.append(i)
else:
non_unique.append(i)
#from that, I need to sort the letters as the for loop is not doing
#what it is supposed to do
unique_sort = [elts for elts in unique_letter if elts not in non_unique]
non_unique1 = [elts for elts in unique_letter if elts in non_unique]
#the worst part is I need to sort again the letters that have appeared more than once and concatenate them into the list again
non_unique = non_unique + non_unique1
non_unique2 = {i:non_unique.count(i) for i in non_unique}
#finally, the letters have been sorted between the unique and the non unique
return 'unique letter is {} and non unique letter is {}'.format(unique_sort,non_unique2)
</code></pre>
<p>The code works. </p>
<p>There is probably an easier way but I don't see how, at least for now. I'm unsatisfied about the pythonic way of the code.</p>
<p>Any help or insight will be welcomed.</p>
|
[] |
[
{
"body": "<p>A simple and pythonic way to accomplish this is using <a href=\"https://docs.python.org/2/library/collections.html#collections.Counter\" rel=\"noreferrer\"><code>collections.Counter</code></a>. It's an easy way to count elements in an iterable. Have a look:</p>\n\n<pre><code>from collections import Counter\n\ndef unique_letters(string: str) -> str:\n \"\"\"\n Finds all the unique/non unique letters in the string\n \"\"\"\n letters = Counter(string)\n\n unique = [key for key in letters if letters[key] == 1]\n non_unique = {key: letters[key] for key in letters if letters[key] > 1}\n return f\"Unique: {unique} | Not Unique: {non_unique}\"\n</code></pre>\n\n<p>This also takes advantage of <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"noreferrer\"><code>f-strings</code></a>, allowing you to directly implement variables into your strings. It's a personal preference, but to me it looks a lot nicer than using <code>.format()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T19:22:08.450",
"Id": "466489",
"Score": "0",
"body": "Hi @Linny, omg!!! so simple. ty."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T18:03:25.730",
"Id": "237852",
"ParentId": "237849",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "237852",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T17:33:22.157",
"Id": "237849",
"Score": "4",
"Tags": [
"python",
"performance"
],
"Title": "Find unique characters and count non unique characters"
}
|
237849
|
<p>I'm a beginner at C++; all my previous programming experience is mainly through PLCs in industrial maintenance. </p>
<p>I have to accept 10 integers and a target value, then print all the pairs that sum to the target.</p>
<p>The pairs cannot be of the same integer. For example, if the target value is 10 then we cannot have a pair of 5 + 5. This code basically executes well enough for me, however I get an overloaded int out at the end; I'm curious why that might be?</p>
<p>Also I understand there are much easier ways to accomplish this task. I feel pretty good with what I was able to come up with given the amount of time I have devoted so I certainly am fine with it, however I wouldn't mind seeing some examples how much more seasoned programmers would have attempted this, if anyone out there is bored.</p>
<pre class="lang-cpp prettyprint-override"><code>#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int run, a, b, ints[11], out[45];
cout << "\n\t\tAfter inputting 11 integers, this program will evaluate\n\tthe first 10 integers, then will display the pairs of said integers\n\twhich when added together the total will equal the 11th integer.";
cout << "\n\n\tPlease enter 11 integers: \n\n";
for (run = 0; run <= 10; run++)
{
cout << "\t\t"; cin >> (ints[run]);
}
system("cls");
run = 0;
for (a = 0; a < 10 && run <= 10; a++)
{
for (b = 1; b < 10 && run <= 10; b++)
{
if (ints[10] == (ints[a] + ints[b]) && ints[a] != ints[b] && run <= 10)
{
out[run] = ints[a];
run++;
out[run] = ints[b];
run++;
}
}
}
cout << "\n\t\tPerforming critical calculations . . .\n\t\t";
system("pause");
cout << "\n\t\t";
if (*max_element(out, out + 10) == 0)
cout << "No sum of integers found to equal desired total. ";
else
{
cout << "Pairs of integers that equal the desired total are as follows; ";
for (int index = 0; index < 11; index++)
{
if (out[index] > 0)
{
cout << "(" << out[index++] << " , " << out[index] << ")";
if (index < 11)
cout << ", ";
else if (index == 11)
break;
}
}
}
system("pause");
return 0;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T21:58:19.507",
"Id": "466503",
"Score": "1",
"body": "This code works for _some_ inputs and fails for others (which OP may not have considered in his testing strategy). Therefore I think a vote-to-close would be harsh; but I also think that OP should have spent a bit of time cleaning up the code before posting, in consideration of others' time. OP: why do you think that the array `out` can get away with only 10 slots, given that there are (10 choose 2) = 45 possible pairs of inputs, and each pair consumes 2 slots in `out`? Also, why did you misspell `Preforming` [sic]?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T22:10:44.177",
"Id": "466504",
"Score": "0",
"body": "Thank you for the input. \n\nClearly programming, and well spelling too isn't quite my forte? sp."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T22:11:44.773",
"Id": "466505",
"Score": "0",
"body": "I apologize for wasting anyone's time. And was unclear of where the best place to post was being that it was slightly working and a post I made previously on stackoverflow was directed to post here so I was just confused and I don't want anyone to be mad at me"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T22:13:14.983",
"Id": "466506",
"Score": "0",
"body": "i initially used 10 slots as the numbers i was using were 1 2 3 4 5 6 7 8 9 10 11 and didn't want to repeat print out"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T23:36:02.800",
"Id": "466511",
"Score": "0",
"body": "code was updated and now shouldn't give an error.."
}
] |
[
{
"body": "<p><strong>Algorithm:</strong><br>\nIt's brute-force, but for ten elements that's fine. However, I don't think it will work correctly - it's going to stop at five pairs regardless of how many were generated. </p>\n\n<p>Also, the outer loop should stop before the last element and the inner loop should start one after the current value of the outer loop. Otherwise you're just making the same comparison multiple times.</p>\n\n<p>The main thing I would suggest that there are other data structures besides basic arrays. In this case, a vector of pairs would work well.</p>\n\n<pre><code>std::vector<std::pair<int,int>> results;\n\n...\n\nresults.push_back(std::make_pair(input[a], input[b]));\n\n...\n\nif(results.size() == 0) \n{\n std::cout << \"No sum of integers found to equal desired total.\\n\";\n}\n\n...\n\nfor(int i = 0; i < results.size(); ++i) \n{\n std::cout << '(' << results[i].first << \", \" << results[i].second << ')';\n</code></pre>\n\n<p>.<br>\n.<br>\n<strong>Style:</strong><br>\nAlways put brackets around your blocks, especially when there's a matching block that does have them (the if/else for showing the results). </p>\n\n<p>Give variables meaningful names, and don't re-use them just because they're the same type. Also, you don't need to (and usually shouldn't) declare them all at the top of the method; declare them where they're used.</p>\n\n<p>Separate the target number as its own variable, having it as the last item of the input array is less clear.</p>\n\n<p>If you're not calling them anything more specific, <strong>i</strong> and <strong>j</strong> are the usual convention for loop variables.</p>\n\n<p>The fake delay for \"critical calculations\" that in fact are already done is a bit silly. :P</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T01:56:29.327",
"Id": "466522",
"Score": "0",
"body": "I cannot thank you enough for taking the time out of your day to provide me with this feedback. This was an extra credit problem I was working on for a class I am taking I find myself spending far too much time focusing on the end result than the meat and potatoes of the program, so without a doubt I will take these critiques to heart."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T00:43:15.050",
"Id": "237866",
"ParentId": "237858",
"Score": "4"
}
},
{
"body": "<p>I'll try and point out bad habits that might cause you problems in larger programs.</p>\n\n<p>Firstly, avoid <code>using namespace std;</code>, especially at such broad scope. This pollutes the global namespace, greatly reducing the benefits of having namespaces at all. It's not much to type <code>std::</code> where you need it, and/or you can selectively import a handful of identifiers into functions where you need them repeatedly.</p>\n\n<p>We can split the functionality of that large <code>main()</code> into three main sections:</p>\n\n<ol>\n<li>Get input values</li>\n<li>Calculate the result</li>\n<li>Print the result</li>\n</ol>\n\n<p>The reason to do this isn't just to help us reason about each part separately (although that's a good thing). A bigger benefit comes when we want to test the function against several sets of inputs to ensure correctness (this is <em>unit testing</em>). With the monolithic <code>main()</code>, we'd need to construct a test harness that runs the whole program for each test case, which is much slower.</p>\n\n<p>We can reduce the huge long line here:</p>\n\n<blockquote>\n<pre><code>cout << \"\\n\\t\\tAfter inputting 11 integers, this program will evaluate\\n\\tthe first 10 integers, then will display the pairs of said integers\\n\\twhich when added together the total will equal the 11th integer.\";\ncout << \"\\n\\n\\tPlease enter 11 integers: \\n\\n\";\n</code></pre>\n</blockquote>\n\n<p>In C++, as in C, we can write string literals in pieces, and the compiler will assemble them into a single string:</p>\n\n<pre><code>std::cout << \"\\n\\t\\tAfter inputting 11 integers, this program will evaluate\\n\"\n \"\\tthe first 10 integers, then will display the pairs of said integers\\n\"\n \"\\twhich when added together the total will equal the 11th integer.\\n\";\nstd::cout << \"\\n\\tPlease enter 11 integers: \\n\\n\";\n</code></pre>\n\n<p>We need to be more careful about reading input here:</p>\n\n<blockquote>\n<pre><code> cout << \"\\t\\t\"; cin >> (ints[run]);\n</code></pre>\n</blockquote>\n\n<p>Reading from a stream can fail (for example, if the user presents something that's not a number, or closes the stream). When that happens, the stream enters the \"fail\" state, and all subsequent reads will also fail, until the state is reset. For a simple program like this, we can probably get away with terminating the program when that happens:</p>\n\n<pre><code> std::cout << \"\\t\\t\";\n std::cin >> ints[run];\n if (!std::cin) {\n std::cerr << \"Failed to read input number\\n\";\n return 1;\n }\n</code></pre>\n\n<p>Similarly, <code>std::system()</code> may fail (as it does on this Debian system, where neither <code>cls</code> or <code>pause</code> are available programs). If the result of this call is non-zero, then we need to deal with the failure. Note also that we're missing the necessary include of <code><cstdlib></code>; we may fail to compile because of that. (Including <code><cstdlib></code> also gives us the useful <code>EXIT_FAILURE</code> macro, which we could use as return value in the error case above.)</p>\n\n<p>We have a bug here:</p>\n\n<blockquote>\n<pre><code> cout << \"(\" << out[index++] << \" , \" << out[index] << \")\";\n</code></pre>\n</blockquote>\n\n<p>We both modify and use <code>index</code> here in the same statement, and the two uses are <em>unsequenced</em> relative to each other. That means it's indeterminate whether the second use gets the initial value of <code>index</code> or the incremented value. What we need to do is to separate these uses into two statements:</p>\n\n<pre><code> std::cout << '(' << out[index++];\n std::cout << \" , \" << out[index] << ')';\n</code></pre>\n\n<p>That said, loops are easier to read if we don't modify the loop counter within the body; we could re-write it to advance by 2 each time:</p>\n\n<pre><code> for (int index = 0; index < 11; index += 2)\n</code></pre>\n\n\n\n<pre><code> std::cout << '(' << out[index] << \" , \" << out[index+1] << ')';\n</code></pre>\n\n<p>This test is redundant:</p>\n\n<blockquote>\n<pre><code> else if (index == 11)\n break;\n</code></pre>\n</blockquote>\n\n<p>The very next code to be executed here is the loop increment (<code>index++</code>) and test (<code>index < 11</code>), which will exit the loop in this case anyway.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T13:15:03.263",
"Id": "466559",
"Score": "0",
"body": "Thank you for this thorough breakdown I will use the information provided in an attempt to prevent future substandard practices. Much appreciated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T10:49:40.570",
"Id": "466696",
"Score": "1",
"body": "`cout << \"(\" << out[index++] << \" , \" << out[index] << \")\"` has defined behavior since C++17 - LHS of `<<` is sequenced before RHS (not saying it's good practice)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T10:58:11.353",
"Id": "466699",
"Score": "0",
"body": "@L.F. Interesting; `g++ -std=c++17` (or `-std=c++2a`) still warns that *operation on `index` may be undefined [`-Wsequence-point`]*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T11:11:09.300",
"Id": "466701",
"Score": "0",
"body": "@TobySpeight It's a bug in both GCC and Clang: https://stackoverflow.com/a/51785055/9716597"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T09:54:02.143",
"Id": "237880",
"ParentId": "237858",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "237866",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T21:29:01.003",
"Id": "237858",
"Score": "1",
"Tags": [
"c++",
"beginner",
"2sum"
],
"Title": "2-sum problem in C++"
}
|
237858
|
<p>I'm trying to make a password program that you can login to or make a new user.
I want to make this better, so any help would be appreciated, also any suggestions to make this better would be good</p>
<pre class="lang-py prettyprint-override"><code>import time
LOGIN = ("Login", "login", "L", "l", "LOGIN")
CREATE = ("Create", "create", "C", "c", "CREATE", "Create Account", "Create account", "create Account", "create account", "CREATE ACCOUNT")
x = 0
newPass = "X"
newUser = "X"
validEntry = {
"Liam" : "liampass",
"Bob" : "bobpass"
} #All current usernames and passwords stored in this dictionary
print("--==Welcome==--")
time.sleep(1)
def choice():
print("Login or Create Account?")
choice = input(":>>>")
if choice in LOGIN:
login()
elif choice in CREATE:
create() #Choice to login or create
def login():
print("""
Please login. Case sensitive.""")
time.sleep(0.5)
print("Username.")
entry = input(":>>>")
if entry in validEntry:
x = 0
while x < 3:
print("Input Password.")
passentry = input(":>>>")
passright = validEntry.get(entry) #Checks dictionary to find password associated with username entered
if passentry == passright:
print("Successful Login!")
x += 5 #Correct password, addition code could be added here
else:
print("""Incorrect password, try again
""")
x += 1 #Incorrect password, allows three attempts
else:
print("Username not recognised!")
login()
def create():
print("Please choose a username")
newUser = str(input(":>>>"))
print("Please choose a password for", newUser)
newPass = str(input(":>>>"))
global newUser, newPass #Globalizes both new password and username for entry to dictionary
choice()
validEntry[newUser] = newPass #Adds new username and password to dictionary
choice() #You can only make one new account then login
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T21:54:10.360",
"Id": "466502",
"Score": "0",
"body": "Welcome to code review where we review working code and provide suggestions on how that code can be improved. Unfortunately we can't help you write code that isn't written yet, such as adding a new username and password to a file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T14:57:28.860",
"Id": "466585",
"Score": "1",
"body": "@pacmaninbw OP rephrased the question since your comment. Looks okay...ish now, I'd say."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T15:12:50.957",
"Id": "466591",
"Score": "1",
"body": "@AlexV VTC retracted"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T17:09:51.660",
"Id": "466613",
"Score": "0",
"body": "@pacmaninbw what is a 'VTC'?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T07:45:48.637",
"Id": "466671",
"Score": "1",
"body": "@Yonlif Vote to close. Whenever a question is in violation of the site's rules (as per the [help/on-topic], community members will close the question so it isn't answered by accident. Closed questions should be fixed *before* they're answered to improve the quality and helpfulness of both the question an answers."
}
] |
[
{
"body": "<p>I have some suggestions, some regarding the code and some regarding the logic of it. Generally this is a nice code.<br>\nLet's begin, logical suggestions:</p>\n\n<ul>\n<li><p>First of all, the code does not run. <code>SyntaxError: name 'newUser' is used prior to global declaration</code>. You should put the <code>global</code> keyword before declaring the variables.</p></li>\n<li><p>Use the <code>__main__</code> function. Usually when writing a good python code you do not write logic outside of functions. This will make your code more readable. You can than put the logic in a <code>while True</code> loop and keep accept users forever and not just twice.</p></li>\n</ul>\n\n<p>Coding suggestions:</p>\n\n<ul>\n<li><p>Magic numbers. The number of time you can accept a wrong password is 3, make it a constant: <code>NUMBER_OF_ERROR = 3</code>.</p></li>\n<li><p>You do not need to declare <code>x</code> outside of the <code>login</code> function.</p></li>\n<li><p>Instead of <code>x += 5</code> just use break, it makes much more sense.</p></li>\n<li><p>Do not call the login function at the end of login. It creates unnecessary recursion.</p></li>\n</ul>\n\n<p>That's it.<br>\nGood luck and have fun</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T17:26:51.623",
"Id": "237920",
"ParentId": "237859",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "237920",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T21:40:16.350",
"Id": "237859",
"Score": "1",
"Tags": [
"python"
],
"Title": "Login and create username and password program"
}
|
237859
|
<p>I was given that assignment recently as part of a coding interview.</p>
<p>The idea is to find if a <a href="https://en.wikipedia.org/wiki/Global_Trade_Item_Number" rel="nofollow noreferrer">gtin</a> is valid or not valid.</p>
<p>The requirements are the following:</p>
<ul>
<li>make sure the input is in a string format</li>
<li>the length must be either 8,12,13,14,17 or 18</li>
</ul>
<p>The algorithm is the following:</p>
<p><a href="https://i.stack.imgur.com/hxvqB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hxvqB.png" alt="enter image description here"></a></p>
<p><strong>TL;DR</strong>: You need to multiply all odd positions by 3 and you have to remove the last position. For example if the GTIN is 13, you need to multiply the 12th position by 3, the 11th position by 1, the 12th position by 3 and so on.</p>
<p>If the GTIN is 8, you need to multiply the 7th position by 3, the 6th by 1, the 5th by 3 and so on.</p>
<p>Once done, you sum all the elements and you find the nearest equal or higher multiple of ten and you substract this from the sum you have obtained. The integer that you obtained should be equal to the last digit (13th position if the GTIN is 13).</p>
<p>If it is not, then the GTIN is an incorrect one.</p>
<p>Here is my code</p>
<pre><code> def gtin_check(gtin: str)-> str:
if not isinstance(gtin, str) or len(gtin) not in (8,12,13,14,17,18):
return 'Not a string'
else:
gtin_lst = [int(x) for x in gtin]
#print("step 1 - give the gtin but as a list of integers",gtin_lst)
gtin_lst.reverse()
#print("step 2 reverse the gtin",gtin_lst)
gtin_original = gtin_lst #saving the list to gtin_original
#print("step 3 : gtin original still reverse",gtin_original)
gtin_lst = gtin_original[1:]
#print("step 4 - gtin_lst starting from the first element",gtin_lst)
gtin_original.reverse()
#print("step 5 - gtin original without reverse , going back to normal ",gtin_original)
# arriving at the algorithm part
gtin_lst = [x*3 if i%2 == 0 else x for i,x in enumerate(gtin_lst)]
#print('step 6 - multiplying by 3 of integers on odd position',gtin_lst)
som_gtin1 = sum(gtin_lst)
#print('step 7 - gtins summation',som_gtin1)
if (som_gtin1 % 10):
som_gtin2 = som_gtin1 + (10 - som_gtin1 % 10) # (10 // gcd(som_gtin1, 10)) * som_gtin1 #int(round(som_gtin1, -1)) #som_gtin1 + (10 - som_gtin1 % 10)
else:
som_gtin2 = som_gtin1
#print('step 8 : multiple of 10 instead of equal or higher summation',som_gtin2-som_gtin1)
if (som_gtin2 - som_gtin1) == gtin_original[-1]:
return True
else:
return False
</code></pre>
<p>The code does what I want but I feel it is not pythonic enough. Any suggestions or insight on how can I write a lighter code are welcomed. </p>
<h2>update 1:</h2>
<p>Example <code>12345670</code> will put True. <code>12345678</code> will put False.</p>
<h2>update 2:</h2>
<p>Since MJ713's feedback, I've commented my code just to make sure you understand my code. Let me know if you have any issues in reading it. I've amended my code to fix the bugs, MJ713 mentionned.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T00:50:06.263",
"Id": "466518",
"Score": "0",
"body": "Unfortunately this code is not working as intended, and therefore it is off-topic. (`round()` will often find a _lower_ multiple of 10 instead of \"equal or higher\", and the line `gtin_lst1 = gtin_lst[1:]` incorrectly removes a number before summing.) If the code is fixed then we can try to improve it. You can use https://www.gs1.org/services/check-digit-calculator to generate some correct GTINs for testing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T06:10:09.643",
"Id": "466527",
"Score": "0",
"body": "@MJ713 will do. I will delete my question in the meantime."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-04T07:48:23.723",
"Id": "467409",
"Score": "0",
"body": "Hi @MJ713, amendment done. I checked my code, things should be ok now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T07:40:54.580",
"Id": "467788",
"Score": "0",
"body": "Dont incorporate changes from answers to your question. It makes up for a confusing thread as Is against rules of this site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T09:01:06.630",
"Id": "467792",
"Score": "0",
"body": "Hi @slepic, I won't. The aim is not make MJ713's work mine, it is to show my code and MJ713's answer is to show what can be improved. If I incorporate his work to mine, where is the progress? :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T13:50:53.403",
"Id": "467967",
"Score": "1",
"body": "@slepic The changes and edits that Andy K is referring to are not from my answer. Rather they were edits to make the question on-topic (since the code was broken at first). These edits were made before I wrote my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T14:13:42.797",
"Id": "467969",
"Score": "0",
"body": "Sure, ok, my fault :)"
}
] |
[
{
"body": "<p>I'll start from the top and work my way down to the bottom.</p>\n<hr />\n<hr />\n<pre><code> def gtin_check(gtin: str)-> str:\n</code></pre>\n<p>Your type-hinting is incorrect here. Except in cases of invalid input, you are returning a boolean, not a string. Which leads me to...</p>\n<pre><code> if not isinstance(gtin, str) or len(gtin) not in (8,12,13,14,17,18):\n return 'Not a string'\n</code></pre>\n<p>In general it is a bad idea to mix two completely different return types for one function, unless there is some pressing reason to do so. The mixing creates more work for whoever is calling your function, since they have to handle both types. (Null value/<code>None</code> is probably the most common exception to this rule; sometimes it's appropriate to return <code>None</code>, e.g. if a function that is searching for a single specific object or value doesn't find one.)</p>\n<p>To get rid of the string return value, I would suggest one of these alternatives:</p>\n<ul>\n<li>If the calling function really needs to know the difference between an input that had a bad check digit, and an input that was invalid in a "stronger" way: either raise an exception, or make your return type an <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">enum</a> with three possible values (e.g. <code>VALID</code>, <code>INVALID</code>, and <code>MALFORMED</code>).</li>\n<li>If the calling function only needs to know whether an input was a valid GTIN or not: just return <code>False</code>.</li>\n</ul>\n<pre><code> if not isinstance(gtin, str) or len(gtin) not in (8,12,13,14,17,18):\n return False\n</code></pre>\n<p>Now let's talk about performance. <code>in</code> / <code>not in</code> checks are generally faster on sets than they are on lists or tuples. This is because sets do clever things with hashing (<span class=\"math-container\">\\$O(1)\\$</span>), while with lists and tuples you have to go down the line and check every value in order (<span class=\"math-container\">\\$O(n)\\$</span>). So let's use a set instead.</p>\n<pre><code> if not isinstance(gtin, str) or len(gtin) not in {8,12,13,14,17,18}:\n return False\n</code></pre>\n<p>While we're doing these other checks, it would also be good to use <code>.isdecimal()</code> to check that the input string is numeric. Right now we don't have any code to catch non-numeric inputs like <code>'asdfghjk'</code>, so we get a slightly ugly error (<code>ValueError: invalid literal for int() with base 10: 'a'</code>).</p>\n<pre><code> if (not isinstance(gtin, str)\n or not gtin.isdecimal()\n or len(gtin) not in {8,12,13,14,17,18}):\n return False\n</code></pre>\n<p>The line was getting a bit long, so I added some line breaks. See the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> document for guidelines on when and how to use line breaks.</p>\n<hr />\n<hr />\n<pre><code> gtin_lst = [int(x) for x in gtin]\n #print("step 1 - give the gtin but as a list of integers",gtin_lst)\n gtin_lst.reverse()\n #print("step 2 reverse the gtin",gtin_lst)\n gtin_original = gtin_lst #saving the list to gtin_original\n #print("step 3 : gtin original still reverse",gtin_original)\n gtin_lst = gtin_original[1:] \n #print("step 4 - gtin_lst starting from the first element",gtin_lst)\n gtin_original.reverse()\n</code></pre>\n<p>This section is confusing - you're putting the original value in a new variable and the altered value in the original variable, not to mention reversing a reversal. It would be easier to understand if you left <code>gtin_lst</code> intact and used negative indexes to extract the subset you need:</p>\n<pre><code> gtin_lst = [int(x) for x in gtin]\n gtin_lst_without_check_digit = gtin_lst[:-1]\n gtin_lst_without_check_digit.reverse()\n</code></pre>\n<hr />\n<hr />\n<pre><code> # arriving at the algorithm part\n gtin_lst = [x*3 if i%2 == 0 else x for i,x in enumerate(gtin_lst)]\n</code></pre>\n<p>It is more "pythonic" to avoid <code>== 0</code> in conditions, and instead use the inherent "falsiness" of <code>0</code>.</p>\n<pre><code>x*3 if not i%2 else x\n</code></pre>\n<p>I see you have already done this in another part of the code: <code>if (som_gtin1 % 10):</code>.</p>\n<hr />\n<hr />\n<pre><code> if (som_gtin1 % 10):\n som_gtin2 = som_gtin1 + (10 - som_gtin1 % 10) # (10 // gcd(som_gtin1, 10)) * som_gtin1 #int(round(som_gtin1, -1)) #som_gtin1 + (10 - som_gtin1 % 10)\n else: \n som_gtin2 = som_gtin1 \n</code></pre>\n<p>The logic here is solid, but this seems like a good place to talk about naming.</p>\n<p>In general, naming variables by the pattern <code>foo1</code>, <code>foo2</code>, etc. is a <a href=\"https://blog.codinghorror.com/code-smells/\" rel=\"nofollow noreferrer\">code smell</a>. If you have more than one of the same kind of thing, why aren't they in some kind of list or collection? And if\nthey aren't the same kind of thing, why do they have the same name? There are exceptions, but I would say this is a bad idea nine times out of ten.</p>\n<p>In this case, <code>som_gtin1</code> and <code>som_gtin2</code> aren't the same kind of thing.</p>\n<ul>\n<li><code>som_gtin1</code> is a sum of some numbers. (Is "som" instead of "sum" a typo, or are you deliberately using a non-English word?)</li>\n<li><code>som_gtin2</code> is <code>som_gtin1</code> rounded to the nearest highest 10. In other words, it is <em>based</em> on a sum, but it is not a sum itself.</li>\n</ul>\n<p>Also, since the function is named <code>gtin_check</code>, we already know that everything we're doing is related to GTINs somehow. So adding <code>_gtin</code> to the variable names doesn't really give the reader any additional information.</p>\n<p>Picking accurate and descriptive names throughout your code will make it easier to read and understand. You will sometimes hear people describe this kind of code as "self-documenting", because it does not need nearly as many comments or external documents.</p>\n<pre><code> if (digits_sum % 10):\n uprounded_sum = digits_sum + (10 - digits_sum % 10)\n else: \n uprounded_sum = digits_sum\n</code></pre>\n<p>Let me be clear: I'm not claiming that <em>my</em> names are perfect either. There's <a href=\"https://www.martinfowler.com/bliki/TwoHardThings.html\" rel=\"nofollow noreferrer\">an old joke</a> that "there are only two hard problems in computer science: cache invalidation and naming things."</p>\n<hr />\n<hr />\n<pre><code> if (som_gtin2 - som_gtin1) == gtin_original[-1]:\n return True\n else:\n return False\n</code></pre>\n<p>I had a computer science professor in college who specifically warned us not to use this construction. So naturally, I didn't notice it until an hour after I finished writing the rest of this answer. </p>\n<p>As my professor pointed out, any logic of the form "if <em>boolean value</em>, return true, else return false" can be reduced to "return <em>boolean value</em>".</p>\n<pre><code> return ((som_gtin2 - som_gtin1) == gtin_original[-1])\n</code></pre>\n<p>The wrapping parentheses aren't strictly necessary, but I think they make the code clearer.</p>\n<hr />\n<hr />\n<h3>Putting it all together</h3>\n<pre><code>def gtin_check(gtin: str) -> bool:\n """Returns whether the input is a well-formed GTIN string."""\n # Check for obvious problems\n if (not isinstance(gtin, str)\n or not gtin.isdecimal()\n or len(gtin) not in (8,12,13,14,17,18)):\n return False\n else:\n # Compute correct "check digit" and compare to input's digit\n original_digits = [int(x) for x in gtin]\n digits_without_check_digit = original_digits[:-1]\n\n digits_without_check_digit.reverse()\n multiplied_digits = [x*3 if not i%2 else x\n for i,x\n in enumerate(digits_without_check_digit)]\n digits_sum = sum(multiplied_digits)\n\n if (digits_sum % 10):\n uprounded_sum = digits_sum + (10 - digits_sum % 10)\n else: \n uprounded_sum = digits_sum\n expected_check_digit = uprounded_sum - digits_sum\n\n return (original_digits[-1] == expected_check_digit)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T12:49:35.243",
"Id": "467812",
"Score": "0",
"body": "The big `else:` is not needed since the `then` branch always returns."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T13:14:29.197",
"Id": "467813",
"Score": "0",
"body": "Dear @MJ713, thank you. Even if these two words are simple, they does not convey well my gratitude for the time you've spent to go through the detailed explanation you gave me. I will have a look this afternoon again to your answer and incorporate it as best pratice. Thank you again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-09T13:43:08.990",
"Id": "467963",
"Score": "0",
"body": "@RolandIllig You're right, but that's more a matter of style since the compiler would presumably treat it the same either way. And both styles are shown as valid in the [PEP 8](https://www.python.org/dev/peps/pep-0008/) document (under the \"Be consistent in return statements\" bullet point)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-07T02:47:39.157",
"Id": "238512",
"ParentId": "237860",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "238512",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T21:47:26.883",
"Id": "237860",
"Score": "2",
"Tags": [
"python",
"performance"
],
"Title": "find if a gtin is valid"
}
|
237860
|
<h1>Context</h1>
<p>The main goal located a configuration <code>NavigationService</code> and <code>NavigationView</code> in one place. In order to minimalization a consequence in case adding, modifying or removing of <code>NavigationItem</code>. I would like to get some feedback about advantages and disadvantages of the my implementation.</p>
<p>We have a <code>Page</code> with <code>NavigationView</code> and <code>Frame</code>. Located in <code>ShellPage</code> and control by <code>ShellViewModel</code>. When a user clicks on <code>NavigationItem</code>, we need to navigate to selected page. In order to do that we create dictionary with items for all pages. The key is full name of ViewModel type and the value is Page type. In addition we need to add <code>NavigationItem</code> into <code>NavigationView</code> to display items. In this way we have two settings: add to dictionary and add to <code>NavigationView</code>.</p>
<p>I saw some <a href="https://github.com/microsoft/WindowsTemplateStudio/tree/master/samples/navigation/MixedNavigationSample.MVVMLight" rel="nofollow noreferrer">example</a> by <code>Window Template Studio</code> and a large <a href="https://github.com/microsoft/InventorySample" rel="nofollow noreferrer">app sample</a> by Microsoft. Both have <em>some</em> places for our two action. I want to one place. I find it easy to add or remove an element without looking for multiple places in the code.</p>
<h1>Description</h1>
<p>The app starts from <code>app.xaml.cs</code>. Both <code>OnLaunched</code> and <code>OnActivated</code> call <code>ActivationService</code>. The goal by default is creage <code>ShellPage</code> by call constructor and navigate to <code>MainPage</code>. More information on <a href="https://github.com/Microsoft/WindowsTemplateStudio/blob/master/docs/activation.md" rel="nofollow noreferrer">here</a>. Not relevant to the post.</p>
<p>Let's start from <code>ShellPage</code>. Inside constructor we call a method <code>InitializeNavigation()</code>.</p>
<pre><code>// shellFrame and navigationView are names of Frame and NavigationView element into XAML
ViewModel.InitializeNavigation(shellFrame, navigationView);
</code></pre>
<p>This method looks like</p>
<pre><code>public void InitializeNavigation(Frame frame, NavigationView navigationView)
{
_navigationView = navigationView;
_navigationView.BackRequested += OnBackRequested;
NavigationService.Initialize(frame);
NavigationService.Navigated += Frame_Navigated;
NavigationService.NavigationFailed += Frame_NavigationFailed;
new NavigationConfig(NavigationService, _navigationView);
}
</code></pre>
<p>The steps described earlier for adding items to the dictionary and creating items to display are here (<em>one place</em>).</p>
<pre><code>new NavigationConfig(NavigationService, _navigationView);
</code></pre>
<p>On the one hand, I don't need a reference to this class in the future. On the other hand, I want to separate this setting from the <code>ShellViewModel</code>. Maybe I need to make it completely static?</p>
<p>For add to dictionary do</p>
<pre><code>private void ConfigureNavService()
{
_navigationService.Configure<ShellViewModel, ShellPage>();
_navigationService.Configure<MainViewModel, MainPage>();
_navigationService.Configure<SettingsViewModel, SettingsPage>();
}
</code></pre>
<p>For add <code>NavigationItem</code> do</p>
<pre><code>private void ConfigureNavView()
{
AddNavItem<MainViewModel>("Home", Symbol.Home);
// Settings is separate item, creates by NavigatonView with XAML IsSettingsVisible="True"
}
</code></pre>
<p>Finally, before showing the entire code, you need to note two static methods.</p>
<pre><code>public static string ConvertToKey<TViewModel>() => typeof(TViewModel).FullName;
public static string GetPageKey(NavigationViewItem item) => item.Tag.ToString();
</code></pre>
<p>Only <code>ConvertToKey()</code> known how to create key from <code>TViewModel</code>. This is done in order to have only one way to get the key and not repeat it where the key is needed. <code>NavigationConfig</code> is a great place because it is where this key is added to the dictionary. The method is required in three places: <code>NavigationConfig.AddNavItem()</code>, <code>NavigationService.Configure()</code>, <code>NavigationService.NavigateTo()</code>.</p>
<p>A similar story with <code>GetPageKey()</code>. Only this method knows where the <code>NavigationItem</code> key is located (<code>Tag</code> property). The method is required in two places: <code>ShellViewModel.OnItemInvoked()</code> and <code>ShellViewModel.IsMenuItemForPageType()</code>.</p>
<p>Thanks for any help!</p>
<h1>Code</h1>
<p><strong>ViewModelLocator</strong></p>
<pre><code>private static ViewModelLocator _current;
public static ViewModelLocator Current => _current ?? (_current = new ViewModelLocator());
private ViewModelLocator()
{
// Services
SimpleIoc.Default.Register<IActivationService, ActivationService>();
SimpleIoc.Default.Register<INavigationService, NavigationService>();
// ViewModels
SimpleIoc.Default.Register<ShellViewModel>();
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<SettingsViewModel>();
}
public ShellViewModel ShellViewModel => SimpleIoc.Default.GetInstance<ShellViewModel>();
public MainViewModel MainViewModel => SimpleIoc.Default.GetInstance<MainViewModel>();
public SettingsViewModel SettingsViewModel => SimpleIoc.Default.GetInstance<SettingsViewModel>();
public IActivationService ActivationService => SimpleIoc.Default.GetInstance<IActivationService>();
</code></pre>
<p><strong>ShellPage.xaml</strong></p>
<pre><code><NavigationView x:Name="navigationView"
IsSettingsVisible="True"
IsBackButtonVisible="Visible"
IsBackEnabled="{x:Bind ViewModel.IsBackEnabled, Mode=OneWay}"
SelectedItem="{x:Bind ViewModel.Selected, Mode=OneWay}"
Header="{x:Bind ViewModel.Selected.Content, Mode=OneWay}">
<i:Interaction.Behaviors>
<ic:EventTriggerBehavior EventName="ItemInvoked">
<ic:InvokeCommandAction Command="{x:Bind ViewModel.ItemInvokedCommand}" />
</ic:EventTriggerBehavior>
</i:Interaction.Behaviors>
<Grid>
<Frame x:Name="shellFrame" />
</Grid>
</NavigationView>
</code></pre>
<p><strong>ShellPage.xaml.cs</strong></p>
<pre><code>private ShellViewModel ViewModel => ViewModelLocator.Current.ShellViewModel;
public ShellPage()
{
InitializeComponent();
ViewModel.InitializeNavigation(shellFrame, navigationView);
}
</code></pre>
<p><strong>ShellViewModel</strong></p>
<pre><code>private bool _isBackEnabled;
private NavigationView _navigationView;
private NavigationViewItem _selected;
private ICommand _itemInvokedCommand;
public bool IsBackEnabled
{
get => _isBackEnabled;
set => Set(ref _isBackEnabled, value);
}
public NavigationViewItem Selected
{
get => _selected;
set => Set(ref _selected, value);
}
public ICommand ItemInvokedCommand
{
get
{
return _itemInvokedCommand ?? (_itemInvokedCommand = new RelayCommand<NavigationViewItemInvokedEventArgs>(OnItemInvoked));
}
}
private INavigationService NavigationService { get; }
public ShellViewModel(INavigationService navigationService)
{
NavigationService = navigationService;
}
public void InitializeNavigation(Frame frame, NavigationView navigationView)
{
_navigationView = navigationView;
_navigationView.BackRequested += OnBackRequested;
NavigationService.Initialize(frame);
NavigationService.Navigated += Frame_Navigated;
NavigationService.NavigationFailed += Frame_NavigationFailed;
new NavigationConfig(NavigationService, _navigationView);
}
private void OnItemInvoked(NavigationViewItemInvokedEventArgs args)
{
if (args.IsSettingsInvoked)
{
NavigationService.NavigateTo<SettingsViewModel>();
return;
}
var item = _navigationView.MenuItems.OfType<NavigationViewItem>().First(menuItem => (string)menuItem.Content == (string)args.InvokedItem);
var pageKey = NavigationConfig.GetPageKey(item);
NavigationService.NavigateTo(pageKey);
}
private void OnBackRequested(NavigationView sender, NavigationViewBackRequestedEventArgs args)
{
NavigationService.GoBack();
}
private void Frame_Navigated(object sender, NavigationEventArgs e)
{
IsBackEnabled = NavigationService.CanGoBack;
Selected = e.SourcePageType == typeof(SettingsPage)
? _navigationView.SettingsItem as NavigationViewItem
: _navigationView.MenuItems.OfType<NavigationViewItem>().FirstOrDefault(menuItem => IsMenuItemForPageType(menuItem, e.SourcePageType));
}
private void Frame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw e.Exception;
}
private bool IsMenuItemForPageType(NavigationViewItem item, Type sourcePageType)
{
var pageKey = NavigationConfig.GetPageKey(item);
var navigatedPageKey = NavigationService.GetKeyForPage(sourcePageType);
return pageKey == navigatedPageKey;
}
</code></pre>
<p><strong>INavigationService</strong></p>
<pre><code>public interface INavigationService
{
event NavigatedEventHandler Navigated;
event NavigationFailedEventHandler NavigationFailed;
bool CanGoBack { get; }
bool CanGoForward { get; }
void Initialize(Frame frame);
void Configure<TViewModel, TView>() where TView : Page;
string GetKeyForPage(Type page);
void GoBack();
void GoForward();
void NavigateTo<TViewModel>(object parameter = null, NavigationTransitionInfo infoOverride = null);
void NavigateTo(string pageKey, object parameter = null, NavigationTransitionInfo infoOverride = null);
}
</code></pre>
<p><strong>NavigationService</strong></p>
<pre><code>public event NavigatedEventHandler Navigated;
public event NavigationFailedEventHandler NavigationFailed;
private Frame _frame;
private object _lastParamUsed;
private readonly ConcurrentDictionary<string, Type> _pages = new ConcurrentDictionary<string, Type>();
private Frame Frame
{
get
{
if (_frame == null)
{
_frame = Window.Current.Content as Frame ?? new Frame();
RegisterFrameEvents();
}
return _frame;
}
set
{
UnregisterFrameEvents();
_frame = value;
RegisterFrameEvents();
}
}
private Type CurrentPage => Frame.Content?.GetType();
public bool CanGoBack => Frame.CanGoBack;
public bool CanGoForward => Frame.CanGoForward;
public void Initialize(Frame frame) => Frame = frame;
public void Configure<TViewModel, TView>() where TView : Page
{
var key = NavigationConfig.ConvertToKey<TViewModel>();
_ = _pages.TryAdd(key, typeof(TView))
? true
: throw new InvalidOperationException($"ViewModel already registered '{key}'");
}
public string GetKeyForPage(Type page)
{
string key = _pages.Where(p => p.Value == page).Select(p => p.Key).FirstOrDefault();
return key ?? throw new ArgumentException(string.Format("ExceptionNavigationServicePageUnknown", page.Name));
}
public void GoBack() => Frame.GoBack();
public void GoForward() => Frame.GoForward();
public void NavigateTo<TViewModel>(object parameter = null, NavigationTransitionInfo infoOverride = null)
{
NavigateTo(NavigationConfig.ConvertToKey<TViewModel>(), parameter, infoOverride);
}
public void NavigateTo(string pageKey, object parameter = null, NavigationTransitionInfo infoOverride = null)
{
_ = _pages.TryGetValue(pageKey, out Type targetPage)
? true
: throw new ArgumentException(string.Format("ExceptionNavigationServicePageNotFound", pageKey), nameof(pageKey));
if (CurrentPage != targetPage || (parameter != null && !parameter.Equals(_lastParamUsed)))
{
_lastParamUsed = Frame.Navigate(targetPage, parameter, infoOverride)
? parameter
: _lastParamUsed;
}
}
private void RegisterFrameEvents()
{
if (_frame != null)
{
_frame.Navigated += Frame_Navigated;
_frame.NavigationFailed += Frame_NavigationFailed;
}
}
private void UnregisterFrameEvents()
{
if (_frame != null)
{
_frame.Navigated -= Frame_Navigated;
_frame.NavigationFailed -= Frame_NavigationFailed;
}
}
private void Frame_Navigated(object sender, NavigationEventArgs e) => Navigated?.Invoke(sender, e);
private void Frame_NavigationFailed(object sender, NavigationFailedEventArgs e) => NavigationFailed?.Invoke(sender, e);
</code></pre>
<p><strong>NavigationConfig</strong></p>
<pre><code>private readonly INavigationService _navigationService;
private readonly NavigationView _navigationView;
public NavigationConfig(INavigationService navigationService, NavigationView navigationView)
{
_navigationService = navigationService;
_navigationView = navigationView;
ConfigureNavService();
ConfigureNavView();
}
private void ConfigureNavService()
{
_navigationService.Configure<ShellViewModel, ShellPage>();
_navigationService.Configure<MainViewModel, MainPage>();
_navigationService.Configure<SettingsViewModel, SettingsPage>();
}
private void ConfigureNavView()
{
AddNavItem<MainViewModel>("Home", Symbol.Home);
// Settings is separate item, creates by NavigatonView with XAML IsSettingsVisible="True"
}
private void AddNavItem<TViewModel>(string title, Symbol symbol)
{
var item = new NavigationViewItem
{
Content = title,
Icon = new SymbolIcon(symbol),
Tag = ConvertToKey<TViewModel>()
};
_navigationView.MenuItems.Add(item);
}
public static string ConvertToKey<TViewModel>() => typeof(TViewModel).FullName;
public static string GetPageKey(NavigationViewItem item) => item.Tag.ToString();
</code></pre>
|
[] |
[
{
"body": "<p>I will describe what I came to on my own at the moment.</p>\n<h1>Advantages</h1>\n<p>The task of one place to configure <code>NavigationService</code> and <code>NavigationView</code> really creates a convenience for making changes. But it only applies to registering <code>ViewModel</code> for <code>NavigationService</code> and elements for <code>NavigationView</code>. The process turns into a single line.</p>\n<pre><code>private void ConfigureNavService()\n{\n _navigationService.Configure<ShellViewModel, ShellPage>();\n _navigationService.Configure<MainViewModel, MainPage>();\n _navigationService.Configure<SettingsViewModel, SettingsPage>();\n}\n\nprivate void ConfigureNavView()\n{\n AddNavItem<MainViewModel>("Home", Symbol.Home);\n}\n</code></pre>\n<p>Also, the presence of logic for calculating the key and extracting it, again, in one place <code>Navigation Config</code>. Convenient to change. You don't need to edit different parts of the code.</p>\n<pre><code>public static string ConvertToKey<TViewModel>() => typeof(TViewModel).FullName;\npublic static string GetPageKey(NavigationViewItem item) => item.Tag.ToString();\n</code></pre>\n<h1>Disadvantages</h1>\n<p>The negative side of the resulting implementation is the mixing of classes. Initially independent, independent <code>Navigationservice</code> and <code>ShellViewModel</code> begin to depend on <code>NavigationConfig</code> and use it not only for configuration, but also in normal work to create and retrieve a key. I mean the methods <code>ConvertToKey()</code>, <code>GetPageKey()</code> required in: <code>NavigationConfig.AddNavItem()</code>, <code>NavigationService.Configure()</code>, <code>NavigationService.NavigateTo()</code>, <code>ShellViewModel.OnItemInvoked()</code>, <code>ShellViewModel.IsMenuItemForPageType()</code>.</p>\n<p>Not to say that it is difficult to track such connections, but it will take time.</p>\n<h1>Changes</h1>\n<p>I keep the principle of one place, but in terms of levels.</p>\n<p>Previously, the configuration process was delayed until the <code>ShellViewModel.InitializeNavigation()</code> (calling <code>NavigationConfig</code>). The following changes occur. <code>NavigationConfig</code> has been removed. Registering valid pages and creating elements for <code>NavigationView</code> are different levels. They are not in the same place.</p>\n<ul>\n<li>Creating <code>NavigationItem</code> is given to <code>XAML</code>markup. That is, where\n<code>NavigationView</code> (<code>ShellPage</code>) is defined there and the elements are described\nnavigations.</li>\n</ul>\n<pre><code><NavigationView.MenuItems>\n <NavigationViewItem x:Uid="ShellPage_MenuItem_Home" Icon="Home" Tag="Mergerify.ViewModels.MainViewModel" />\n</NavigationView.MenuItems>\n</code></pre>\n<ul>\n<li>Pages are registered in <code>ViewModelLocator</code>.</li>\n</ul>\n<pre><code>private ViewModelLocator()\n{\n SimpleIoc.Default.Register<IActivationService, ActivationService>();\n SimpleIoc.Default.Register<INavigationService, NavigationService>();\n\n Register<ShellViewModel, ShellPage>();\n Register<MainViewModel, MainPage>();\n Register<SettingsViewModel, SettingsPage>();\n}\n\nprivate void Register<TViewModel, TView>() where TViewModel : class\n{\n SimpleIoc.Default.Register<TViewModel>();\n NavigationService.Configure<TViewModel, TView>();\n}\n\n</code></pre>\n<p>What happened to static methods?</p>\n<ul>\n<li><code>GetPageKey()</code>. Required to obtain a key located in the\n<code>NavigationItem</code>. Because now the navigation elements are in\n<code>ShellPage</code>, method moved to <code>ShellViewModel</code>. And that's the only thing\nthe place where this method is required.</li>\n<li><code>ConvertToKey()</code>. <code>NavigationService</code> contains the <code>_pages</code> dictionary with valid\nit has a method for adding new pages <code>Configure ()</code>. Therefore, it is\nthe only place that knows what the key looks like. For check of the pages created\nmethod <code>Configure<TViewModel, TView>()</code>. With its help, registration takes place\nwithout need to know what the key looks like. From here, the <code>ConvertToKey()</code> method\nbecame private and is located in the <code>NavigationService</code>.</li>\n</ul>\n<h1>Conclusion</h1>\n<p>The described changes made it possible to remove the mixing of classes. Each uses only what he needs and does not associate with the other as it was before. However, the original goal of a single location differs somewhat from the new implementation of a single location by level.</p>\n<p>At the moment, one bug of the changes made has been found. It consists in the fact that the key for <code>NavigationItem</code> fits into the element's markup manually. At the moment, I switched to reducing the key with <code>Type.FullName</code> to <code>Type.Name</code>. Then it is enough to write the name from <code>ViewModel</code> in the navigation elements. For example, instead full name I write only name <code>MainViewModel</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T14:39:21.880",
"Id": "237973",
"ParentId": "237863",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "237973",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T23:18:17.410",
"Id": "237863",
"Score": "4",
"Tags": [
"c#",
"object-oriented",
"dependency-injection",
"mvvm",
"uwp"
],
"Title": "Configuring NavigationService and NavigationView in one place"
}
|
237863
|
<p>I have created this first-timer implementation of Merge Sort
and I got confused by the C++ syntax once or twice.</p>
<p>So I have some questions about this code:</p>
<pre><code>#include <iostream>
#include <thread>
#include <cstdlib>
#include <vector>
#define NUM 1048576*2
int sort(std::vector<int>* vec);
void run(std::vector<int>* vec, int left, int right);
void merge(std::vector<int>* vec, int left, int mid, int right);
int main() {
srand(time(NULL));
std::vector<int> tobesorted;
for(int i = 0; i < NUM; i++){
tobesorted.push_back(rand());
}
sort(&tobesorted);
for(int i = 0; i < NUM; i++){
std::cout << tobesorted[i] << ", ";
}
std::cout << std::endl;
std::cout << "End of Program!";
}
int sort(std::vector<int>* pvec){
int size = pvec->size();
std::thread t1(run, pvec, 0, 0.25*size);
std::thread t2(run, pvec, 0.25*size+1, 0.5*size);
std::thread t3(run, pvec, 0.5*size+1, 0.75*size);
std::thread t4(run, pvec, 0.75*size, size-1);
t1.join();
t2.join();
t3.join();
t4.join();
std::thread t5(merge, pvec, 0, 0.25*size, 0.5*size);
merge(pvec, 0.5*size+1, 0.75*size, size-1);
t5.join();
merge(pvec, 0, 0.5*size, size-1);
return 1;
}
void run(std::vector<int>* pvec, int left, int right){
if(right - left == 0){
return;
}
int mid = (left+ right)/2;
run(pvec, left,mid);
run(pvec, mid+1, right);
merge(pvec, left, mid, right);
}
void merge(std::vector<int>* pvec, int left, int mid, int right){
int ileft = 0;
int iright = 0;
int index = 0;
std::vector<int> leftvec;
std::vector<int> rightvec;
int j = 0;
for(int i= left; i <= mid; i++){
leftvec.push_back(pvec[0][i]);
}
j = 0;
for(int i= mid+1; i <= right; i++){
rightvec.push_back(pvec[0][i]);
}
while(ileft < leftvec.size() && iright < rightvec.size()){
if(leftvec[ileft] > rightvec[iright]){
pvec[0][left+index] = leftvec[ileft++];
index++;
} else {
pvec[0][left+index] = rightvec[iright++];
index++;
}
}
while(ileft < leftvec.size()){
pvec[0][left+index] = leftvec[ileft++];
index++;
}
while(iright < rightvec.size()){
pvec[0][left+index] = rightvec[iright++];
index++;
}
}
</code></pre>
<ol>
<li><p>I think I should have better optimized for better cache use, do you see any opportunities there?</p></li>
<li><p>What could have been generally improved on that code?</p></li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T01:59:50.663",
"Id": "466523",
"Score": "3",
"body": "FYI, the deal with `std::thread t1(run, vec, left, right);` is that `thread`'s constructor makes thread-local copies of things by default. (That's the conservative, thread-safe choice.) If you really want references, the trick is to do `std::thread t1(run, std::ref(vec), left, right);`."
}
] |
[
{
"body": "<p>This code doesn't work, as can be shown by including <code><algorithm></code> and changing the output:</p>\n\n<pre><code>std::cout << std::is_sorted(tobesorted.begin(), tobesorted.end()) << std::endl;\n</code></pre>\n\n<hr>\n\n<p>Other things that are surprising:</p>\n\n<ul>\n<li>We pass pointers but always assume they are not null. That suggests we should be using references instead.</li>\n<li>Misspelt <code>std::srand</code> and <code>std::time</code> - though I'd recommend using <code><random></code> instead.</li>\n<li><code>std::endl</code> used where there's no need to flush output - just write <code>\\n</code> instead.</li>\n<li>Why are we using <code>int</code> rather than <code>std::size_t</code> for our <code>left</code> and <code>right</code> indices?</li>\n<li>Use of floating-point multiplication for integer arithmetic.</li>\n<li>Unused variable <code>j</code>.</li>\n</ul>\n\n<hr>\n\n<p>There's a risk of overflow here:</p>\n\n<blockquote>\n<pre><code>int mid = (left+ right)/2;\n</code></pre>\n</blockquote>\n\n<p>Better would be</p>\n\n<pre><code>auto mid = left + (right - left) / 2;\n</code></pre>\n\n<hr>\n\n<p>This code can be re-written:</p>\n\n<blockquote>\n<pre><code>std::vector<int> leftvec;\nstd::vector<int> rightvec;\n\nfor(int i= left; i <= mid; i++){\n leftvec.push_back(pvec[0][i]);\n}\nfor(int i= mid+1; i <= right; i++){\n rightvec.push_back(pvec[0][i]);\n}\n</code></pre>\n</blockquote>\n\n<p>Those vectors will likely re-allocate several times as they are filled, because we didn't <code>reserve()</code> capacity. Instead of those loops, we could use the appropriate constructor:</p>\n\n<pre><code>std::vector<int> leftvec(pvec->begin()+left, pvec->begin()+mid);\nstd::vector<int> rightvec(pvec->begin()+mid, pvec->>begin()+right+1);\n</code></pre>\n\n<p>It would be easier if we passed iterators rather than indices here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T18:53:25.363",
"Id": "466617",
"Score": "0",
"body": "Thank you for your answer! I will rewrite my code.\n\nOne Thing:\n\n`8,7,7,6,3,2,2,2,2,1,\nSorted 0\nEnd of Program!\nElapsed time: 0.000204397 s`\n\nYour code says it is not sorted, seems sorted to me..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T19:34:13.037",
"Id": "466621",
"Score": "0",
"body": "Your version (in the question) produces much more output than that, and most of the biggest values were near the beginning. Oh, I see you're sorting in reverse order; that means you'd need to use `std::is_sorted(begin, end, std::greater())`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T11:14:39.963",
"Id": "237887",
"ParentId": "237867",
"Score": "5"
}
},
{
"body": "<p>Some other observations, in addition to <a href=\"https://codereview.stackexchange.com/a/237887/188857\">Toby Speight's answer</a>:</p>\n\n<ul>\n<li><p>Sort your includes.</p></li>\n<li><p><code>#define NUM 1048576*2</code> should be <code>constexpr std::size_t num = 1048576*2</code> (or 2097152) instead.</p></li>\n<li><p>This loop:</p>\n\n<pre><code>std::vector<int> tobesorted;\nfor(int i = 0; i < NUM; i++){\n tobesorted.push_back(rand());\n}\n</code></pre>\n\n<p>can be simplified: (requires <code><algorithm></code>)</p>\n\n<pre><code>std::vector<int> numbers(num);\nstd::generate_n(numbers.begin(), num, []{ return std::rand(); });\n</code></pre>\n\n<p>or, better, with <code><random></code> and a separate function: (requires <code><algorithm></code> and <code><random></code>)</p>\n\n<pre><code>std::vector<int> generate()\n{\n static std::mt19937_64 engine{std::time(nullptr)};\n std::uniform_int_distribution<int> dist{}; // [0, INT_MAX] by default\n\n std::vector<int> result(num);\n std::generate(result.begin(), result.end(), [&]{ return dist(engine); });\n return result;\n}\n\n// in main()\nauto numbers = generate(); // guaranteed copy elision\n</code></pre></li>\n<li><p>This loop:</p>\n\n<pre><code>for(int i = 0; i < NUM; i++){\n std::cout << tobesorted[i] << \", \";\n}\n</code></pre>\n\n<p>can be replaced with (requires <code><algorithm></code> and <code><iterator></code>)</p>\n\n<pre><code>std::copy(numbers.begin(), numbers.end(),\n std::ostream_iterator<int>{std::cout, \", \"});\n</code></pre></li>\n<li><p>Avoid <code>std::endl</code> unless the flushing semantics is necessary. See <a href=\"https://stackoverflow.com/q/213907/9716597\"><code>std::endl</code> vs <code>\\n</code></a> for more information.</p></li>\n<li><p>Use <code>[begin, end)</code> (including begin, excluding end) style instead of <code>[begin, end]</code> (including both begin and end) in order to eliminate the <code>+1</code> / <code>-1</code>. Rewrite <code>0.25*size</code> as <code>size / 4</code>, <code>0.5*size</code> as <code>size / 2</code>, and <code>0.75*size</code> as <code>size / 4 * 3</code>.</p></li>\n<li><p>Instead of using <code>std::thread</code> directly, consider the more high-level <code>std::async</code> and <code>std::future</code>:</p>\n\n<pre><code>constexpr std::size_t thread_num = 4;\nauto chunk_size = vec.size() / thread_num;\n\nstd::vector<std::future<void>> tasks;\ntasks.reserve(thread_num);\nfor (std::size_t i = 0; i < thread_num; ++i) {\n tasks.push_back(std::async(std::launch::async,\n [](auto first, auto last) { std::sort(first, last); },\n vec.begin() + chunk_size * i,\n vec.begin() + chunk_size * (i + 1)\n ));\n}\nfor (auto& task : tasks) {\n task.get();\n}\n// similarly for merging\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T19:48:28.550",
"Id": "466622",
"Score": "1",
"body": "Using `std::async()` over `std::thread()` should (have not tested) be a huge advantage in most applications. The cost of threads is quite high but async should be re-using its own pool of background threads. For simple apps like this not much of a difference but for larger applications re-using the pool of threads should be an advantage."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T13:35:46.663",
"Id": "237898",
"ParentId": "237867",
"Score": "2"
}
},
{
"body": "<h2>Overview</h2>\n<p>You are passing a <code>std::vector<></code> to be sorted. There are lots of container types that could be used in its place (<code>std::array</code>, C-Array, <code>std::dequeue</code>, <code>std::string</code> etc).</p>\n<p>It is more traditional to allow sorting via iterators. You pass the beginning and end of the iterator sequence you want to sort.</p>\n<pre><code>template<typename I>\nvoid sort(I begin, I end);\n</code></pre>\n<p>This way you can use the sort on any of the above types of container.</p>\n<hr />\n<p>Threads are relatively expensive to start. You better have a lot of data too sort before you split that sort across multiple threads. You may get some benefit from using <code>std::async</code> rather than <code>std::thread</code> as the runtime should manage a pool of threads for handling async actions (thus the threads will be-reused and thus not cost as much to spin up).</p>\n<p>But this will depend on the sophistication of the current runtime and will only be beneficial if you are using lots of async actions that can re-use threads from the pool (with only 5 threads not much re-use but with a larger program that does a lot of sorting that balance may change).</p>\n<hr />\n<h2>Code Review</h2>\n<p>The old #define is no longer used for constants. Macros should be reserved for Hardware/OS/Compiler variations. The language has better alternatives for most other uses of macros.</p>\n<pre><code>#define NUM 1048576*2\n</code></pre>\n<p>On this case:</p>\n<pre><code>constexpr int My_NUM = 1048576*2; // Has explicit type information associated.\n // Is not a text replacement which\n // could lead to unexpected errors.\n</code></pre>\n<p>What is the result of:</p>\n<pre><code> int test1 = sizeof NUM;\n int test2 = sizeof My_NUM;\n</code></pre>\n<hr />\n<p>If the parameter is never <code>nullptr</code> then don't use pointers.</p>\n<pre><code>int sort(std::vector<int>* vec);\nvoid run(std::vector<int>* vec, int left, int right);\nvoid merge(std::vector<int>* vec, int left, int mid, int right);\n</code></pre>\n<p>Generally you should never be using pointers in C++. There is usually a better way to do it (when you get advanced then pointers come back but lets stay away from them until you master the rest of the language).</p>\n<p>In this case passing by reference is a better choice:</p>\n<pre><code>int sort(std::vector<int>& vec);\nvoid run(std::vector<int>& vec, int left, int right);\nvoid merge(std::vector<int>& vec, int left, int mid, int right);\n</code></pre>\n<p>Though as mentioned above using iterator would even better (and more idiomatic).</p>\n<pre><code>template<typename I>\nint sort(I begin, I end);\ntemplate<typename I>\nvoid run(I begin, I end);\ntemplate<typename I>\nvoid merge(I begin, I mid, I end);\n</code></pre>\n<hr />\n<p>Misspelled:</p>\n<pre><code> srand(time(NULL));\n\n // Should be\n std::srand(std::time(nullptr));\n</code></pre>\n<hr />\n<h2>Minor optimizations:</h2>\n<pre><code> std::thread t1(run, pvec, 0, 0.25*size);\n std::thread t2(run, pvec, 0.25*size+1, 0.5*size);\n std::thread t3(run, pvec, 0.5*size+1, 0.75*size);\n std::thread t4(run, pvec, 0.75*size, size-1);\n /// ^ missing +1 is this a bug?\n t1.join();\n t2.join();\n\n // Why are you waiting on t3 and t4 before starting the merge.\n // If t1 and t2 are finished then start the merge operation.\n // You can then wait on t3 and t4 once this has started.\n\n t3.join();\n t4.join();\n\n std::thread t5(merge, pvec, 0, 0.25*size, 0.5*size);\n merge(pvec, 0.5*size+1, 0.75*size, size-1);\n t5.join();\n\n merge(pvec, 0, 0.5*size, size-1);\n\n // If a function can only return one value\n // Why have it? \n return 1;\n}\n</code></pre>\n<hr />\n<p>You create temporary vectors every recursive call to merge:</p>\n<pre><code>void merge(std::vector<int>* pvec, int left, int mid, int right){\n\n std::vector<int> leftvec;\n std::vector<int> rightvec;\n</code></pre>\n<p>This can get very expensive. Why not create the temporary vectors once (up in sort() then re-use parts at every level. This will make the code more efferent overall.</p>\n<hr />\n<p>Copying is fine for simple objects (like int). But what if you want to sort a vector of large objects? Then copying (the result of a push) is very expensive. So you should prefer to try and move objects.</p>\n<pre><code> leftvec.push_back(pvec[0][i]);\n rightvec.push_back(pvec[0][i]);\n\n leftvec.push_back(std::move(pvec[0][i]));\n rightvec.push_back(std::move(pvec[0][i]));\n</code></pre>\n<p>If you already have the containers pre-built (as suggested by the last option for optimizing) then you can simply move the objects between containers.</p>\n<pre><code> std::move(pvec[0][i], destination);\n</code></pre>\n<hr />\n<p>You could use a standard algorithm for this:</p>\n<pre><code> while(ileft < leftvec.size()){\n pvec[0][left+index] = leftvec[ileft++];\n index++;\n }\n\n while(iright < rightvec.size()){\n pvec[0][left+index] = rightvec[iright++];\n index++;\n }\n\n /// Why not\n\n std::move( std::begin(leftvec) + iLeftm std::end(leftVec), std::begin(pvec) + left+index);\n std::move( std::begin(rightvec) + iLeftm std::end(rightvec), std::begin(pvec) + left+index);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T17:50:51.357",
"Id": "466864",
"Score": "0",
"body": "Hey,\nthanks for this incredibly useful insight. I will certainly look up const expression and iterators..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T17:57:16.090",
"Id": "237988",
"ParentId": "237867",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "237988",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T01:38:50.530",
"Id": "237867",
"Score": "4",
"Tags": [
"c++",
"algorithm",
"multithreading",
"reinventing-the-wheel",
"mergesort"
],
"Title": "C++ Merge Sort Algorithm"
}
|
237867
|
<p>It takes in a string from the command line. prints out the length of the string.
I'm mostly looking for tips and general convention suggestions <br>
But I'm open to any other criticism also. <br>
Roast it please thanks. </p>
<pre><code>global _start
extern printf
section .data
arg_err db `Invalid Arg Length\n\0`
len_arg_err equ $ - arg_err
arg_frmt db `%d\n\0`
section .text
_start:
mov ecx, DWORD [esp]
cmp ecx, 2
jne _error_ext ; Args != 2?
mov eax,DWORD [esp+8] ;char** argv
mov ecx, eax
_label:
mov dl, byte [ecx]
cmp dl, 0; read byte and comp to 0
je _exit
add ecx, 1
jmp _label
_exit:
sub ecx,eax ; subtract end addr from start addr
push ecx
push arg_frmt
call printf
mov eax, 1
int 0x80
_error_ext:
mov ecx, arg_err
mov edx, len_arg_err
call _print
mov eax, 1
int 0x80
_print: ; needs ecx as char* edx as char* len
push eax
push ebx
mov eax, 4
mov ebx, 1
int 0x80
pop ebx
pop eax
retn
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T05:26:52.633",
"Id": "466526",
"Score": "0",
"body": "Explicit loops are usually suboptimal in x86 ISA. Consider `repnz` prefix. [This answer](https://stackoverflow.com/questions/49840755/minimal-opcode-size-x86-64-strlen-implementation) is a good starting point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T06:56:34.020",
"Id": "466530",
"Score": "0",
"body": "strlen.asm:40: error: symbol `_print' undefined"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T21:51:30.020",
"Id": "466763",
"Score": "0",
"body": "Welcome to Code Review! Please do not update the code in your question. Please see [_what you may and may not do after receiving answers_](http://meta.codereview.stackexchange.com/a/1765)."
}
] |
[
{
"body": "<blockquote>\n<pre><code>mov dl, byte [ecx]\ncmp dl, 0; read byte and comp to 0 \nje _exit\n</code></pre>\n</blockquote>\n\n<p>There are various alternatives, for example:</p>\n\n<pre><code>cmp byte [ecx], 0\nje _exit\n</code></pre>\n\n<p>And:</p>\n\n<pre><code>mov dl, [ecx] ; note: BYTE would be redundant, but you can put it if you like\ntest dl, dl\njz _exit\n</code></pre>\n\n<p>For that loop overall,</p>\n\n<blockquote>\n<pre><code>_label:\n mov dl, byte [ecx]\n cmp dl, 0; read byte and comp to 0 \n je _exit\n add ecx, 1 \n jmp _label\n</code></pre>\n</blockquote>\n\n<p>This is a \"2 jump loop\", but it can be a \"1 jump loop\", for example:</p>\n\n<pre><code>_label:\n mov dl, [ecx]\n inc ecx\n test dl, dl\n jnz _label\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code> dec ecx\n_label:\n inc ecx\n cmp byte [ecx], 0\n jne _label\n</code></pre>\n\n<p>(<a href=\"https://stackoverflow.com/q/36510095/555045\">here</a> are some details about <code>inc</code> vs <code>add</code>)</p>\n\n<p>For fast loops like this, having two jumps in the loop can easily slow them down to half the speed.</p>\n\n<p><code>repnz scasb</code> is an option, but it's not that great. Small loops like this can run in 1 cycle per iteration on most CPUs anyway, and <code>repnz scasb</code> is not better than that (often worse, such as 2 cycles per byte on Ryzen and Haswel). The special optimizations for <code>rep movs</code> and <code>rep stos</code> don't apply to <code>rep scas</code>.</p>\n\n<p>There are faster ways to implement <code>strlen</code>, that are not based on byte-by-byte loops but detect the presence of a zero inside a bigger block, using SIMD (<a href=\"https://www.strchr.com/sse2_optimised_strlen\" rel=\"nofollow noreferrer\">example</a>) or SWAR (<a href=\"https://stackoverflow.com/q/11787810/555045\">example</a>). That way speeds much higher than 1 byte per cycle can be reached. Perhaps some future processor would implement a \"fast rep scas\" feature in a similar way..</p>\n\n<blockquote>\n<pre><code>mov ecx, arg_err\nmov edx, len_arg_err\ncall _print\nint 0x80\n</code></pre>\n</blockquote>\n\n<p>This is mysterious, there is no <code>_print</code> function and there is a stray system call without selecting any particular entry point, or perhaps <code>_print</code> was meant to put a suitable value in <code>eax</code>? </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T15:07:39.047",
"Id": "466587",
"Score": "0",
"body": "It was another label I had defined I thought I switched everything over to use printf so I didn't include the function in my post. I'll edit the post when I get home today. It just set things up for the print syscall"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T22:13:30.150",
"Id": "466633",
"Score": "0",
"body": "I'm having trouble googling these \"SIMD or SWAR\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T22:34:26.250",
"Id": "466635",
"Score": "2",
"body": "@DNS_Jeezus I linked some examples. I could link the general concepts as well but I get good results if I google for them"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-22T01:36:27.573",
"Id": "500428",
"Score": "0",
"body": "@DNS_Jeezus: One thing I'd add to this answer: `movzx edx, byte [ecx]` avoids a false dependency on the previous iteration. If you don't specifically *want* to merge a new low byte into the existing register value, use `movzx` for byte and word loads. It's just a simple zero-extending load like RISC machines do, not a load+merge. (https://uops.info/ and [Why doesn't GCC use partial registers?](https://stackoverflow.com/q/41573502))"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T12:57:41.907",
"Id": "237895",
"ParentId": "237869",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T03:15:51.880",
"Id": "237869",
"Score": "5",
"Tags": [
"assembly",
"x86",
"nasm"
],
"Title": "Program for string length in x86"
}
|
237869
|
<p>I need to run a evaluation for large (1 Million) number of components and build a string with error which has comma separated error codes. As the final string is to be persisted in RDBMS TABLE.COLUMN with MAX length for 255, I need to truncate the string (not abruptly) and append an ellipses to indicate there were more failures.</p>
<p>Here is what I have</p>
<pre><code>public class ErrorCodeStringBuilder {
private boolean isFirst = true;
private boolean isFull = false;
private StringBuilder stringBuilder;
private int MAX_CAP = 250;
private int curLength = 0;
private String ELLIPSES = "...";
public ErrorCodeStringBuilder() {
stringBuilder = new StringBuilder(20);
}
public void append(String str) {
curLength = curLength + str.length();
if (curLength >= MAX_CAP) {
isFull = true;
}
checkAndAppend(str);
}
private void checkAndAppend(String str) {
if (!isFull) {
if (isFirst) {
stringBuilder.append(str);
isFirst = false;
} else {
stringBuilder.append(",");
stringBuilder.append(str);
}
}
}
public String toString() {
if (isFull) {
return stringBuilder.toString() + "," + ELLIPSES;
}
return stringBuilder.toString();
}
}
</code></pre>
<p>Unit Tests:</p>
<pre><code>import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ErrorCodeStringBuilderTest {
@Test
public void testMaxLength() {
ErrorCodeStringBuilder errorCodeStringBuilder = new ErrorCodeStringBuilder();
//10
errorCodeStringBuilder.append("0123456789");
//20
errorCodeStringBuilder.append("0123456789");
//30
errorCodeStringBuilder.append("0123456789");
//40
errorCodeStringBuilder.append("0123456789");
//50
errorCodeStringBuilder.append("0123456789");
//100
errorCodeStringBuilder.append("abcdefghijklmnopqrstuvwxyz0123456789ABCDEFHIJKLMNO");
//150
errorCodeStringBuilder.append("abcdefghijklmnopqrstuvwxyz0123456789ABCDEFHIJKLMNO");
//200
errorCodeStringBuilder.append("abcdefghijklmnopqrstuvwxyz0123456789ABCDEFHIJKLMNO");
//250
errorCodeStringBuilder.append("abcdefghijklmnopqrstuvwxyz0123456789ABCDEFHIJKLMNO");
//260
errorCodeStringBuilder.append("0123456789");
String result = errorCodeStringBuilder.toString();
assertTrue(result, result.length() < 255);
assertTrue(result.endsWith("..."));
}
@Test
public void testAppend() {
ErrorCodeStringBuilder errorCodeStringBuilder = new ErrorCodeStringBuilder();
//10
errorCodeStringBuilder.append("0123456789");
//20
errorCodeStringBuilder.append("0123456789");
String result = errorCodeStringBuilder.toString();
assertEquals(result, "0123456789,0123456789");
}
@Test
public void testNotAbruptTruncate() {
ErrorCodeStringBuilder errorCodeStringBuilder = new ErrorCodeStringBuilder();
//10
errorCodeStringBuilder.append("0123456789");
//20
errorCodeStringBuilder.append("0123456789");
//30
errorCodeStringBuilder.append("0123456789");
//40
errorCodeStringBuilder.append("0123456789");
//50
errorCodeStringBuilder.append("0123456789");
//100
errorCodeStringBuilder.append("abcdefghijklmnopqrstuvwxyz0123456789ABCDEFHIJKLMNO");
//150
errorCodeStringBuilder.append("abcdefghijklmnopqrstuvwxyz0123456789ABCDEFHIJKLMNO");
//200
errorCodeStringBuilder.append("abcdefghijklmnopqrstuvwxyz0123456789ABCDEFHIJKLMNO");
//254
errorCodeStringBuilder.append("XXabcdefghijklmnopqrstuvwxyz0123456789ABCDEFHIJKLMNOXX");
String result = errorCodeStringBuilder.toString();
assertEquals(result, "0123456789,0123456789,0123456789,0123456789,0123456789,abcdefghijklmnopqrstuvwxyz0123456789ABCDEFHIJKLMNO," +
"abcdefghijklmnopqrstuvwxyz0123456789ABCDEFHIJKLMNO" +
",abcdefghijklmnopqrstuvwxyz0123456789ABCDEFHIJKLMNO,...");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T06:49:12.910",
"Id": "466528",
"Score": "2",
"body": "To make the question more complete, you should add the unit tests that you have written to the question. This would demonstrate how the code is used and which edge cases you already considered."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T08:17:07.117",
"Id": "466532",
"Score": "0",
"body": "@RolandIllig Thanks for your time. I updated the questions with the tests."
}
] |
[
{
"body": "<p>Not taking the comma and the ellipses into account when calculating the resulting string length and instead setting the max length to 250 is an ugly hack. The code is also a bit buggy, because if the first error message happens to be 250 characters long, you only get ellipses in the result even though there would have been room for the error message, a comma and ellipses.</p>\n\n<p>You should create a method for calculating the result length if a string was appended.</p>\n\n<pre><code>private int calculateResultingLength(String str) {\n int result = stringBuilder.length();\n if (result > 0) {\n result += 1; // Account for a comma.\n }\n if (errorsDropped) {\n result += ELLIPSES.length();\n }\n result += str.length();\n\n return result;\n}\n</code></pre>\n\n<p>The second <code>isFull</code> check in <code>checkAndAppend</code> is redundant because you already do that check in the append method and checkAndAppend is private. The isFull is now also misleading, because it tells that an error was dropped. The next error might be shorter and fit into the string. I rename it to <code>errorsDropped</code>.</p>\n\n<pre><code>public void append(String str) {\n if (calculateResultingLength(str) >= MAX_CAP) {\n errorsDropped = true;\n } else {\n performAppend(str);\n }\n}\n</code></pre>\n\n<p>The <code>isFirst</code> field is redundant. You know the append is the first one if the stringBuilder is empty:</p>\n\n<pre><code>private void performAppend(String str) {\n if (stringBuilder.length() > 0) {\n stringBuilder.append(\",\");\n }\n stringBuilder.append(str);\n}\n</code></pre>\n\n<p>The performAppend method became a bit pointless now. You could just write:</p>\n\n<pre><code>public void append(String str) {\n if (calculateResultingLength(str) >= MAX_CAP) {\n errorsDropped = true;\n return;\n }\n\n if (stringBuilder.length() > 0) {\n stringBuilder.append(\",\");\n }\n stringBuilder.append(str);\n}\n</code></pre>\n\n<p>The MAX_CAP and ELLIPSES are named as if they were constants but they are variables. They should be static and final. Also, no need to abbreviate here.</p>\n\n<pre><code>private static final int MAX_CAPACITY = 255;\nprivate static final String ELLIPSES = \"...\";\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T08:50:12.803",
"Id": "466533",
"Score": "0",
"body": "Thanks. I completely missed the comma part. Regarding the first error message being long, I did not consider that case because of the assumption that error codes would be much smaller than that. I agree with all the other comments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T21:22:01.743",
"Id": "466629",
"Score": "1",
"body": "Firstly, if you append a 200 character string, then a 100 character string (_overflow flagged_), then a 40 character string (_hey, this one fits!_), you get `\"first-string,third-string,...\"` where as the OP would return just `\"first-string,...\"`, so are getting a very different behaviour. Secondly, if you add five 50 character strings, yielding a 254 character temporary result, and then add one more string, the overflow flag is set. When the result is finally requested, 4 additional characters are added to the buffered 254 character string, which exceeds the 255 character limit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T11:17:41.977",
"Id": "466705",
"Score": "0",
"body": "I should have mentioned that this was an intentional breach from the original. Since we're talking about displaying errors from a million checks in 255 characters, it seemed like this was mostly \"nice to know\" and the actual content of the string was pretty irrelevant. Then again... if presented with a task like this in real life I'd question the sensibility of the task and suggest that a simple boolean \"there_were_errors\" flag was set to the database."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T08:23:10.937",
"Id": "237875",
"ParentId": "237871",
"Score": "7"
}
},
{
"body": "<p>I think my approach to this problem would be to separate it into two completely independent classes.</p>\n\n<p>The first class would take a <code>List<String></code> and modify that collection to conform to your length constraint. The result of this transformation could be a new, potentially shorter, <code>List<String></code>, perhaps with a \"...\" as the last element where required. Or it could be an object that encapsulates an <code>int</code> for the number of entries to keep and a <code>boolean</code> for whether truncation was necessary.</p>\n\n<p>The second class would then create the comma-separated list. The implementation of this will depend on how you implemented the first class. Don't forget that if you're using Java 8 then you can use the following quite delightful snippet of code to turn a <code>List<String></code> into a comma-separated <code>String</code>:</p>\n\n<pre><code>list.stream().collect(Collectors.joining(\",\"))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T10:28:07.907",
"Id": "237881",
"ParentId": "237871",
"Score": "1"
}
},
{
"body": "<p><strong>Test naming</strong></p>\n\n<p>Consider dropping 'test' from the front of your test names and using the extra space to add something describing the expected outcome for the test, maybe something like...</p>\n\n<pre><code>append_overflowMaxLength_maxLengthNotExceeded\nappend_withinBuffer_addsMessage\nappend_overflowMaxLength_entireExceptionReplacedWithElipses\n</code></pre>\n\n<p><strong>assertEquals</strong></p>\n\n<p>You're passing your parameters to <code>assertEquals</code> the wrong way round (your expected is your actual). Frameworks like <a href=\"http://joel-costigliola.github.io/assertj/assertj-core-quick-start.html\" rel=\"noreferrer\">assertJ</a> can make assertions more intuitive.</p>\n\n<pre><code>assertThat(result).isEqualTo(\"...\");\nassertThat(result).endsWith(\"...\");\nassertThat(result).hasSizeLessThan(255);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T12:12:13.720",
"Id": "466551",
"Score": "0",
"body": "These names are still a bit word soup. I prefer as plain english as possible. Like \"appendsEllipsesWhenMessageIsDropped()\" or \"separatesMessagesWithComma()\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T12:21:28.310",
"Id": "466552",
"Score": "1",
"body": "@TorbenPutkonen that's fair enough, naming's somewhat stylistic and it's not uncommon to have some indication of the method under test in the name of the test. If you prefer as plain English as possible, then I think you would prefer the fluent assertions since they tend to read that way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T13:24:06.587",
"Id": "466560",
"Score": "0",
"body": "For classes that have many public methods that is a well justified practise."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T11:41:08.537",
"Id": "237889",
"ParentId": "237871",
"Score": "5"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/a/237875/100620\">Torben Putkonen's answer</a> is good, but it still has some flaws.</p>\n\n<p>If <code>stringBuilder.length() == 199</code>, and you add message with string length 53, then the string length with become <code>199 + 1 + 53 == 253 < MAX_CAPACITY</code>. Now you have a problem. If you add another string, say length 50, you exceed the capacity and set <code>errorsDropped = true;</code>.</p>\n\n<p>Now, when <code>toString()</code> is called, the <code>stringBuilder().toString() + \",...\"</code> is returned, which is 257 characters! This is too big for the \"RDBMS TABLE.COLUMN with MAX length of 255\".</p>\n\n<p>There are two approaches you can take:</p>\n\n<ol>\n<li>Limit the accumulation length to 251 characters (255 less the 4 characters in <code>\",...\"</code>)</li>\n<li>Allow the accumulation length to reach 255 characters, but remove the last message(s) if insufficient room exists to add <code>\",...\"</code> when necessary.</li>\n</ol>\n\n<p>Demonstrating approach #2, incorporating Torben's <code>private static final</code> members & removal of redundant fields. <em>Note</em>: Assumes the error messages themselves have no embedded commas.</p>\n\n<pre><code>public class ErrorCodeStringBuilder {\n\n private static final int MAX_CAPACITY = 255;\n private static final String ELLIPSES = \"...\";\n\n private StringBuilder stringBuilder = new StringBuilder(20);\n private boolean overflow = false;\n\n public void append(String str) {\n if (!overflow) {\n if (stringBuilder.length() > 0)\n stringBuilder.append(',');\n\n stringBuilder.append(str);\n\n int length = stringBuilder.length();\n if (length > MAX_CAPACITY) {\n int last_comma = stringBuilder.lastIndexOf(\",\", MAX_CAPACITY - ELLIPSES.length());\n stringBuilder.replace(last_comma + 1, length, ELLIPSES);\n overflow = true;\n }\n }\n }\n\n @Override\n public String toString() {\n return stringBuilder.toString();\n }\n}\n</code></pre>\n\n<p>Using <code>.lastIndexOf(\",\", MAX_CAPACITY - ELLIPSES.length())</code> ensures we find a comma at position 252 or earlier. If the second last message ends at 253, and another message is added with a comma at position 254, an earlier comma will be found, and the these last two messages are replaced with the ellipses.</p>\n\n<p><em>Bonus</em>: This even handles the edge case of the first string longer than 252 characters. If the first string is 300 characters, then <code>last_comma</code> will become <code>-1</code> (not found), and <code>.replace(last_comma + 1, length, ELLIPSES)</code> will replace starting from index 0 ... which is the entire string.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T09:37:20.823",
"Id": "466691",
"Score": "0",
"body": "thanks for pointing this out. I added a unit test for this case."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T21:08:44.110",
"Id": "237928",
"ParentId": "237871",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "237875",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T06:01:59.900",
"Id": "237871",
"Score": "9",
"Tags": [
"java",
"strings",
"unit-testing"
],
"Title": "Building string with max length"
}
|
237871
|
<p>Today I have attempted a Codility exercise "Fish" (<a href="https://app.codility.com/programmers/lessons/7-stacks_and_queues/fish/" rel="nofollow noreferrer">https://app.codility.com/programmers/lessons/7-stacks_and_queues/fish/</a>), and I have to say I found it to be:
1) Not necessarily "easy" as implied by the page, AND
2) Quite satisfying to figure out in the end.
Below the text of the challenge:</p>
<blockquote>
<p>You are given two non-empty arrays A and B consisting of N integers.
Arrays A and B represent N voracious fish in a river, ordered
downstream along the flow of the river.</p>
<p>The fish are numbered from 0 to N − 1. If P and Q are two fish and P <
Q, then fish P is initially upstream of fish Q. Initially, each fish
has a unique position.</p>
<p>Fish number P is represented by A[P] and B[P]. Array A contains the
sizes of the fish. All its elements are unique. Array B contains the
directions of the fish. It contains only 0s and/or 1s, where:</p>
<ul>
<li><p>0 represents a fish flowing upstream,</p></li>
<li><p>1 represents a fish flowing downstream.</p></li>
</ul>
<p>If two fish move in opposite directions and there are no other
(living) fish between them, they will eventually meet each other. Then
only one fish can stay alive − the larger fish eats the smaller one.
More precisely, we say that two fish P and Q meet each other when P <
Q, B[P] = 1 and B[Q] = 0, and there are no living fish between them.
After they meet:</p>
<ul>
<li><p>If A[P] > A[Q] then P eats Q, and P will still be flowing downstream,</p></li>
<li><p>If A[Q] > A[P] then Q eats P, and Q will still be flowing upstream.</p></li>
</ul>
<p>We assume that all the fish are flowing at the same speed. That is,
fish moving in the same direction never meet. The goal is to calculate
the number of fish that will stay alive.</p>
</blockquote>
<p>My solution is a bit playful, and I was wondering if anyone could have a look and let me know if this is a correct way of solving this problem. All comments will be appreciated.</p>
<pre><code>import java.util.ArrayDeque;
// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");
class Solution {
public int solution(int[] A, int[] B) {
ArrayDeque<Fish> safetyPool = new ArrayDeque<Fish>();
ArrayDeque<Fish> activePool = new ArrayDeque<Fish>();
for (int i = 0; i < A.length; i++) {
activePool.offer(Fish.cFish(A[i], B[i]));
}
while(!activePool.isEmpty()) {
// System.out.println(safetyPool + " " + activePool);
Fish safeFish = safetyPool.peekLast();
Fish swimmingFish = activePool.peekFirst();
if (safeFish != null) {
if (safeFish.dir == 1) {
if (safeFish.dir != swimmingFish.dir) {
if (safeFish.att > swimmingFish.att) {
activePool.removeFirst();
} else {
safetyPool.removeLast();
}
} else {
safetyPool.offer(activePool.pollFirst());
}
} else {
safetyPool.offer(activePool.pollFirst());
}
} else {
safetyPool.offer(activePool.pollFirst());
}
}
return safetyPool.size();
}
}
class Fish {
public int att;
public int dir;
public Fish(int att, int dir) {
this.att = att;
this.dir = dir;
}
public static Fish cFish(int att, int dir) {
return new Fish(att, dir);
}
@Override
public String toString() {
return String.format("Fish(att: %d, dir: %d)", att, dir);
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T15:19:54.190",
"Id": "466592",
"Score": "0",
"body": "Welcome to Code Review, I edited your post adding the text of the challenge."
}
] |
[
{
"body": "<p>I have some suggestions.</p>\n\n<ol>\n<li>When declaring variable that has inheritance, uses the interface in the left declaration part; this will make the code easier to refactor.</li>\n</ol>\n\n<p><strong>Before</strong> </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>ArrayDeque<Fish> safetyPool = new ArrayDeque<Fish>();\nArrayDeque<Fish> activePool = new ArrayDeque<Fish>();\n</code></pre>\n\n<p><strong>After</strong> </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Deque<Fish> safetyPool = new ArrayDeque<Fish>();\nDeque<Fish> activePool = new ArrayDeque<Fish>();\n</code></pre>\n\n<ol start=\"2\">\n<li>When using the diamond operators with variables, declared the type in the left side, the right one will become optional; since it's declared in the variable side.</li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>Deque<Fish> safetyPool = new ArrayDeque<>();\nDeque<Fish> activePool = new ArrayDeque<>();\n</code></pre>\n\n<ol start=\"3\">\n<li>To remove the <code>Arrow Code</code> in the while, I suggest that you read the blog post made by Jeff Atwood <a href=\"https://blog.codinghorror.com/flattening-arrow-code/\" rel=\"nofollow noreferrer\"><code>Flattening Arrow Code</code></a>. In my opinion, it's the best way to get rid this kind of code.</li>\n</ol>\n\n<p>The logic contained in the while can be refactored.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>while (!activePool.isEmpty()) {\n Fish safeFish = safetyPool.peekLast();\n Fish swimmingFish = activePool.peekFirst();\n\n if (safeFish == null || safeFish.dir != 1 || safeFish.dir == swimmingFish.dir) {\n safetyPool.offer(activePool.pollFirst());\n continue;\n }\n\n if (safeFish.att > swimmingFish.att) {\n activePool.removeFirst();\n } else {\n safetyPool.removeLast();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T02:04:53.780",
"Id": "466648",
"Score": "0",
"body": "Thanks Doi9t, I really appreciate your comments. I am still new to Java, and have seen the approach from paragraphs 1&2 of your answer in other spots, but could never figure out why it was being done this way. Now I know, that this is to allow us an easier access to polymorphic features downstream from the declarations.\nParagraph 3 is pure gold as well - I am one of these programmers, who sharpens the arrow head quite a lot at times. The article you linked really helps with change of my habits. A+ answer! :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T23:50:57.510",
"Id": "237934",
"ParentId": "237872",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "237934",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T06:40:26.327",
"Id": "237872",
"Score": "4",
"Tags": [
"java",
"programming-challenge",
"stack",
"queue"
],
"Title": "Codility Fish (queue) programming challenge"
}
|
237872
|
<p>Recently got this coding assignment as the first round of interview at a tech organization. I could get the expected result, however, my code failed the best practices check.</p>
<p>Please let me know if it needs a different approach or specific things are missing. I was confused about how to add tests since this will fetch real-time information which will change.</p>
<p>This was the problem statement (not verbatim, from what I recall): </p>
<blockquote>
<p>There is an API <a href="https://api.bart.gov/docs/etd/" rel="nofollow noreferrer">https://api.bart.gov/docs/etd/</a> for train and
station information. </p>
</blockquote>
<p>Information provided: API key (or there was an option to generate API key and use that), sample output.</p>
<p>Query and display:</p>
<blockquote>
<ol>
<li>The current time</li>
<li>Trains leaving Montogomery Station at the current time</li>
<li>Restrict up to 10 trains</li>
<li>Sort result in ascending order of departure time and also mention the destination name.</li>
</ol>
</blockquote>
<p>This was my code:</p>
<pre><code>import requests
import json
import sys
class TrainInfo(object):
def __init__(self, station_code, station_name, number_of_records=10, api_key=API_KEY_PROVIDED):
self.url = 'http://api.bart.gov/api/etd.aspx?'
self.station_code = station_code
self.station_name = station_name
self.number_of_records = number_of_records
self.api_key = api_key
def __get_data(self):
# private method to make http request and return JSON response
request_parameters = {'cmd': 'etd',
'orig': self.station_code,
'key': self.api_key,
'json': 'y'}
try:
response_object = requests.get(self.url, request_parameters)
except requests.exceptions.RequestException as e:
print('HTTP get request failed!')
sys.exit(1)
try:
data_to_parse = response_object.json()
except json.decoder.JSONDecodeError as e:
print('HTTP response cannot be converted to JSON!')
sys.exit(1)
return data_to_parse
def __parse_data(self, data):
# private method to parse the JSON response and return a dictionary where
# delay times are mapped to destination names
raw_data = self.__get_data()
delay_station_map = {}
# list of dictionaries with destination as key and list of departures to destination(estimate)
station_data = data['root']['station'][0]['etd']
for item in station_data:
for d in item['estimate']:
# populate dictionary where key = delay in mins, value = destination
try:
delay_station_map[int(d['minutes'])] = item['destination']
except ValueError:
pass
return delay_station_map
def __fetch_data(self):
raw_data = self.__get_data()
parsed_data = self.__parse_data(raw_data)
return parsed_data
def __print_header(self, current_time):
# Private method to format and print header line for output
header_line = "Trains leaving from {} at {}".format(self.station_name, current_time)
print("*" * len(header_line))
print(header_line)
print("*" * len(header_line))
def get_current_time(self):
# get the current time from the JSON response
raw_data = self.__get_data()
return raw_data['root']['time']
def print_data(self, curr_time):
# print header
self.__print_header(curr_time)
# get dictionary with delays mapped to destinations
parsed_data = self.__fetch_data()
# get destination with max length for formatting output
length_of_dest_names = [len(value) for value in parsed_data.values()]
max_dest_length = max(length_of_dest_names)
for k in sorted(parsed_data.keys())[:self.number_of_records]:
print(" To {0:{1}} in {2} mins".format(parsed_data[k], max_dest_length, k))
# Test Code
if __name__ == "__main__":
test_valid_stationid = TrainInfo('MONT', 'Montgomery St.')
curr_time = test_valid_stationid.get_current_time()
test_valid_stationid.print_data(curr_time)
#test_invalid_stationid = TrainInfo('INVALID', 'Montgomery St.')
#curr_time = test_invalid_stationid.get_current_time()
#test_invalid_stationid.print_data(curr_time)
#test_input_api_key = TrainInfo('INVALID', 'Montgomery St.')
#curr_time = test_invalid_stationid.get_current_time()
#test_invalid_stationid.print_data(curr_time)
#test_invalid_api_key = TrainInfo('MONT', 'Montgomery St.', api_key='')
#curr_time = test_invalid_api_key.get_current_time()
#test_invalid_api_key.print_data(curr_time)
#test_invalid_api_key = TrainInfo('MONT', 'Montgomery St.', api_key='')
#curr_time = test_invalid_api_key.get_current_time()
#test_invalid_api_key.print_data(curr_time)
#test_change_num_of_records = TrainInfo('MONT', 'Montgomery St.', 5)
#curr_time = test_change_num_of_records.get_current_time()
#test_change_num_of_records.print_data(curr_time)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T08:58:52.487",
"Id": "466536",
"Score": "1",
"body": "I rephrased your question to be more in line with what is suggested at the [guide on how to write a good question](/help/how-to-ask). Feel free to change it again if I misunderstood something."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T12:50:56.477",
"Id": "466556",
"Score": "0",
"body": "1) For which Python version is this written? 2) Are you aware you've posted an API key in public view?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T14:22:45.450",
"Id": "466578",
"Score": "1",
"body": "@Mast: 1) Python 3.4 2) The key was provided in the question, I have now edited my question to remove it."
}
] |
[
{
"body": "<p>In general if you have try blocks like yours</p>\n\n<pre><code> try:\n response_object = requests.get(self.url, request_parameters)\n except requests.exceptions.RequestException as e: \n print('HTTP get request failed!')\n sys.exit(1)\n try:\n data_to_parse = response_object.json()\n except json.decoder.JSONDecodeError as e:\n print('HTTP response cannot be converted to JSON!')\n sys.exit(1)\n return data_to_parse\n</code></pre>\n\n<p>You should rewrite them to</p>\n\n<pre><code> try:\n response_object = requests.get(self.url, request_parameters)\n data_to_parse = response_object.json()\n except requests.exceptions.RequestException as e: \n print('HTTP get request failed!') \n sys.exit(1)\n except json.decoder.JSONDecodeError as e:\n print('HTTP response cannot be converted to JSON!')\n sys.exit(1)\n\n return data_to_parse\n</code></pre>\n\n<p>I think is a bit more cleaner this way, but you choose :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T07:20:32.720",
"Id": "466670",
"Score": "0",
"body": "The code in the finally block will execute even if there is no exception and we do not want the code to stop execution if there's no exception"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T08:46:32.187",
"Id": "466683",
"Score": "0",
"body": "Yes you are right, just correct now thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T11:12:22.473",
"Id": "466702",
"Score": "0",
"body": "I try to limit my try-catch blocks as much as possible, so it is as clear as possible what part can raise which exception. I don't think moving from 2 blocks to 1 is an improvement"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T16:12:09.930",
"Id": "237915",
"ParentId": "237873",
"Score": "0"
}
},
{
"body": "<p>Instead of the class, I would use just methods, and string those together:</p>\n\n<ul>\n<li>query the information for a station</li>\n<li>parsing this info to get the departure information</li>\n<li>sort that info in the requested order</li>\n<li>display this information</li>\n</ul>\n\n<h1><code>sys.exit</code></h1>\n\n<p>Why do you exit the program if an error occurs? Now no one else can use this method. Better would be to raise an appropriate exception, and let the caller handle this. Fail fast, fail hard, but also fail clearly, so you can find out what exactly happened.</p>\n\n<h1>getting the response</h1>\n\n<p>This can be as simple as </p>\n\n<p>BART_URL = \"<a href=\"http://api.bart.gov/api/edt.aspx\" rel=\"nofollow noreferrer\">http://api.bart.gov/api/edt.aspx</a>\"</p>\n\n<pre><code>def get_edt(\n station_code: str, *, api_key: str = API_KEY_PROVIDED, url: str = BART_URL,\n):\n \"\"\"queries api.bart.gov for the departure data of the station\"\"\"\n request_parameters = {\n \"cmd\": \"edt\",\n \"key\": api_key,\n \"json\": \"y\",\n \"orig\": station_code,\n }\n response = requests.get(url, request_parameters)\n return response.json()\n</code></pre>\n\n<p>This will raise a <code>ConnectionError</code> when no connection can be established, or a <code>JSONDecodeError</code> if the response is not parsable. You can extend this method in a few ways</p>\n\n<pre><code>class FetchException(Exception): pass\n\ndef get_edt(\n station_code: str, *, api_key: str = API_KEY_PROVIDED, url: str = BART_URL,\n):\n \"\"\"queries api.bart.gov for the departure data of the station\"\"\"\n request_parameters = {\n \"cmd\": \"edt\",\n \"key\": api_key,\n \"json\": \"y\",\n \"orig\": station_code,\n }\n try:\n response = requests.get(url, request_parameters)\n except requests.ConnectionError:\n raise FetchException(f\"no connection to {url} could be established\")\n if response.status_code != \"200\":\n raise FetchException(f\"\"\"\n something went wrong when fetching the data. status_code: {response.status_code}\n {response.text}\n \"\"\")\n return response.json()\n</code></pre>\n\n<h1>parsing the response</h1>\n\n<p>Getting the time and station name out of the response is fairly easy:</p>\n\n<pre><code>def parse_header(response):\n root = response[\"root\"]\n time = root[\"time\"]\n station = root[\"station\"][0]\n station_name = station[\"name\"]\n\n return {\n \"time\": time,\n \"station\": station_name\n }\n</code></pre>\n\n<p>You can simplify this by returning a <code>tuple</code> or extend the capabilities by transforming the date and time to a <code>datetime</code>, returning a <code>namedtuple</code> or even a <code>Header</code> object, depending on how far you want to go here. I think the <code>dict</code> is a nice balance between simplicity and extensibility.</p>\n\n<p>For the example response on the Bart website this returns <code>{'time': '10:20:31 AM PDT', 'station': 'Richmond'}</code></p>\n\n<h1>parse the departures</h1>\n\n<p>What is important about these departures is the destination and minutes until departure. Since the response is a nested structures, grouped per destination, the simplest would be to use a double loop, and just yield the departures</p>\n\n<pre><code>def parse_departures(response):\n try:\n departures = response[\"root\"][\"station\"][0][\"etd\"]\n except (KeyError, IndexError):\n raise ValueError(\"invalid response\")\n for destination_info in departures:\n destination = destination_info[\"destination\"]\n for estimates in destination_info.get(\"estimate\", []):\n minutes_str = estimates[\"minutes\"]\n if minutes_str == \"leaving\":\n minutes = 0\n else:\n minutes = int(minutes_str) + int(estimates.get(\"delay\", 0))\n yield minutes, destination\n</code></pre>\n\n<blockquote>\n<pre><code>list(parse_departures(response))\n</code></pre>\n</blockquote>\n\n<pre><code>[(239, 'Fremont'),\n (13, 'Fremont'),\n (28, 'Fremont'),\n (6, 'Millbrae'),\n (21, 'Millbrae'),\n (36, 'Millbrae')]\n</code></pre>\n\n<p>Since this is a tuple with the minutes until departure as first element, sorting requires just a call to <code>sorted</code></p>\n\n<h2>bug</h2>\n\n<p>There is also a possible bug in your __parse_data method. In <code>delay_station_map</code>, if there is a train leaving the the same time but on another platform, <code>delay_station_map[int(d['minutes'])] = item['destination']</code> will overwrite one of those.</p>\n\n<h1>putting it together</h1>\n\n<p>This can go behind a <code>__main__</code> guard</p>\n\n<pre><code>if __name__ == \"__main__\":\n# response = get_edt(\"MONT\",)\n header = parse_header(response)\n departures = sorted(parse_departures(response))\n\n print(f\"trains departing from {header['station']} at {header['time']}\")\n print(\"=-\" * 10)\n for minutes, destination in departures[:10]:\n print(f\"in {minutes} minutes the train to {destination} leaves\")\n</code></pre>\n\n<p>again, with the example response:</p>\n\n<blockquote>\n<pre><code>trains departing from Richmond at 10:20:31 AM PDT\n=-=-=-=-=-=-=-=-=-=-\nin 6 minutes the train to Millbrae leaves\nin 13 minutes the train to Fremont leaves\nin 21 minutes the train to Millbrae leaves\nin 28 minutes the train to Fremont leaves\nin 36 minutes the train to Millbrae leaves\nin 239 minutes the train to Fremont leaves\n</code></pre>\n</blockquote>\n\n<h1>overall</h1>\n\n<p>Since there is very little state, there is little reason to use a class. Especially a convoluted one as yours. Try to think of the different steps needed to get to the solution, and try to split your code according to those steps. That will generally be the clearest code, which needs the least explanation and comments, and is most easily testable. The units have the least effect on each other.</p>\n\n<p>Brandon Rhodes has a nice talk on clean architecture <a href=\"https://rhodesmill.org/brandon/talks/#clean-architecture-python\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>And Jack Diederich has a very well known talk about when not to use classes <a href=\"https://youtu.be/o9pEzgHorH0\" rel=\"nofollow noreferrer\">here</a>. This is one of the cases where a class is overkill. If you later want to display more information, like the platform, direction, color etc, you can think about introducing classes to this problem, if a dict doesn't suffice anymore.</p>\n\n<p>In your solution, the data is fetched 3 times, once for the current time, twice to get the departures. This should be a giveaway that something is wrong. </p>\n\n<p>Trying to figure out what went on in the code took some jumping back and forth as well, while using the smaller methods, strung together almost explains itself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T16:44:21.573",
"Id": "466736",
"Score": "0",
"body": "Thank you, this looks very clean! My initial solution did not have any class because I did not find it would be useful either. But I was specifically asked to submit again by implementing OOP"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T11:10:42.357",
"Id": "237963",
"ParentId": "237873",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "237963",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T08:09:19.133",
"Id": "237873",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"interview-questions",
"api"
],
"Title": "Query and display train and station information"
}
|
237873
|
<p>I am doing a Pandas project on alcohol consumption. For your information, the dataset has the following columns:</p>
<p>| Continent | Country | Beer | Spirit | Wine |</p>
<p>The following is my code:</p>
<pre><code># Separating data by continent
# ----------------------------
data_asia = data[data['Continent'] == 'Asia']
data_africa = data[data['Continent'] == 'Africa']
data_europe = data[data['Continent'] == 'Europe']
data_north = data[data['Continent'] == 'North America']
data_south = data[data['Continent'] == 'South America']
data_ocean = data[data['Continent'] == 'Oceania']
top_5_asia_beer = data_asia.nlargest(5, ['Beer Servings'])[['Country', 'Beer Servings']]
top_5_asia_spir = data_asia.nlargest(5, ['Spirit Servings'])[['Country', 'Spirit Servings']]
top_5_asia_wine = data_asia.nlargest(5, ['Wine Servings'])[['Country', 'Wine Servings']]
top_5_asia_pure = data_asia.nlargest(5, ['Total Litres of Pure Alcohol'])[['Country', 'Total Litres of Pure Alcohol']]
top_5_africa_beer = data_africa.nlargest(5, ['Beer Servings'])[['Country', 'Beer Servings']]
top_5_africa_spir = data_africa.nlargest(5, ['Spirit Servings'])[['Country', 'Spirit Servings']]
top_5_africa_wine = data_africa.nlargest(5, ['Wine Servings'])[['Country', 'Wine Servings']]
top_5_africa_pure = data_africa.nlargest(5, ['Total Litres of Pure Alcohol'])[['Country', 'Total Litres of Pure Alcohol']]
top_5_europe_beer = data_europe.nlargest(5, ['Beer Servings'])[['Country', 'Beer Servings']]
top_5_europe_spir = data_europe.nlargest(5, ['Spirit Servings'])[['Country', 'Spirit Servings']]
top_5_europe_wine = data_europe.nlargest(5, ['Wine Servings'])[['Country', 'Wine Servings']]
top_5_europe_pure = data_europe.nlargest(5, ['Total Litres of Pure Alcohol'])[['Country', 'Total Litres of Pure Alcohol']]
top_5_north_beer = data_north.nlargest(5, ['Beer Servings'])[['Country', 'Beer Servings']]
top_5_north_spir = data_north.nlargest(5, ['Spirit Servings'])[['Country', 'Spirit Servings']]
top_5_north_wine = data_north.nlargest(5, ['Wine Servings'])[['Country', 'Wine Servings']]
top_5_north_pure = data_north.nlargest(5, ['Total Litres of Pure Alcohol'])[['Country', 'Total Litres of Pure Alcohol']]
top_5_south_beer = data_south.nlargest(5, ['Beer Servings'])[['Country', 'Beer Servings']]
top_5_south_spir = data_south.nlargest(5, ['Spirit Servings'])[['Country', 'Spirit Servings']]
top_5_south_wine = data_south.nlargest(5, ['Wine Servings'])[['Country', 'Wine Servings']]
top_5_south_pure = data_south.nlargest(5, ['Total Litres of Pure Alcohol'])[['Country', 'Total Litres of Pure Alcohol']]
top_5_ocean_beer = data_ocean.nlargest(5, ['Beer Servings'])[['Country', 'Beer Servings']]
top_5_ocean_spir = data_ocean.nlargest(5, ['Spirit Servings'])[['Country', 'Spirit Servings']]
top_5_ocean_wine = data_ocean.nlargest(5, ['Wine Servings'])[['Country', 'Wine Servings']]
top_5_ocean_pure = data_ocean.nlargest(5, ['Total Litres of Pure Alcohol'])[['Country', 'Total Litres of Pure Alcohol']]
</code></pre>
<p>I understand the ridiculousness of my code in terms of duplicity and repetitiveness. Can anyone please share tips and tricks to refactor the code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T11:28:39.013",
"Id": "466548",
"Score": "2",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] |
[
{
"body": "<p>Depends on what you want to do with it. It seems a bit odd to store each top 5 in its own variable.</p>\n\n<p>For starters, you can slice a DataFrame by continent using <code>.groupby</code>:</p>\n\n<pre><code>for continent, continent_data in data.groupby(\"Continent\"):\n # `continent` is now the name of the continent (you don't have to type the continent names manually)\n # `continent_data` is a dataframe, being a subset of the `data` dataframe\n</code></pre>\n\n<p><strong>Edit based on first comment</strong>: if you want to plot the variables, it's definitely not a good idea to store them each in a separate variable. Do you already know how you want to visualize your data? That's something you will need to work toward. I can't really see a top 5 countries for each type of alcoholic beverage for each continent in one plot.</p>\n\n<pre><code>continents = []\ntop5s = {}\nfor continent, continent_data in data.groupby(\"Continent\"):\n continents.append(continent)\n for beverage_column in [\"Beer Servings\", \"Spirit Servings\", \"Wine Servings\"]:\n topcountries = continent_data.nlargest(5, beverage_column)\n # do something with the data, such as:\n print(f\"Top 5 countries in {continent} for {beverage}:\")\n for row in topcountries.iterrows():\n print(f\"- {row.Country}: {row['beverage_column']} servings\")\n</code></pre>\n\n<p>To be very exact: <code>groupby()</code> doesn't return an iterable of tuples, but actually just a GroupBy object that implements iterability (i.e. <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.__iter__.html\" rel=\"nofollow noreferrer\">the <code>__iter__()</code> method</a>). </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T09:36:04.400",
"Id": "466539",
"Score": "0",
"body": "Oh, I now realised that the groupby() function returns a tuple of categories and dataframe subsets. Thanks.\n\nSorry for not informing more, I actually intend to later make a graph for the top 5 of each drink category for each continent. Any advice for this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T11:20:35.543",
"Id": "466706",
"Score": "0",
"body": "See my edits :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T18:46:09.560",
"Id": "466748",
"Score": "0",
"body": "Yeah, I found out about GroupBy object in the documentation. Silly me for mistaking tuples. Thanks."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T09:03:17.557",
"Id": "237877",
"ParentId": "237876",
"Score": "1"
}
},
{
"body": "<h2>sample_data</h2>\n\n<pre><code>np.random.seed(42)\n\ndrinks = [\"Beer\", \"Spirit\", \"Wine\"]\ncontinents = [\n \"Asia\",\n \"Africa\",\n \"Europe\",\n \"North America\",\n \"South America\",\n \"Oceania\",\n]\ncountries = [f\"country_{i}\" for i in range(10)]\nindex = pd.MultiIndex.from_product(\n (continents, countries), names=[\"continent\", \"country\"]\n)\ndata = np.random.randint(1_000_000, size=(len(index), len(drinks )))\n\ndf = pd.DataFrame(index=index, columns=columns, data=data).reset_index()\n</code></pre>\n\n<h1>data structures</h1>\n\n<p>The most jarring about this, is that each datapoint has it's own variable. </p>\n\n<p>A first step would be to use dictionaries:</p>\n\n<pre><code>data_by_continent = {\n continent: df.loc[df[\"continent\"] == continent]\n for continent in continents\n}\n</code></pre>\n\n<p>Note that I used <code>.loc</code> to explicitly make a copy instead of a view to prevent changes in one part of the code contaminating another.</p>\n\n<p>Then the spirit consumption per continent is:</p>\n\n<pre><code>spirit_per_continent = {\n continent: data.loc[\n data[\"Spirit\"].nlargest(5).index, [\"country\", \"Spirit\"]\n ]\n for continent, data in data_by_continent.items()\n}\n</code></pre>\n\n<p>and nested per beverage</p>\n\n<pre><code>consumption_per_drink_continent = {\n drink: {\n continent: data.loc[\n data[drink].nlargest(5).index, [\"country\", drink]\n ]\n for continent, data in data_by_continent.items()\n }\n for drink in drinks\n}\n</code></pre>\n\n<h1>pandas groupby</h1>\n\n<p>If you reform your dataframe into a tidy format, you can use an easy groupby.</p>\n\n<p><a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.melt.html\" rel=\"nofollow noreferrer\"><code>pandas.melt</code></a> is a very handy method to shape a dataframe</p>\n\n<pre><code>df2 = pd.melt(\n df,\n id_vars=[\"continent\", \"country\"],\n var_name=\"drink\",\n value_name=\"consumption\",\n)\n</code></pre>\n\n<blockquote>\n<pre><code> continent country drink consumption\n....\n175 Oceania country_5 Wine 456551\n176 Oceania country_6 Wine 894498\n177 Oceania country_7 Wine 899684\n178 Oceania country_8 Wine 158338\n179 Oceania country_9 Wine 623094\n</code></pre>\n</blockquote>\n\n<h1>groupby</h1>\n\n<p>now you can use <code>groupby</code>, and then later join on the index of <code>df2</code> to introduce the country</p>\n\n<pre><code>(\n df2.groupby([\"continent\", \"drink\"])[\"consumption\"]\n .nlargest(5)\n .reset_index([\"continent\", \"drink\"])\n .sort_values(\n [\"continent\", \"drink\", \"consumption\"], ascending=[True, True, False]\n )\n .join(df2[\"country\"])\n)\n</code></pre>\n\n<blockquote>\n<pre><code> continent drink consumption country\n17 Africa Beer 953277 country_7\n19 Africa Beer 902648 country_9\n15 Africa Beer 527035 country_5\n13 Africa Beer 500186 country_3\n14 Africa Beer 384681 country_4\n... ... ... ... ...\n162 South America Wine 837646 country_2\n160 South America Wine 742139 country_0\n167 South America Wine 688519 country_7\n161 South America Wine 516588 country_1\n166 South America Wine 136330 country_6\n\n90 rows × 4 columns\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T18:48:28.830",
"Id": "466749",
"Score": "0",
"body": "The melt() function seems useful. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T13:11:11.257",
"Id": "237967",
"ParentId": "237876",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T08:51:47.027",
"Id": "237876",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"pandas"
],
"Title": "Alcohol consumption project"
}
|
237876
|
<h3>Background</h3>
<p>I crated a CLI tool which executes an <code>npm</code> command (to create a react app) and modifies the contents of the generated files. It was a practice attempt at creating CLI tools for NodeJS and a chance for me to experience publishing NPM packages.</p>
<h3>What I set out to do</h3>
<p>My plan was to create something which follows the below workflow (in order):</p>
<ol>
<li>user invokes the cli command</li>
<li>user inputs the name of their project</li>
<li>program calls <code>create-react-app</code> to create an app based on project name</li>
<li>program deletes the existing <code>.gitignore</code> file when project has been created</li>
<li>program downloads the latest <code>.gitignore</code> file for nodejs</li>
</ol>
<p>I got used to prototyping a lot with <code>create-react-app</code> and got tired of modifying the <code>.gitignore</code> file every time I wanted to add <code>.env</code> or code coverage files. So I created this tool to do this for me. In the future I hope to also modify the <code>README.md</code> file and allow the users to open the project in vscode when everything has been generated and all files have been modified etc.</p>
<h3>The code</h3>
<p>The tool, in it's entirety is here:</p>
<pre><code>#!/usr/bin/env node
const chalk = require("chalk");
const figlet = require("figlet");
const exec = require("child_process").exec;
const Ora = require("ora");
const fs = require("fs");
const https = require("https");
// create an input interface
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout
});
function execShellCommand(cmd) {
return new Promise((resolve, reject) => {
exec(cmd, (error, stdout, stderr) => {
if (error) {
console.warn(error);
console.warn(stdout);
console.warn(stderr);
}
resolve(stdout ? stdout : stderr);
});
});
}
// 1. clear the console
process.stdout.write("\x1Bc");
// 2. print some fancy text
console.log(
chalk.green(figlet.textSync("My CLI Tool", { horizontalLayout: "full" }))
);
// 3. ask user for a project name
readline.question(`What is your project name? `, name => {
console.log(`\n`); // add a space
let firstSpinner = new Ora(
`Creating a new React project named: ${name} ... this may take a while\n`
);
firstSpinner.start();
// 4. Create a create-react-app project
execShellCommand(`npx create-react-app ${name}`).then(() => {
firstSpinner.succeed();
console.log(`Project ${name} created!\n\n`);
// 5. Remove the existing .gitignore file from that project folder
let secondSpinner = new Ora(
`Removing the original ${name}/.gitignore file...\n`
);
secondSpinner.start();
fs.unlink(`./${name}/.gitignore`, err => {
if (err) {
console.error(err);
return;
}
//file removed
secondSpinner.succeed();
console.log(`Original ${name}/.gitignore file removed!\n\n`);
// 6. Place new .gitignore file in that project directory
let thirdSpinner = new Ora(`Placing new .gitignore file...\n`);
thirdSpinner.start();
let newGitignore = fs.createWriteStream(`./${name}/.gitignore`); // cannot declare anywhere else as the folder has not been created before this point
https
.get(
`https://raw.githubusercontent.com/github/gitignore/master/Node.gitignore`,
res => {
res.pipe(newGitignore);
newGitignore.on("finish", () => {
newGitignore.close();
thirdSpinner.succeed();
console.log(
`New ${name}/.gitignore created!\n\n\nClosing CLI tool\n`
);
readline.close();
process.exit();
});
}
)
.on("error", err => {
fs.unlink(newGitignore);
console.error(err);
process.exit();
});
});
});
readline.close();
});
</code></pre>
<h3>Reflection</h3>
<p>After I created the tool, I realised there are several ways in which I can enhance the user's experience - e.g. adding <code>yargs</code> to implement a <code>help</code> function or parsing of arguments into my CLI tool. </p>
<h3>Questions</h3>
<p>I was wondering how I could improve my code to be more efficient. Perhaps I could learn some best practices before I publish this as an <code>npm</code> package. In particular, I'd like to know if there is any other way for me to create, start and stop my spinners which doesn't involve creating 3 separate ones for various 'checkpoint' sections of my code. And whether my use of <code>exec()</code> is efficient/ best suited for this kind of CLI app.</p>
|
[] |
[
{
"body": "<h1>Preliminary thoughts</h1>\n\n<p>The script looks decent and makes good use of <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-6'\" rel=\"tag\">ecmascript-6</a> features like arrow functions and template literals. I like the use of the chalk and Ora plugins. </p>\n\n<h1>Main questions</h1>\n\n<blockquote>\n <p><em>I'd like to know if there is any other way for me to create, start and stop my spinners which doesn't involve creating 3 separate ones for various 'checkpoint' sections of my code.</em></p>\n</blockquote>\n\n<p>I admit that I wasn't familiar with the library <a href=\"https://github.com/sindresorhus/ora\" rel=\"nofollow noreferrer\">ora</a> but after reading over the API I see that a single spinner can be used for all three lines. See the sample below, where the first spinner is re-used in place of <code>secondSpinner</code>:</p>\n\n<pre><code>const spinner = new Ora(\n `Creating a new React project named: ${name} ... this may take a while\\n`\n);\nspinner.start(); \n\n// 4. Create a create-react-app project\n execShellCommand(`npx create-react-app ${name}`).then(() => {\n spinner.succeed();\n console.log(`Project ${name} created!\\n\\n`);\n\n // 5. Remove the existing .gitignore file from that project folder\n spinner.start(`Removing the original ${name}/.gitignore file...\\n`);\n</code></pre>\n\n<p>And then after the gitignore file is unlinked, that spinner can be referenced again</p>\n\n<pre><code> spinner.succeed();\n console.log(`Original ${name}/.gitignore file removed!\\n\\n`);\n\n // 6. Place new .gitignore file in that project directory\n spinner.start(`Placing new .gitignore file...\\n`);\n</code></pre>\n\n<blockquote>\n <p><em>And whether my use of <code>exec()</code> is efficient/ best suited for this kind of CLI app.</em></p>\n</blockquote>\n\n<p>I looked at <a href=\"https://stackabuse.com/executing-shell-commands-with-node-js/\" rel=\"nofollow noreferrer\">this post</a> which mentions using <code>exec()</code> as well as <code>spawn()</code>:</p>\n\n<blockquote>\n <h3>When to use exec and spawn?</h3>\n \n <p>The key difference between <code>exec()</code> and <code>spawn()</code> is how they return the data. As <code>exec()</code> stores all the output in a buffer, it is more memory intensive than <code>spawn()</code>, which streams the output as it comes.</p>\n \n <p>Generally, if you are not expecting large amounts of data to be returned, you can use <code>exec()</code> for simplicity. Good examples of use-cases are creating a folder or getting the status of a file. However, if you are expecting a large amount of output from your command, then you should use <code>spawn()</code>. A good example would be using command to manipulate binary data and then loading it in to your Node.js program.</p>\n</blockquote>\n\n<p>You could consider switching the code to using <code>spawn()</code> but it appears the argument handling may need to be altered. </p>\n\n<p>Another thing to consider would be instead of deleting the gitignore file, just overwrite it with the contents of the downloaded file - then if that happens to fail then it wouldn't be deleted.</p>\n\n<h1>Other feedback</h1>\n\n<h2>Error handling</h2>\n\n<p>It would be wise to add error handling functions - for example, chain on a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch\" rel=\"nofollow noreferrer\"><code>.catch()</code></a> after the <code>execShellCommand.then()</code> call.</p>\n\n<h2>Callback hell</h2>\n\n<p>The code becomes <em>not-so-shallow</em> i.e. has a few indentation levels towards the final steps. <a href=\"http://callbackhell.com/\" rel=\"nofollow noreferrer\">CallbackHell.com</a> has some tips to avoid this - e.g. naming those anonymous callback functions, just as you did with <code>execShellCommand()</code>. This may require passing parameters - can be done with <code>Function.bind()</code>.</p>\n\n<h2>Constants</h2>\n\n<p>These can be used for values that never change</p>\n\n<blockquote>\n<pre><code>`https://raw.githubusercontent.com/github/gitignore/master/Node.gitignore`,\n</code></pre>\n</blockquote>\n\n<p>This seems like a good candidate for a constant declared at the beginning of the code. While it appears it is only used in one spot, it is a bit long to have sitting in the code, and if it ever needs to be updated in the future, it would be easier to find it at the top of the code instead of buried in the code.</p>\n\n<p>I would call that constant something like <code>GITHUB_NODE_GITIGNORE_PATH</code> - which isn't exactly brief but it is shorter than the entire URL.</p>\n\n<h2>Other uses for <code>const</code></h2>\n\n<p>Other variables that don't get re-assigned can be declared with <code>const</code> as well, even if they aren't really a <em>constant</em> - e.g. arrays that get pushed into, objects that get mutated. This helps avoid accidental re-assignment. Notice in the sample code I gave above to re-use a single spinner I used <code>const spinner</code>.</p>\n\n<h2>Readline closed in two spots</h2>\n\n<p>I see <code>readline.close();</code> in two spots - one within the callback function to <code>newGitignore.on(\"finish\")</code> as well as one at the end of the callback function to </p>\n\n<blockquote>\n<pre><code>readline.question(`What is your project name? `\n</code></pre>\n</blockquote>\n\n<p>Perhaps only one call should exist - possibly in a <code>.finally()</code> callback.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T19:15:39.607",
"Id": "238130",
"ParentId": "237879",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "238130",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T09:51:33.983",
"Id": "237879",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"console",
"file-system",
"ecmascript-6"
],
"Title": "NodeJS CLI script to create React apps"
}
|
237879
|
<p>In an interview I was asked to solve two JavaScript questions. I thought I did pretty well because I:</p>
<ul>
<li>Covered the edge cases</li>
<li>Wrote comprehensive tests</li>
<li>Documented the code using jsdoc</li>
</ul>
<p>The interviewer responded with this exact feedback:</p>
<blockquote>
<p>Overly Complex Solution, Strange Coding Conventions, Poorly
Structured, Hard to Understand, Overly Complex Solution but the first
solution did handle edge cases well.</p>
</blockquote>
<p>I'm a little confused by the feedback (why include "Overly Complex" twice <em>and</em> "Hard to Understand", which is basically the same thing) - I would appreciate a second set of eyes and more detailed feedback on <em>why</em> this is "Overly Complex."</p>
<p>English is not my first language; please let me know if anything is unclear.</p>
<blockquote>
<p>Q1. Given transactions calculate the balance between start-end time for a specific category.</p>
<pre><code>// Sample transactions, if we say find category:eating transactions between
2020-01-01, 2020-02-25 it should return 400
[{
id:1,
amount:100,
category:'eating',
sourceAccount: 'A',
targetAccount: 'B',
time: '2020-01-02T00:00:00Z'
},
{
id:2,
amount:210,
category:'shopping',
sourceAccount: 'A',
targetAccount: 'B',
time: '2020-01-01T00:00:00Z'
},
{
id:3,
amount:300,
category:'eating',
sourceAccount: 'A',
targetAccount: 'B',
time: '2020-02-02T02:02:00Z'
}]
</code></pre>
</blockquote>
<pre><code>// My code
/**
* Transaction object from consumer bank account
* @typedef {Object} Transaction
* @property {number} id
* @property {string} sourceAccount
* @property {string} targetAccount
* @property {number} amount
* @property {string} category
* @property {string} time
*/
/**
* Calculate the balance in a specific category within the specified time period.
* @param {Transaction} [transactions=[]] - Account transactions
* @param {string} category - Target category
* @param {object} startTime - Beginning period (Date object)
* @param {object} endTime - End period (Date object)
* @returns {number} Calculated balance
*/
function getBalanceByCategoryInPeriod(transactions = [], category, startTime, endTime) {
const {
id:1,
amount:100,
category:'eating',
sourceAccount: 'A',
targetAccount: 'B',
time: '2018-03-12T12:33:00Z'
}= transactions
if (!isString(category)) throw new Error('Parameter category is not a string');
if (!isValidDateObject(startTime)) throw new Error('Parameter startTime is not a valid date string');
if (!isValidDateObject(endTime)) throw new Error('Parameter endTime is not a valid date string');
if (endTime <= startTime) throw new Error('End time cannot be lower than start time');
return transactions.reduce((acc, cur) => {
const errors = isValidTransactionObject(cur, transactionSchema);
if (errors.length > 0) {
console.warn(`Transaction properties are not valid, calculating total balance without, ${cur.id}`, errors);
return acc;
}
const targetDate = new Date(cur.time).getTime();
const isBetweenTimeRange = endTime.getTime() > targetDate && targetDate >= startTime.getTime();
if (cur.category === category && isBetweenTimeRange) return acc + cur.amount;
return acc;
}, 0);
}
/*** UTILS ***/
const isString = value => typeof value === 'string';
const isNumber = value => typeof value === 'number' && !isNaN(value);
const isValidDateString = value => /(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+)|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d)|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d)/.test(value);
const isValidDateObject = value => value instanceof Date && !isNaN(value);
const transactionSchema = {
id: isNumber,
amount: isNumber,
sourceAccount: isString,
targetAccount: isString,
category: isString,
time: isValidDateString
};
const isValidTransactionObject = (object = {}, schema) => {
if (!schema) throw new Error('Schema must be provided to validator function');
return Object.keys(schema)
.filter(key => !schema[key](object[key]))
.map(key => new Error(`${key} is invalid.`));
};
</code></pre>
<blockquote>
<p>Q2. Given transactions find duplicate transactions (same amount, category, sourceAccount, targetAccount) within one minute period and return them as grouped, grouped arrays should be ordered by first element's id inside of that array. (This one is pretty hard to explain, so just check out input and expected output)</p>
<pre><code>//Sample input
[
{
id: 3,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:34:30.000Z'
},
{
id: 5,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:00.000Z'
},
{
id: 6,
sourceAccount: 'A',
targetAccount: 'C',
amount: 250,
category: 'other',
time: '2018-03-02T10:33:05.000Z'
},
{
id: 4,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:36:00.000Z'
},
{
id: 2,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:50.000Z'
},
{
id: 1,
sourceAccount: 'A',
targetAccount: 'C',
amount: 250,
category: 'other',
time: '2018-03-02T10:33:00.000Z'
}
];
</code></pre>
<pre><code>//Expected Output
[
[
{
id: 1,
sourceAccount: 'A',
targetAccount: 'C',
amount: 250,
category: 'other',
time: '2018-03-02T10:33:00.000Z'
},
{
id: 6,
sourceAccount: 'A',
targetAccount: 'C',
amount: 250,
category: 'other',
time: '2018-03-02T10:33:05.000Z'
}
],
{
id: 5,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:00.000Z'
},
{
id: 2,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:33:50.000Z'
},
{
id: 3,
sourceAccount: 'A',
targetAccount: 'B',
amount: 100,
category: 'eating_out',
time: '2018-03-02T10:34:30.000Z'
}
]
]
</code></pre>
</blockquote>
<p>My code: </p>
<pre><code>/**
* Transaction object from consumer bank account
* @typedef {Object} Transaction
* @property {number} id
* @property {string} sourceAccount
* @property {string} targetAccount
* @property {number} amount
* @property {string} category
* @property {string} time
*/
const MUST_MATCH_PROPS = ['sourceAccount', 'targetAccount', 'amount', 'category'];
/**
* Groups sorted transactions array based on conditions
* @param {[Transaction]} arr
* @returns {Array.<Array.<Transaction>>]} - Duplicate Transactions
*/
const groupDuplicateTransactions = arr => {
const subArrays = [];
for (let runner = 1, prevDuplicate = false, arrInd = -1; runner < arr.length; runner++) {
if (isDuplicate(arr[runner], arr[runner - 1])) {
if (!prevDuplicate) arrInd++;
if (!subArrays[arrInd]) subArrays[arrInd] = [];
subArrays[arrInd].push(arr[runner - 1]);
if (runner === arr.length - 1) subArrays[arrInd].push(arr[runner]);
prevDuplicate = true;
} else {
if (prevDuplicate) subArrays[arrInd].push(arr[runner - 1]);
prevDuplicate = false;
}
}
return subArrays;
}
/**
* Finds duplicate transactions in n*log(n)
* @param {[Transaction]} [transactions=[]] - Account transactions
* @returns {[Transaction]} - Duplicate Transactions
*/
const findDuplicateTransactions = (transactions = []) => {
const sortedTransactions = [...transactions] // To ensure immutability. If there is memory constraints I'd prefer mutating
.filter(transaction => isValidTransactionObject(transaction, transactionSchema).length === 0) // Just to be sure objects are valid transaction objects, objects which are not can be ignored while running algorithm but for the sake of cleanness I have decided to filter out beforehands
.sort(sorter);
return groupDuplicateTransactions(sortedTransactions).sort((x, y) => x[0].id - y[0].id);
}
/*** UTILS ***/
const compareFields = (x, y, fields) => fields.every(p => x[p] === y[p]);
const isInOneMinute = (x, y) => Math.abs(new Date(x.time) - new Date(y.time)) < 60000;
const isDuplicate = (x, y) => compareFields(x, y, MUST_MATCH_PROPS) && isInOneMinute(x, y);
const sorter = (a, b) => {
if (a.sourceAccount === b.sourceAccount) {
if (a.targetAccount === b.targetAccount) {
if (a.amount === b.amount) {
if (a.category === b.category) {
return b.time < a.time ? 1 : -1;
}
return b.category < a.category ? 1 : -1;
}
return b.amount < a.amount ? 1 : -1;
}
return b.targetAccount < a.targetAccount ? 1 : -1;
}
return b.sourceAccount < a.sourceAccount ? 1 : -1;
};
const isString = value => typeof value === 'string';
const isNumber = value => typeof value === 'number' && !isNaN(value);
const isValidDateString = value =>
/(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+)|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d)|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d)/.test(
value
);
const isValidDateObject = value => value instanceof Date && !isNaN(value);
const transactionSchema = {
id: isNumber,
amount: isNumber,
sourceAccount: isString,
targetAccount: isString,
category: isString,
time: isValidDateString
};
const isValidTransactionObject = (object = {}, schema) => {
if (!schema) throw new Error('Schema must be provided to validator function');
return Object.keys(schema)
.filter(key => !schema[key](object[key]))
.map(key => new Error(`${key} is invalid.`));
};
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T11:27:51.767",
"Id": "466547",
"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."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T11:56:49.697",
"Id": "466550",
"Score": "2",
"body": "Welcome to posting on CodeReview@SE. `why someone just write Overly Complex 2 times` my first thought was that the assessments quoted seem to be from more than one *someone*. At least until you see reason to assume someone tries to hurt you (how unprofessional!), think *non-appreciative*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T12:40:36.400",
"Id": "466554",
"Score": "2",
"body": "For me the feedback seems like it was automatically created by tags that the reviewer can click. And for one of the tags (\"Overly Complex Solution\") it seems the reviewer added a custom explanation (which said something nice), which made it show up a second time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T12:48:47.040",
"Id": "466555",
"Score": "0",
"body": "Check the `Expected Output`: the bracketing is off (and, possibly, indentation)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T14:07:01.193",
"Id": "466576",
"Score": "1",
"body": "@KaPy3141: that would explain the conspicuous capitalisation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T15:08:41.413",
"Id": "466588",
"Score": "0",
"body": "@greybeard Thank you for editing and yes that might be true. That's actually a reason I want to get some review and feedback on the test in this platform. I just want to understand from other developers perspective what I did wrong, because still it seems fine for me except minor things. When you look at algorithm questions in Leetcode or Hackerrank of course most of them looks hard to understand unless you track. And this task doesn't look different for me, I mean it is not like developing api, website or application so you can architecture your code based and maintain coding styles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T15:20:06.880",
"Id": "466593",
"Score": "0",
"body": "Do you actually want the code reviewing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T15:27:23.940",
"Id": "466595",
"Score": "1",
"body": "@Pod Yes, I feel I can't see things that I am doing wrong. That's why I need"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T21:32:28.763",
"Id": "466632",
"Score": "0",
"body": "Sometimes honest feedback can be... *honest*."
}
] |
[
{
"body": "<blockquote>\n <p>why someone just write Overly Complex 2 times </p>\n</blockquote>\n\n<p>I don't know what format you originally received this information in, but it looks like there are 4 \"tags\" applied to your application:</p>\n\n<ol>\n<li>Overly Complex Solution</li>\n<li>Strange Coding Conventions</li>\n<li>Poorly Structured </li>\n<li>Hard to Understand </li>\n</ol>\n\n<p>With someone having modified the first one to include some extra information:</p>\n\n<ul>\n<li>Overly Complex Solution but the first solution did handle edge cases well.</li>\n</ul>\n\n<p>Which says to me that multiple people look at your solution and \"rate\" it, and multiple people thought it was Overly Complex, with one of those people adding extra detail.</p>\n\n<blockquote>\n <p>why someone just write Overly Complex 2 times and Hard to Understand again which means the same. </p>\n</blockquote>\n\n<p>I don't know their system, but <strong>overly complex</strong> and <strong>hard to understand</strong> are two different things. Here is an pseudo-code example that is <strong>overly complex</strong> yet <strong>easy to understand</strong>:</p>\n\n<pre><code>list = [\n -1 + 1,\n 0 + 1,\n 1 + 1,\n 2 + 1,\n 2 + 2,\n 1 + 4,\n 3 + 3,\n 1 + 6,\n]\n</code></pre>\n\n<p>It is a pointlessly complex way of saying \"[0, 1, 2, 3, 4, 5, 6, 7]\", yet I think it's pretty easy to understand?</p>\n\n<p>Therefore they are two separate categories in their system.</p>\n\n<blockquote>\n <p>I was just waiting for the result and didn't even asked for feedback yet</p>\n</blockquote>\n\n<p>The feedback is the result :)</p>\n\n<blockquote>\n <p>English is not my first language but what I understand from feedback is something that can help me to improve also this mail sounds so offensive and destructive. I am not going to ask for detailed feedback because of that reason. </p>\n</blockquote>\n\n<p>Feedback doesn't <em>have</em> to help you improve, it could simply be an \"explanation\" of why they rejected you.</p>\n\n<hr>\n\n<p>In terms of an actual code review, I'll point out that I don't know their system so I'll guess at what they meant for each category:</p>\n\n<blockquote>\n <ol>\n <li>Overly Complex Solution</li>\n </ol>\n</blockquote>\n\n<p>This is the hardest for me to explain, because there's no much code here really, and the steps you take don't seem <em>that</em> complex, but then again I don't know what the ideal, \"simple\" solution is. Your code is very functional and callback-based. Perhaps they were after something more straight forward and procedural?</p>\n\n<p>Perhaps something like this:</p>\n\n<pre><code>const groupDuplicateTransactions = arr => {\n const subArrays = [];\n for (let runner = 1, prevDuplicate = false, arrInd = -1; runner < arr.length; runner++) {\n if (isDuplicate(arr[runner], arr[runner - 1])) {\n if (!prevDuplicate) arrInd++;\n if (!subArrays[arrInd]) subArrays[arrInd] = [];\n subArrays[arrInd].push(arr[runner - 1]);\n if (runner === arr.length - 1) subArrays[arrInd].push(arr[runner]);\n prevDuplicate = true;\n } else {\n if (prevDuplicate) subArrays[arrInd].push(arr[runner - 1]);\n prevDuplicate = false;\n }\n }\n return subArrays;\n}\n</code></pre>\n\n<p>could be expressed differently? e.g. you declare 3 things in the for-initialiser, one called <code>arrInd</code> and one called <code>runner</code>. These are unidiomatic names for such iterating variables. And what's the difference between the two? To figure that out we must deeply inspect the code. We don't want to do that -- we want the code to obviously tell us what these things are.</p>\n\n<p>Perhaps the interviewers felt this method of iterating was too complex for them?</p>\n\n<blockquote>\n <ol start=\"2\">\n <li>Strange Coding Conventions</li>\n </ol>\n</blockquote>\n\n<p>This I have to agree with. Coding conventions are usually designed to make code easer to read, so that we can read a lot of it quickly. Your code is incredibly dense and requires a lot of <em>careful reading</em>. I have a hard time even figuring out which line belongs with which other statements. You could have written the exact same thing in a way that doesn't require <em>careful reading</em>. </p>\n\n<p>As an example, let's look at <code>groupDuplicateTransactions</code> again:</p>\n\n<pre><code>const groupDuplicateTransactions = arr => {\n const subArrays = [];\n for (let runner = 1, prevDuplicate = false, arrInd = -1; runner < arr.length; runner++) {\n if (isDuplicate(arr[runner], arr[runner - 1])) {\n if (!prevDuplicate) arrInd++;\n if (!subArrays[arrInd]) subArrays[arrInd] = [];\n subArrays[arrInd].push(arr[runner - 1]);\n if (runner === arr.length - 1) subArrays[arrInd].push(arr[runner]);\n prevDuplicate = true;\n } else {\n if (prevDuplicate) subArrays[arrInd].push(arr[runner - 1]);\n prevDuplicate = false;\n }\n }\n return subArrays;\n}\n</code></pre>\n\n<p>could be:</p>\n\n<pre><code>const groupDuplicateTransactions = (arr) => {\n const subArrays = [];\n\n for (let runner = 1, prevDuplicate = false, arrInd = -1; runner < arr.length; runner++) {\n if (isDuplicate(arr[runner], arr[runner - 1])) {\n if (!prevDuplicate) arrInd++;\n if (!subArrays[arrInd]) subArrays[arrInd] = [];\n\n subArrays[arrInd].push(arr[runner - 1]);\n\n if (runner === arr.length - 1) subArrays[arrInd].push(arr[runner]);\n\n prevDuplicate = true;\n } else {\n if (prevDuplicate) subArrays[arrInd].push(arr[runner - 1]);\n\n prevDuplicate = false;\n }\n }\n return subArrays;\n}\n</code></pre>\n\n<p>All I've done here is add a bit of whitespace, and suddenly things are more obvious and quickly-readable. </p>\n\n<p>Most coding standards don't like single-line if-statements. So taking it a step further:</p>\n\n<pre><code>const groupDuplicateTransactions = (arr) => {\n const subArrays = [];\n\n for (let runner = 1, prevDuplicate = false, arrInd = -1; runner < arr.length; runner++) {\n if (isDuplicate(arr[runner], arr[runner - 1])) {\n if (!prevDuplicate) {\n arrInd++;\n }\n if (!subArrays[arrInd]) { \n subArrays[arrInd] = [];\n }\n\n subArrays[arrInd].push(arr[runner - 1]);\n\n if (runner === arr.length - 1) {\n subArrays[arrInd].push(arr[runner]);\n }\n prevDuplicate = true;\n } else {\n if (prevDuplicate) {\n subArrays[arrInd].push(arr[runner - 1]);\n }\n prevDuplicate = false;\n }\n }\n return subArrays;\n}\n</code></pre>\n\n<p>Additionally, your code is not consistent. \nThe average line is (approx) 20 characters in length, but then you have some whoppers like this:</p>\n\n<blockquote>\n<pre><code> .filter(transaction => isValidTransactionObject(transaction, transactionSchema).length === 0) // Just to be sure objects are valid transaction objects, objects which are not can be ignored while running algorithm but for the sake of cleanness I have decided to filter out beforehands\n</code></pre>\n</blockquote>\n\n<p>That comment could have easily been a multi-line comment on the line before. Instead you chose to put it all on one line. Why? I imagine most people wouldn't even see the comment as it's way off screen, and they've not had to scroll for any reason before this.</p>\n\n<blockquote>\n <ol start=\"3\">\n <li>Poorly Structured </li>\n </ol>\n</blockquote>\n\n<p>I'm not sure how their system differentiates this from 1 or 2, as one person's \"Strange Coding Conventions\" is another person's \"poorly structured\". </p>\n\n<p>If they mean the placement of functions within a file, then it seems ok to me... based on the assumption that you were restricted to a single file. Otherwise it would have been best to use multiple files, e.g. \"utils.js\" for all the stuff under <code>/*** UTILS ***/</code></p>\n\n<blockquote>\n <ol start=\"4\">\n <li>Hard to Understand </li>\n </ol>\n</blockquote>\n\n<p>I think this category is a combination of 1,2,3. But if we are to separate it out then we should remember the maxim that code is read more often than it's written, and your code doesn't appear to be optimised for reading. </p>\n\n<p>e.g.</p>\n\n<pre><code>const sorter = (a, b) => {\n if (a.sourceAccount === b.sourceAccount) {\n if (a.targetAccount === b.targetAccount) {\n if (a.amount === b.amount) {\n if (a.category === b.category) {\n return b.time < a.time ? 1 : -1;\n }\n return b.category < a.category ? 1 : -1;\n }\n return b.amount < a.amount ? 1 : -1;\n }\n return b.targetAccount < a.targetAccount ? 1 : -1;\n }\n return b.sourceAccount < a.sourceAccount ? 1 : -1;\n};\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>const sorter = (a, b) => {\n if (a.sourceAccount !== b.sourceAccount) {\n return b.sourceAccount < a.sourceAccount ? 1 : -1;\n }\n else if (a.targetAccount !== b.targetAccount) {\n return b.targetAccount < a.targetAccount ? 1 : -1;\n }\n else if (a.amount !== b.amount) {\n return b.amount < a.amount ? 1 : -1;\n }\n else if (a.category !== b.category) {\n return b.category < a.category ? 1 : -1;\n }\n else {\n return b.time < a.time ? 1 : -1;\n }\n};\n</code></pre>\n\n<p>The second version has more locality. i.e. you check <code>sourceAccount</code>, then on the next line you use it. No more lines after the first two refer to <code>sourceAccount</code>. Whereas in your version you have to \"remember\" that we've failed that check then go down 10 lines to the use of the fields.</p>\n\n<p>It also requires less indentation. If you structure had 50 fields, would you indent 50 times?</p>\n\n<p>At the end of the day your interviewers will take the code \"as a whole\", and if it's too dense and indented for them then they'll just reject it out right. You, as the code-writer, should go out of your way to make it <strong>very simple and obvious to them</strong> what the code does.</p>\n\n<blockquote>\n <p>was just waiting for the result and didn't even asked for feedback yet but I got this one which make me feel like garbage after 5-6 years experience. \n I am not going to ask for detailed feedback because of that reason. </p>\n</blockquote>\n\n<p>Don't let a single bad interview disheartend you. Remember: A lot of this is subjective. You might like tight, dense code with single line ifs. The interviewers probably didn't. Maybe your next interviewer will?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T16:36:42.137",
"Id": "466606",
"Score": "1",
"body": "Hello Pod, thank you very much for taking time and reviewed the code detailed. After I looked at code assesment platform blog posts I saw this evaluation criterias, http://bit.ly/2SXcV8u . I agree almost everything you said, most of the things you mentioned I didn't even consider during the task, because I was focused more on how I solve the task efficient way (time complexity)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T16:37:56.277",
"Id": "466607",
"Score": "0",
"body": "1. Overly Complex=I implemented Q2. with more declarative on first run but I realized there are so many redundant operations I am doing, I could simply write in single loop with two pointer (js pointer =) ). So I think that is kind of a wrong assumption. And I couldn't find a way to solve that question more expressive and performant way. Because I declare more than one variable I couldn't come up with meaningful names the other option was using i,j,k var names which personally I found harder to read while I see those answers. But I guess that's kind of personal mistake that I am doing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T16:38:01.797",
"Id": "466608",
"Score": "0",
"body": "2. Strange coding convention: I totally agree what you are saying I guess I didn't find those deal breaker and focused only the algorithmic solution and testing with every possible case.\n3. Yes you are right the solution should be in single file thats why I write same functions in both questions. Just tried to show 'utils' is different. I'd personally extract validators, utility functions and typedefs in different files if it was possible.\n4. Yes that's the most stupid thing that I see in this task and felt embarrassed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T17:06:33.453",
"Id": "466612",
"Score": "0",
"body": "Out of interest: What is the name of the assessment platform? And remember, for your next interview, your interviewers are often looking at your code quality as much as they are the correctness. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-04T21:08:43.980",
"Id": "467502",
"Score": "0",
"body": "For the second version of `sorter` the `else` keywords can be eliminated because the previous conditional blocks have `returns`..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T14:35:37.490",
"Id": "467721",
"Score": "0",
"body": "It's a matter of style regarding the `dangling else` :) In a lot of other contexts I would remove the dangling-else! In *this* case I like the dangling-else as it shows every case has been accounted for. If I removed the else my eyes would see the level-0-indented-return and I would assume that one of the ifs could also reach there, so my eyes would dart back to those to check there wasn't a missing return or a condition inside the sibling if-statments. i.e. it makes it similar to a switch"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T15:55:57.683",
"Id": "237914",
"ParentId": "237882",
"Score": "6"
}
},
{
"body": "<p>I have little to add to what Pod said.</p>\n\n<p>There is nothing wrong with compact code. Your code could be very efficient, and there is clearly a lot of effort in it, but I agree <strong>readability</strong> could be improved. Indeed the small details count, even whitespace is important in code.</p>\n\n<p>The important takeaways:</p>\n\n<p>Good code should have a natural <strong>flow</strong> and should be <strong>visually appealing</strong>. As an experiment look at the <strong>shape</strong> of your code standing in front of your screen at a distance of one meter (or 3 feet). Do you like what you see ?\nIt is cliché but you only get one chance to make a first impression, and code leaves an impression too. An interview is highly subjective too. Even a good product needs some dressing-out to sell better.</p>\n\n<p>Just for fun I did a copy-paste in Notepad++ and zoomed out. It looks like this:\n<a href=\"https://i.stack.imgur.com/o2mS4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/o2mS4.png\" alt=\"enter image description here\"></a></p>\n\n<p>I have to say I have seen worse. But maybe you will be looking at things through new lenses now.</p>\n\n<p>Next point: avoid all redundancy, that means your checks should take place in a logical order.</p>\n\n<p>I totally agree about the <strong>single-line if statements</strong>, avoid them. Quite a bad habit, possibly laziness for which I can't find justification. Opening and closing brackets (with proper indentation of course) make the block more readable and less ambiguous. Shorter is not always better.</p>\n\n<p>Rather than put a lot of <code>ifs</code>, sometimes a <code>switch</code> statement will make more sense. Possibly it will make the code purpose even clearer, depending on the conditions you are testing. </p>\n\n<p>Nested <code>if</code> blocks or long sequences of <code>else if</code> can be avoided by <strong>returning early</strong> or <strong>branching out early</strong> while maintaining a single return point. Discussion about the concept: <a href=\"https://mikeschinkel.me/2019/better-alternative-to-return-early-php-wordpress/\" rel=\"nofollow noreferrer\">A better alternative to “return early” – PHP / WordPress edition</a></p>\n\n<p>Not to mention the ternary operator.</p>\n\n<p>Another good practice: <strong>comments</strong>.\nWhile good code should speak for itself, it doesn't hurt to put a few comments here and there. \nIt shows that: 1) you had a clear idea in mind, 2) you are trying to help whomever will have to work on this code, including <em>yourself</em> (in 6 months you will have lost your train of thought and you'll have to re-analyze your own code), 3) you are capable of documenting your code, 4) you put yourself in the shoes of another person (including interviewers).</p>\n\n<p>Even if you know you will be judged on your technical proficiency rather than your English writing skills, even if you are short on time, take the time to <strong>comment</strong> even if it's just two lines. Essentials parts of the code are not commented at all. The parts that are less obvious to understand deserve some explanation.</p>\n\n<p>What I gather is that they just didn't like your style. One thing to keep in mind is that development is often <strong>teamwork</strong> rather than solo. The interviewers may be figuring out if you would be capable of working in a team, if you already follow good practices, consistent naming conventions etc.</p>\n\n<p>Don't let this unfortunate experience put you out. The good news is that minor changes in style can have a huge impact as exemplified in the useful comments you've got here. Hopefully you will like <strong>our</strong> feedback better !</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T21:15:27.990",
"Id": "237929",
"ParentId": "237882",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T10:53:56.373",
"Id": "237882",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"node.js",
"interview-questions"
],
"Title": "Calculate transaction balances and find duplicate transactions"
}
|
237882
|
<p>this is my code to implement DFS with recursion but no stack. I ran few test cases which turned out to be positive but wanted to check the efficiency of the code. </p>
<pre><code>graph = {'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'E']),
'D': set(['B', 'F']),
'E': set(['C', 'B', 'F']),
'F': set(['D', 'E'])}
visited_nodes = set()
is_visited = {}
#seen_nodes = set()
seen_nodes = []
def unseen_neighbors(start_node):
unseen = []
for i in graph[start_node]:
if is_visited.get(i, 'NA') == 'NA':
unseen.append(i)
print ('start node and unseen ', start_node, unseen)
return unseen
def DFS(graph, start_node):
is_visited[start_node] = True
#seen_nodes.append(start_node)
#print ('seen ', seen_nodes)
#add_neighbors(start_node)
unseen = unseen_neighbors(start_node)
if len(unseen) == 0:
return
for i in unseen:
if is_visited.get(i, 'NA') == 'NA':
seen_nodes.append(i)
DFS(graph, i)
if __name__ == "__main__":
seen_nodes.append('A')
DFS(graph, 'A')
print ("DFS Traversal ", seen_nodes, set(seen_nodes))
</code></pre>
|
[] |
[
{
"body": "<p>Well, your code is indeed doing DFS and it is doing tail recursion. I don't see any improvement from an algorithm perspective. \nOne low-hanging fruit is to get rid of <code>seen_nodes</code> as it seems to exist only for debugging purposes. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T02:45:01.593",
"Id": "237941",
"ParentId": "237884",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T10:58:24.147",
"Id": "237884",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"recursion"
],
"Title": "DFS with recursion and without stack"
}
|
237884
|
<p>Just for fun and practice purpose, I have written a short program in C# console with few classes which will create 30 seats for a cinema during program initialization with these options.</p>
<ul>
<li>Print all seats</li>
<li>Seed 20 random taken seats</li>
<li>Print all empty seats</li>
<li>Print all taken seats</li>
</ul>
<p>I think my algorithm for generate 20 random taken seats doesn't look that efficient. I thought of extra space, which is the taken list. For that, while generated empty seats not equal with required empty seats, I will remove the random seat and push that random seat to taken list. But the problem with this is to print all the complete 30 seats, I have merge taken and empty list.</p>
<p>Anyway is my code for review.</p>
<pre><code> /// <summary>
/// One cinema will have many seats
/// </summary>
public class Cinema
{
private readonly List<Seat> seats;
public Cinema()
{
// Maximum number of seat of any cinema is 30.
seats = new List<Seat>(30);
GenerateCompleteSeats();
}
private void GenerateCompleteSeats()
{
int totalRow = 3;
int totalCol = 10;
for (int i = 0; i < totalRow; i++)
{
for (int y = 0; y < totalCol; y++)
{
seats.Add(new Seat(i+1, y+1));
}
}
}
private void PrintSeats(List<Seat> _seats)
{
foreach (var item in _seats)
{
Console.WriteLine($"Row: {item.Row}. Col: {item.Col}. Status: {item.Status}");
}
}
internal void PrintCompleteSeats()
{
Console.WriteLine("Total seats: " + seats.Count);
PrintSeats(seats);
}
internal void SeedCinemaSeats()
{
const int totalTakenSeatsNeeded = 20;
int totalGeneratedEmptySeats = 0;
// totalSeats will keep increasing until equal to total empty seats needed
while (totalGeneratedEmptySeats != totalTakenSeatsNeeded)
{
// Generate a random number
var randomNo = new Random();
// Get a random seat
var randomSeat = seats[randomNo.Next(seats.Count)];
// Remove random seat
//seats.Remove(randomSeat);
// Update random seat status
if(randomSeat.Status == Seat.EnumStatus.Empty)
{
randomSeat.Status = Seat.EnumStatus.Taken;
totalGeneratedEmptySeats++;
}
}
}
internal void PrintEmptySeats()
{
var empty = seats.Where(s => s.Status == Seat.EnumStatus.Empty);
Console.WriteLine("Total Seats: " + empty.Count());
PrintSeats(empty.ToList());
}
internal void PrintTakenSeats()
{
var taken = seats.Where(s => s.Status == Seat.EnumStatus.Taken);
Console.WriteLine("Total Seats: " + taken.Count());
PrintSeats(taken.ToList());
}
}
public class Seat
{
public int Row { get; }
public int Col { get; }
public EnumStatus Status { get; set; }
/// <summary>
/// A valid seat object will always need row and col.
/// </summary>
/// <param name="row"></param>
/// <param name="col"></param>
public Seat(int row, int col)
{
this.Row = row;
this.Col = col;
this.Status = EnumStatus.Empty;
}
public enum EnumStatus
{
Empty, Taken
}
}
static void Main(string[] args)
{
// Initialize Cinema
var cinema = new Cinema();
while (true)
{
Console.Clear();
Console.WriteLine("1. Print all Seats in Cinema");
Console.WriteLine("2. Seed some sample booked seats");
Console.WriteLine("3. Print empty/available seats");
Console.WriteLine("4. Print taken seats");
var opt = Console.ReadLine();
switch (opt)
{
case "1":
cinema.PrintCompleteSeats();
break;
case "2":
cinema.SeedCinemaSeats();
break;
case "3":
cinema.PrintEmptySeats();
break;
case "4":
cinema.PrintTakenSeats();
break;
default:
break;
}
Console.ReadKey();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T12:55:54.253",
"Id": "466558",
"Score": "0",
"body": "It would make it much easier for some users if you had the necessary using statements in the code. Did you write this as 1 file or 3 files?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T13:32:50.643",
"Id": "466566",
"Score": "1",
"body": "WRT `var randomNo = new Random();`: https://stackoverflow.com/a/768001/648075"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T14:03:19.933",
"Id": "466575",
"Score": "0",
"body": "@pacmaninbw 3 files. So set as static for random. Thanks BCdotWEB"
}
] |
[
{
"body": "<p>The menu should include an option to exit the program.</p>\n\n<p>It might be nice if the menu refreshed after every option was completed.</p>\n\n<p>The seats open or taken would be clearer if the theater was printed as a matrix, maybe use the letters <code>E</code> and <code>T</code> to show empty and taken seats.</p>\n\n<p>For future reviews it would probably be better to show each file rather than merging them all together.</p>\n\n<p>It's not clear why the this reference was used in the seat constructor. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T15:45:37.493",
"Id": "237913",
"ParentId": "237885",
"Score": "2"
}
},
{
"body": "<h2>Picking random seats</h2>\n\n<blockquote>\n <p>I think my algorithm for generate 20 random taken seats doesn't look that efficient.</p>\n</blockquote>\n\n<pre><code>while (totalGeneratedEmptySeats != totalTakenSeatsNeeded)\n{\n // Generate a random number\n var randomNo = new Random();\n\n // Get a random seat\n var randomSeat = seats[randomNo.Next(seats.Count)];\n\n // Remove random seat\n //seats.Remove(randomSeat);\n\n // Update random seat status\n if(randomSeat.Status == Seat.EnumStatus.Empty)\n {\n randomSeat.Status = Seat.EnumStatus.Taken;\n totalGeneratedEmptySeats++;\n }\n}\n</code></pre>\n\n<p>You shouldn't recreate a new <code>Random</code> (= random number <strong>generator</strong>, not a number by itself) for every new number, you should be using the same <code>Random</code> and requesting numbers multiple times. To that effect, put your initialization outside of the loop:</p>\n\n<pre><code>var random = new Random();\n\nwhile(...)\n{\n // ...\n}\n</code></pre>\n\n<p>The randomization process can also be optimized, as you're currently running into possible retries when you randomly select a seat you had already selected before. That's inefficient, and it can be avoided by changing your \"shuffle and draw\" approach.</p>\n\n<p>Using the example of a deck of cards, if you want to draw 10 random cards, you don't need to draw these cards separately, shuffling the deck again each time (and putting the drawn card back in the deck on top of that). You can simply shuffle the deck and take the top 10 cards. Since the deck is in random order, the top 10 cards are as random as any other group of 10 cards would be.</p>\n\n<p>This also avoids having to retry draws, as the top 10 cards of the deck are guaranteed to not overlap with one another.</p>\n\n<p>Using LINQ, this can be done quite tersely:</p>\n\n<pre><code>var shuffledSeats = seats.OrderBy(seat => random.Next());\n</code></pre>\n\n<p>Usually, you pick an ordering method that related to the seat (e.g. <code>OrderBy(seat => seat.Price)</code>), but in this case, we tell LINQ to order it by a random number, which effectively means that LINQ will randomly order our list.</p>\n\n<p>We then take the first 20 seats:</p>\n\n<pre><code>var twentyRandomSeats = shuffledSeats.Take(20);\n</code></pre>\n\n<p>and then we register these seats as taken:</p>\n\n<pre><code>foreach(var seat in twentyRandomSeats)\n{\n seat.Status = Seat.EnumStatus.Taken;\n}\n</code></pre>\n\n<p>These operations can be chained together:</p>\n\n<pre><code>foreach(var seat in seats.OrderBy(seat => random.Next()).Take(20))\n{\n seat.Status = Seat.EnumStatus.Taken;\n}\n</code></pre>\n\n<p>Whether you chain them or not is up to you. It's a readability argument. It's definitely not wrong to keep the steps separate if you find it clearer.</p>\n\n<hr>\n\n<h2>Separating taken seats from empty seats</h2>\n\n<blockquote>\n <p>I will remove the random seat and push that random seat to taken list. But the problem with this is to print all the complete 30 seats, I have merge taken and empty list.</p>\n</blockquote>\n\n<p>This can indeed be an issue when you want to handle the complete list too. And you don't want to store three separate lists (all, taken, empty) as they may become desynchronized and it's a generally cumbersome juggling act.</p>\n\n<p>Since each seat carries its own status which indicates whether it's taken or not, we can simple keep all seats together in a single list, and then <strong>filter</strong> that list when we need to. </p>\n\n<p>LINQ allows for a terse and clean to read syntax:</p>\n\n<pre><code>var emptySeats = seats.Where(seat => seat.Status == Seat.EnumStatus.Empty);\nvar takenSeats = seats.Where(seat => seat.Status == Seat.EnumStatus.Taken);\n</code></pre>\n\n<p>Since your <code>seats</code> list is a class field, you can define the other lists as computed class fields:</p>\n\n<pre><code>class Cinema\n{\n private readonly List<Seat> seats = new List<Seat>();\n\n private List<Seat> takenSeats => seats.Where(seat => seat.Status == Seat.EnumStatus.Taken);\n private List<Seat> emptySeats => seats.Where(seat => seat.Status == Seat.EnumStatus.Empty);\n}\n</code></pre>\n\n<p>You can add null-checking here if you need it, but I would generally advise to avoid having nulls instead of continually having to check for it. To that effect, I've given <code>seats</code> a default value. As long as you don't explicitly make it <code>null</code>, you don't need to continually null check.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T15:12:24.970",
"Id": "466719",
"Score": "0",
"body": "`Seat` could be a struct rather than a class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T15:38:33.453",
"Id": "466724",
"Score": "1",
"body": "@RickDavin: Feel free to add an answer of your own. Code reviews aren't mutually exclusive, several answers can each add valuable information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T22:57:33.953",
"Id": "466770",
"Score": "1",
"body": "@Flater. That short random algorithm using linq you gave is awesome. I did a simple blackjack app before for fun. But couldn't figure out that, it can be used in here also. Thanks a lot for great code review."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T14:17:12.037",
"Id": "237969",
"ParentId": "237885",
"Score": "4"
}
},
{
"body": "<p>It seems you are a beginner / hobbyist / learner. This was not intended as an offense since we were all beginners once.</p>\n\n<p>The biggest advice I could pass on is that you should separate the UI from the logic. Anything with displaying output or requesting input is part of that UI. The <code>Cinema</code> class should not be issuing <code>Console.WriteLine</code>. Rather it could instead return a string and leave it up to the UI on what to do with that string.</p>\n\n<p>@Flater had good points all around, particularly about having the Random instance be defined at the class level. As for randomizing seats, I would treat all the seats like a deck of card. I would randomly shuffle a deck once, and then deal each card as requested. I would not randomly shuffle, deal one card, and then randomly shuffle again for the next card. I suggest you look into the <strong>Fisher Yates Shuffle</strong> (several examples are here on CR).</p>\n\n<p>The <code>Seat</code> class could become an immutable struct instead. You may consider overriding <code>ToString</code> to print an \"E\" or \"T\" for empty or taken, or perhaps \"O\" and \"X\" for open and taken.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T22:48:58.120",
"Id": "466767",
"Score": "0",
"body": "Thanks for the code review and pointers. Yeah I haven't refactor my code in that posted version for the separation of concern because I just focus on that random algorithm for quick review. Anyway, now I have created 6 projects in that one solution to split them up as separation of concern purpose and make sure that all my `Console.Writeline` in my Console project. you mean `Seat` should be a `struct` instead of `class`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T01:19:32.970",
"Id": "466779",
"Score": "0",
"body": "After I change the `Seat` from `class` to `struct`, it doesn't compile. Looks like after changed to `struct`, I can't modify its property."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T15:42:33.263",
"Id": "466847",
"Score": "0",
"body": "Then keep `Seat` as a class. You should still override `ToString`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T20:41:52.660",
"Id": "466896",
"Score": "0",
"body": "May I know the reason to override tostring? Because now I have modify it using extension method to format it to single letter. But data will save as enum"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T18:14:42.133",
"Id": "237990",
"ParentId": "237885",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "237969",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T11:00:01.803",
"Id": "237885",
"Score": "5",
"Tags": [
"c#"
],
"Title": "Algorithm movie ticket booking"
}
|
237885
|
<p>I just implemented a version of A* search in JavaScript for educational purposes. I'd really love it if you could take a look and tell me how to improve my code.</p>
<p>The <code>grid</code> passed in is just a multidimensional array (2-D array) where each slot in the inner array is an object with property <code>weight</code>.</p>
<p>The point of this function is to build an "algorithm visualizer", where I have all the nodes that were visited by A* (<code>visited</code>) and all the nodes that A* eventually selected to be part of the shortest path (<code>path</code>). I later take this and display this to the user with my UI logic.</p>
<p>In terms of the heuristic, I use Euclidean Distance.</p>
<pre><code>import PriorityQueue from "./data structures/priorityqueue";
export default function astar(grid, startNode, endNode) {
function isValid(r, c) {
if (r < 0 || c < 0) {
return false;
}
if (r < grid.length && c < grid[r].length) {
return true;
}
return false;
}
function calculateHeuristic(r, c) {
let row = (endNode[0] - r) ** 2;
let col = (endNode[1] - c) ** 2;
return (row + col) ** (1 / 2);
}
let dist = [], // represents distances from start to node
visited = [], // list of all the nodes A* visits
ordering = []; // final ordering
for (let r = 0; r < grid.length; r++) {
let row = [],
orderingRow = [];
for (let c = 0; c < grid[r].length; c++) {
row.push(Number.MAX_VALUE);
orderingRow.push(null);
}
dist.push(row);
ordering.push(orderingRow);
}
let d = 0;
let pqueue = new PriorityQueue();
let priority = calculateHeuristic(startNode[0], startNode[0]) + d;
pqueue.enqueue([startNode[0], startNode[1], startNode, d], priority);
let cur,
neighbors = [
[1, 0],
[-1, 0],
[0, 1],
[0, -1]
];
while (!pqueue.isEmpty()) {
cur = pqueue.dequeue();
let r = cur.element[0],
c = cur.element[1],
origin = cur.element[2],
d = cur.element[3];
visited.push([r, c]);
if (dist[r][c] <= d) {
continue;
}
ordering[r][c] = origin;
dist[r][c] = d;
if (r === endNode[0] && c === endNode[1]) {
break;
}
for (let n of neighbors) {
let rr = r + n[0];
let cc = c + n[1];
if (!isValid(rr, cc)) {
continue;
}
let dd = d + grid[rr][cc].weight;
if (dd < dist[rr][cc]) {
priority = dd + calculateHeuristic(rr, cc);
pqueue.enqueue([rr, cc, [r, c], dd], priority);
}
}
}
let path = [endNode];
let r = endNode[0],
c = endNode[1];
while (r !== startNode[0] || c !== startNode[1]) {
path.push(ordering[r][c]);
[r, c] = ordering[r][c];
}
path.reverse();
return { visited, path };
}
</code></pre>
<p>Thank you for reading and I look forward to your critiques. </p>
|
[] |
[
{
"body": "<p>Having 3 parallel 2D arrays in javascript for simple data is a bit overkill. Put those in a single 2D array or you can fold it into the grid's nodes.</p>\n\n<p>If you want step by step visualization then you'll need to break up your function into sections: <code>init</code>, <code>step</code> and <code>finalize</code>.</p>\n\n<p><code>init</code> is everything before the main while loop.</p>\n\n<p><code>step</code> is the while loop body</p>\n\n<p><code>finalize</code> is only triggered when the loop otherwise breaks or exits.</p>\n\n<p>Whether you group all the data it needs (like pqueue, dist, etc.) into an object that gets passed in or become globals doesn't really matter when it's for educational reasons. But if they are in a single object then it's easier for the visualizer to get that as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T15:10:50.757",
"Id": "466589",
"Score": "0",
"body": "Thanks for the comments! I agree that a single 2D array makes a lot more sense. I'll be making those changes.\n\nSorry, for the visualizer, that's meant to be in React (so a completely different class). I just wrote this as a class in a separate folder to separate the UI logic from the not-UI logic. I implement a function called \"paintNodes\" in my React Component that takes in the list and then adds a Timeout and prints out the nodes. \n\nThanks for your help!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T15:22:01.577",
"Id": "466594",
"Score": "0",
"body": "@SomyaAgrawal I believe that showing the algorithm split up instead as a monolith is wothwhile though. Especially as it teaches that you don't need to make the algorithm spit out the result immediately but can instead let it work in timeslices without needing threads"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T15:32:02.283",
"Id": "466596",
"Score": "0",
"body": "You're right. Thanks for the suggestion.\n\nI will work on implementing that in the future."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T12:36:39.930",
"Id": "237894",
"ParentId": "237892",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "237894",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T12:10:33.407",
"Id": "237892",
"Score": "1",
"Tags": [
"javascript",
"algorithm"
],
"Title": "A* Search in JavaScript"
}
|
237892
|
<p>I am new to Haskell and currently trying to port my solutions for the 2019 installment of the coding challenge AdventOfCode to Haskell. So, I would very much appreciate any suggestions how to make the code more readable and more idiomatic. In particular, I am interested in whether my use of the <code>State</code> monad is sensible here.</p>
<p>This post is about the combined result from <a href="https://adventofcode.com/2019/day/2" rel="nofollow noreferrer">day 2</a>, <a href="https://adventofcode.com/2019/day/5" rel="nofollow noreferrer">day 5</a>, and <a href="https://adventofcode.com/2019/day/9" rel="nofollow noreferrer">day 9</a>, an interpreter for a simple assembly language called IntCode. If you have not solved these problems and still intend to do so, stop reading immediately.</p>
<p>I have kept the entire solution for each part of each day in a single module with a single exported function that prints the solution. Without this selfimposed restriction, I would have split this code into different modules. For day 9 part 1 it starts as follows.</p>
<pre class="lang-hs prettyprint-override"><code>module AdventOfCode20191209_1
(
systemCheck
) where
import System.IO
import Data.List.Split
import Data.List
import Data.Maybe
import qualified Data.HashMap.Strict as Map
import Control.Monad.State
import Data.Digits
systemCheck :: IO ()
systemCheck = do
inputText <- readFile "Advent20191209_1_input.txt"
let code = toIntCode inputText
let result = executeCode code [1]
print result
</code></pre>
<p>Now, let me explain the setting, i.e. the IntCode language, and how I have implemented the different features.</p>
<p>As the name might suggest, the input is a stream/list of integer values.
In the problems, it is provided as a comma separated string, which I read as follows.</p>
<pre class="lang-hs prettyprint-override"><code>type IntCode = [Int]
toIntCode :: String -> IntCode
toIntCode = map read . splitOn ","
</code></pre>
<h2>Process State</h2>
<p>This code also functions as the bases for the process memory, which is essentially infinite and initialized by the code itself inside its index range and by zero outside. </p>
<pre class="lang-hs prettyprint-override"><code>newtype Memory = Memory (Map.HashMap Int Int) deriving (Eq, Show)
readMemory :: Int -> State Memory Int
readMemory pointer = gets $ \(Memory m) -> Map.lookupDefault 0 pointer m
writeToMemory :: Int -> Int -> State Memory ()
writeToMemory pointer 0 = modify $ \(Memory m) -> Memory $ Map.delete pointer m
writeToMemory pointer value = modify $ \(Memory m) -> Memory $ Map.alter (\_ -> Just value) pointer m
fromIntCode :: IntCode -> Memory
fromIntCode = Memory . Map.fromList . indexedIntCode
indexedIntCode :: IntCode -> [(Int, Int)]
indexedIntCode = zip [0..]
</code></pre>
<p>In addition to memory, there is an input stream used by the <code>Get</code> operation,</p>
<pre class="lang-hs prettyprint-override"><code>newtype InputStream = InputStream [Int] deriving (Eq, Show)
addInput :: Int -> State InputStream ()
addInput input = modify $ \(InputStream xs) -> InputStream $ xs ++ [input]
addInputs :: [Int] -> State InputStream ()
addInputs inputs = modify $ \(InputStream xs) -> InputStream $ xs ++ inputs
popInput :: State InputStream (Maybe Int)
popInput = state $ \input@(InputStream xs) -> case xs of
[] -> (Nothing, input)
y:ys -> (Just y, InputStream ys)
</code></pre>
<p>There are two more stateful objects involved in the computation, an instruction pointer and a relative base pointer, both starting at zero. The instruction pointer is what the name suggests and the relative base pointer is used for one of the methods to read arguments described later. </p>
<p>I have combined these into a <code>ProcessState</code> type.</p>
<pre class="lang-hs prettyprint-override"><code>data ExecutionStatus = Running | Blocked | Terminated | Error deriving (Eq, Show, Enum)
data ProcessState = ProcessState {
memory :: Memory,
inputs :: InputStream,
instructionPointer :: Int,
relativeBasePointer :: Int,
status :: ExecutionStatus
} deriving (Eq, Show)
processStatus :: State ProcessState ExecutionStatus
processStatus = gets $ status
hasShutDown :: State ProcessState Bool
hasShutDown = do
currentStatus <- processStatus
case currentStatus of
Terminated -> return True
Error -> return True
_ -> return False
isRunning :: State ProcessState Bool
isRunning = do
currentStatus <- processStatus
case currentStatus of
Running -> return True
_ -> return False
setProcessStatus :: ExecutionStatus -> State ProcessState ()
setProcessStatus processStatus = do
stopped <- hasShutDown
if stopped
then return ()
else modify $ \s -> s{status = processStatus}
terminateProcess :: State ProcessState ()
terminateProcess = setProcessStatus Terminated
abortProcess :: State ProcessState ()
abortProcess = setProcessStatus Error
setInstructionPointer :: Int -> State ProcessState ()
setInstructionPointer pointer = modify $ \s -> s {instructionPointer = pointer}
processInstructionPointer :: State ProcessState Int
processInstructionPointer = gets $ instructionPointer
incrementInstructionPointer :: Int -> State ProcessState ()
incrementInstructionPointer offset = do
instructionPointer <- processInstructionPointer
setInstructionPointer (instructionPointer + offset)
setRelativeBasePointer :: Int -> State ProcessState ()
setRelativeBasePointer pointer = modify $ \s -> s {relativeBasePointer = pointer}
processRelativeBasePointer :: State ProcessState Int
processRelativeBasePointer = gets $ relativeBasePointer
incrementRelativeBasePointer :: Int -> State ProcessState ()
incrementRelativeBasePointer offset = do
relativeBasePointer <- processRelativeBasePointer
setRelativeBasePointer (relativeBasePointer + offset)
readProcessMemory :: Int -> State ProcessState Int
readProcessMemory pointer = gets $ \ProcessState{memory = m} -> evalState (readMemory pointer) m
writeToProcessMemory :: Int -> Int -> State ProcessState ()
writeToProcessMemory pointer value = modify $ \s@ProcessState{memory = m} -> s {memory = execState (writeToMemory pointer value) m}
addProcessInput :: Int -> State ProcessState ()
addProcessInput additionalInput = modify $ \s@ProcessState{inputs = inputStream} -> s {inputs = execState (addInput additionalInput) inputStream}
addProcessInputs :: [Int] -> State ProcessState ()
addProcessInputs additionalInputs = modify $ \s@ProcessState{inputs = inputStream} -> s {inputs = execState (addInputs additionalInputs) inputStream}
popProcessInput :: State ProcessState (Maybe Int)
popProcessInput = state $ \s@ProcessState{inputs = inputStream} ->
let (input, newInputs) = runState popInput inputStream
in (input, s {inputs = newInputs})
initializeProcess :: IntCode -> [Int] -> ProcessState
initializeProcess code initialInputs = ProcessState {
memory = fromIntCode code,
inputs = InputStream initialInputs,
instructionPointer = 0,
relativeBasePointer = 0,
status = Running}
</code></pre>
<p>Most of the associated methods are basically plumbing between the stateful operations on the process state and the underlying stateful operations.
I have added an execution status that is used to indicate that the process has terminated, via <code>hasShutDown</code>. Moreover, it will be used to halt execution in case the process blocks due to missing input. This is necessary for applications as in part 2 of <a href="https://adventofcode.com/2019/day/7" rel="nofollow noreferrer">day 7</a> or on <a href="https://adventofcode.com/2019/day/23" rel="nofollow noreferrer">day 23</a>.</p>
<h2>Instructions</h2>
<p>Each step of a computation starts by reading the value in memory the instruction pointer points to. This encodes two kinds of information: the opcode for the operation and the modes used to read the arguments from memory.</p>
<pre class="lang-hs prettyprint-override"><code>data IntCodeInstruction = IntCodeInstruction {
opcode :: OpCode,
argumentSpecifications :: [ArgumentSpecification]
} deriving (Eq, Show)
data ArgumentSpecification = ArgumentSpecification {
argumentMode :: ArgumentMode,
operationMode :: OperationMode
} deriving (Eq, Show)
</code></pre>
<h3>Reading Arguments</h3>
<p>There are three basic modes how to read data.</p>
<pre class="lang-hs prettyprint-override"><code>toArgumentMode :: Int -> Maybe ArgumentMode
toArgumentMode 0 = Just Pointer
toArgumentMode 1 = Just Value
toArgumentMode 2 = Just Relative
toArgumentMode _ = Nothing
</code></pre>
<p>In general, the information relating to the nth argument is at an offset of n from the instruction pointer. In value mode, this is the argument, in pointer mode, it is the value of the pointer to the data and in relative mode, it is the offset from the relative base pointer where to look for the data. Unfortunately, this is not all. If the argument specifies a location to write to in memory, it the argument is the pointer instead of the data at the location the pointer points to. To encode this, I introduced an operation mode, which depends on the opcode.</p>
<pre class="lang-hs prettyprint-override"><code>data OperationMode = Read | Write deriving (Eq, Show)
</code></pre>
<p>Putting this together, I read arguments as follows.</p>
<pre class="lang-hs prettyprint-override"><code>instructionArguments :: IntCodeInstruction -> State ProcessState Arguments
instructionArguments instruction = do
basePointer <- processInstructionPointer
let enumeratedArgumentSpecifications = zip [1..] (argumentSpecifications instruction)
in mapM (instructionArgument basePointer) enumeratedArgumentSpecifications
instructionArgument :: Int -> (Int, ArgumentSpecification) -> State ProcessState Int
instructionArgument basePointer (offset, argumentSpec) =
let evaluationPointer = basePointer + offset
in case argumentMode argumentSpec of
Value -> readProcessMemory evaluationPointer
Pointer -> case operationMode argumentSpec of
Write -> readProcessMemory evaluationPointer
Read -> do
transitiveEvaluationPointer <- readProcessMemory evaluationPointer
readProcessMemory transitiveEvaluationPointer
Relative -> do
relativeBase <- processRelativeBasePointer
baseIncrement <- readProcessMemory evaluationPointer
let targetPointer = relativeBase + baseIncrement
in case operationMode argumentSpec of
Write -> return targetPointer
Read -> readProcessMemory targetPointer
</code></pre>
<h3>Decoding Instructions</h3>
<p>The instruction itself is encoded as follows. The last two digits of the value in memory the instruction pointer points to represent the opcode. the higher digits represent the argument modes to be used, in inverted order when read, i.e. the lowest digit belongs to the first argument. Missing argument modes default to pointer mode.</p>
<pre class="lang-hs prettyprint-override"><code>intCodeInstruction :: State ProcessState (Maybe IntCodeInstruction)
intCodeInstruction = do
instructionPointer <- processInstructionPointer
instructionValue <- readProcessMemory instructionPointer
return (do -- Maybe
opcode <- toOpCode (instructionValue `mod` 100)
argumentSpecs <- toArgumentSpecifications opcode (instructionValue `div` 100)
return (IntCodeInstruction opcode argumentSpecs))
toArgumentSpecifications :: OpCode -> Int -> Maybe [ArgumentSpecification]
toArgumentSpecifications opcode argumentSpecifier =
do -- Maybe
maybeSpecifiedArgumentModes <- argumentModesFromSpecifier argumentSpecifier
specifiedArgumentModes <- sequence maybeSpecifiedArgumentModes
let
operationModes = associatedOperationModes opcode
numberOfMissingElements = length operationModes - length specifiedArgumentModes
in if numberOfMissingElements < 0
then Nothing
else let paddedArgumentsModes = specifiedArgumentModes ++ replicate numberOfMissingElements Pointer
in return (zipWith ArgumentSpecification paddedArgumentsModes operationModes)
argumentModesFromSpecifier :: Int -> Maybe [Maybe ArgumentMode]
argumentModesFromSpecifier 0 = Just []
argumentModesFromSpecifier x
| x < 0 = Nothing
| otherwise = Just (map toArgumentMode (reverse (digits 10 x)))
</code></pre>
<h3>OpCodes</h3>
<p>Now, let me come to the opcodes; there are 10 of them.</p>
<pre class="lang-hs prettyprint-override"><code>data OpCode = Add | Multiply | Get | Put | JumpIfTrue | JumpIfFalse | LessThan | Equals | IncrementRelativeBase | Stop deriving (Eq, Show, Enum)
toOpCode :: Int -> Maybe OpCode
toOpCode 1 = Just Add
toOpCode 2 = Just Multiply
toOpCode 3 = Just Get
toOpCode 4 = Just Put
toOpCode 5 = Just JumpIfTrue
toOpCode 6 = Just JumpIfFalse
toOpCode 7 = Just LessThan
toOpCode 8 = Just Equals
toOpCode 9 = Just IncrementRelativeBase
toOpCode 99 = Just Stop
toOpCode _ = Nothing
</code></pre>
<p>Each opcode is accociated with one operation and hence also with one set of requires arguments. </p>
<pre class="lang-hs prettyprint-override"><code>--operation modes in order of arguments
associatedOperationModes :: OpCode -> [OperationMode]
associatedOperationModes Add = [Read, Read, Write]
associatedOperationModes Multiply = [Read, Read, Write]
associatedOperationModes Get = [Write]
associatedOperationModes Put = [Read]
associatedOperationModes JumpIfTrue = [Read, Read]
associatedOperationModes JumpIfFalse = [Read, Read]
associatedOperationModes LessThan = [Read, Read, Write]
associatedOperationModes Equals = [Read, Read, Write]
associatedOperationModes IncrementRelativeBase = [Read]
associatedOperationModes Stop = []
type Arguments = [Int]
associatedOperation :: OpCode -> (Arguments -> State ProcessState (Maybe Int))
associatedOperation Add = handleTerminationAndRun . add
associatedOperation Multiply = handleTerminationAndRun . multiply
associatedOperation Get = handleTerminationAndRun . getOperation
associatedOperation Put = handleTerminationAndRun . putOperation
associatedOperation JumpIfTrue = handleTerminationAndRun . jumpIfTrue
associatedOperation JumpIfFalse = handleTerminationAndRun . jumpIfFalse
associatedOperation LessThan = handleTerminationAndRun . lessThan
associatedOperation Equals = handleTerminationAndRun . equals
associatedOperation IncrementRelativeBase = handleTerminationAndRun . incrementRelativeBase
associatedOperation Stop = handleTerminationAndRun . stop
</code></pre>
<h2>Code Execution</h2>
<p>Code execution generally works by reading input instructions, executing the associated operations and then advancing the instruction pointer to after the last argument, unless the operation alters the instruction pointer itself.</p>
<h3>Operations</h3>
<p>All operations share the same signature, <code>Arguments -> State ProcessState (Maybe Int)</code>, in order to easily associate them with opcodes. The general operations assume that the process has not terminated. To guard against that, there is a special method used in the accociation with the opcodes.</p>
<pre class="lang-hs prettyprint-override"><code>handleTerminationAndRun :: State ProcessState (Maybe Int) -> State ProcessState (Maybe Int)
handleTerminationAndRun state = do
stopped <- hasShutDown
if stopped
then return Nothing
else state
</code></pre>
<p>We always return <code>Nothing</code> and do not alter the process state if the process has already shut down.</p>
<p>The individual operations work as follows.</p>
<p>Arithmetic operations apply the associated operator to their first two arguments and then write to the third. </p>
<pre class="lang-hs prettyprint-override"><code>add :: Arguments -> State ProcessState (Maybe Int)
add = applyBinaryOperationAndWrite (+)
multiply :: Arguments -> State ProcessState (Maybe Int)
multiply = applyBinaryOperationAndWrite (*)
applyBinaryOperationAndWrite :: (Int -> Int -> Int) -> (Arguments -> State ProcessState (Maybe Int))
applyBinaryOperationAndWrite binaryOp arguments = do
let
targetPointer = arguments!!2
value = binaryOp (head arguments) (arguments!!1)
in writeToProcessMemory targetPointer value
incrementInstructionPointer 4
setProcessStatus Running
return Nothing
</code></pre>
<p>Binary comparisons are similar. However, they encode the return value by 1 for True and 0 for False.</p>
<pre class="lang-hs prettyprint-override"><code>lessThan :: Arguments -> State ProcessState (Maybe Int)
lessThan = applyBinaryComparisonAndWrite (<)
equals :: Arguments -> State ProcessState (Maybe Int)
equals = applyBinaryComparisonAndWrite (==)
applyBinaryComparisonAndWrite :: (Int -> Int -> Bool) -> (Arguments -> State ProcessState (Maybe Int))
applyBinaryComparisonAndWrite binaryComp arguments = do
let
targetPointer = arguments!!2
value = if (head arguments) `binaryComp` (arguments!!1)
then 1
else 0
in writeToProcessMemory targetPointer value
incrementInstructionPointer 4
setProcessStatus Running
return Nothing
</code></pre>
<p>The two jump instructions set the instruction pointer to their second argument if the first arguments represents the corresponding truthyness. (again with 0 == False, /= 0 == True)</p>
<pre class="lang-hs prettyprint-override"><code>jumpIfTrue :: Arguments -> State ProcessState (Maybe Int)
jumpIfTrue = jumpIf (/= 0)
jumpIfFalse :: Arguments -> State ProcessState (Maybe Int)
jumpIfFalse = jumpIf (== 0)
jumpIf :: (Int -> Bool) -> (Arguments -> State ProcessState (Maybe Int))
jumpIf test arguments = do
if test (head arguments)
then setInstructionPointer (arguments!!1)
else incrementInstructionPointer 3
setProcessStatus Running
return Nothing
</code></pre>
<p>In addition to these operations to modify the instruction pointer, there is an operation that increments the relative base pointer by its first argument.</p>
<pre class="lang-hs prettyprint-override"><code>incrementRelativeBase :: Arguments -> State ProcessState (Maybe Int)
incrementRelativeBase arguments = do
incrementRelativeBasePointer $ head arguments
incrementInstructionPointer 2
setProcessStatus Running
return Nothing
</code></pre>
<p>To read from the input stream, there is the <code>Get</code> operation, which i called <code>getOperation</code> because of the name clash with <code>get</code> from <code>State</code>. It reads the first value from the input stream and writes it to its only argument. If the nput stream is empty, it blocks.</p>
<pre class="lang-hs prettyprint-override"><code>getOperation :: Arguments -> State ProcessState (Maybe Int)
getOperation arguments = do
maybeInput <- popProcessInput
case maybeInput of
Nothing -> do
setProcessStatus Blocked
return Nothing
Just input -> do
let
targetPointer = head arguments
in writeToProcessMemory targetPointer input
incrementInstructionPointer 2
setProcessStatus Running
return Nothing
</code></pre>
<p>The only operation providing output from the process is the <code>Put</code> operation, which I again named <code>putOperation</code> because of the clash with <code>put</code> from <code>State</code>. It simply outputs its first argument.</p>
<pre class="lang-hs prettyprint-override"><code>putOperation arguments = do
incrementInstructionPointer 2
setProcessStatus Running
let newOutputValue = head arguments
in return $ Just newOutputValue
</code></pre>
<p>Finally, there is the <code>stop</code> operation to terminte the process.</p>
<pre class="lang-hs prettyprint-override"><code>stop :: Arguments -> State ProcessState (Maybe Int)
stop _ = do
terminateProcess
return Nothing
</code></pre>
<h3>Code Execution Coordination</h3>
<p>Now that all the pieces of the computation are specified, it only needs to be wired up. I do this using the following stateful computations.</p>
<pre class="lang-hs prettyprint-override"><code>continueExecution :: State ProcessState [Int]
continueExecution = do
maybeResult <- executeNextInstruction
running <- isRunning
if running
then do
remainingResult <- continueExecution
case maybeResult of
Nothing -> return remainingResult
Just result -> return (result:remainingResult)
else return []
executeNextInstruction :: State ProcessState (Maybe Int)
executeNextInstruction = do
maybeInstruction <- intCodeInstruction
case maybeInstruction of
Nothing -> do
abortProcess
return Nothing
Just instruction -> executeInstruction instruction
executeInstruction :: IntCodeInstruction -> State ProcessState (Maybe Int)
executeInstruction instruction = do
arguments <- instructionArguments instruction
let operation = associatedOperation (opcode instruction)
in operation arguments
</code></pre>
<p>As a convenience function, I add a function that can be used to initialize a process state and run the computation, throwing away the final state.</p>
<pre class="lang-hs prettyprint-override"><code>executeCode :: IntCode -> [Int] -> [Int]
executeCode code initialInputs =
let initialState = initializeProcess code initialInputs
in evalState continueExecution initialState
</code></pre>
<p>For day 9, this function is sufficient. However, in problems like part 2 of day 7, <code>continueExecution</code> needs to be used direcly in order to wire up a stateful computation with resuming after blocking temporarily. </p>
|
[] |
[
{
"body": "<p><strong>Disclaimer:</strong> It has been a while since I've written Haskell in production. Also, while I usually like to review <em>all</em> the code, I have to admit that there is too much for me in this case. Instead, I'll try to focus on what I've seen from a short glance, raise concerns and show alternatives where applicable.</p>\n<p>But first, let's give praise.</p>\n<h1>Types are everywhere</h1>\n<p>This is great. You've put a type signature on every top-level value, and never one on an intermediate binding. This enables me to reason about your code even without a compiler that would usually help me with the review.</p>\n<p>You also introduced proper <code>newtype</code>s instead of <code>HashMap Int Int</code> or other non-semantic types. Overall, well-done.</p>\n<h1>Stateless vs stateful functions</h1>\n<p>Next, we come into a territory that's probably subject to personal opinion: should one write functions in terms of the <code>State</code> monad, or without?</p>\n<p>Let's have a look at our first <code>State</code>ful function:</p>\n<pre><code>writeToMemory :: Int -> Int -> State Memory ()\nwriteToMemory pointer 0 = modify $ \\(Memory m) -> Memory $ Map.delete pointer m\nwriteToMemory pointer value = modify $ \\(Memory m) -> Memory $ Map.alter (\\_ -> Just value) pointer m\n</code></pre>\n<p>While seemingly innocent, those functions provide some problems later on. For example in <code>writeToProcessMemory</code> we have to conjure a new <code>State</code>:</p>\n<pre><code>writeToProcessMemory :: Int -> Int -> State ProcessState ()\nwriteToProcessMemory pointer value = \n modify $ \\s@ProcessState{memory = m} -> \n s {memory = execState (writeToMemory pointer value) m} -- <- execState\n</code></pre>\n<p>Our stateful functions force us to create and <code>exec</code> a new <code>State</code> just to apply a function. That's cumbersome.</p>\n<p>What happened if we used another <code>writeToMemory</code>?</p>\n<pre><code>writeToMemory :: Int -> Int -> Memory -> Memory\nwriteToMemory pointer 0 (Memory m) = Memory $ Map.delete pointer m\nwriteToMemory pointer value (Memory m) = Memory $ Map.insert pointer value m\n\nwriteToProcessMemory :: Int -> Int -> State ProcessState ()\nwriteToProcessMemory pointer value = \n modify $ \\s@ProcessState{memory = m} -> \n s {memory = writeToMemory pointer value m}\n</code></pre>\n<p>No more <code>execState</code>, and we don't have to wrap around <code>State</code> to understand this function.</p>\n<h2>Some more examples for simpler building blocks</h2>\n<p>Another example where the <code>State</code>ful function is much more verbose than a non-<code>State</code>ful one is <code>hasShutDown</code>:</p>\n<pre><code>hasShutDown :: State ProcessState Bool\nhasShutDown = do\n currentStatus <- processStatus\n case currentStatus of\n Terminated -> return True -- alignment added by me\n Error -> return True\n _ -> return False\n</code></pre>\n<p>Those seven lines need to get carefully processed by a reviewer. However, we can simply split it into two functions:</p>\n<pre><code>hasShutDown' :: ProcessState -> Bool\nhasShutDown' Terminated = True\nhasShutDown' Error = True\nhasShutDown' _ = False\n\nhasShutDown :: State ProcessState Bool\nhasShutDown = hasShutDown' <$> processStatus\n</code></pre>\n<p>Even with the additional empty line and types, the overall length stayed at 7 lines. However, it is now a lot easier to examine <code>hasShutDown'</code> in my point of view.</p>\n<h2><em>My</em> general rule of thumb</h2>\n<p>If you have a function with type <code>a -> b</code> for some <code>a</code> and <code>b</code>, keep it out of the <code>State</code> monad as much as possible to make it easier for reuse. If you have a function with type <code>a -> (b, a)</code>, then it's a lot easier to handle with <code>State</code>.</p>\n<p>However, that is <em>my</em> general rule of thumb. Your style might vary.</p>\n<h1>Consider lenses</h1>\n<p>Let's get back to our new <code>writeToProcessMemory</code>:</p>\n<pre><code>writeToProcessMemory :: Int -> Int -> State ProcessState ()\nwriteToProcessMemory pointer value = \n modify $ \\s@ProcessState{memory = m} -> \n s {memory = writeToMemory pointer value m}\n</code></pre>\n<p>While I usually dislike lenses when overused, as they introduce a new dependency (use <code>microlens-platform</code> instead of <code>lens</code> if you don't need prisms, isomorphisms or similar), they can make this function even shorter:</p>\n<pre><code>writeToProcessMemory :: Int -> Int -> State ProcessState ()\nwriteToProcessMemory pointer value = memory %= writeToMemory pointer value\n</code></pre>\n<p>However, this needs <code>memory</code> to be a lens; it's a design decision whether to use them, but they can simplify code a lot.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-30T20:03:04.983",
"Id": "480626",
"Score": "0",
"body": "Thank you very much for your review, especially on the guideline regarding the use, or rather avoidance, of the `State` monad for building blocks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T10:35:39.623",
"Id": "480657",
"Score": "0",
"body": "@M.Doerner You're welcome. Sorry that it took so long, given that you've asked this question in February."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T11:05:56.680",
"Id": "244609",
"ParentId": "237893",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244609",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T12:19:44.590",
"Id": "237893",
"Score": "4",
"Tags": [
"haskell"
],
"Title": "Complete IntCode Computer - AdventOfCode day 2, 5 and 9 in Haskell"
}
|
237893
|
<p>I have two lists:</p>
<ol>
<li><strong>Users</strong> - [<code><UserObject1></code>, <code><UserObject2></code>, ...]</li>
<li><strong>Contributions</strong> - [<code><ContributionObject1></code>, <code><ContributionObject2></code>, ...]</li>
</ol>
<p>Every <code>ContributionObject</code> further can have single or multiple <code>UserObject</code> in it which are mentioned as <code>person_links</code> here and both the objects that are <code>ContributionObject</code> and <code>UserObject</code> has certain methods and attributes.</p>
<p><code>UserObject</code> has an attribute <code>affiliation</code>.</p>
<p>I have to check whether <code>UserObject</code> from <strong>Users</strong> and have the same <code>affiliation</code> to one of the <code>UserObject</code> from <code>ContributionObject</code> from <strong>Contributions</strong>.</p>
<p>If yes, I have to make a dictionary where <code>key</code> will be the <code>user</code> from <strong>Users</strong> and <code>value</code> will be an array of ceratin <code>ContributionObject</code> attributes that is <code>title</code> and <code>url</code>.</p>
<p>I am able to do it with the following logic.</p>
<p>I wanted to ask if this logic can be improved further?</p>
<p>If there is another efficient way to do this task, do mention that. Thanks for all the help. :)</p>
<pre class="lang-py prettyprint-override"><code>conflicts = dict()
for user in users:
if user.affiliation:
for contribution in contributions:
if not conflicts.get(user):
conflicts[user] = [
(
contribution.title,
contribution.url,
)
for person in contribution.person_links
if user.affiliation in person.affiliation
]
else:
conflicts[user] += [
(
contribution.title,
contribution.url,
)
for person in contribution.person_links
if user.affiliation in person.affiliation
]
</code></pre>
<p>I tried to find out better ways to update dict values on SO but they were mostly about updating the existing values(overriding) not about adding(appending) to an existing value.</p>
|
[] |
[
{
"body": "<p>Considering DRY principal, this</p>\n\n<pre><code>if not conflicts.get(user):\n conflicts[user] = [\n (\n contribution.title,\n contribution.url,\n )\n for person in contribution.person_links\n if user.affiliation in person.affiliation\n ]\nelse:\n conflicts[user] += [\n (\n contribution.title,\n contribution.url,\n )\n for person in contribution.person_links\n if user.affiliation in person.affiliation\n ]\n</code></pre>\n\n<p>can and should be replaced with a <a href=\"https://docs.python.org/3.8/library/collections.html#collections.defaultdict\" rel=\"nofollow noreferrer\"><code>defaultdict</code></a>:</p>\n\n<pre><code>from collections import defaultdict\n\nconflicts = defaultdict(list)\n...\nfor contribution in contributions:\n conflicts[user].extend((contribution.title, contribution.url)\n for person in contribution.person_links\n if user.affiliation in person.affiliation)\n</code></pre>\n\n<p>Or at least take advantage of <a href=\"https://docs.python.org/3.8/library/stdtypes.html#dict.setdefault\" rel=\"nofollow noreferrer\"><code>dict.setdefault</code></a> (while preferring a dict literal over a call to <code>dict</code> to save method look-up time):</p>\n\n<pre><code>conflicts = {}\n...\nfor contribution in contributions:\n conflicts.setdefault(user, []).extend((contribution.title, contribution.url)\n for person in contribution.person_links\n if user.affiliation in person.affiliation)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T13:28:22.477",
"Id": "237897",
"ParentId": "237896",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "237897",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T13:19:48.950",
"Id": "237896",
"Score": "2",
"Tags": [
"python",
"performance",
"algorithm",
"hash-map"
],
"Title": "Iterating lists and updating dictionary for corresponding match logic improvement"
}
|
237896
|
<p>This function takes a list, deletes every occurrence of the number 13 <em>and</em> deletes the number present after 13 in every instance and then prints the sum of the list. </p>
<p>How can I shorten it?</p>
<pre><code>def average(nums):
thirteen_idx = []
bad_idx = []
final_list = []
num_length = len(nums)-1
#list of indexes where 13 resides
for i in range(len(nums)):
if nums[i] == 13:
thirteen_idx.append(i)
#make list of indexes where 13 resides and the index after it (bad_idx)
for i in range(len(thirteen_idx)):
bad_idx.append(thirteen_idx[i])
bad_idx.append(thirteen_idx[i]+1)
#delete any index from bad_idx that is greater than the highest index in nums
if bad_idx[-1] > num_length:
bad_idx.pop(len(bad_idx)-1)
#we now have a list of all bad indexes (bad_idx)
#iterate thru nums and move any non bad index into a final_list
for i in range(len(nums)):
if i not in bad_idx:
final_list.append(nums[i])
print (sum(final_list))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T15:01:45.977",
"Id": "466586",
"Score": "1",
"body": "What is the result wanted for `[13, 13, 1]`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T13:29:39.470",
"Id": "466712",
"Score": "0",
"body": "@greybeard: the code, as posted, produces `0` for that."
}
] |
[
{
"body": "<p>if you just wanna filter 13 from the list of entries then you can do something like this</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>l = [1,2,13,14,13,12,14,12,13]\nfiltered_list = list(filter(lambda x: x!= 13, l))\nprint(sum(filtered_list)\n</code></pre>\n\n<p>Further your requirement is not clear, can you elaborate this part <em>\"and deletes the number after the 13x\"</em> a bit more?</p>\n\n<p>Ok Here is the code I suggest, have a look at this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get_zipped_list(given_list):\n # return list(zip(given_list, list(filter(lambda x: x != 13, given_list))))\n return list(zip(given_list, given_list[1:]))\n\n\ndef sum_excluding_13_and_following(given_list):\n length = len(given_list)\n if 0 < length <= 2:\n return sum(filter(lambda x: x != 13, given_list))\n elif all(x == 13 for x in given_list):\n return 0\n elif length >= 3:\n zipped_list = get_zipped_list(given_list)\n pairs_with_13_as_leading_elem = list(filter(lambda x: x[0] == 13, zipped_list))\n if given_list[-1] == 13:\n del given_list[-1]\n return sum(given_list) - sum([sum(x) for x in zip(*pairs_with_13_as_leading_elem)])\n else:\n return 0\n\n\nlist_1 = [1, 2, 13, 14, 13, 12, 14, 12, 13]\nlist_2 = [13, 1, 2, 13, 14, 13, 12, 14, 12, 13]\nlist_3 = [1, 2, 13, 14, 13, 12, 14, 12]\n\nsmall_ls_1 = [1, 13]\nsmall_ls_2 = [13, 10]\nsmall_ls_3 = [13, 13]\n\nall_13s = [13, 13, 13, 13]\n\nprint(sum_excluding_13_and_following(all_13s))\nprint(sum_excluding_13_and_following(small_ls_1))\nprint(sum_excluding_13_and_following(small_ls_2))\nprint(sum_excluding_13_and_following(small_ls_3))\nprint(sum_excluding_13_and_following(list_1))\nprint(sum_excluding_13_and_following(list_2))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T08:47:38.777",
"Id": "466569",
"Score": "0",
"body": "Trying to get the sum of a list of numbers. The only catch is not to count the number 13 or the next number in the list after 13. Example: if the list was (1, 13, 6, 8, 9, 13) you would not include the first 13, the number after it, 6, or the last 13 (there is no number after the last 13 to omit, this caused me many problems with index out of range errors)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T09:31:25.087",
"Id": "466570",
"Score": "1",
"body": "Instead of removing why don't you simply sum the numbers you don't want and then substract it from the total of the list ? In your example that would be `(1+13+6+8+9+13) - (13+6+13)`. *If you don't need the filtered list later* then there's no point in filtering it when you can just do maths"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T09:33:39.063",
"Id": "466571",
"Score": "0",
"body": "he can simply remove the 13's or the count of 13's but the only issue might be with the follow up number which also should be skipped"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T10:00:18.503",
"Id": "466572",
"Score": "0",
"body": "@jra updated my post with some code and test samples, please check if that works for you, I can add some comments in for better readability if you want"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T08:42:24.983",
"Id": "237900",
"ParentId": "237899",
"Score": "2"
}
},
{
"body": "<p>There are a lot of things you can do.</p>\n\n<ol>\n<li><p>Don't use an additional list <code>bad_idx</code> and do everything using the list <code>nums</code>.</p></li>\n<li><p>When you find the index of each of the 13s in the first for loop, delete the \n value there itself by using:</p>\n\n<pre><code>nums.remove(13)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>nums.pop(i)\n</code></pre></li>\n<li><p>After removing 13s, remove the value next to the 13s by using:</p>\n\n<pre><code>nums.pop(i+1)\n</code></pre></li>\n</ol>\n\n<p>By doing all this you aren't using 2 additional lists <code>bad_idx</code> and <code>final_list</code>, plus you are looping 2 fewer times.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T08:51:26.443",
"Id": "466573",
"Score": "0",
"body": "What if 13 is the last number in the list, then i+1 is index out of range."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T09:24:28.797",
"Id": "466574",
"Score": "1",
"body": "Easy! add a conditional statement before deleting the number next to 13 like this: if i!=(len(lis)-1): and then include the line to delete the number"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T13:45:26.510",
"Id": "466715",
"Score": "1",
"body": "Once you removed the 13s, the values directly after will be at position `i`, **not** position `i + 1`, as all the following items in the list will have shifted up a position! For the same reason, you don't want to iterate over a list and remove items at the same time, unless you plan to iterate *from the end*. Iteration will not account for the updated indices and will easily lead to bugs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T13:48:20.150",
"Id": "466716",
"Score": "0",
"body": "Given an input sequence of size N, it doesn't matter all that much if you are then using 1, 2 or 3 sequential loops over the input lists. If more loops make code easier to read, just use more loops. All you are doing is perhaps increase the fixed cost per iteration."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T08:44:54.660",
"Id": "237901",
"ParentId": "237899",
"Score": "2"
}
},
{
"body": "<p>An alternative, <strong>if you don't need the filtered list later on</strong>, is to iterate over and sum only the numbers you want:</p>\n\n<pre><code>def myfunc(l): \n it = iter(l) \n total = 0 \n try: \n for i in it: \n if i == 13: \n next(it) # skip the number following a '13'\n else: \n total += i \n return total \n except StopIteration: \n return total \n</code></pre>\n\n<p>The trick here is to transform the list into an iterator to make use of the <code>next()</code> function to easily skip the value following a <code>13</code>.</p>\n\n<p>Using the list <code>[13,99,3]</code>:</p>\n\n<p>When using the iterator in the for-loop what it does is, at the beginning of each loop it will take the next value in the iterator and place it into the variable <code>i</code>. When we use the <code>next(i)</code> we say to the iterator \"give me the next value please\" but we don't do anything with it, so at the next loop the iterator will give us again the next value.</p>\n\n<p>It may not be clear so here's an example with the list<code>[13,99,3]</code>:</p>\n\n<ul>\n<li><code>it</code> is an iterator which state is \"13 then 99 then 3\" at the beginning</li>\n<li>1st loop: we ask for the next value in <code>it</code>: we get <code>13</code>. The iterator state is now \"99 then 3\"\n\n<ul>\n<li>since <code>i == 13</code> we ask for the next value (<code>next(it)</code>), it gives us <code>99</code> (but we don't do anything with it as you can see) the state of the iterator is now \"3\"</li>\n</ul></li>\n<li>2nd loop: we ask for the next value in <code>it</code> (which state is \"3\" according to the previous point): so we get <code>3</code>. The state of the iterator is now empty.\n\n<ul>\n<li>since <code>3 !== 13</code> we add it to the <code>total</code>.</li>\n</ul></li>\n<li>The iterator is empty so we quit the loop and return the total</li>\n</ul>\n\n<p>But, as you can see, if 13 is the last element in the iterator when we'll ask for the <code>next(it)</code> it will raise an error, this is why we use the <code>try/except</code> block, because we now that the end of an iteration is indicated by an exception (<a href=\"https://docs.python.org/3/library/stdtypes.html#iterator-types\" rel=\"nofollow noreferrer\">doc here</a>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T14:32:12.293",
"Id": "466580",
"Score": "1",
"body": "Does this handle `1, 2, 13, 13, 3, 4` correctly? I.e. `1, 2, 3, 4` or `1, 2, 4`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T18:00:08.090",
"Id": "466616",
"Score": "0",
"body": "I believe this code is wrong; I'd expect `1, 2, 13, 13, 3, 4` to sum to *7*, but your code produces *10*. The code in the question produces 7 for that input."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T15:43:28.930",
"Id": "466729",
"Score": "0",
"body": "I believe you could fix that problem by adding a `while i == 13: i = next(it)` loop inside the `if` branch, but I can't say I'm fond of the iterator approach to this problem at the moment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T15:45:42.883",
"Id": "466730",
"Score": "0",
"body": "Other nitpicks: your function body is indented 5 spaces rather than 4, and you have a redundant `return total` both in the `try:` and in the `except StopIteration:` blocks. Just put a single `return total` at the end of the function (outside of the `try...except` statement) and use `pass` in the except handler."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T10:21:26.533",
"Id": "237902",
"ParentId": "237899",
"Score": "4"
}
},
{
"body": "<p>Your output is simply a sum of certain numbers. You don't need to build intermediary lists at all here, just <em>select the numbers you want to sum</em>, by looping. Your criteria are that the <em>current</em> number should not be 13, and the <em>preceding</em> number should not be 13.</p>\n\n<p>To achieve this, you could just use a loop that remembers the preceding number:</p>\n\n<ul>\n<li>initialize a <code>preceding</code> variable to a value you can easily test for. Here, any value other than 13 would do, and <code>None</code> is probably a good sentinel value.</li>\n<li>In a loop over the numbers, if the <em>current</em> number is not 13 <em>and</em> the <em>preceding</em> number is not 13, add it to the running total.</li>\n<li>At the end of the loop, set <code>preceding</code> to the current number. That way, when you go back to the top of the loop body, <code>preceding</code> will still contain the number from the preceding iteration.</li>\n</ul>\n\n<p>So, given an input of <code>[17, 13, 3, 9]</code>, you'd want to sum the first and the last number. We start with <code>preceding</code> set to <code>None</code>, <code>result</code> is set to <code>0</code> and we iterate 4 times:</p>\n\n<ol>\n<li><code>preceding = None</code>, set <code>current</code> to the first value <code>17</code>.\n\n<ul>\n<li><code>preceding != 13 and current != 13</code> is <em>true</em>, so add the current value to the result -> <code>result = 0 + 17 = 17</code>.</li>\n<li>set <code>preceding = current</code>, so <code>17</code></li>\n</ul></li>\n<li><code>preceding = 17</code>, set <code>current</code> to the second value <code>13</code>.\n\n<ul>\n<li><code>preceding != 13 and current != 13</code> is <strong>false</strong> (<code>current</code> is set to 13), so <em>skip</em> this value.</li>\n<li>set <code>preceding = current</code>, so <code>13</code></li>\n</ul></li>\n<li><code>preceding = 13</code>, set <code>current</code> to the third value <code>3</code>.\n\n<ul>\n<li><code>preceding != 13 and current != 13</code> is <strong>false</strong> (<code>preceding</code> is set to 13), so <em>skip</em> this value.</li>\n<li>set <code>preceding = current</code>, so <code>3</code></li>\n</ul></li>\n<li><code>preceding = 3</code>, set <code>current</code> to the forth value <code>9</code>.\n\n<ul>\n<li><code>preceding != 13 and current != 13</code> is <em>true</em>, so add the current value to the result -> <code>result = 17 + 9 = 26</code>.</li>\n<li>set <code>preceding = current</code>, so <code>9</code></li>\n</ul></li>\n</ol>\n\n<p>and you end up with <code>result = 26</code>.</p>\n\n<p>Generally speaking, when you find yourself wanting to look <em>ahead</em> in a <code>for</code> loop, turn the problem around and look <em>behind</em> instead. It is <em>much simpler</em>, as your loop will already have processed the items behind.</p>\n\n<p>Translating those steps above to Python code looks like this:</p>\n\n<pre><code>def sum_without_13s(nums):\n \"\"\"Sum all values that are not equal to 13 or directly follow 13\"\"\"\n\n # the running total of qualifying numbers\n result = 0\n # the preceding value in the loop, set at the end of the loop body\n preceding = None # any value that is not 13 would do\n\n for value in nums:\n # only add to the sum if this value and the preceding value are both\n # *not* equal to 13.\n if value != 13 and preceding != 13:\n result += value\n\n # for the next iteration, remember the current value so we can\n # skip any values that followed 13.\n preceding = value\n\n return result\n</code></pre>\n\n<p>That's the most <em>readable</em> method of implementing your algorithm. The function produces the sum of integers not 13, and not directly following 13:</p>\n\n<pre><code>>>> sum_without_13s([13, 99, 3]) # only 3 fits criteria, so should produce 3\n3\n>>> sum_without_13s([99, 3]) # no 13s, so sum should be 102\n102\n>>> sum_without_13s([1, 2, 13, 13, 3, 4]) # only 1, 2, and 4 should be summed == 7\n7\n</code></pre>\n\n<p>Note that the function also <em>returns</em> the result, rather than print the result to the console. If you want to see the output of your function, you can always print the returned value:</p>\n\n<pre><code>>>> theanswer = sum_without_13s([17, 13, 19, 18, 13, 13, 3, 7])\n>>> print(theanswer)\n42\n</code></pre>\n\n<h2>Other looping constructs that give you access to the preceding value</h2>\n\n<p>You could in principle make use of <a href=\"https://docs.python.org/3/library/itertools.html#itertools.chain\" rel=\"nofollow noreferrer\"><code>itertools.chain()</code></a> and <a href=\"https://docs.python.org/3/library/functions.html#zip\" rel=\"nofollow noreferrer\"><code>zip()</code></a> to produce an iterator of <code>(preceding, current)</code> tuples to loop over, and so make it possible to filter and sum in a generator expression.</p>\n\n<p>The above 'preceding value' approach is a variant of the <a href=\"https://docs.python.org/3/library/itertools.html#itertools-recipes\" rel=\"nofollow noreferrer\"><code>pairwise()</code> function from the <code>itertools</code> recipes section</a>. But where <code>pairwise()</code> starts with <code>(nums[0], nums[1])</code> and ends at <code>(nums[-2], nums[-1])</code>, we really need to be starting with <code>(None, nums[0])</code> <em>first</em> because we wouldn't want to skip either the first or the last value in your input from consideration.</p>\n\n<p>So here's a <code>with_preceding()</code> function, with a configurable default value for that first element of the first tuple:</p>\n\n<pre><code>from itertools import chain, tee\n\ndef with_preceding(iterable, default=None):\n \"s -> (default, s0), (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = tee(iterable)\n return zip(chain((default,), a), b)\n</code></pre>\n\n<p>which then can be used in an alternate implementation using a generator expression, like this:</p>\n\n<pre><code>def sum_without_13s_iter(nums):\n \"\"\"Sum all values that are not equal to 13 or directly follow 13\"\"\"\n return sum(\n current\n for preceding, current in with_preceding(nums)\n if preceding != 13 and current != 13\n )\n</code></pre>\n\n<p>However, readability suffers, in my eyes, and for little gain as the above is actually <em>slower</em> than the first version. See the small benchmark at the very end.</p>\n\n<h2>Performance considerations</h2>\n\n<p>I tried to construct what I hoped would be a <em>faster</em> function using iterators, the <code>itertools</code> and <code>operator</code> modules and the <code>sum()</code>, <code>map()</code> and <code>zip()</code> functions to try and avoid the Python interpreter loop altogether, but this was simply not any faster; at best I could get it to be about 5-10% <em>slower</em> than the above first version of the function.</p>\n\n<p>If performance <em>is</em> a concern, then you should really be using numpy arrays anyway. With a numpy array of integers as the input, the function can be expressed as:</p>\n\n<pre><code>import numpy as np\n\ndef array_sum_without_13s(numarray):\n \"\"\"Sum all values in an array that are not equal to 13 or directly follow 13\"\"\"\n # boolean array with True where the input array has 13\n is13 = numarray == 13\n # boolean array with True where the input array is preceded by 13\n follows13 = np.concatenate(([False], is13[:-1]))\n # sum of all values that don't fit either of the above criteria\n return np.sum(numarray[~(is13 | follows13)])\n</code></pre>\n\n<p>As stated, this function expects a numpy array as the input:</p>\n\n<pre><code>>>> import numpy as np\n>>> array_sum_without_13s(np.array([13, 99, 3]))\n3\n>>> array_sum_without_13s(np.array([99, 3]))\n102\n>>> array_sum_without_13s(np.array([1, 2, 13, 13, 3, 4]))\n7\n>>> array_sum_without_13s(np.array([17, 13, 19, 18, 13, 13, 3, 7]))\n42\n</code></pre>\n\n<p>Given an input of 1 million integers, the numpy version takes ~3.5 milliseconds versus the pure-Python version taking ~89 milliseconds. Numpy is the numeric processing champion, hands down:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>In [1]: import random\n ...: import numpy as np\n ...: from codereview237899 import sum_without_13s, array_sum_without_13s\n ...: testdata = random.choices(range(1_000), k=1_000_000)\n ...: testarray = np.array(testdata)\n ...:\n\nIn [2]: %timeit sum_without_13s(testdata)\n88.7 ms ± 2.12 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n\nIn [3]: %timeit array_sum_without_13s(testarray)\n3.55 ms ± 81.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n\nIn [4]: %timeit sum_without_13s_iter(testdata)\n119 ms ± 13.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n</code></pre>\n\n<p>The last test there is for the <code>with_preceding()</code> and generator expression variant above; it's a disappointing 35% slower.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T13:58:45.887",
"Id": "237906",
"ParentId": "237899",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T08:31:13.763",
"Id": "237899",
"Score": "5",
"Tags": [
"python"
],
"Title": "Remove every occurence of the number 13 and the next number from a list, then sum the result"
}
|
237899
|
<p>I have some legacy code which gets a list of <code>Student</code>s and their corresponding <code>School</code>. It's LinqToSql and there is no lazy loading:</p>
<pre><code>public class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
public School AttendedSchool { get; set; }
public Student(int studentId) {
// code to get the student from the database goes here, this
// gets FirstName, LastName and SchoolId from the db.
FirstName = dbResult.FirstName;
LastName = dbResult.LastName;
AttendedSchool = new School(dbResult.SchoolId);
}
}
public class School
{
public string SchooolName { get; set; }
public School(int schoolId) {
// go to database and call 'GetDbSchool' using schoolId
SchoolName = resultFromDatabase.SchoolName;
}
}
</code></pre>
<p>There are thousands of students but only a handful of schools. Because of the way the code is built we see a <code>GetDbSchool</code> call to the database every time a Student is created but this clearly isn't required, it's getting the same school details again and again. I want a simple cache of schools to prevent so many db calls. The cache doesn't need a mechanism to empty or update and if there is a race condition and the school is fetched from the database twice that's not a problem. This is the caching code I've written:</p>
<pre><code>public static class SchoolCache
{
public static School GetSchool(int schoolId)
{
if (MemoryCache.Default["school_" + schoolId] != null)
{
return (School)MemoryCache.Default["school_" + schoolId.ToString()];
}
var cachePolicy = new CacheItemPolicy { SlidingExpiration = TimeSpan.FromSeconds(100) };
var schoolFromDb = // go to database to get the school details
MemoryCache.Default.Add("school_" + schoolId, schoolFromDb, cachePolicy);
return schoolFromDb;
}
}
</code></pre>
<p>Then in the School class I can use the cache and we get one db call per school:</p>
<pre><code>public School(int schoolId) {
SchoolName = SchoolCache.GetSchool(schoolId).SchoolName;
}
</code></pre>
<p>It works as expected but I don't see many caches this simple, most examples and implementations are more complicated. Are there any obvious problems with this simple implementation?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T14:56:03.243",
"Id": "466584",
"Score": "1",
"body": "Welcome to Code Review! Please have a look at our [question guidelines](/help/how-to-ask) and change your title to describe what the code is supposed to do, not your concerns about it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T17:04:48.423",
"Id": "466611",
"Score": "0",
"body": "You seem to seek an advice rather then code review. If this is the case, you might want to post your question on Software Engineering SE instead."
}
] |
[
{
"body": "<p>This is a really bad pattern: neither your <code>Student</code> nor your <code>School</code> class should be responsible for retrieving themselves from the DB. Imagine retrieving a list of 100 <code>Student</code>s: that would mean 100+ queries to the DB. You can't even apply filters (e.g. get all the <code>Student</code>s who go to one <code>School</code>).</p>\n\n<p>Your caching mechanism is solving the wrong problem. What you should do is:</p>\n\n<ul>\n<li>Get all <code>School</code>s and store them in a <code>Dictionary<int, School></code> where the key is the Id of the <code>School</code>.</li>\n<li>Get all <code>Student</code>s, and then loop through them and attach the <code>School</code> based on the <code>SchoolId</code>.</li>\n</ul>\n\n<p>Two queries instead of hundreds or thousands.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T16:01:56.553",
"Id": "466600",
"Score": "0",
"body": "You are 100% correct, the business objects shouldn't be responsible for retrieving themselves from the DB. This is a small part of a large code base which I need to be careful making changes to. I've over-simplified my example, the students are retrieved in a single query. The problem is that a 'Populate' function in Student repeatedly ends up calling 'GetDbSchool' by using `new School` in the way described above. The code above reduces ~9000 db calls (the number of students) to ~30 (the number of schools). I want to know specifically if there are problems with the caching strategy."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T15:21:22.290",
"Id": "237911",
"ParentId": "237908",
"Score": "3"
}
},
{
"body": "<p>Seems you know that getting them individually is a bad idea but you are stuck with some legacy code. For your new code the biggest issue you will have is this line.</p>\n\n<pre><code>if (MemoryCache.Default[\"school_\" + schoolId] != null)\n{\n return (School)MemoryCache.Default[\"school_\" + schoolId.ToString()];\n}\n</code></pre>\n\n<p>you should retrieve the value and store in a variable. Then check if that variable is null or not and return the variable if not null. The odds are low but there is a chance the value is there for the If statement but ejected from the cache before it runs the statement to return the value.</p>\n\n<p>If you want it to be multi-threaded then you would also need to change some code. For now I assume you don't care about that part. </p>\n\n<p><strong>Update for multi threaded</strong></p>\n\n<p>While memory cache is thread safe your code has the issue of potentially allowing calls that happen at the same time to hit the database. In pseudocode you code does this</p>\n\n<ol>\n<li>Check if it's in the cache</li>\n<li>retrieve the value from cache</li>\n<li>do the database call</li>\n<li>save the value in the cache</li>\n</ol>\n\n<p>I already said in a non-multi threaded environment how 1 & 2 can cause issue. In a multi threaded a thread 1 could be doing step 3 and thread 2 could check step 1 and it will return it's not in the cache. Then thread 2 skips to step 3, because it's not in the cache yet because thread 1 hasn't saved it there yet. In the end it will not throw, as memory cache is threadsafe but will create extra database calls that are then ignored. </p>\n\n<p>If you are using .net core then you can just use GetOrCreate method. In .net framework we can create that method ourselves. </p>\n\n<p>-- .net framework from here on out</p>\n\n<p>The easiest way is to use Lazy to hold the call to the database and store the Lazy object in the cache. MemoryCache has a method for <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.runtime.caching.memorycache.addorgetexisting?view=netframework-4.8\" rel=\"nofollow noreferrer\">AddOrGetExisting</a>_that will handle if it should insert the value or return it back. The downside is now the call is in the cache if the call threw an exception we cached that exception, typically not what is desired. We will need to check for that and evict the cache if it's an exception.</p>\n\n<pre><code>public static TItem GetOrCreate<TItem>(this MemoryCache cache, string key, Func<string, TItem> factory, CacheItemPolicy policy)\n{\n // wrap the factory in a lazy so we don't execute the factory every time\n var lazy = new Lazy<TItem>(() => factory(key));\n // cache will return the value from cache or null if it inserted it\n var result = cache.AddOrGetExisting(key, lazy, policy) as Lazy<TItem> ?? lazy;\n // now the factory is wrapped in the cache. if it threw an Exception then all callers would get the Exception\n // trap for that an evict the cache if its an exception\n try\n {\n return result.Value;\n }\n catch (Exception e)\n {\n // evict factory that threw exceptions\n cache.Remove(key);\n throw;\n }\n}\n</code></pre>\n\n<p>You could also make this handle async as well with some minor tweaks.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T11:13:38.767",
"Id": "466704",
"Score": "0",
"body": "I thought MemoryCache was thread safe, can you outline changes I'd need to make to make my cache safe for multi-threaded use?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T14:45:00.140",
"Id": "466718",
"Score": "0",
"body": "@jonaglon I updated my answer"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T18:45:34.700",
"Id": "237923",
"ParentId": "237908",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "237923",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T14:09:04.400",
"Id": "237908",
"Score": "2",
"Tags": [
"c#",
"cache"
],
"Title": "Simple c# MemoryCache mechanism to reduce number of db calls"
}
|
237908
|
<p>02/02/2020 is a <a href="https://en.wikipedia.org/wiki/Palindrome#Dates" rel="nofollow noreferrer">palindrome day</a> because reading the date left-to-right or right-to-left still refers to the same calendar date. And because it doesn't
matter whether you use the DD/MM/YYYY format or the MM.DD.YYYY format, it's called a <em>Universal Palindrome Day</em>.</p>
<p>No one year can have more than 1 palindrome day. This is important because we need only consider the year to obtain a chronological list through sorting.</p>
<p>In the 10000 year period, that we can express using 4 decimal digits, there are precisely 366 palindrome days.</p>
<pre class="lang-none prettyprint-override"><code>366 is (31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31)
</code></pre>
<p>Every combination of day and month numbers produces a valid date. No special care has to be taken of the 29th of February since both 2092 (29/02/2092) and
9220 (02.29.9220) will indeed be leap years. Let's hope we're still around...</p>
<p>Combining day and month is done using nested loops. The outer loop necessarily iterates over the month because we can only know the iteration count for the
inner loop once we have chosen a month and consulted a lookup table (LUT) to find out how many days that particular month has.</p>
<p>Just combining alone will not produce the sought for chronological order. Ordinarily we would sort <strong>the outputs</strong> from the combining operation, but I've discovered that sorting <strong>the inputs</strong> to the combining part can be much faster. Even faster than producing an unsorted list! Moreover, where sorting
the outputs heavily depends on the quality of the chosen sort method, sorting the inputs does not (much). My code never has to sort more than 31 values.</p>
<p>I could easily have opted to not sort at all, if only I would have used more lookup tables. The trouble with lookup tables is to know when enough is
enough. The extreme being one big lookup table with the final results at the ready. Where's the fun in that?<br>
That's not to say that I've not explored it: replacing the 70 code bytes in PALINDR1.ASM_Part1 with the 214 bytes of 4 embedded lookup tables will bring the execution time down from 5.4 µsec to 3.0 µsec.</p>
<pre class="lang-none prettyprint-override"><code> 5.4 µsec PALINDR1.ASM Sorted inputs
6.9 µsec PALINDR2.ASM Unsorted
111.8 µsec PALINDR3.ASM Sorted outputs
</code></pre>
<p>Of course these timings don't include the <code>int 21h</code> DOS.PrintString call.</p>
<pre class="lang-none prettyprint-override"><code>; PALINDR1.ASM (c) 2020 Sep Roland
; --------------------------------
; assemble with FASM
ORG 256
; This program lists all palindrome days according to DD/MM/YYYY
; It sorts the inputs to obtain a chronological list
; Part 1 fills 4 ordered tables with the reversed textual representations
; of months and days
push 31 30 29 12 ; (1)
mov bp, 1010'1101'0101b ; LUT DaysPerMonth (1 is 31, 0 is less)
mov di, T12
mov bx, 1
NextT: pop dx ; (1) -> DX={12,29,30,31}
push di ; (2) DI points behind a sentinel zero
lea cx, [bx-1]
rep movsw ; Copy the mother table
mov cl, 10 ; CONST
.Next: mov ax, bx
div cl
add ax, 3030h
shr bp, 1 ; Hiding the DaysPerMonth info
rcl ax, 1 ; ... in bit 0
add di, 2
push di ; (3)
.Sort: mov [di], si ; Garbage the 1st time
sub di, 2
mov si, [di-2] ; This could read the sentinel
cmp si, ax
jg .Sort
mov [di], ax
pop di ; (3)
inc bx
cmp bx, dx
jbe .Next
xor ax, ax ; Zero terminator on each table is at
stosw ; the same time sentinel of next table
pop si ; (2) New table is mother of next table
cmp dx, 31
jb NextT
; Part 2 makes all the valid month and day combinations (366 in all)
mov si, T12
lodsw
shr ax, 1 ; -> CF (*) Extract DaysPerMonth info
; The outer loop updates the month and century fields
Outer: push si ; (4)
mov si, T12+(12+1+29+1+30+1)*2 ; Point at T31
jc .a ; (*) OK, 31 days
sub si, (30+1)*2 ; Point at T30
cmp ax, "02" ; Is it February ?
jne .a ; No, 30 days
sub si, (29+1)*2 ; Point at T29, 29 days
.a: mov [String+3], ax ; 2-digit month
mov [String+6], ah ; 2-digit century
mov [String+7], al
lodsw
shr ax, 1
; The inner loop updates the day and year fields
Inner: mov [String+0], ax ; 2-digit day
mov [String+8], ah ; 2-digit year
mov [String+9], al
mov dx, String
mov ah, 09h ; DOS.PrintString
int 21h
lodsw
shr ax, 1 ; No info to extract, but
jnz Inner ; ... used as iterator test
pop si ; (4)
lodsw
shr ax, 1 ; -> CF (*) Extract DaysPerMonth info
jnz Outer
mov ax, 4C00h ; DOS.Terminate
int 21h
; --------------------------------------
String: db '../../....', 13, 10, '$'
ALIGN 2
dw 0 ; Sentinel
T12: rw 12+1+29+1+30+1+31+1
</code></pre>
<p>For comparison here are the unsorted and post-sorted DD/MM/YYYY versions:</p>
<pre class="lang-none prettyprint-override"><code>; PALINDR2.ASM (c) 2020 Sep Roland
; --------------------------------
; assemble with FASM
ORG 256
; This program lists all palindrome days according to DD/MM/YYYY
; It does not produce a chronological list
; The code makes all the valid month and day combinations (366 in all)
xor si, si ; Month
; The outer loop updates the month and century fields
Outer: mov cl, [MDays+si] ; LUT DaysPerMonth
inc si
mov ax, si
aam
add ax, "00"
mov [String+6], ax ; 2-digit century
mov [String+3], ah ; 2-digit month
mov [String+4], al
xor di, di ; Day
; The inner loop updates the day and year fields
Inner: inc di
mov ax, di
aam
add ax, "00"
mov [String+8], ax ; 2-digit year
mov [String+0], ah ; 2-digit day
mov [String+1], al
mov dx, String
mov ah, 09h ; DOS.PrintString
int 21h
dec cl ; Next day
jnz Inner
cmp si, 12 ; Next month
jb Outer
mov ax, 4C00h ; DOS.Terminate
int 21h
; --------------------------------------
String: db '../../....', 13, 10, '$'
MDays: db 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
</code></pre>
<pre class="lang-none prettyprint-override"><code>; PALINDR3.ASM (c) 2020 Sep Roland
; --------------------------------
; assemble with FASM
ORG 256
; This program lists all palindrome days according to DD/MM/YYYY
; It sorts the outputs to produce a chronological list
; Part 1 creates an ordered list of palindrome years
xor dx, dx ; Table size
xor si, si ; Month
; The outer loop inserts the reversed textual representation of the month
; as the most significant part of the 4-byte string in EBX
; e.g. for February - EBX=5048____h (EBX="__02")
Outer: mov cl, [MDays+si] ; LUT DaysPerMonth
inc si
mov ax, si
aam
add ax, "00"
xchg al, ah
mov bx, ax
shl ebx, 16
xor di, di ; Day
; The inner loop inserts the reversed textual representation of the day
; as the least significant part of the 4-byte string in EBX
; e.g. for 1 February - EBX=50484948h (EBX="0102")
Inner: inc di
mov ax, di
aam
add ax, "00"
xchg al, ah
mov bx, ax
; MergeSorting EBX into the growing table
; e.g. EBX=50484948h (EBX="0102") corresponds to the year 2010
mov bp, dx
Look: mov eax, [Table+bp-4] ; This could read the sentinel
cmp eax, ebx
jb Found
mov [Table+bp], eax
sub bp, 4
jnz Look
Found: mov [Table+bp], ebx ; Add new element
add dx, 4 ; The array grows
dec cl ; Next day
jnz Inner
cmp si, 12 ; Next month
jb Outer
; Part 2 displays the whole list of completed palindrome days
mov si, Table
mov di, String
mov dx, di
Show: lodsd
mov [di], ax ; 2-digit day
bswap eax
mov [di+3], ah ; \ 2-digit month
mov [di+4], al ; /
mov [di+6], eax ; 4-digit year
mov ah, 09h ; DOS.PrintString
int 21h
cmp si, Table+366*4
jb Show
mov ax, 4C00h ; DOS.Terminate
int 21h
; --------------------------------------
String: db '../../....', 13, 10, '$'
MDays: db 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
ALIGN 4
dd 0 ; Sentinel
Table: rd 366
</code></pre>
<h2>Final note on the MM.DD.YYYY format (not shown)</h2>
<p>Quoting one paragraph:</p>
<blockquote>
<p>Combining day and month is done using nested loops. The outer loop necessarily iterates over the month because we can only know the iteration count for the inner loop once we have chosen a month and consulted a lookup table (LUT) to find out how many days that particular month has.</p>
</blockquote>
<p>This constraint is of no importance for the unsorted and post-sorted MM.DD.YYYY versions, but for the pre-sorted MM.DD.YYYY version I don't see any way around it. Any ideas?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T15:45:49.267",
"Id": "466597",
"Score": "0",
"body": "All US-format palindrome dates are all ISO-8601-format palindrome dates, of course."
}
] |
[
{
"body": "<h2>This program lists all palindrome days according to MM.DD.YYYY.</h2>\n\n<p>The code makes all the valid month and day combinations (366 in all).<br>\nIt uses 4 pre-sorted lookup tables (embedded for speed) to obtain a chronological list.</p>\n\n<p>In the MM.DD.YYYY format the most significant part of the year YYYY reflects in the day DD. This will be used for the outer loop.<br>\nThe outer loop runs through the T31 list so as to process all the possible day numbers. </p>\n\n<p>In the MM.DD.YYYY format the least significant part of the year YYYY reflects in the month MM. This will be used for the inner loop. However the number of iterations will vary depending on the day value being greater (a), equal (b) or smaller (c) than 30:</p>\n\n<p>(a).The inner loop runs through the T7 list when the outer loop processes the day number 31. Stored as '31'.<br>\n(b).The inner loop runs through the T11 list when the outer loop processes the day number 30. Stored as '30'.<br>\n(c).The inner loop runs through the T12 list for every other day number that the outer loop processes.</p>\n\n<p>The T31 list is an ordered list of the 2-characters ASCII representation of the numbers in the range [1,31].<br>\nThe T12 list is an ordered list of the 2-characters ASCII representation of the numbers in the set {1,2,3,4,5,6,7,8,9,10,11,12}. Months that have 29+ days. (For the purpose of this program February has 29 days.)<br>\nThe T11 list is an ordered list of the 2-characters ASCII representation of the numbers in the set {1,3,4,5,6,7,8,9,10,11,12}. Months that have 30+ days.<br>\nThe T7 list is an ordered list of the 2-characters ASCII representation of the numbers in the set {1,3,5,7,8,10,12}. Months that have 31 days.</p>\n\n<pre><code> 2-chars List List\nNumber ASCII Entry Order\n---------------------------------\n 1 -> '01' -> 3130h 4th\n 2 -> '02' -> 3230h 8th\n 3 -> '03' -> 3330h 11th\n\n 10 -> '10' -> 3031h 1st\n 11 -> '11' -> 3131h 5th\n 12 -> '12' -> 3231h 9th\n\n 20 -> '20' -> 3032h 2nd\n 21 -> '21' -> 3132h 6th\n 22 -> '22' -> 3232h 10th\n\n 30 -> '30' -> 3033h 3rd\n 31 -> '31' -> 3133h 7th\n</code></pre>\n\n<p>The chronological ordering of the final result, which demands digits reversal, comes naturally from sorting these <strong>text-based</strong> tables.</p>\n\n<pre><code> mov si, T31\n lodsw\nOuter:\n push si\n mov si, T7\n cmp ax, \"31\"\n je @f\n mov si, T11\n cmp ax, \"30\"\n je @f\n mov si, T12\n@@:\n mov [String+3], ax ;Day\n mov [String+6], ah ;Century\n mov [String+7], al\n lodsw\nInner:\n mov [String], ax ;Month\n mov [String+8], ah ;Year\n mov [String+9], al\n mov dx, String\n mov ah, 09h ;Print string\n int 21h\n lodsw\n test ax, ax\n jnz Inner\n pop si\n lodsw\n test ax, ax\n jnz Outer\n\n mov ax, 4C00h ;Exit to DOS\n int 21h\n\n ALIGN 2\nT7:\n db '10011203050708'\n dw 0\nT11:\n db '1001111203040506070809'\n dw 0\nT12:\n db '100111021203040506070809'\n dw 0\nT31:\n db '10203001112131021222031323041424051525061626071727081828091929'\n dw 0\nString:\n db '..........',13,10,'$'\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T15:29:39.323",
"Id": "238116",
"ParentId": "237909",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "238116",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T14:18:43.363",
"Id": "237909",
"Score": "4",
"Tags": [
"performance",
"algorithm",
"assembly",
"palindrome",
"x86"
],
"Title": "A fast generator of palindrome dates in chronological order"
}
|
237909
|
<p>I'm trying to calculate with <code>SUMIFS</code> and <code>COUNTIFS</code> some data.</p>
<p>The output sheet looks like this:</p>
<p><a href="https://i.stack.imgur.com/rNnxx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rNnxx.png" alt="Output Data"></a></p>
<p>I've hidden some irrelevant or sensitive data to make it easy to go to the point.</p>
<p>My code runs an array on this worksheet and calculates per each day and user some KPIs I need from this worksheet:</p>
<p><a href="https://i.stack.imgur.com/HmkVC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HmkVC.png" alt="Input Data"></a></p>
<p>The calculation is pretty simple, but it impacts heavily on the performance:</p>
<pre><code>Option Explicit
Sub Test()
With Hoja4
Dim arrTotal As Variant: arrTotal = .UsedRange.Value
Dim Fecha As Double
Dim i As Long
For i = 2 To UBound(arrTotal)
Fecha = arrTotal(i, 1)
arrTotal(i, 13) = CalculaLlamadas(CStr(arrTotal(i, 2)), Fecha, 1, 4)
arrTotal(i, 14) = CalculaFCR(CStr(arrTotal(i, 2)), Fecha, 1, 4)
arrTotal(i, 15) = CalculaLlamadas(CStr(arrTotal(i, 2)), Fecha, 3, 5)
arrTotal(i, 16) = CalculaFCR(CStr(arrTotal(i, 2)), Fecha, 3, 5)
arrTotal(i, 17) = CalculaLlamadas(CStr(arrTotal(i, 2)), Fecha, 30, 6)
arrTotal(i, 18) = CalculaFCR(CStr(arrTotal(i, 2)), Fecha, 30, 6)
Next i
.UsedRange.Value = arrTotal
End With
End Sub
Private Function CalculaFCR(Agente As String, Fecha As Double, Dias As Byte, Columna As Byte) As Long
Dim FechaFin As Double: FechaFin = Fecha + Dias
With Hoja37
CalculaFCR = Application.SumIfs(.Columns(Columna), .Columns(1), Agente, _
.Columns(2), ">=" & Fecha, .Columns(2), "<=" & FechaFin)
End With
End Function
Private Function CalculaLlamadas(Agente As String, Fecha As Double, Dias As Byte, Columna As Byte) As Long
Dim FechaFin As Double: FechaFin = Fecha + Dias
With Hoja37
CalculaLlamadas = Application.CountIfs(.Range("A:A"), Agente, _
.Range("B:B"), ">=" & Fecha, .Columns(2), "<=" & FechaFin)
End With
CalculaLlamadas = LLamadas
End Function
</code></pre>
<p>As you can see on the code, the logic is pretty easy calculate how many times an user shows between 2 dates, and get the sum of a column for these dates.</p>
<p>I can't figure out how to make this quicker, I've also tried using an array to loop through it instead using the countif and the sumif, but it takes even longer because the input sheet has 40k (1 and half month of data) rows and its likely to be increased with days to come.</p>
<p>Any suggestions on how to improve the performance for this task?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T21:10:08.463",
"Id": "466627",
"Score": "0",
"body": "How long does it run for? Have you identified a blottleneck? Why can't the sumifs/countifs be on the actual worksheet? Is `Worksheet.UsedRange` just the range you need or it's larger? I wouldn't consider it reliable - it'll break as soon as you enter any arbitrary scratchpad calculation anywhere to the right of the table."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T21:24:17.153",
"Id": "466630",
"Score": "0",
"body": "It runs for several minutes, the bottleneck is either the sumif/countif or looping through the whole array inevery iteration from the main array. I always delete rows and columns to avoid undesired data on my `UsedRange` so in this case is reliable. Do you have any guidance on how to improve this @MathieuGuindon?"
}
] |
[
{
"body": "<p>You are generally correct in using <code>Application</code> functions (<code>SumIfs</code> and <code>CountIfs</code>) over rolling your own functions, as the built-in functions in Excel should be optimized in the DLL than anything you could write in VBA. The difference in performance is due to the organization of the data.</p>\n\n<p>The key to my example below is to pre-process the input data into a form that reduces the \"lookup\" time of all the data. For comparison sake, using <code>SumIfs</code> and <code>CountIfs</code> will always be working with your entire data range. Your data set may be large (40k+ rows), so these Excel functions will always take a fixed amount of time. I timed my example to process 45,500 rows in 44.8 seconds. (I'll share a <code>GenerateData</code> sub that I created to set up the inputs for you or anyone else to double-check my work.)</p>\n\n<p>The simple reccommendation for processing large amounts of data is to use a memory-based array. You're already doing this with your <code>arrTotal</code> array. There are two main issues in performance with this: 1) the Excel functions are still accessing the Worksheet object to process <code>SumIfs</code> and <code>CountIfs</code>, and 2) there is no optimization in the <code>arrTotal</code> data to help speed things up. This is where my own example starts.</p>\n\n<p>First, I want to create an array from the input data that is \"ordered\". In this case, it means a memory-based array with the data sorted first on <code>Agente</code> and then on <code>Fecha Completa</code>. Please note that my code calculates the used area of the spreadsheet in a manner that should always be accurate (see @MathieuGuindon's comment). This function returns an ordered array:</p>\n\n<pre><code>Private Function OrderedInputs() As Variant\n '--- first sort the input data by Agente, then by date\n With Hoja37\n Dim inputArea As Range\n Dim lastRow As Long\n lastRow = .Cells(.Rows.count, 1).End(xlUp).Row\n Set inputArea = .Range(\"A2\").Resize(lastRow - 1, 6)\n With .Sort\n .SortFields.Clear\n .SortFields.Add Key:=inputArea.Columns(1), SortOn:=xlSortOnValues, _\n Order:=xlAscending, DataOption:=xlSortNormal\n .SortFields.Add Key:=inputArea.Columns(2), SortOn:=xlSortOnValues, _\n Order:=xlAscending, DataOption:=xlSortNormal\n .SetRange inputArea\n .Header = xlNo\n .MatchCase = False\n .Orientation = xlTopToBottom\n .SortMethod = xlPinYin\n .Apply\n\n '--- now grab the data into a memory-based array\n Dim inputData As Variant\n inputData = inputArea.Value\n\n '--- assuming the original data was sorted by date, then by Agente\n ' we'll put it back\n .SortFields.Clear\n .SortFields.Add Key:=inputArea.Columns(2), SortOn:=xlSortOnValues, _\n Order:=xlAscending, DataOption:=xlSortNormal\n .SortFields.Add Key:=inputArea.Columns(1), SortOn:=xlSortOnValues, _\n Order:=xlAscending, DataOption:=xlSortNormal\n .SetRange inputArea\n .Header = xlNo\n .MatchCase = False\n .Orientation = xlTopToBottom\n .SortMethod = xlPinYin\n .Apply\n End With\n End With\n OrderedInputs = inputData\nEnd Function\n</code></pre>\n\n<p>Having a sorted, ordered set of data is nice, but it's not nearly optimized enough yet. When you're processing this much data, you want to be able to immediately access any given agent's data. The way to do this is a <code>Dictionary</code>, using the agent's name as the key. Associated with each agent, is the date plus FCR1, FCR3, and FCR30 data values -- and there are multiple sets of this data for each agent. So for each agent, we can build a <code>Collection</code> of this data. The best way to do this is to create a simple object class called <code>AgentData</code>.</p>\n\n<pre><code>'--- Class: AgentData\nOption Explicit\n\nPublic day As Date\nPublic fcr1 As Long\nPublic fcr3 As Long\nPublic fcr30 As Long\n</code></pre>\n\n<p>All the fields are public because you really don't need to manipulate the data going in or coming out. Building up a <code>Collection</code> of <code>AgentData</code> objects starts with looping through all the (ordered) input data by name, and creating a <code>Collection</code> entry for each date:</p>\n\n<pre><code>Private Function BuildAgentData(ByRef inputArray As Variant) As Dictionary\n '--- we're creating a Dictionary of Agentes for quick lookup\n ' each Item in the Dictionary is an ordered Collection of AgentData\n ' objects, i.e. the objects are in date ascending order\n Dim agentes As Dictionary\n Set agentes = New Dictionary\n\n Dim i As Long\n Dim thisAgente As String\n Dim aData As AgentData\n Dim allAgentData As Collection\n For i = LBound(inputArray, 1) To UBound(inputArray, 1)\n If thisAgente <> inputArray(i, 1) Then\n thisAgente = inputArray(i, 1)\n '--- create the first entry\n Set aData = New AgentData\n aData.day = inputArray(i, 2)\n aData.fcr1 = inputArray(i, 4)\n aData.fcr3 = inputArray(i, 5)\n aData.fcr30 = inputArray(i, 6)\n Set allAgentData = New Collection\n allAgentData.Add aData\n agentes.Add thisAgente, allAgentData\n Else\n '--- increase the size of the array by one and add the date\n Set allAgentData = agentes(thisAgente)\n Set aData = New AgentData\n aData.day = inputArray(i, 2)\n aData.fcr1 = inputArray(i, 4)\n aData.fcr3 = inputArray(i, 5)\n aData.fcr30 = inputArray(i, 6)\n allAgentData.Add aData\n End If\n Next i\n Set BuildAgentData = agentes\nEnd Function\n</code></pre>\n\n<p>This reduces the beginning of your test sub to:</p>\n\n<pre><code>Dim sortedInputData As Variant\nDim agentes As Dictionary\nsortedInputData = OrderedInputs()\nSet agentes = BuildAgentData(sortedInputData)\nDebug.Print \"There are \" & UBound(sortedInputData, 1) & \" rows of input data.\"\n</code></pre>\n\n<p>There are changes to your <code>Calcula</code> functions, but the main test sub changes very little:</p>\n\n<pre><code>With Hoja4\n Dim arrTotal As Variant: arrTotal = .UsedRange.Value\n Dim fecha As Double\n Dim i As Long\n For i = 2 To UBound(arrTotal)\n fecha = arrTotal(i, 1)\n arrTotal(i, 13) = CalculaLlamadas2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 1, 4)\n arrTotal(i, 14) = CalculaFCR2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 1, 4)\n arrTotal(i, 15) = CalculaLlamadas2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 3, 5)\n arrTotal(i, 16) = CalculaFCR2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 3, 5)\n arrTotal(i, 17) = CalculaLlamadas2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 30, 6)\n arrTotal(i, 18) = CalculaFCR2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 30, 6)\n Next i\n .UsedRange.Value = arrTotal\nEnd With\n</code></pre>\n\n<p>Each of the <code>Calcula</code> functions will now use both the <code>sortedInputData</code> and the <code>agentes</code> dictionary as inputs. Instead of being forced to loop through all 40,000+ rows to count and sum for every single agent, the function immediately accesses the collection of data for each agent (via the <code>Dictionary</code>), and then can loop through the <code>Collection</code> (which may have as many entries as needed, but still is far, far less than the original input set).</p>\n\n<pre><code>Private Function CalculaFCR2(ByRef inputData As Variant, ByRef agentDates As Dictionary, _\n ByVal agente As String, ByVal fecha As Date, _\n ByVal dias As Long, ByVal columna As Long) As Long\n Dim fechaFin As Date\n fechaFin = fecha + dias\n Dim sum As Long\n If agentDates.Exists(agente) Then\n Dim aData As Variant\n Set aData = agentDates(agente)\n Dim item As Variant\n For Each item In aData\n If (item.day >= fecha) And (item.day <= fechaFin) Then\n Select Case columna\n Case 4\n sum = sum + item.fcr1\n Case 5\n sum = sum + item.fcr3\n Case 6\n sum = sum + item.fcr30\n End Select\n ElseIf (item.day > fechaFin) Then\n Exit For\n End If\n Next item\n CalculaFCR2 = sum\n Else\n '--- error processing if the agente doesn't exist\n End If\nEnd Function\n\nPrivate Function CalculaLlamadas2(ByRef inputData As Variant, ByRef agentDates As Dictionary, _\n ByVal agente As String, ByVal fecha As Date, _\n ByVal dias As Long, ByVal columna As Long) As Long\n Dim fechaFin As Date\n fechaFin = fecha + dias\n Dim count As Long\n If agentDates.Exists(agente) Then\n Dim aData As Variant\n Set aData = agentDates(agente)\n Dim item As Variant\n For Each item In aData\n If (item.day >= fecha) And (item.day <= fechaFin) Then\n count = count + 1\n ElseIf (item.day > fechaFin) Then\n Exit For\n End If\n Next item\n CalculaLlamadas2 = count\n Else\n '--- error processing if the agente doesn't exist\n End If\nEnd Function\n</code></pre>\n\n<p>I added a software timer class to measure execution time on my laptop (Intel Core i5-6300, 2.40GHz) and received the following results:</p>\n\n<pre><code>There are 4550 rows of input data.\nTime to build ordered inputs: 0.078 seconds\nTotal Run Time: 4.407 seconds\n\nThere are 45500 rows of input data.\nTime to build ordered inputs: 0.484 seconds\nTotal Run Time: 44.797 seconds\n</code></pre>\n\n<p>For reference, here are the three code modules you need to add:</p>\n\n<p>Class: <code>AgentData</code></p>\n\n<pre><code>'--- Class: AgentData\nOption Explicit\n\nPublic day As Date\nPublic fcr1 As Long\nPublic fcr3 As Long\nPublic fcr30 As Long\n</code></pre>\n\n<p>Class: <code>StopWatch</code></p>\n\n<pre><code>Option Explicit\n'--- from https://stackoverflow.com/a/939260/4717755\n\nPrivate mlngStart As Long\nPrivate Declare Function GetTickCount Lib \"kernel32\" () As Long\n\nPublic Sub StartTimer()\n mlngStart = GetTickCount\nEnd Sub\n\nPublic Function EndTimer() As Long\n EndTimer = (GetTickCount - mlngStart)\nEnd Function\n</code></pre>\n\n<p>Code Module: <code>Module1</code></p>\n\n<pre><code>Option Explicit\n\nSub Test()\n Dim sw As StopWatch\n Set sw = New StopWatch\n sw.StartTimer\n\n Dim sortedInputData As Variant\n Dim agentes As Dictionary\n sortedInputData = OrderedInputs()\n Set agentes = BuildAgentData(sortedInputData)\n Debug.Print \"There are \" & UBound(sortedInputData, 1) & \" rows of input data.\"\n Debug.Print \"Time to build ordered inputs: \" & CDbl((sw.EndTimer / 1000#)) & \" seconds\"\n\n With Hoja4\n Dim arrTotal As Variant: arrTotal = .UsedRange.Value\n Dim fecha As Double\n Dim i As Long\n For i = 2 To UBound(arrTotal)\n fecha = arrTotal(i, 1)\n arrTotal(i, 13) = CalculaLlamadas2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 1, 4)\n arrTotal(i, 14) = CalculaFCR2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 1, 4)\n arrTotal(i, 15) = CalculaLlamadas2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 3, 5)\n arrTotal(i, 16) = CalculaFCR2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 3, 5)\n arrTotal(i, 17) = CalculaLlamadas2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 30, 6)\n arrTotal(i, 18) = CalculaFCR2(sortedInputData, agentes, CStr(arrTotal(i, 2)), fecha, 30, 6)\n Next i\n .UsedRange.Value = arrTotal\n End With\n Debug.Print \"Total Run Time: \" & CDbl((sw.EndTimer / 1000#)) & \" seconds\"\nEnd Sub\n\nPrivate Function CalculaFCR2(ByRef inputData As Variant, ByRef agentDates As Dictionary, _\n ByVal agente As String, ByVal fecha As Date, _\n ByVal dias As Long, ByVal columna As Long) As Long\n Dim fechaFin As Date\n fechaFin = fecha + dias\n Dim sum As Long\n If agentDates.Exists(agente) Then\n Dim aData As Variant\n Set aData = agentDates(agente)\n Dim item As Variant\n For Each item In aData\n If (item.day >= fecha) And (item.day <= fechaFin) Then\n Select Case columna\n Case 4\n sum = sum + item.fcr1\n Case 5\n sum = sum + item.fcr3\n Case 6\n sum = sum + item.fcr30\n End Select\n ElseIf (item.day > fechaFin) Then\n Exit For\n End If\n Next item\n CalculaFCR2 = sum\n Else\n '--- error processing if the agente doesn't exist\n End If\nEnd Function\n\nPrivate Function CalculaLlamadas2(ByRef inputData As Variant, ByRef agentDates As Dictionary, _\n ByVal agente As String, ByVal fecha As Date, _\n ByVal dias As Long, ByVal columna As Long) As Long\n Dim fechaFin As Date\n fechaFin = fecha + dias\n Dim count As Long\n If agentDates.Exists(agente) Then\n Dim aData As Variant\n Set aData = agentDates(agente)\n Dim item As Variant\n For Each item In aData\n If (item.day >= fecha) And (item.day <= fechaFin) Then\n count = count + 1\n ElseIf (item.day > fechaFin) Then\n Exit For\n End If\n Next item\n CalculaLlamadas2 = count\n Else\n '--- error processing if the agente doesn't exist\n End If\nEnd Function\n\nPrivate Function OrderedInputs() As Variant\n '--- first sort the input data by Agente, then by date\n With Hoja37\n Dim inputArea As Range\n Dim lastRow As Long\n lastRow = .Cells(.Rows.count, 1).End(xlUp).Row\n Set inputArea = .Range(\"A2\").Resize(lastRow - 1, 6)\n With .Sort\n .SortFields.Clear\n .SortFields.Add Key:=inputArea.Columns(1), SortOn:=xlSortOnValues, _\n Order:=xlAscending, DataOption:=xlSortNormal\n .SortFields.Add Key:=inputArea.Columns(2), SortOn:=xlSortOnValues, _\n Order:=xlAscending, DataOption:=xlSortNormal\n .SetRange inputArea\n .Header = xlNo\n .MatchCase = False\n .Orientation = xlTopToBottom\n .SortMethod = xlPinYin\n .Apply\n\n '--- now grab the data into a memory-based array\n Dim inputData As Variant\n inputData = inputArea.Value\n\n '--- assuming the original data was sorted by date, then by Agente\n ' we'll put it back\n .SortFields.Clear\n .SortFields.Add Key:=inputArea.Columns(2), SortOn:=xlSortOnValues, _\n Order:=xlAscending, DataOption:=xlSortNormal\n .SortFields.Add Key:=inputArea.Columns(1), SortOn:=xlSortOnValues, _\n Order:=xlAscending, DataOption:=xlSortNormal\n .SetRange inputArea\n .Header = xlNo\n .MatchCase = False\n .Orientation = xlTopToBottom\n .SortMethod = xlPinYin\n .Apply\n End With\n End With\n OrderedInputs = inputData\nEnd Function\n\nPrivate Function BuildAgentData(ByRef inputArray As Variant) As Dictionary\n '--- we're creating a Dictionary of Agentes for quick lookup\n ' each Item in the Dictionary is an ordered Collection of AgentData\n ' objects, i.e. the objects are in date ascending order\n Dim agentes As Dictionary\n Set agentes = New Dictionary\n\n Dim i As Long\n Dim thisAgente As String\n Dim aData As AgentData\n Dim allAgentData As Collection\n For i = LBound(inputArray, 1) To UBound(inputArray, 1)\n If thisAgente <> inputArray(i, 1) Then\n thisAgente = inputArray(i, 1)\n '--- create the first entry\n Set aData = New AgentData\n aData.day = inputArray(i, 2)\n aData.fcr1 = inputArray(i, 4)\n aData.fcr3 = inputArray(i, 5)\n aData.fcr30 = inputArray(i, 6)\n Set allAgentData = New Collection\n allAgentData.Add aData\n agentes.Add thisAgente, allAgentData\n Else\n '--- increase the size of the array by one and add the date\n Set allAgentData = agentes(thisAgente)\n Set aData = New AgentData\n aData.day = inputArray(i, 2)\n aData.fcr1 = inputArray(i, 4)\n aData.fcr3 = inputArray(i, 5)\n aData.fcr30 = inputArray(i, 6)\n allAgentData.Add aData\n End If\n Next i\n Set BuildAgentData = agentes\nEnd Function\n</code></pre>\n\n<p>And at the bottom of <code>Module1</code> is the bonus sub to create the input data:</p>\n\n<pre><code>Sub GenerateData()\n Dim names() As String\n '--- from http://listofrandomnames.com/\n names = Split(\"Lori,Norah,Valorie,Evita,Alden,Tressa,Carrol,\" & _\n \"Leeanna,Alexia,Marlyn,Wilhemina,Lanell,Kari,\" & _\n \"Rose,Arianne,Lesa,Royal,Maura,Sherie,Lahoma\", \",\")\n Const START As Date = #1/1/2020#\n Const FINISH As Date = #3/31/2020#\n Const LOGINS_PER_DAY As Long = 500\n\n '--- output setup\n Dim entry As Range\n Dim day As Date\n Dim i As Long\n Dim index As Long\n With Hoja4\n .Cells.Clear\n .Range(\"A1\").Value = \"Fecha\"\n .Range(\"B1\").Value = \"Login\"\n .Range(\"F1\").Value = \"Centro\"\n .Range(\"F1\").Value = \"Centro\"\n .Range(\"M1\").Value = \"Encuestas 1\"\n .Range(\"N1\").Value = \"FCR 1\"\n .Range(\"O1\").Value = \"Encuestas 3\"\n .Range(\"P1\").Value = \"FCR 3\"\n .Range(\"Q1\").Value = \"Encuestas 30\"\n .Range(\"R1\").Value = \"FCR 30\"\n Set entry = .Range(\"A2\")\n For day = START To FINISH\n For i = LBound(names) To UBound(names)\n entry.Cells(1, 1).Value = day\n entry.Cells(1, 2).Value = names(i)\n Set entry = entry.Offset(1, 0)\n Next i\n Next day\n End With\n\n '--- input setup\n With Hoja37\n .Cells.Clear\n .Range(\"A1\").Value = \"Agente\"\n .Range(\"B1\").Value = \"Fecha Completa\"\n .Range(\"D1\").Value = \"FCR 1\"\n .Range(\"E1\").Value = \"FCR 3\"\n .Range(\"F1\").Value = \"FCR 30\"\n Set entry = .Range(\"A2\")\n For day = START To FINISH\n For i = 1 To LOGINS_PER_DAY\n index = CLng((UBound(names) - LBound(names)) * Rnd() + LBound(names))\n entry.Cells(1, 1).Value = names(index)\n entry.Cells(1, 2).Value = day\n entry.Cells(1, 4).Value = IIf(Rnd() > 0.5, 1, 0)\n entry.Cells(1, 5).Value = IIf(Rnd() > 0.5, 1, 0)\n entry.Cells(1, 6).Value = IIf(Rnd() > 0.5, 1, 0)\n Set entry = entry.Offset(1, 0)\n Next i\n Next day\n End With\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T07:36:28.063",
"Id": "466938",
"Score": "0",
"body": "Upvoted ur answer Peter, will try it whenever possible, crazy days at work right now :("
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T22:27:58.280",
"Id": "238008",
"ParentId": "237910",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T14:28:30.950",
"Id": "237910",
"Score": "2",
"Tags": [
"performance",
"vba",
"excel"
],
"Title": "Performance on countifs and sumifs"
}
|
237910
|
<p>I have a simple application that reads a couple of csv files and outputs the input into catalogues for the website. However, users have a habit of opening the csv files and inserting extra columns etc and it causes obvious issues, I have tried to tell people not mess with the files with no success, so i thought i would come up with a way round it. Is there a better way of doing it than this?</p>
<pre><code> private static List<CatalogueLine> ImportCatalogueLines()
{
List<CatalogueLine> tempCatalogueLines = new List<CatalogueLine>();
try
{
using (StreamReader reader = new StreamReader(ConfigurationManager.AppSettings["catalogue-lines-import-file"]))
{
int? catCodeColumn = null;
int? prodCodeColumn = null;
// Validate the column headers
string[] header = reader.ReadLine().ToLower().Split(',');
for (int i = 0; i < header.Length - 1; i++)
{
if (header[i] == "catcode")
catCodeColumn = i;
if (header[i] == "prodcode")
prodCodeColumn = i;
}
if (catCodeColumn.HasValue == false || prodCodeColumn.HasValue == false)
{
Console.WriteLine("Unable to validate the column headers, cancel the import.");
return tempCatalogueLines;
}
// Loop the rest of the lines.
while (!reader.EndOfStream)
{
// Split the line
string[] catalogueLine = reader.ReadLine().Split(',');
tempCatalogueLines.Add(new CatalogueLine
{ CatCode = catalogueLine[(int)catCodeColumn], ProdCode = catalogueLine[(int)prodCodeColumn] });
Console.Write($"\rImporting Catalogue Lines:\t{ catalogueLine[(int)prodCodeColumn] } ");
}
}
Console.Write($"\rImporting Catalogue Lines:\tCompleted. ");
}
catch (FileNotFoundException e)
{
Console.WriteLine($"{ e.Message }");
return tempCatalogueLines;
}
catch (IOException e)
{
Console.WriteLine($"{ e.Message }");
return tempCatalogueLines;
}
return tempCatalogueLines;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T15:50:29.973",
"Id": "466598",
"Score": "0",
"body": "Welcome to code review, unfortunately there is not enough code to review here, we prefer to see full classes to provide a better review. This isn't even a full function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T21:08:12.947",
"Id": "466902",
"Score": "0",
"body": "@pacmaninbw it is a full function though. But we'd need more information about the CSV to help you out Lee"
}
] |
[
{
"body": "<h1>Input Injection</h1>\n\n<p>Your function seems to depend at least on the input file, but this file is asked for by the function. You should follow the IoC principle and pass the file from outside (through function parameter).</p>\n\n<pre><code>var file = ConfigurationManager.AppSettings[\"catalogue-lines-import-file\"];\nvar lines = ImportCatalogueLines(file);\n</code></pre>\n\n<p>Maybe like that, but dont get confused, as your method Is private, this should be pushed even further, somewhere outside the entire class....</p>\n\n<h1>Always False Conditional</h1>\n\n<pre><code>if (header[i] == \"catcode\")\n catCodeColumn = i;\n\n if (header[i] == \"prodcode\")\n prodCodeColumn = i\n</code></pre>\n\n<p>It Is impossible for header[i] to be equal to two different values at the same time. Use else if or switch.</p>\n\n<h1>Duplicit Columns Check</h1>\n\n<p>Further if you are super paranoid you might want to check that catCodeColumn And prodCodeColumn Is not assigned more than once. That would mean there Is a duplicit column header (one that you care of).</p>\n\n<h1>Redundant Comparisions</h1>\n\n<pre><code>catCodeColumn.HasValue == false || prodCodeColumn.HasValue == false\n</code></pre>\n\n<p>The comparision to false Is redundant, use the negation operator \"!\".</p>\n\n<pre><code>!catCodeColumn.HasValue || !prodCodeColumn.HasValue\n</code></pre>\n\n<p>Or use de Morgans law</p>\n\n<pre><code>!(catCodeColumn.HasValue && prodCodeColumn.HasValue)\n</code></pre>\n\n<h1>Split by comma or do proper csv parsing?</h1>\n\n<p>In case some column value contains a comma character (not talking about the quotes needed for it to work), your implementation Will fail to handle it. Of course only if the csv ever contains such values. Even if it should not, you say that users can modify it as they like. Time to get paranoid!</p>\n\n<h1>Error Reporting</h1>\n\n<p>You should not log everything to Console inside the function. Especially not if you caught an exception, mute it and return possibly half-built result. Instead throw a custom exception, possibly let it carry the half-built list. But dont return with incomplete result. And put the logging to Its own scope.</p>\n\n<h1>General Remarks</h1>\n\n<p>Other than that I think your approach Is quite reasonable. If you cannot hardcode or configure the columns offset ať compile time, you have to determine it dynamically... But ofc if you used a proper csv parser with additional features like header checking, the code would look quite different, probably shorter...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T16:25:51.127",
"Id": "237916",
"ParentId": "237912",
"Score": "2"
}
},
{
"body": "<p>In addition of @slepic answer, you might need to do something about the files themselves. So, instead of trying to fix everything from the code, you would be better if you secure the files or move the data to a database engine instead of using CVS. </p>\n\n<p>For securing the CSVs files, you could move them into a directory and give read-only permission to everyone, and full permission to you and the application only. This way, they can view the files, but they can't make any modifications.</p>\n\n<p>If they need to add some new rows to the CSVs, you could ask them to send the new data to you or someone else to add them to the files. At the end, you only need one person who can modify these files not everyone. You can also make <code>Excel</code> templates with <code>locked</code> cells that can be used to add new rows for everyone, so they would just send it to you to update current CSVs. </p>\n\n<p>Best approach would be using a database and a solution to save the data and have a better control on it. This would be much easier to handle. Then, export the data to CSV whenever needed. </p>\n\n<p>if you can't switch the data to a database, I would suggest using some CSV parser library such as <code>FileHelper</code> and <code>CsvHelper</code>. However, if external libraries are off-limits (for work requirements), you can add more handling in your code (along with above suggestions). </p>\n\n<p>To validate the columns you can do this : </p>\n\n<pre><code>public static bool ValidateCatalogueLinesHeader(string line)\n{\n var columnNames = new string[] { \"catcode\", \"prodcode\" };\n\n // Validate the column headers\n var header = line.Split(',');\n\n if (header.Length != columnNames.Length)\n {\n //throw new InvalidDataException($\"the parsed csv has {header.Length} which is different than the provided number of columns\"); \n return false;\n }\n\n // non-null columns counter\n int countColumns = 0;\n\n foreach (var column in columnNames)\n {\n foreach (var headerName in header)\n {\n if (string.IsNullOrEmpty(headerName))\n {\n //throw new ArgumentNullException(nameof(headerName)); \n return false;\n }\n\n if (column.Equals(headerName, StringComparison.InvariantCultureIgnoreCase))\n {\n countColumns++;\n break;\n }\n }\n }\n\n // double ensurance;\n if (countColumns != columnNames.Length)\n {\n //throw new InvalidDataException(\"Unable to validate the column headers\"); \n return false;\n }\n\n return true;\n}\n</code></pre>\n\n<p>then your code can be something like this : </p>\n\n<pre><code>private static List<CatalogueLine> ImportCatalogueLines()\n{\n var filePath = ConfigurationManager.AppSettings[\"catalogue-lines-import-file\"];\n\n // will cover null, empty string, and also the existing's of the file \n if (!File.Exists(filePath)) { throw new FileNotFoundException(filePath); }\n\n List<CatalogueLine> tempCatalogueLines = new List<CatalogueLine>();\n\n using (var reader = new StreamReader(filePath))\n {\n var validateHeader = ValidateCatalogueLinesHeader(reader.ReadLine());\n\n if(!validateHeader) { throw new InvalidDataException(\"Unable to validate the column headers\"); }\n\n while (!reader.EndOfStream)\n {\n var streamedLine = reader.ReadLine();\n\n // check this line first\n if (string.IsNullOrEmpty(streamedLine)) { throw new ArgumentNullException(nameof(streamedLine)); }\n\n // notice, you're parsing integers, some integers could have commas separators \n // in case you have more than one comma, you should handle it \n // for time being, just throw an error\n\n // count number of commas \n var countComma = streamedLine.Count(x => x == ',');\n\n if (countComma > 1)\n {\n throw new InvalidDataException(\"the streamed line has more than one comma.\");\n }\n\n // only parse if there is one comma\n if (countComma == 1)\n {\n var line = streamedLine.Split(',');\n\n // ensure that this line has the same columns count\n if (line.Length == 2)\n {\n // since it is two elements, we can specify them manually to avoid extra loops\n // try parse them first to validate they are valid integers\n\n var isValidCat = int.TryParse(line[0], out int catCode); \n\n var isValidProd = int.TryParse(line[1], out int prodCode);\n\n // if both values are valid, add them to the list.\n if (isValidCat && isValidProd)\n {\n tempCatalogueLines.Add(new CatalogueLine { CatCode = catCode, ProdCode = prodCode });\n }\n }\n }\n }\n\n return tempCatalogueLines;\n }\n} \n</code></pre>\n\n<p>I have moved the header validation to a separated method because of readability, and also for code-reuse (in case you want to validate the header somewhere else). A better place for <code>ValidateCatalogueLinesHeader</code> would be inside the <code>CatalogueLine</code> class. And if there is mutliple CSVs models, then you can make an interface with <code>bool IsValid(string line);</code> or you can add <code>TryParse</code> method. this can improve your code. </p>\n\n<p>Also, I have comment out thrown exceptions <code>throw new ...</code> which would give you some idea on what's happening in the code. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T01:10:23.577",
"Id": "237936",
"ParentId": "237912",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "237916",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T15:31:56.550",
"Id": "237912",
"Score": "2",
"Tags": [
"c#",
"csv"
],
"Title": "Parsing CSV header for validation"
}
|
237912
|
<p>The intention is to transcribe .docx files to have modified font and font sizes while keeping the run attributes such as bold, underline, italic etc. I'll then add some headers and graphics to the newly created target.docx files</p>
<p>How to reconstruct paragraphs from runs? Each one, currently, gets it's own separate line!</p>
<pre><code>from docx import Document
from docx.shared import Pt
def main(filename):
try:
src_doc = Document(filename)
trg_doc = Document()
style = trg_doc.styles['Normal']
font = style.font
font.name = 'Times'
font.size = Pt(11)
for p_cnt in range(len(src_doc.paragraphs)):
for r_cnt in range(len(src_doc.paragraphs[p_cnt].runs)):
curr_run = src_doc.paragraphs[p_cnt].runs[r_cnt]
print('Run: ', curr_run.text)
paragraph = trg_doc.add_paragraph()
if curr_run.bold:
paragraph.add_run(curr_run.text).bold = True
elif curr_run.italic:
paragraph.add_run(curr_run.text).italic = True
elif curr_run.underline:
paragraph.add_run(curr_run.text).underline = True
else:
paragraph.add_run(curr_run.text)
trg_doc.save('../Output/the_target.docx')
except IOError:
print('There was an error opening the file')
if __name__ == '__main__':
main("../Input/Current_File.docx")
</code></pre>
<p>nput:</p>
<p>1.0 PURPOSE The purpose of this procedure is to ensure all feedback is logged, documented and any resulting complaints are received, evaluated, and reviewed in accordance with 21 CFR Part 820 and ISO 13485</p>
<p>Output:</p>
<p>PURPOSE The purpose of this procedure is to ensure</p>
<p>all feedback is logged,</p>
<p>documented and any resulting complaints are received,</p>
<p>evaluated, and reviewed</p>
<p>in accordance with 21 CFR P art 820</p>
<p>and ISO 13485 .</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T17:32:57.080",
"Id": "466614",
"Score": "0",
"body": "Hello, do you have a question? You want an evaluation? Please describe in words why did you post this question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T17:33:35.613",
"Id": "466615",
"Score": "0",
"body": "Also, could you provide the `stdout`? Where is the `'Run: ', curr_run.text ` output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T13:30:39.917",
"Id": "466713",
"Score": "0",
"body": "Since the `problem` was resolved on stackoverflow that means it was off-topic for this site. Could you please remove the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T12:18:32.610",
"Id": "466832",
"Score": "0",
"body": "[Cross-posted on Stack Overflow](https://stackoverflow.com/q/60379522/1014587)"
}
] |
[
{
"body": "<p>This modification resolves this issue.\nThanks to Scanny at Stack Overflow</p>\n\n<pre><code>for src_paragraph in src_doc.paragraphs:\n tgt_paragraph = tgt_doc.add_paragraph()\n for src_run in src_paragraph.runs:\n print('Run: ', src_run.text)\n tgt_run = tgt_paragraph.add_run(src_run.text)\n if src_run.bold:\n tgt_run.bold = True\n if src_run.italic:\n tgt_run.italic = True\n if src_run.underline:\n tgt_run.underline = True\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T22:42:21.970",
"Id": "237932",
"ParentId": "237919",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T17:25:10.077",
"Id": "237919",
"Score": "1",
"Tags": [
"python"
],
"Title": "Transcribe .docx files via python-docx to modify font and font size. Need to reconstruct paragraphs in target files"
}
|
237919
|
<p>This is not a traditional maze where you find the shortest path (like the gif on the left). In order to solve it, you need to visit every available node before reaching the end, where once a node is visited it turns into a wall (like the gif on the right).</p>
<p><a href="https://i.stack.imgur.com/fYXql.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/fYXql.gif" alt="Incorrect maze gif"></a> <a href="https://i.stack.imgur.com/0HnwW.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/0HnwW.gif" alt="Correct maze gif"></a></p>
<p>My current solution works quickly for smaller mazes or ones with a lot of walls, <a href="https://i.stack.imgur.com/K4cuY.png" rel="noreferrer">such as this</a>, usually finding a path within a couple seconds. But it takes a lot longer as the size of the maze increases or has more open space, <a href="https://i.stack.imgur.com/7icba.png" rel="noreferrer">such as this</a> (nearly 5 minutes to find a path). <strong>Ideally I would like solve mazes up to a 15x20 size in ~30 seconds.</strong></p>
<p>Here is an overview:</p>
<ol>
<li><p>Input the <code>maze</code> (2D list of <code>Tile</code> objects), <code>start</code> node , and <code>end</code> node to the <code>MazeSolver</code> class. </p></li>
<li><p>A neighboring node is chosen (up, right, down, left).</p></li>
<li><p>If that node <code>is_open()</code>, then check if it <code>is_safe()</code> to visit. A node is safe if visiting it will not obstruct our path to any other open node in the maze. This involves an <a href="https://en.wikipedia.org/wiki/A*_search_algorithm" rel="noreferrer">A* search</a> from that node to every other open node, to quickly check if the path exists (every node returned in the path can be skipped for its own search to reduce the number of A* searches).</p></li>
<li><p>If it <code>is_safe()</code>, visit the node and link their <code>next</code> and <code>prev</code> attributes.</p></li>
<li><p>If the node is not open or not safe, add it to the <code>closed</code> list.</p></li>
<li><p>If all 4 neighbors are in <code>closed</code>, backtrack to the previous node.</p></li>
<li><p>Repeat 2-6 until <code>end</code> is reached, return the path if found.</p></li>
</ol>
<p>At this point I am unsure how to improve the algorithm. <strong>I am aware of techniques like <code>cython</code> to speed up the execution time of your code, but my real goal is to add some logic to make the solution smarter and faster.</strong> (Although feel free to recommend these techniques as well, I don't imagine multiprocessing could work here?).</p>
<p>I believe adding some logic as to how a neighbor is chosen may be the next step. Currently, a direction is picked from the list <code>MazeSolver.map</code>, and is used until the neighbor in that direction is not open. Then the next one in the list is chosen, and it just cycles through in order. So there is no intelligent decision making for choosing the neighbor.</p>
<p>Many path finding algorithms assign weights and scores, but how can I tell if one neighbor is more important now than another? The start and end positions can be anywhere in the maze, and you have to visit every node, so the distance to the end node seems insignificant. Or is there a way to predict that a node is not safe without having to do an A* search with each other node? Perhaps separating the maze into smaller chunks and then combining them afterwards would make a difference? All suggestions are welcome, even an entirely new method of solving.</p>
<p>Here is the code.</p>
<pre><code>class Tile:
def __init__(self, row, column):
self.position = (row, column)
self.mode = 1 # 1 = open, 0 = closed (wall)
self.next = self.prev = None
self.closed = []
def __add__(self, other):
return (self.position[0] + other[0], self.position[1] + other[1])
class MazeSolver:
def __init__(self, maze, start, end):
self.maze = maze
self.h, self.w = len(maze) - 1, len(maze[0]) - 1
self.start = maze[start[0]][start[1]]
self.end = maze[end[0]][end[1]]
self.current = self.start
self.map = [(-1, 0), (0, 1), (1, 0), (0, -1)] # Up, right, down, left
def solve(self):
i = 0
while self.current != self.end:
node = self.current + self.map[i]
if self.is_open(node):
if self.is_safe(node):
# Link two nodes like a Linked List
self.current.next = self.maze[node[0]][node[1]]
self.current.next.prev = self.current
self.current.mode -= 1
self.current = self.current.next
continue
else:
self.current.closed.append(node)
else:
i += 1 if i < 3 else -3 # Cycle through indexes in self.map
if len(self.current.closed) == 4:
if self.current == self.start:
# No where to go from starting node, no path exists.
return 0
self.current.closed = []
self.current = self.current.prev
self.current.mode += 1
self.current.closed.append(self.current.next.position)
return self.get_path()
def is_open(self, node):
'''Check if node is open (mode = 1)'''
if node in self.current.closed:
return 0
elif any([node[0]>self.h, node[0]<0, node[1]>self.w, node[1]<0]):
# Node is out of bounds
self.current.closed.append(node)
return 0
elif self.maze[node[0]][node[1]].mode == 0:
self.current.closed.append(node)
return self.maze[node[0]][node[1]].mode
def is_safe(self, node):
'''Check if path is obstructed when node is visitied'''
nodes = [t.position for row in self.maze for t in row if t.mode > 0]
nodes.remove(self.current.position)
# Sorting positions by greatest manhattan distance (which reduces calls to astar)
# decreases solve time for the small maze but increases it for the large maze.
# Thus at some point the cost of sorting outweighs the benefit of fewer A* searches.
# So I have left it commented out:
#nodes.sort(reverse=True, key=lambda x: abs(node[0] - x[0]) + abs(node[1] - x[1]))
board = [[tile.mode for tile in row] for row in self.maze]
board[self.current.position[0]][self.current.position[1]] = 0
checked = []
for goal in nodes:
if goal in checked:
continue
sub_maze = self.astar(board, node, goal)
if not sub_maze:
return False
else:
checked = list(set(checked + sub_maze))
return True
def astar(self, maze, start, end):
'''An implementation of the A* search algorithm'''
start_node = Node(None, start)
end_node = Node(None, end)
open_list = [start_node]
closed_list = []
while len(open_list) > 0:
current_node = open_list[0]
current_index = 0
for index, item in enumerate(open_list):
if item.f < current_node.f:
current_node = item
current_index = index
open_list.pop(current_index)
closed_list.append(current_node)
if current_node == end_node:
path = []
current = current_node
while current is not None:
path.append(current.position)
current = current.parent
return path
children = []
for new_position in [(0, -1), (0, 1), (-1, 0), (1, 0)]:
node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1])
if node_position[0] > (len(maze) - 1) or node_position[0] < 0 or node_position[1] > (len(maze[0]) -1) or node_position[1] < 0:
continue
if maze[node_position[0]][node_position[1]] == 0:
continue
new_node = Node(current_node, node_position)
children.append(new_node)
for child in children:
if child in closed_list:
continue
child.g = current_node.g + 1
child.h = ((child.position[0] - end_node.position[0])**2) + ((child.position[1] - end_node.position[1])**2)
child.f = child.g + child.h
if child in open_list:
if child.g > open_list[open_list.index(child)].g:
continue
open_list.append(child)
return []
def get_path(self):
path = []
pointer = self.start
while pointer is not None:
path.append(pointer.position)
pointer = pointer.next
return path
class Node:
'''Only used by the MazeSolver.astar() function'''
def __init__(self, parent=None, position=None):
self.parent = parent
self.position = position
self.g = self.h = self.f = 0
def __eq__(self, other):
return self.position == other.position
</code></pre>
<p>If you would like to run the mazes from the pictures I linked above (<a href="https://i.stack.imgur.com/K4cuY.png" rel="noreferrer">Small</a>, <a href="https://i.stack.imgur.com/7icba.png" rel="noreferrer">Large</a>):</p>
<pre><code>import time
def small_maze():
maze = [[Tile(r, c) for c in range(11)] for r in range(4)]
maze[1][1].mode = 0
for i in range(11):
if i not in [3, 8]:
maze[3][i].mode = 0
return maze
def large_maze():
maze = [[Tile(r, c) for c in range(15)] for r in range(10)]
for i in range(5, 8):
maze[4][i].mode = 0
maze[5][5].mode = maze[5][7].mode = maze[6][5].mode = 0
return maze
C = MazeSolver(small_maze(), (3, 8), (3, 3)) #(large_maze(), (2, 2), (5, 6))
t = time.time()
path = C.solve()
print(round(time.time() - t, 2), f'seconds\n\n{path}')
# The end node should always have some walls around it to avoid
# the need to check if it was reached prematurely.
</code></pre>
<p><hr>
<strong>Edit:</strong></p>
<p>Thanks to trentcl for pointing out that this problem is a Hamiltonian path. I have rewritten the code to represent the maze as an adjacency matrix, and implemented the Hamiltonian path algorithm based on <a href="https://www.geeksforgeeks.org/hamiltonian-cycle-backtracking-6/" rel="noreferrer">this tutorial</a>. The performance on the small maze was identical to my original method, but was much slower on the large maze (I interrupted the execution after 15 minutes). </p>
<pre><code>class MazeSolver:
def __init__(self, maze, start):
graph = self.to_graph(maze)
self.n = len(graph)
vertices = list(graph.keys())
self.key_map = {vertices[i]: i for i in range(self.n)}
self.graph = self.to_matrix(graph)
self.start = self.key_map[start]
def to_graph(self, maze):
'''Convert maze to graph with the structure {position: [neighbor positions]}'''
graph = {(r, c): [] for c in range(len(maze[0])) for r in range(len(maze)) if maze[r][c]}
for r, c in graph.keys():
for pos in [(r-1, c), (r+1, c), (r, c-1), (r, c+1)]:
try:
if maze[pos[0]][pos[1]] and pos[0] >= 0 and pos[1] >= 0:
graph[(r, c)].append(pos)
except IndexError:
pass
return graph
def to_matrix(self, graph):
'''Convert graph to adjacency matrix.
matrix[i][j] == 1 indicates there is an edge from i to j'''
edges = [(vertex, neighbor) for vertex in graph for neighbor in graph[vertex]]
edge_numbers = [(self.key_map[edge[0]], self.key_map[edge[1]]) for edge in edges]
matrix = [[0] * self.n for i in range(self.n)]
for edge in edge_numbers:
matrix[edge[0]][edge[1]] = 1
return matrix
def solve(self):
path = [-1] * self.n
path[0] = self.start
if self.hamiltonian_path(path, 1):
index_map = {v: k for k, v in self.key_map.items()}
return [index_map[vertex] for vertex in path]
else:
return 0
def hamiltonian_path(self, path, pos):
if pos == self.n:
return True
for v in range(self.n):
if self.is_safe(v, pos, path):
path[pos] = v
if self.hamiltonian_path(path, pos+1):
return True
path[pos] = -1
return False
def is_safe(self, v, pos, path):
if self.graph[path[pos-1]][v] == 0:
return False
return all(vertex != v for vertex in path)
def small_maze():
maze = [[1] * 11 for i in range(4)]
maze[1][1] = 0
for i in range(11):
if i not in [3, 8]:
maze[3][i] = 0
return maze
def large_maze():
maze = [[1] * 15 for i in range(10)]
for i in range(5, 8):
maze[4][i] = 0
maze[5][5] = maze[5][7] = maze[6][5] = 0
return maze
C = MazeSolver(small_maze(), (3, 8)) #(large_maze(), (2, 2))
t = time.time()
path = C.solve()
print(round(time.time() - t, 2), f'seconds\n\n{path}')
</code></pre>
<p><a href="https://www.hackerearth.com/practice/algorithms/graphs/hamiltonian-path/tutorial/" rel="noreferrer">Another tutorial</a> discusses a faster method using dynamic programming, called the Held-Karp algorithm. However, it seems to perform even worse (<em>I had to interrupt the execution for the small maze</em>). I don't know if I implemented it incorrectly because it worked with the tiny maze I used in the gifs.</p>
<pre><code> def check_using_dp(self):
n = self.n
dp = [[False] * (1 << n) for i in range(n)]
for i in range(n):
dp[i][1 << i] = True
for i in range(1 << n):
for j in range(n):
if i & (1 << j):
for k in range(n):
if j != k and (i & (1 << k)) and self.graph[k][j] and dp[k][i ^ (1 << j)]:
dp[j][i] = True
break
for i in range(n):
if dp[i][(1 << n) - 1]:
return True
return False
maze = [[0, 0, 1, 1, 0],
[1, 1, 1, 1, 1],
[1, 0, 0, 0, 0]]
C = MazeSolver(maze, (1, 4))
C.check_using_dp()
</code></pre>
<p>I don't understand how it could be faster when it contains a loop of <code>2**n</code> iterations (in the case of the small maze this is 17 billion). Can someone explain to me how to implement this algorithm properly?</p>
<p>The most time consuming calculations in my original method are the A* searches. Realizing that an open node only accessible from 1 direction is automatically not safe (except for the end node), I added a check in <code>is_safe()</code> before any calls to <code>astar()</code> to return False if any open node has less than two open neighbors. This resulted in a huge improvement in performance, solving the large maze in 14 seconds! Is it possible to achieve this level of performance with Hamiltonian path algorithms? </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T18:55:31.270",
"Id": "466618",
"Score": "4",
"body": "You're looking for a [Hamiltonian path](https://en.wikipedia.org/wiki/Hamiltonian_path) in the undirected graph of open nodes with given start and end points."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T19:04:57.733",
"Id": "466619",
"Score": "0",
"body": "Thanks, I will read about it and try to implement it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T11:13:06.953",
"Id": "466703",
"Score": "0",
"body": "@alec networkx has some functionality for finding Hamiltonian paths."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T22:12:30.900",
"Id": "466909",
"Score": "0",
"body": "Unfortunately it is only for directed graphs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T07:39:32.647",
"Id": "466939",
"Score": "0",
"body": "Please don't update the question. Just ask another one with the new code that you need reviewed and make a small reference to this question for more context."
}
] |
[
{
"body": "<p>Instead of using a different function for your dynamic programming solution (which I believe, if done correctly, will solve your problem), just add an lru_cache decorator to your recursive hamiltonian path function. Make sure to make the arguments sent to that function immutable (tuples recommended). Try it and let us know.</p>\n\n<p>It should look something like:</p>\n\n<pre><code>from functools import lru_cache\n\n@lru_cache\ndef hamiltonian_path(self, path, pos):\n path = list(path)\n if pos == self.n:\n return True\n\n for v in range(self.n):\n if self.is_safe(v, pos, path):\n path[pos] = v\n\n if self.hamiltonian_path(tuple(path), pos+1):\n return True\n path[pos] = -1\n\n return False\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T07:24:28.367",
"Id": "466936",
"Score": "0",
"body": "This would certainly be convenient, but the function needs to pass a list specifically because it's a mutable type, and when it gets updated this is reflected in all copies. I will give a shot at rewriting the structure to work with tuples but just casting between list and tuple in the existing code doesn't get the result."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T04:00:31.113",
"Id": "238083",
"ParentId": "237922",
"Score": "2"
}
},
{
"body": "<p>Have you run a profiler on your code? It would help identify where the code is spending most of its time. If I had to guess, I would say the A* search is taking up most of the time for larger mazes. Try using a <a href=\"https://en.wikipedia.org/wiki/Flood_fill\" rel=\"nofollow noreferrer\">flood fill</a> algorithm instead. If all the empty squares don't change to the same color, then a move has created two disconnected areas and the move is unsafe.</p>\n\n<p>I also don't think you need to check every move to see if it is safe. Only check when a move is likely to be unsafe. For example, the current tile isn't touching a wall (or used tile), but the next tile would be touching.</p>\n\n<p>Pre-calculate all possible moves for small groups of tiles may help. Say 2x2, 2X3, 3x3, ... 5x6, etc. Then use them to try to solve a smaller maze.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T07:30:18.517",
"Id": "466937",
"Score": "0",
"body": "Yes the A* search is the most time consuming calculation, I mentioned in the last paragraph of the question. Using a flood fill algorithm seems like a great idea! I'd imagine one flood fill would be a lot faster than multiple A* searches. Identifying when a move is likely to be unsafe is a bit trickier. I will try these suggestions tomorrow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T19:51:30.733",
"Id": "467098",
"Score": "0",
"body": "Using a flood fill turned out to be a fantastic suggestion, thank you. The execution time to solve the large maze decreased from 14 seconds all the way down to 0.85 seconds!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T06:55:03.330",
"Id": "238088",
"ParentId": "237922",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T18:42:09.903",
"Id": "237922",
"Score": "11",
"Tags": [
"python",
"performance",
"python-3.x",
"pathfinding"
],
"Title": "Path finding solution for a maze whose state changes during the solve"
}
|
237922
|
<p>I recently downloaded an app called "SoloLearn" to improve my coding skills as I am a beginner with Java while I am not at home. Today I solved the following challenge: <a href="https://i.stack.imgur.com/QTkGF.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QTkGF.jpg" alt="challenge"></a>
Everything worked but I have a feeling that there is a much easier way to get it done.
Here is my code:</p>
<pre><code>import java.util.ArrayList;
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String input = s.nextLine();
s.close();
System.out.println(replace(input));
}
public static String replace(String input)
{
ArrayList <Integer> numbers= new ArrayList<>();
for(int i = 0; i < input.length(); i++)
{
String number = input.substring(i, i + 1);
String lastChar;
if(i != 0)
lastChar = input.substring(i - 1, i);
else
lastChar = "";
if(isNumber(number) && Integer.parseInt(number) >= 0 && Integer.parseInt(number)<= 10)
{
numbers.add(Integer.parseInt(number));
}
if(lastChar.equals("1") && number.equals("0"))
{
numbers.add(10);
}
}
String replacer = "";
if(numbers.size() > 0)
{
for(int number : numbers)
{
switch(number)
{
case 0: replacer = "zero";
break;
case 1: replacer = "one";
break;
case 2: replacer = "two";
break;
case 3: replacer = "three";
break;
case 4: replacer = "four";
break;
case 5: replacer = "five";
break;
case 6: replacer = "six";
break;
case 7: replacer = "seven";
break;
case 8: replacer = "eight";
break;
case 9: replacer = "nine";
break;
case 10: replacer = "ten";
break;
}
input = input.replace(number + "", replacer);
}
} else
{
return input;
}
input = input.replace("onezero","ten");
return input;
}
public static boolean isNumber(String word)
{
try
{
Integer.parseInt(word);
} catch(NumberFormatException e)
{
return false;
}
return true;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T20:10:32.273",
"Id": "466623",
"Score": "10",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles. Also, please copy and paste the text of the task description instead of embedding an image."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T04:21:10.197",
"Id": "466659",
"Score": "1",
"body": "I hate it when such challenges are themselves written by utter nitwits. I mean you've got a lot of **number characters** but you decide that for **numbers 10 or under** you replace with the word. What the f* is a \"number character\"? Has the writer ever considered calling it a **digit**? \"He who cannot teaches\" in optima forma."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T06:36:35.143",
"Id": "466667",
"Score": "1",
"body": "Bug: in the string `\"1 1111\"` all digits are replaced."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T06:37:30.123",
"Id": "466668",
"Score": "1",
"body": "To make this question complete, please add your unit tests so that we can see which edge cases you forgot to handle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T09:18:31.657",
"Id": "466688",
"Score": "3",
"body": "Welcome to Code Review! Your image of text [isn't very helpful](//meta.unix.stackexchange.com/q/4086). It can't be read aloud or copied into an editor, and it doesn't index very well. Additionally, there's no indication that you're permitted to re-publish it here. Please [edit] your post to incorporate your own description of the challenge."
}
] |
[
{
"body": "<h2>better splitting method</h2>\n\n<p>instead of comparing each character of the string, use an regex! </p>\n\n<pre><code>String input = ...\nString output = new String(input);\nPattern p = Pattern.compile(\"\\\\d+\");\nMatcher m = p.matcher(input);\nwhile(m.find()) {\n String occurrence = m.group();\n int number = Integer.parseInt(m.group());\n if (number >= 0 && number <=10){\n String numberWord = replace(number);\n output = output.substring(0,m.start())+\n output.substring(m.start()).replace(occurrence, numberWord);\n }\n}\n</code></pre>\n\n<h2>avoid magic numbers</h2>\n\n<p>instead of returning the replacement for numbers in code you should define them separately - this allows you to change language easier and offers more maintaince on further usage. (here magic numbers are these <code>Strings</code> of wach number)</p>\n\n<pre><code>private final String[] mapping = {\"zero\", \"one\", ..., \"ten\"};\n\npublic String replace(int number){\n return mapping[number];\n}\n</code></pre>\n\n<h2>naming</h2>\n\n<p><code>replace</code> is a generic name and should have a better name. <code>toWord</code> might be more suitable but it's up to you.</p>\n\n<h2>fun fact</h2>\n\n<p><a href=\"https://i.stack.imgur.com/UnslF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UnslF.png\" alt=\"enter image description here\"></a>\n(Copyright: <a href=\"https://xkcd.com/208/\" rel=\"nofollow noreferrer\">XKCD</a>)</p>\n\n<h2>improvement</h2>\n\n<p>thanks to <a href=\"https://codereview.stackexchange.com/users/2035/rotora\">RoToRa</a> i learned how to properly use <code>StringBuffer</code> and <code>Matcher</code> </p>\n\n<pre><code>String input = ...\nPattern p = Pattern.compile(\"\\\\d+\");\nMatcher m = p.matcher(input);\nStringBuffer sb = new StringBuffer();\nwhile (m.find()) {\n int number = Integer.parseInt(m.group());\n if (number >= 0 && number <=10){\n m.appendReplacement(sb, mapping[number]);\n }\n}\nm.appendTail(sb);\nString output = sb.toString();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T08:58:10.273",
"Id": "466811",
"Score": "1",
"body": "This solution doesn't work. `String.replace` will always replace the first occurrence even if it was skipped in previous iterations of the loop. For example, `\"12 and 1\"` becomes `\"one2 and one\"`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T09:31:28.203",
"Id": "466815",
"Score": "0",
"body": "@RoTaRa sorry, you are right, it replaces the first occurences - i've enriched my test string into the following: `String input = \"i need 12 apples and 4 pumpkins - at 10 o'clock. There is 0 chance of failing. and 1 for the test\";` i have adjusted the code - thank you very much for pointing that out!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T09:38:30.513",
"Id": "466816",
"Score": "2",
"body": "BTW, have a look at `Matcher`s methods `appendReplacement` and `appendTail` which were designed to handle multiple replacements like this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T09:51:42.957",
"Id": "466818",
"Score": "0",
"body": "@RoTaRa - i was reading the [Matcher API](https://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html) but i'm still not very good in using regexs - thanks you for sharing your knowledge! (i'll adjust my answer, when i know how to apply your hints)... **as Graditude i'll add a pic from XKCD** that came up to my mind, when working with regex..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T10:01:15.387",
"Id": "466823",
"Score": "1",
"body": "There are many cases where regular expressions are either over-kill or create difficult to understand code, however in this case I believe it is a good solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T12:10:56.917",
"Id": "466830",
"Score": "0",
"body": "XKCD : fixed now! - thank you very much =)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T12:29:36.620",
"Id": "466834",
"Score": "1",
"body": "@MartinFrank I've added an enhanced solution as answer. I hope your solution stays the accepted one as it more closely matches the challenge level."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T09:50:38.167",
"Id": "237960",
"ParentId": "237924",
"Score": "3"
}
},
{
"body": "<p>I think that using a <code>StringBuilder</code> rather than manipulating the input string, would be more appropriate here. Using a string array of the number words can reduce the whole thing to basically a simple loop. Something like this would work:</p>\n\n<pre><code>static String[] words = {\n \"zero\",\n \"one\",\n \"two\",\n \"three\",\n \"four\",\n \"five\",\n \"six\",\n \"seven\",\n \"eight\",\n \"nine\",\n \"ten\"\n};\nstatic String replaceNums(String input) {\n StringBuilder sb = new StringBuilder();\n int limit = input.length();\n for (int i = 0; i < limit; ++i) {\n char temp = input.charAt(i);\n if (Character.isDigit(temp)) {\n if (i < limit - 1 && temp == '1' && input.charAt(i + 1) == '0') {\n sb.append(words[10]);\n ++i;\n } else {\n sb.append(words[temp - '0']);\n }\n } else {\n sb.append(temp);\n }\n }\n return sb.toString();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T08:49:16.247",
"Id": "466808",
"Score": "1",
"body": "This solution replaces all numbers greater than 10, for example `\"11\"` becomes `\"oneone\"`, but should stay `\"11\"`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T11:46:52.637",
"Id": "466828",
"Score": "0",
"body": "Thank you, I am going to take a look at the String Builder Class."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T16:26:12.137",
"Id": "237981",
"ParentId": "237924",
"Score": "1"
}
},
{
"body": "<p>The deeper you go the more exceptions you'll find when it comes to the number representation. It is for a reason that the text is just lowercase, but it doesn't specify if you can find e.g. floating points.</p>\n\n<p>Here is a more advanced example which tries to be a bit more practical for real world situations and minimizes the code. Note also the use of constants (<code>static final</code> class fields in Java).</p>\n\n<p>Also note the explanation of the regular expression in the comments. For hard-to-read regular expressions I would very much add this in my own code as well, and explain <strong>what</strong> it tries to do at the very least. Otherwise the next programmers will have a hell of a time figuring it out themselves.</p>\n\n<p>Code without integer literals should generally be preferred over code with integer literals most of the time. Let the computer do the counting.</p>\n\n<pre><code>private static final String[] NUMBER_NAMES = new String[] { \"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\",\n \"seven\", \"eight\", \"nine\", \"ten\" };\n\n// A digit which is not preceded or followed by another word character,\n// using negative lookbehind & lookahead).\n// Word characters (`\\\\w`) include digits.\n// Comma's and dots are also excluded. 10 is a special case.\nprivate static final Pattern NUMBER_PATTERN = Pattern.compile(\"(?<!(\\\\w|[.,]))(\\\\d|10)(?!(\\\\w|[.,]))\");\n\npublic static String replaceNumbersWithNumberNames(String test) {\n StringBuilder lineWithNumberNames = new StringBuilder();\n Matcher numberMatcher = NUMBER_PATTERN.matcher(test);\n while (numberMatcher.find()) {\n String numberName = NUMBER_NAMES[Integer.parseInt(numberMatcher.group())];\n numberMatcher.appendReplacement(lineWithNumberNames, numberName);\n }\n numberMatcher.appendTail(lineWithNumberNames);\n return lineWithNumberNames.toString();\n}\n\npublic static void main(String[] args) {\n // digit at start, end, within a word, a 10 and 100, handled correctly!\n String test = \"4 (nor 10 or 100 nor 0.5, even if you're XS4ALL) shalt thou not count,\"\n + \" neither shalt thou count 2, excepting that thou then proceedeth to 3\";\n System.out.println(replaceNumbersWithNumberNames(test));\n}\n</code></pre>\n\n<p>This will print:</p>\n\n<pre><code>four (nor ten or 100 nor 0.5, even if you're XS4ALL) shalt thou not count, \\\nneither shalt thou count two, excepting that thou then proceedeth to three\n</code></pre>\n\n<p>Apologies for the Pythons for the addition between parentheses.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T12:40:25.373",
"Id": "466837",
"Score": "0",
"body": "i did the same right now =) and added that to my answer - RoToRa pointed out the same point as you do... (proper usage of Regex and Stringbuffer)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T12:41:09.507",
"Id": "466838",
"Score": "0",
"body": "your regex is better! far better +1"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T12:21:58.227",
"Id": "238034",
"ParentId": "237924",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T19:31:14.837",
"Id": "237924",
"Score": "-2",
"Tags": [
"java"
],
"Title": "How do I simplify the following code which solves the attached challenge?"
}
|
237924
|
<p>There is a popular game called <a href="https://play.google.com/store/apps/details?id=de.lotum.whatsinthefoto.us" rel="nofollow noreferrer">4 Pics 1 Word</a> that presents to the user 4 pictures representing a common word. The word has to be typed by selecting some of the 9 random letters appearing below the images.</p>
<p>The German version of this app has an annoying bug. When the random letters contain a letter from the set ÄÖÜß, it is guaranteed that the desired word contains this letter. This is unfair. The algorithm for picking the random letters seems to be: take the letters of the word and fill up the rest with equally distributed letters from the alphabet A-Z. This algorithm can be implemented fast but often selects a Q without the corresponding U.</p>
<p>I wanted to see whether it is possible to generate random letters that are "more naturally random". The first step to reach this goal is to pick the letters according to the frequency they appear in the corpus of all words to be guessed. The following code does exactly that.</p>
<p>I know that the code is slow and can be optimized for speed in several ways. That's not the point of the code. The main purpose is to serve as the reference implementation that is as simple to understand (and mathematically verify) as possible. It should clearly demonstrate the underlying concepts and ideas. It can later be compared with more optimized versions of the code, to verify that the probabilities in the optimized code are still correct.</p>
<pre><code>package de.roland_illig.wordprob
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
/**
* Given a [word] from a set of [words], generate [n] random letters
* that contain all the letters from the [word].
* The returned letters should be "as random as possible".
*/
fun randomLetters(
words: Set<String>,
word: String,
n: Int,
rnd: (Int) -> Int
): String {
require(word in words) { word }
require(n >= word.length) { "$n < $word" }
val wordCodePoints = word.codePoints().toArray()
val allLetters = words.joinToString("").codePoints().toArray()
while (true) {
val codePoints = IntArray(n) { allLetters[rnd(allLetters.size)] }
if (codePoints.containsAll(wordCodePoints))
return String(codePoints, 0, codePoints.size)
}
}
private fun IntArray.containsAll(sub: IntArray): Boolean {
val remaining = mutableMapOf<Int, Int>()
for (cp in this) remaining[cp] = (remaining[cp] ?: 0) + 1
for (cp in sub) {
val rem = remaining[cp] ?: return false
if (rem == 0) return false
remaining[cp] = rem - 1
}
return true
}
class WordProbabilitiesKtTest {
private val seqs = mutableListOf<Seq>()
@AfterEach
fun tearDown() {
for (seq in seqs) {
check(seq.i == seq.ns.size) {
"partly used sequence ${seq.ns.asList()}"
}
}
}
@Test
fun containsAll() {
fun Array<Int>.containsAll(sub: Array<Int>) =
toIntArray().containsAll(sub.toIntArray())
assertThat(arrayOf(1, 2, 3).containsAll(arrayOf(1, 2, 3))).isTrue()
assertThat(arrayOf(1, 2, 3).containsAll(arrayOf(1, 2))).isTrue()
assertThat(arrayOf(1, 2, 3).containsAll(arrayOf())).isTrue()
assertThat(arrayOf(1, 2, 3).containsAll(arrayOf(1, 1))).isFalse()
assertThat(arrayOf(1, 2, 3).containsAll(arrayOf(4))).isFalse()
}
@Test
fun randomLetters() {
assertThat(randomLetters(setOf("a", "b"), "a", 1, seq(0))).isEqualTo("a")
assertThat(randomLetters(setOf("a", "b"), "b", 1, seq(1))).isEqualTo("b")
assertThat(randomLetters(setOf("a", "b"), "a", 1, seq(1, 0))).isEqualTo("a")
assertThat(randomLetters(setOf("a", "b"), "a", 2, seq(1, 0))).isEqualTo("ba")
assertThat(randomLetters(
setOf("cat", "dog"),
"cat",
3,
seq(3, 4, 5, 1, 3, 5, 1, 0, 2)
)).isEqualTo("act")
}
@Test
fun `randomLetters, generator exhausted`() {
assertThatThrownBy { randomLetters(setOf("a", "b"), "a", 2, seq(1, 1, 1, 1, 1)) }
.isExactlyInstanceOf(ArrayIndexOutOfBoundsException::class.java)
}
@Test
@Disabled("Tests the test code, fails too late, at tearDown")
fun `randomLetters, generator partly used`() {
randomLetters(setOf("a", "b"), "a", 2, seq(1, 1, 1, 1, 1, 0, 0, 7))
}
private fun seq(vararg ns: Int): (Int) -> Int {
val seq = Seq(*ns).also { seqs += it }
return { seq.next() }
}
private class Seq(internal vararg val ns: Int) {
internal var i = 0
fun next(): Int = ns[i].also {
check(i < ns.size) { "reached end of ${ns.asList()}" }
i++
}
}
}
</code></pre>
<p>A future version of that code might take into account that in German, the letter Q is always followed by a U. This could be based on a Markov chain. But for now I am satisfied with fixing the unfair distribution of single letters.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T15:21:31.593",
"Id": "466720",
"Score": "1",
"body": "Other then advising you should to look into Property-testing, I don't have any advice..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T00:30:17.823",
"Id": "467669",
"Score": "1",
"body": "If I'm not mistaken, you search for letters until you've got all letters of the word. However, that might take forever. It's better to first add the letters of word and then fill up with random letters from the word list. Finally, **shuffle** the characters. You could remove the word from the list of words or not, that's up to you."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T19:34:27.110",
"Id": "237925",
"Score": "1",
"Tags": [
"random",
"kotlin"
],
"Title": "Generate random letters containing a word"
}
|
237925
|
<p>I am trying to XOR two files each 1Mb which contains only 0 and 1. It works, but I think it is very slow for the C++ program - approximately 4 sec.</p>
<p>Could someone, please, suggest the fastest XOR method on large files or at least tell what you think about XORing 1MB files running time? May 0.5sec or 1sec? or even less...
What should be my goal related to time?</p>
<p>PS
Yes, I did not read files by chunks or mapping them.</p>
<pre><code>#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <iterator>
using namespace std;
inline std::vector<int> read_vector_from_disk(std::string file_path)
{
std::ifstream instream(file_path, std::ios::in | std::ios::binary);
std::vector<int> data((std::istreambuf_iterator<char>(instream)), std::istreambuf_iterator<char>());
return data;
}
int main()
{
// Open result file.
fstream new_file;
new_file.open("output.txt", ios::out | ios::app);
if (!new_file)
{
cout << "File creation failed";
}
// Here we will store the result
std::vector<int> xored_file;
std::vector<int> in_data = read_vector_from_disk("first_arg.txt");
std::vector<int> out_data = read_vector_from_disk("second_arg.txt");
//creating iterator
vector<int>::iterator first_iter = in_data.begin();
vector<int>::iterator second_iter = out_data.begin();
//printing all elements
cout << "XOR-ed elements are: ";
for (; first_iter != in_data.end() && second_iter != out_data.end(); first_iter++, second_iter++)
{
int xored = *first_iter ^ *second_iter;
xored_file.push_back(xored);
}
// Print result.
vector<int>::iterator out_iter = xored_file.begin();
for (; out_iter != xored_file.end(); out_iter++)
{
new_file << *out_iter;
}
cout << "Complete";
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T20:15:31.653",
"Id": "466624",
"Score": "1",
"body": "Please provide the command / flags / settings you use to compile this program. Also to give you a (rough) reference: The expected speed of a proper implementation of this should be ~1ms for the actual operation and maybe 10ms or so for the IO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T08:55:08.163",
"Id": "466685",
"Score": "0",
"body": "Can you be more specific about the input and output format? From the code, it's hard to tell what you mean. Obviously, all files contain only 0 and 1 at the bit level, so are you saying that every character in the file is one of two values? If so, which two - `0` and `1`, or `'0'` and `'1'`?"
}
] |
[
{
"body": "<blockquote>\n<pre><code>#include <cstring>\n</code></pre>\n</blockquote>\n\n<p>seems unused.</p>\n\n<blockquote>\n<pre><code>using namespace std;\n</code></pre>\n</blockquote>\n\n<p>Not a good plan - just use the <code>std::</code> qualifier, or import just the names you need, in the smallest reasonable scope.</p>\n\n<blockquote>\n<pre><code>inline std::vector<int> read_vector_from_disk(std::string file_path)\n{\n std::ifstream instream(file_path, std::ios::in | std::ios::binary);\n std::vector<int> data((std::istreambuf_iterator<char>(instream)), std::istreambuf_iterator<char>());\n return data;\n}\n</code></pre>\n</blockquote>\n\n<p>This is a very inefficient way to copy a file into memory - the vector will likely have to reallocate (copying its contents) several times, as the input iterators can't be used to predict the eventual size.</p>\n\n<p>Two faster approaches would be</p>\n\n<ul>\n<li>memory-map the file contents, probably using Boost::interprocess</li>\n<li>work in a streaming fashion with character-by-character input (e.g. using <code>std::transform()</code>)</li>\n</ul>\n\n<p>Also, there's no check whether any of this reading succeeded at all. That's bad.</p>\n\n<blockquote>\n<pre><code>std::vector<int> xored_file;\n</code></pre>\n</blockquote>\n\n<p>Again, we have a vector we'll append to without first reserving capacity. That's reducing your efficiency. I don't see why we need to store a copy of output, instead of immediately writing it to the output stream.</p>\n\n<p>When we've finished writing, we should close the file and confirm that it was successfully written:</p>\n\n<pre><code>new_file.close();\nif (!new_file) {\n std::cerr << \"Failed to write output file\\n\";\n return EXIT_FAILURE;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T05:55:24.260",
"Id": "466663",
"Score": "0",
"body": "Thanks for the detailed answer! Just some things worth mentioning by me:\n- I have used `vactor<int>` due to be sure that 0's and 1's which I read from files are integer and I will be able to XOR them just 0 and 1 and not a chars"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T08:36:23.123",
"Id": "466677",
"Score": "0",
"body": "Oh, that's a good point - `unsigned char` would probably be a better choice for bitwise operations."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T20:30:35.497",
"Id": "237927",
"ParentId": "237926",
"Score": "6"
}
},
{
"body": "<p>Since streams have iterators, you can save a lot of time by processing the files directly. As has been pointed out <code>std::transform</code> works wonders in this regard.</p>\n\n<p>I would also suggest putting the algorithm in a function and keep <code>main</code> uncluttered.</p>\n\n<p>Returning 0 from <code>main</code> is no longer necessary with modern compilers. If yours needs it, upgrade it.</p>\n\n<p>A function using stream iterators could look something like this:</p>\n\n<pre><code>#include <iostream>\n#include <fstream>\n#include <algorithm>\n#include <iterator>\n#include<ios>\n\ntypedef std::istreambuf_iterator<char> ItIn;\ntypedef std::ostreambuf_iterator<char> ItOut;\n\nusing std::string;\nusing std::ifstream;\nusing std::ofstream;\nusing std::ios;\n\nvoid xor2files(string inFile1, string inFile2, string outFile)\n{\n ifstream in1(inFile1, ios::in | ios::binary);\n ifstream in2(inFile2, ios::in | ios::binary);\n ofstream out(outFile, ios::out);\n if (!in1 || !in2 || !out)\n {\n std::cerr << \"Invalid file name\";\n }\n ItIn itIn1(in1);\n ItIn itIn2(in2);\n ItOut itOut(out);\n ItIn end;\n std::transform(itIn1, end, itIn2, itOut,\n [](char a, char b) -> char {return (char)(((a - '0') ^ (b - '0')) + '0'); });\n}\nint main()\n{\n\n string first = \"first_arg.txt\";\n string second = \"second_arg.txt\";\n string out = \"output.txt\";\n xor2files(first, second, out);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T08:39:19.517",
"Id": "466678",
"Score": "0",
"body": "That's pretty much what I had in mind when I mentioned `std::transform` - thanks for expanding on that. Probably worth mentioning that some error checking is required after the transform as well as before."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T08:40:28.047",
"Id": "466679",
"Score": "1",
"body": "That lambda is almost unreadable (add linebreaks!) and contains a C-style cast. The error handling is ambiguous (you only guess that the file name is somehow invalid) and lacks a `return`. Lastly, note that the output is writing char-values formatted as integers in the original code. That's a problem with that code being a bit unclear, but your code does something different."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T08:46:30.533",
"Id": "466682",
"Score": "0",
"body": "My imagination had a simple `std::bit_xor{}` rather than that lambda, but perhaps I misinterpreted the problem statement?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T08:51:49.197",
"Id": "466684",
"Score": "0",
"body": "Also, to get the same behaviour as the original (stop output at the end of the shortest file), we may need to `std::swap(itIn1, itIn2)` so that the shorter input comes first."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T10:08:26.090",
"Id": "466694",
"Score": "0",
"body": "Thanks, this is working fine I just changed ```return (char)``` to ```return (int)``` due to in the first case in output file I've got the same which in my previous codes)) - \"NUL NUL NUL\" - (ASCII of 0???)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T06:38:58.803",
"Id": "237949",
"ParentId": "237926",
"Score": "3"
}
},
{
"body": "<h1>Efficiency</h1>\n<p>There are several parts in your program that all take time:</p>\n<ul>\n<li>Reading two files.</li>\n<li>Allocating memory (input vectors and output vector).</li>\n<li>Performing the XOR loop.</li>\n<li>Writing one file.</li>\n</ul>\n<p>Reading and writing are probably the most expensive parts, because they require IO, but that part can not be removed. Another aspect is parsing and formatting, which might be improved a bit, but I wouldn't bother with this at the moment. For the future, an as you mentioned yourself, memory-mapping the raw bytes would probably be the fastest way.</p>\n<p>Allocating memory and the algorithm are a different beast. You run through the input files to build up the two vectors. Then, you run through the vectors and perform an algorithm on the pairwise elements. Finally, you discard the two vectors again. The relevant point to observe is that you only need each element once and exactly in the order that they occur in the input file. So, you can simplify this part by just reading two elements and then writing the result of the XOR. That way, you only need two local variables and no memory allocation for the vectors. This is the first optimization I'd try.</p>\n<p>Concerning your question what performance to expect, my gut feeling is similar to yours, that 4s is too long. However, this depends a lot on the computer you use. What you could do to find out is to write a benchmark. Simply write 1M zeros and ones to a file and measure how long that takes. Similarly, just read the files, immediately discarding each value. Compare that to reading and storing the data in a vector as well. With these numbers, you should get a better feeling what to expect and also which part takes how much time.</p>\n<h1>Further Notes</h1>\n<ul>\n<li>It's not really clear what your code expects as input format and output format. You are using <code>istream_iterator<char></code>, which takes single characters. However, it still skips whitespace. I guess you don't expect any whitespace within the files, but that isn't obvious.</li>\n<li>Another aspect of this is that you blow up a <code>char</code> to a <code>int</code>. This quadruples the memory requirement without any benefit. Further, and that's really bad, you take a letter (like "1" or "0"), then treat it as integer (with ASCII encoding, that's 49 and 48) and finally write integers to the output. This is confusing and I'm not even sure it is what you intended. It also makes me wonder if you have tests. If you don't get it right, it's useless if it runs fast!</li>\n<li>When opening the output file fails, you output a message and blindly continue doing something that can never succeed. You should have thrown an exception there.</li>\n<li>The same applies to opening the input files. If that fails, throw an exception.</li>\n<li>The case that the two files have different numbers of elements is not really handled. Again, throw an exception.</li>\n<li>Don't create objects/variables that you only need much later. In this case, this applies e.g. to the output vector. It applies to the output file as well, although this could be defended, because it avoids costly operations that can't succeed anyway (see comment above). It also applies to the iterators used in the loops.</li>\n<li>You are sometimes documenting what your code does, like "Open result file", "creating iterator" and "printing all elements". This isn't helpful, since anyone can see what that does. In the third case, it is even a lie, because nothing is printed! This is typical beginners' behaviour and will vanish automatically once you're more familiar with the language, so don't worry about it too much. As a general rule, the "what?" comments are useless. The "how?" comments are sometimes important, though you should strive to make it clear from the code. The most important ones are the "why?" comments, because those document decisions you made.</li>\n<li>Look up "range based <code>for</code> loops" (<code>for (auto e : some_vector) {...}</code>), which would reduce your code a bit.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T09:44:44.313",
"Id": "466692",
"Score": "0",
"body": "I can say, that I am sanitizing, checking and validating both files before sending them as an argument but, of course, I totally agree that validation is a better choice anyway."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T08:35:34.417",
"Id": "237958",
"ParentId": "237926",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "237949",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T17:46:59.273",
"Id": "237926",
"Score": "2",
"Tags": [
"c++",
"performance",
"cryptography"
],
"Title": "XOR two files together"
}
|
237926
|
<p>I am looking to optimize one function that returns error messages to the user.</p>
<pre><code> /// <summary>
/// Handles the Ouverture event of the PrescriptionVue control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void PrescriptionVueOuverture(object sender, EventArgs e)
{
Message message = ServiceCouchePolygoneFacade.Instance.RecalculerSuperficiePolygone();
Message message2 = ServicePrescriptionFacade.Instance.MettreAJourTablePrescription();
if (message != null || message2 != null)
{
if (message != null)
{
this.prescriptionVue.AfficherMessage(message);
}
else
{
this.prescriptionVue.AfficherMessage(message2);
}
this.prescriptionVue.Fermer();
}
this.InitialiserVue();
}
</code></pre>
<p>I have 2 service that conduct different manipulation and both of them returns an Object "Message" that are either gonna bu null or contain the error.</p>
<p>What im looking to optimize is the condition block in wich i look if either of those are null and if one isnt, wich one, so that i can send the one that contains the error.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T23:41:49.897",
"Id": "466638",
"Score": "2",
"body": "This code uses functions and or objects that are not defined in the code. To give a good review we would need to see at least the class this function is a member of."
}
] |
[
{
"body": "<p>one way to do it is to use <code>coalesce</code> : </p>\n\n<pre><code>/// <summary>\n/// Handles the Ouverture event of the PrescriptionVue control.\n/// </summary>\n/// <param name=\"sender\">The source of the event.</param>\n/// <param name=\"e\">The <see cref=\"System.EventArgs\"/> instance containing the event data.</param>\nprivate void PrescriptionVueOuverture(object sender, EventArgs e)\n{ \n var message = ServiceCouchePolygoneFacade.Instance.RecalculerSuperficiePolygone() ?? ServicePrescriptionFacade.Instance.MettreAJourTablePrescription();\n\n if(message != null)\n {\n this.prescriptionVue.AfficherMessage(message);\n\n this.prescriptionVue.Fermer();\n }\n\n this.InitialiserVue();\n}\n</code></pre>\n\n<p>the <code>coalesce</code> would evaluate the left-hand operand, if it's null, then it'll get the right-hand operand. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T15:51:43.413",
"Id": "466731",
"Score": "0",
"body": "I never used ?? operator, looks like its coming to bite me, i'll look into it more often, thakn you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T02:03:11.753",
"Id": "237938",
"ParentId": "237930",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "237938",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T21:45:43.513",
"Id": "237930",
"Score": "1",
"Tags": [
"c#",
"beginner"
],
"Title": "Beginner programmer on sending error messages"
}
|
237930
|
<p>I coded a function that takes an array with numbers and randomly chooses one of these numbers (Returns the index of the chosen one).
The value of each number works as an weight which determines the probability to that number be chosen.<br><br></p>
<p>E.G.: A possible input for the function could be <code>[1.5, 3.5, 2.0, 1.3]</code> and the respective probabilities would be <code>18.07%</code>, <code>42.16%</code>, <code>24.09%</code>, <code>15.66%</code>. In other words, <em>the probability to choose a number is proportional to that number</em>.<br><br></p>
<p>The function:</p>
<pre><code>function chooseIndex(weights){
let weightSum = 0;
weights.forEach(weight => {
weightSum += weight;
});
let choice = Math.random()*weightSum; // [0 ~ weightSum[
let retIndex;
weights.some((weight, index) => {
choice -= weight;
if(choice < 0){
retIndex = index;
return true;
}
});
return retIndex;
}
</code></pre>
<p>I don't know why, but I feel it could be better about performance.<br>
Any suggestions will be very welcome ;D</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T00:55:31.320",
"Id": "466641",
"Score": "0",
"body": "The first section doesn't define the data structure referenced in the second part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T03:27:55.090",
"Id": "466649",
"Score": "0",
"body": "@RayButterworth Which data structure? `weights`? That's the input parameter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T03:53:20.827",
"Id": "466652",
"Score": "0",
"body": "So, what you label as \"Probabilities\" is the argument for the `weights` parameter. In that case, I will now guess that `value/weight` doesn't really mean the value from the \"Array\" divided by the weight from the \"Probabilities\". If that's true, the \"Array\" is totally irrelevant. It was all a bit confusing (or at least I was confused by it)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T04:01:32.597",
"Id": "466655",
"Score": "0",
"body": "@RayButterworth As I read it, \"Array\" is the input, and \"Probabilities\" is just a sort of explanatory label or illustration. In other words, given the input `[1.5, 3.5, 2, 1.3]`, the function is expected to output `0` 18.07% of the time, `1` 42.16% of the time, `2` 24.09% of the time, and `3` 15.66% of the time. And you're right that \"value/weight\" is not mathematical, it's just \"value or weight, whichever term you want to use\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T04:20:44.867",
"Id": "466658",
"Score": "0",
"body": "Sorry, guys. Its on me. I should explain better about the input and my english doesn't help so much. I'll edit it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T05:13:22.690",
"Id": "466661",
"Score": "0",
"body": "Welcome to Code Review! I have rolled back your latest 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)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T05:26:30.060",
"Id": "466662",
"Score": "0",
"body": "Sorry @Heslacher Newbie here. I will roll it back."
}
] |
[
{
"body": "<h3>More concise code</h3>\n<p>First, you can compute <code>weightSum</code> using a <code>reduce()</code> function instead. I am not sure if there is any particular performance benefit to this or not, but it does allow you to put everything on one line if you like that sort of thing.</p>\n<pre><code>const weightSum = weights.reduce((sum, weight) => sum + weight, 0);\n</code></pre>\n<p>Similarly, in newer versions of Javascript you can use <code>weights.findIndex()</code> instead of <code>weights.some()</code> to make your code more concise. However this will not work in Internet Explorer.</p>\n<pre><code> const retIndex = weights.findIndex((weight) => {\n choice -= weight;\n return (choice < 0);\n });\n return retIndex;\n</code></pre>\n<p>Now, on to efficiency.</p>\n<h3>Efficiency - using input once</h3>\n<p>If you only plan to use each input <em>once</em>, then the algorithm you have is <em>close</em> to the best fit for the job. But the time to produce an output increases linearly with the size of the input (<em>O(n)</em>). We can improve that. (Thanks <a href=\"https://codereview.stackexchange.com/users/6499/roland-illig\">Roland Illig</a>.)</p>\n<p>Say that at the top, instead of simply taking the sum, we generate a new array with all the intermediate steps to get to the sum. E.g. for the input <code>[1.5, 3.5, 2, 1.3]</code> we create the array <code>[1.5, 5, 7, 8.3]</code>. This leads us to more or less the inverse of your current method; instead of subtracting weights from one side of the less-than comparison (i.e. from <code>choice</code>), we are adding them to the other side.</p>\n<pre><code> const accumulatedWeights = weights.slice(0, 1);\n weights.slice(1).forEach((weight, i) => {\n accumulatedWeights[i] = weight + accumulatedWeights[i - 1];\n });\n weightSum = accumulatedWeights[accumulatedWeights.length - 1];\n\n let choice = Math.random() * weightSum; // [0 ~ weightSum]\n let retIndex;\n accumulatedWeights.some((accumulatedWeight, index) => {\n if(choice < accumulatedWeight){\n retIndex = index;\n return true;\n }\n });\n return retIndex;\n</code></pre>\n<p>Now, this is not <em>yet</em> an improvement on your current method. The key is that this new array <code>accumulatedWeights</code> has a useful property: we know it is sorted, ordered from least to most (assuming no negative weights, which would frankly break everything anyway). This means we can do a binary search on it. Instead of using <code>.some()</code> to go from one end of the array to the other, we can start by checking in the middle of the array, and then "zoom in" on the half that must contain the correct value, then repeat.</p>\n<p>Think about if there are 100 values in the input, and the random number generated corresponds to the value at index 99. Without binary search, we have to go through the whole array and do 100 operations to find the correct index; with binary search we only have to do around 7. (All 100 -> top 50 -> top 25 -> top 12 or 13 -> top 6 or 7 -> top 3 or 4 -> top 1 or 2 -> definitely top 1.) This is <em>O(log n)</em> time efficiency, a big improvement over <em>O(n)</em>.</p>\n<p>Unfortunately I don't have time to write out a full binary search function, but see <a href=\"https://stackoverflow.com/questions/22697936/binary-search-in-javascript\">this StackOverflow post</a>.</p>\n<h3>Efficiency - using input many times</h3>\n<p>But what if you wanted to use each input <em>more</em> than once? E.g. you want to select ten million randomized indexes in a row based on the same weighting scheme.</p>\n<p>Well, in that case you could follow the advice of <a href=\"https://stackoverflow.com/a/8435261\">this other StackOverflow post</a>:</p>\n<ul>\n<li>First, build a big array where each number you want to select appears some number of times in proportion to its weight. E.g. for the weights <code>[1.5, 3.5, 2, 1.3]</code>, you would generate an array with fifteen <code>0</code>s, thirty-five <code>1</code>s, twenty <code>2</code>s, and thirteen <code>3</code>s.</li>\n<li>Then, pick a random element from the big array (i.e. compute an index via <code>Math.floor(Math.random() * big_array.length)</code> and return the element at that index) ten million times in a row.</li>\n</ul>\n<p>You pay a certain cost up front to set up the big array, but once you have it set up, the time to find another result is constant (<em>O(1)</em>), no matter how long the original input was.</p>\n<p>Whether or not this is more efficient in practice depends entirely on your use case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T06:28:46.250",
"Id": "466665",
"Score": "1",
"body": "In addition to \\$\\mathcal O(n)\\$ and \\$\\mathcal O(1)\\$, you can also have a time \\$\\mathcal O(\\log n)\\$ space \\$\\mathcal O(n)\\$ algorithm by using a binary search into the array of cumulated weights, \\$n\\$ being the number of elements in the array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T06:35:30.160",
"Id": "466666",
"Score": "1",
"body": "@RolandIllig By \"array of cumulated weights\" do you mean something like `[1.5, 5, 7, 8.3]` for the input `[1.5, 3.5, 2, 1.3]`? Hmm...that's a good point. I think I can see what you're getting at."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T06:39:10.307",
"Id": "466669",
"Score": "0",
"body": "Yep, exactly that."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T03:53:07.753",
"Id": "237945",
"ParentId": "237931",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-25T22:39:05.940",
"Id": "237931",
"Score": "5",
"Tags": [
"javascript",
"statistics"
],
"Title": "Select array element by its weight/probability"
}
|
237931
|
<p>I am new to community and please pardon me if I didn't provide information as intended.
This code is supposed to be creating a custom model which will be used with <code>lmfit</code> for curve fitting purposes. <code>hc(q,radius,pd)</code> is the function. It is one of the simplest functions that I will be using but even this function is taking quite a bit in python compared to Matlab. <code>q</code> values which are created for the sake of simplicity will be replaced by the experimental values and it will be used to fit the intensity from 1D SAXS results.
The difference between the vectorization and for loop is almost double. Although the documentation suggests to use for Loop, it gives slower results. </p>
<p>I am trying to learn Python, coming from Matlab. I have a very simple code for starting purposes:</p>
<pre><code>from numpy import vectorize
from scipy import integrate
from scipy.special import j1
from math import sqrt, exp, pi, log
import matplotlib.pyplot as plt
import numpy as np
from numpy import empty
def plot_hc(radius, pd):
q = np.linspace(0.008, 1.0, num=500)
y = hc(q, radius, pd)
plt.loglog(q, y)
plt.show()
def hc_formfactor(q, radius):
y = (1.0 / q) * (radius * j1(q * radius))
y = y ** 2
return y
def g_distribution(z, radius, pd):
return (1 / (sqrt(2 * pi) * pd)) * exp(
-((z - radius) / (sqrt(
2) * pd)) ** 2)
def ln_distribution(z, radius, pd):
return (1 / (sqrt(2 * pi) * pd * z / radius)) * exp(
-(log(z / radius) / (sqrt(2) * pd)) ** 2)
# Dist=1(for G_Distribution)
# Dist=2(for LN Distribution)
Dist = 1
@vectorize
def hc(x, radius, pd):
global d
if Dist == 1:
nmpts = 4
va = radius - nmpts * pd
vb = radius + nmpts * pd
if va < 0:
va = 0
d = integrate.quad(lambda z: g_distribution(z, radius, pd), va, vb)
elif Dist == 2:
nmpts = 4
va = radius - nmpts * pd
vb = radius + nmpts * pd
if va < 0:
va = 0
d = integrate.quad(lambda z: ln_distribution(z, radius, pd), va, vb)
else:
d = 1
def fun(z, x, radius, pd):
if Dist == 1:
return hc_formfactor(x, z) * g_distribution(z, radius, pd)
elif Dist == 2:
return hc_formfactor(x, z) * ln_distribution(z, radius, pd)
else:
return hc_formfactor(x, z)
y = integrate.quad(lambda z: fun(z, x, radius, pd), va, vb)[0]
return y/d[0]
if __name__ == '__main__':
plot_hc(radius=40, pd=0.5)
</code></pre>
<p>As suggested in the documentation, I should use for loop, but that reduced the speed even more. The code using for loop is as follows:</p>
<pre><code>from numpy import vectorize
from scipy import integrate
from scipy.special import j1
from math import sqrt, exp, pi, log
import matplotlib.pyplot as plt
import numpy as np
from numpy import empty
def plot_hc(radius, pd):
q = np.linspace(0.008, 1.0, num=500)
y = hc(q, radius, pd)
plt.loglog(q, y)
plt.show()
def hc_formfactor(q, radius):
y = (1.0 / q) * (radius * j1(q * radius))
y = y ** 2
return y
def g_distribution(z, radius, pd):
return (1 / (sqrt(2 * pi) * pd)) * exp(
-((z - radius) / (sqrt(
2) * pd)) ** 2)
def ln_distribution(z, radius, pd):
return (1 / (sqrt(2 * pi) * pd * z / radius)) * exp(
-(log(z / radius) / (sqrt(2) * pd)) ** 2)
# Dist=1(for G_Distribution)
# Dist=2(for LN Distribution)
Dist = 1
def hc(q, radius, pd):
if Dist == 1:
nmpts = 4
va = radius - nmpts * pd
vb = radius + nmpts * pd
if va < 0:
va = 0
d = integrate.quad(lambda z: g_distribution(z, radius, pd), va,vb)
elif Dist == 2:
nmpts = 4
va = radius - nmpts * pd
vb = radius + nmpts * pd
if va < 0:
va = 0
d = integrate.quad(lambda z: ln_distribution(z, radius, pd), va, vb)
else:
d = 1
def fun(z, q, radius, pd):
if Dist == 1:
return hc_formfactor(q, z) * g_distribution(z, radius, pd)
elif Dist == 2:
return hc_formfactor(q, z) * ln_distribution(z, radius, pd)
else:
return hc_formfactor(q, z)
y = empty([len(q)])
for n in range(len(q)):
y[n] = integrate.quad(lambda z: fun(z, q[n], radius, pd), va, vb)[0]
return y / d[0]
if __name__ == '__main__':
plot_hc(radius=40, pd=0.5)
</code></pre>
<p>I don't understand, what should I do to optimise the code? If I run the same program for the same values in Matlab it is very fast. I don't know what mistake I did here. Also, some suggested to use jit from numba to speed up the integration, but I am not sure how to implement it. Please help :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T09:28:56.007",
"Id": "466690",
"Score": "0",
"body": "Welcome to Code Review! We need to know *what the code is intended to achieve*. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](https://codereview.meta.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](https://codereview.meta.stackexchange.com/q/2436), rather than your concerns about the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T09:56:57.283",
"Id": "466693",
"Score": "1",
"body": "@TobySpeight Thanks a lot for your reply and for correcting me. Being a beginner, its always good to learn from the experts in the community. Thanks for the suggestions. I have edited the title as well as provided information in the text. Please let me know if I need to provide more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T02:35:03.007",
"Id": "466782",
"Score": "1",
"body": "@Graipher Thanks a lot for your comment. It was a mistake I made when I copied and pasted the code."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T03:00:53.433",
"Id": "237942",
"Score": "1",
"Tags": [
"python",
"matlab",
"vectorization",
"scipy",
"numba"
],
"Title": "Custom Model intended to be used for Curve Fitting. Vectorization vs For Loop and jit numba capabilities"
}
|
237942
|
<p>First I'm not sure what this is called formally but whatever.</p>
<p>Basically I need to form "wildcard buckets". I think the best way to explain what I need to do is to take an example. For instance, say I have the three words "aaa", "aab", and "baa".</p>
<p>Let me use <code>*</code> as the wildcard. Then from <code>aaa</code> I can form <code>-aa</code>, <code>a-a</code>, <code>aa-</code>, <code>--a</code>, <code>a--</code>, <code>a-a</code>, and <code>---</code>. I then add these to a dictionary where the keys are the buckets and values are sets of (complete) words that fit these buckets. I repeat for all my words. So in the end I get that, for instance, <code>-a-</code> fits all three of the example words that I have above.</p>
<p>I have working code, but it is very slow in forming these buckets when I have a word list that has hundreds of thousands of words.</p>
<pre><code>for numberSpaces in range(0, len(word) + 1): # loop through all spaces of word
buckets = itertools.combinations(range(0, len(word)), numberSpaces)
for indicesToReplace in buckets: # for each index in this combination
newWord = word
for index in indicesToReplace: # replace character with "*"
newWord = newWord[0:index] + "*" + newWord[index + 1:]
if newWord not in bucketDictionary.keys(): # Add to dictionary
bucketDictionary[newWord] = set()
bucketDictionary[newWord].add(word)
</code></pre>
<p>I would like to know how to best optimize this code. I've tried recursion but I'm not sure if that is any better than this iterative method.</p>
<p>Thank you!</p>
|
[] |
[
{
"body": "<p>I think the way to optimize it is to try an entirely different approach -- given a pattern that matches all the words in a set, and a new word to add to the set, how do you modify the pattern to match the new word as well? Simple answer: as long as the non-wild characters in the pattern match the new word, leave them; otherwise change the pattern to have a wildcard at that position. You could implement this either recursively or iteratively.</p>\n\n<pre><code>from typing import List\n\nWILD = \"*\"\n\ndef build_common_pattern(words: List[str]) -> str:\n \"\"\"Build a pattern matching all input words.\n WILD matches any single character.\"\"\"\n pattern = words[0]\n for word in words:\n assert len(word) == len(pattern)\n for i in range(len(word)):\n assert word[i] != WILD\n if pattern[i] != word[i]:\n pattern = pattern[:i] + WILD + pattern[i+1:]\n return pattern\n\nprint(build_common_pattern([\"aaa\", \"aab\", \"baa\"]))\n</code></pre>\n\n<p>This is also a potential use case for <code>functools.reduce</code>:</p>\n\n<pre><code>def build_common_pattern(words: List[str]) -> str:\n \"\"\"Build a pattern matching all input words.\n WILD matches any single character.\"\"\"\n def union(a: str, b: str) -> str:\n result = \"\"\n assert len(a) == len(b)\n for i in range(len(a)):\n result += a[i] if a[i] == b[i] else WILD\n return result\n\n return reduce(union, words)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T07:28:52.747",
"Id": "237952",
"ParentId": "237943",
"Score": "4"
}
},
{
"body": "<p>Starting with the <a href=\"https://codereview.stackexchange.com/a/237952/98493\">answer</a> by <a href=\"https://codereview.stackexchange.com/users/213275/sam-stafford\">@SamStafford</a>, you could take this even further and make it a nice inheritance exercise by using a sub-class of <code>str</code> that compares true to any other character:</p>\n\n<pre><code>class WildCard(str):\n def __eq__(self, other):\n # all other strings are equal to the wildcard\n return isinstance(other, str)\n\nSTAR = WildCard(\"*\")\n\ndef build_common_pattern(words):\n \"\"\"Build a pattern matching all input words.\n WILD matches any single character.\"\"\"\n pattern = list(words[0])\n for word in words:\n assert len(word) == len(pattern)\n pattern = [p if c == p else STAR for c, p in zip(word, pattern)]\n return \"\".join(pattern)\n</code></pre>\n\n<p>This way you avoid having to do many string slices, although this makes it only perform better for really large strings (patterns with each character having a 50% chance to be a wildcard and a length of more than 1k characters):</p>\n\n<p><a href=\"https://i.stack.imgur.com/hIbFr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hIbFr.png\" alt=\"enter image description here\"></a></p>\n\n<hr>\n\n<p>However, this does not solve the exact problem your code solves, since it does not build a dictionary mapping patterns to words that match it. For this I can only give you some stylistic advice on how to improve your code.</p>\n\n<ul>\n<li><p>Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which recommends <code>lower_case</code> for functions and variables.</p></li>\n<li><p>You can use <a href=\"https://docs.python.org/3/library/collections.html#collections.defaultdict\" rel=\"nofollow noreferrer\"><code>collections.defaultdict(set)</code></a> to avoid having to check if you have seen a pattern before.</p></li>\n<li><p><code>range</code> starts by default at <code>0</code>, and so do slices.</p></li>\n<li><p>Use the same way I used above to avoid string slices and iterate over the word/pattern instead.</p></li>\n</ul>\n\n\n\n<pre><code>from collections import defaultdict\nfrom itertools import combinations\n\ndef build_buckets(words):\n buckets_dict = defaultdict(set)\n for word in words:\n for number_spaces in range(len(word) + 1): # loop through all spaces of word\n buckets = combinations(range(len(word)), number_spaces)\n for indices in map(set, buckets): # for each index in this combination\n new_word = \"\".join(c if i not in indices else \"*\"\n for i, c in enumerate(word))\n buckets_dict[new_word].add(word)\n return buckets_dict\n</code></pre>\n\n<p>Note that this is probably a futile effort, since if there were no wordlist, the number of patterns grows exponentially. Since you do have a wordlist it does not, but the number of patterns will still increase rapidly. For 15 words of length 15, your code already takes almost 2 seconds.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T16:55:06.550",
"Id": "237982",
"ParentId": "237943",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T03:12:16.750",
"Id": "237943",
"Score": "3",
"Tags": [
"python",
"parsing"
],
"Title": "Word bucketing in Python"
}
|
237943
|
<p>gist of this project is that I have two datasets,</p>
<pre><code>1. dfCore, which contains station_code and station_name
2. dfMetrix, which contains station_name
</code></pre>
<p>the <code>station_name</code> form <code>dfMetrix</code> is supposed to tell me how to join to <code>dfCore</code>, based on
either the <code>station_code</code> or <code>station_name</code> column in <code>dfMetrix</code>.</p>
<p>none of the potential matches are exact so I have to use regex to try and compare the
key strings from <code>dfMetrix.station_code</code> to <code>dfCore.station_name</code> and <code>dfCore.station_code</code>.</p>
<p>because I need to do this matching based on regex I need to establish confidence levels
for potential matches. Later on I could potentially hook these confidence offsets to a
machine learning algorithm, but the basic point here is to create a script for doing this
in this particular situation, which I can extend for further needs in the future.</p>
<p>I'm posting here as a response to a comment on the question I posted earlier on SO <a href="https://stackoverflow.com/questions/60406032/pandas-expand-series-of-dataframes?noredirect=1#comment106859443_60406032">here</a></p>
<p>I have this here for now because it didn't seem appropriate to post the script on SO, and so I will update this to reflect the final version once my SO question is resolved.</p>
<p>The theory on how I'm doing this is pretty simple. I have an object called PatternKey which holds a single word from one of the values in <code>dfMetrix.station_name</code> (called the 'Key')then compares that word using regex to all the words in a <code>dfCore.station_name</code> or <code>dfCore.station_code</code> (called the 'Target').</p>
<p>I then use DataFrames to try and keep all the data straight.</p>
<pre><code>import re
import uuid
import copy
import functools
import pandas as pd
dctCore = {
'ID': {0: 36366, 1: 36660, 2: 39740, 3: 39828, 4: 40348, 5: 35853},
'Name': {0: 'DirecTV News ', 1: 'ION Network ', 2: 'SUR SPANISH MIAMI ', 3: 'BET SAN FRANCISCO ', 4: 'CNBC TAMPA BAY ', 5: 'VH1 LOS ANGELES '},
'CoreCode': {0: 'DTNC ', 1: 'ION ', 2: 'MISUR', 3: 'NCBET', 4: 'TBCNB', 5: 'ADVH1'},
'Market': {0: 'Cable ', 1: 'Cable ', 2: 'Advanced TV ', 3: 'Sacramento-Stockton ', 4: 'Advanced TV ', 5: 'Los Angeles '},
'MarketCode': {0: '9200', 1: '9200', 2: '9500', 3: '5010', 4: '9500', 5: '3680'},
'BreakType': {0: 'N', 1: 'N', 2: 'N', 3: 'L', 4: 'N', 5: 'L'}
}
dctMetrix = {
'station_name': {0: 'ABC', 1: 'American Heroes', 2: 'American Heroes', 3: 'American Movie Classics', 4: 'American Movie Classics', 5: 'Animal Planet', 6: 'Animal Planet', 7: 'Antenna', 8: 'Arts & Entertainment', 9: 'BBC America', 10: 'BBC America', 11: 'BET Her', 12: 'BET Her', 13: 'BET Jams', 14: 'BET Soul', 15: 'Black Entertainment Television', 16: 'Bloomberg', 17: 'Bloomberg', 18: 'Bounce', 19: 'Bravo', 20: 'Bravo', 21: 'CBS Sports Network', 22: 'Charge', 23: 'CNBC', 24: 'CNBC', 25: 'CNBC World', 26: 'CNN', 27: 'CNN', 28: 'Comedy Central', 29: 'Comet', 30: 'Country Music Television', 31: 'Country Music Television', 32: 'Cozi', 33: 'Criminal Investigation', 34: 'Destination America', 35: 'Destination America', 36: 'Discovery Channel', 37: 'Discovery Channel', 38: 'Discovery Family Channel', 39: 'Discovery Family Channel', 40: 'Discovery Life', 41: 'Discovery Life', 42: 'E! Entertainment', 43: 'E! Entertainment', 44: 'Escape', 45: 'ESPN', 46: 'ESPN', 47: 'ESPN Classic', 48: 'ESPN Classic', 49: 'ESPN News', 50: 'ESPN News', 51: 'ESPN U', 52: 'ESPN U', 53: 'ESPN2', 54: 'ESPN2', 55: 'Fox Business Network', 56: 'Fox Business Network', 57: 'Fox News Channel', 58: 'Fox News Channel', 59: 'Fox Sports 1', 60: 'Fox Sports 1', 61: 'Fox Sports 2', 62: 'FX', 63: 'FX', 64: 'FX Movie Channel', 65: 'FXX', 66: 'fyi', 67: 'fyi', 68: 'Game Show Network', 69: 'Game Show Network', 70: 'Great American Country', 71: 'Great American Country', 72: 'Hallmark Channel', 73: 'Hallmark Channel', 74: 'Hallmark Movies and Mysteries', 75: 'Hallmark Movies and Mysteries', 76: 'Heroes & Icons', 77: 'HGTV', 78: 'History Channel', 79: 'History Channel', 80: 'HLN', 81: 'ID', 82: 'Independent Film Channel', 83: 'Independent Film Channel', 84: 'ION Plus', 85: 'Lifetime', 86: 'Lifetime Movie Network', 87: 'Lifetime Real Women', 88: 'Lifetime Real Women', 89: 'Logo', 90: 'Logo', 91: 'MLB Network', 92: 'Motor Trend', 93: 'Motor Trend', 94: 'MSNBC', 95: 'MSNBC', 96: 'MTV', 97: 'MTV Live', 98: 'MTV2', 99: 'MTV2', 100: 'National Geographic Channel', 101: 'National Geographic Channel', 102: 'National Geographic Wild', 103: 'National Geographic Wild', 104: 'NBC Sports Network', 105: 'NBC Sports Network', 106: 'NBC Universo', 107: 'NBC Universo', 108: 'Ovation', 109: 'Oxygen', 110: 'Paramount Network', 111: 'Reelz', 112: 'Science', 113: 'Science', 114: 'Sundance Channel', 115: 'Syfy', 116: 'Syfy', 117: 'TBD Channel', 118: 'TBS', 119: 'The Golf Channel', 120: 'The Golf Channel', 121: 'The Learning Channel', 122: 'The Learning Channel', 123: 'The NFL Network', 124: 'The NFL Network', 125: 'The Weather Channel', 126: 'The Weather Channel', 127: 'This TV', 128: 'TNT', 129: 'TNT', 130: 'Tr3s', 131: 'Travel Channel', 132: 'truTV', 133: 'truTV', 134: 'TVLand', 135: 'Unknown', 136: 'Unknown', 137: 'USA Network', 138: 'USA Network', 139: 'VH-1', 140: 'Viceland', 141: 'Viceland', 142: 'WGN Superstation', 143: 'WGN Superstation', 144: "Women's Entertainment", 145: 'youtoo America'}, 'station_code': {0: 'ABC1', 1: 'HERO', 2: 'HERO', 3: 'AMC', 4: 'AMC', 5: 'ANPL', 6: 'ANPL', 7: 'ANTEN1', 8: 'A-AND-E', 9: 'BBCA', 10: 'BBCA', 11: 'CENT', 12: 'CENT', 13: 'MTVJ', 14: 'BETS', 15: 'BET', 16: 'BLOOM', 17: 'BLOOM', 18: 'BOUNC1', 19: 'BRAVO', 20: 'BRAVO', 21: 'CBSSPNET', 22: 'CHARG1', 23: 'CNBC', 24: 'CNBC', 25: 'CNBCW', 26: 'CNN', 27: 'CNN', 28: 'COM', 29: 'COMET1', 30: 'CMT', 31: 'CMT', 32: 'COZIT1', 33: 'CIN', 34: 'DESA', 35: 'DESA', 36: 'DSC', 37: 'DSC', 38: 'DSCF', 39: 'DSCF', 40: 'FITTV', 41: 'FITTV', 42: 'ETV', 43: 'ETV', 44: 'ESCAP1', 45: 'ESPN', 46: 'ESPN', 47: 'ESNPC', 48: 'ESNPC', 49: 'ESPNW', 50: 'ESPNW', 51: 'ESPNU', 52: 'ESPNU', 53: 'ESPN2', 54: 'ESPN2', 55: 'FBN', 56: 'FBN', 57: 'FNC', 58: 'FNC', 59: 'FS1', 60: 'FS1', 61: 'FOXSP2', 62: 'FX', 63: 'FX', 64: 'FXM', 65: 'FXX', 66: 'FYI', 67: 'FYI', 68: 'GSN', 69: 'GSN', 70: 'GAC', 71: 'GAC', 72: 'HALL', 73: 'HALL', 74: 'HLMKM', 75: 'HLMKM', 76: 'HEROS1', 77: 'HGTV', 78: 'HIST', 79: 'HIST', 80: 'CNNH', 81: 'ID-SD', 82: 'IFC', 83: 'IFC', 84: 'IONLF1', 85: 'LIFE', 86: 'LMN', 87: 'LRW', 88: 'LRW', 89: 'LOGO', 90: 'LOGO', 91: 'MLBN', 92: 'VEL', 93: 'VEL', 94: 'MSNBC', 95: 'MSNBC', 96: 'MTV', 97: 'PALL', 98: 'MTV2', 99: 'MTV2', 100: 'NGC', 101: 'NGC', 102: 'NGCW', 103: 'NGCW', 104: 'NBCSP', 105: 'NBCSP', 106: 'MUN2', 107: 'MUN2', 108: 'OVATION', 109: 'OXYGEN', 110: 'SPIKE-TV', 111: 'REELZ', 112: 'SCICHN', 113: 'SCICHN', 114: 'SUND', 115: 'SYFY', 116: 'SYFY', 117: 'TBD1', 118: 'TBS', 119: 'GOLF', 120: 'GOLF', 121: 'TLC', 122: 'TLC', 123: 'NFLNET', 124: 'NFLNET', 125: 'WEA', 126: 'WEA', 127: 'THISTV1', 128: 'TNT', 129: 'TNT', 130: 'TR3S', 131: 'TRVL', 132: 'TRU-TV', 133: 'TRU-TV', 134: 'TVL', 135: 'DRMETRIX', 136: 'GRIT1', 137: 'USA', 138: 'USA', 139: 'VH1', 140: 'H2', 141: 'H2', 142: 'WGN', 143: 'WGN', 144: 'WE', 145: 'YOUTOO'},
'breaktype': {0: 'N', 1: 'L', 2: 'N', 3: 'L', 4: 'N', 5: 'L', 6: 'N', 7: 'N', 8: 'L', 9: 'L', 10: 'N', 11: 'L', 12: 'N', 13: 'N', 14: 'N', 15: 'N', 16: 'L', 17: 'N', 18: 'N', 19: 'L', 20: 'N', 21: 'N', 22: 'N', 23: 'L', 24: 'N', 25: 'N', 26: 'L', 27: 'N', 28: 'N', 29: 'N', 30: 'L', 31: 'N', 32: 'N', 33: 'N', 34: 'L', 35: 'N', 36: 'L', 37: 'N', 38: 'L', 39: 'N', 40: 'L', 41: 'N', 42: 'L', 43: 'N', 44: 'N', 45: 'L', 46: 'N', 47: 'L', 48: 'N', 49: 'L', 50: 'N', 51: 'L', 52: 'N', 53: 'L', 54: 'N', 55: 'L', 56: 'N', 57: 'L', 58: 'N', 59: 'L', 60: 'N', 61: 'N', 62: 'L', 63: 'N', 64: 'L', 65: 'L', 66: 'L', 67: 'N', 68: 'L', 69: 'N', 70: 'L', 71: 'N', 72: 'L', 73: 'N', 74: 'L', 75: 'N', 76: 'N', 77: 'L', 78: 'L', 79: 'N', 80: 'N', 81: 'L', 82: 'L', 83: 'N', 84: 'N', 85: 'N', 86: 'N', 87: 'L', 88: 'N', 89: 'L', 90: 'N', 91: 'N', 92: 'L', 93: 'N', 94: 'L', 95: 'N', 96: 'N', 97: 'N', 98: 'L', 99: 'N', 100: 'L', 101: 'N', 102: 'L', 103: 'N', 104: 'L', 105: 'N', 106: 'L', 107: 'N', 108: 'N', 109: 'N', 110: 'N', 111: 'N', 112: 'L', 113: 'N', 114: 'N', 115: 'L', 116: 'N', 117: 'N', 118: 'L', 119: 'L', 120: 'N', 121: 'L', 122: 'N', 123: 'L', 124: 'N', 125: 'L', 126: 'N', 127: 'N', 128: 'L', 129: 'N', 130: 'N', 131: 'N', 132: 'L', 133: 'N', 134: 'N', 135: '', 136: 'N', 137: 'L', 138: 'N', 139: 'N', 140: 'L', 141: 'N', 142: 'L', 143: 'N', 144: 'N', 145: 'N'}
}
dfCore = pd.DataFrame(dctCore)
dfMetrix = pd.DataFrame(dctMetrix)
confidence_levels = {
'AMERICAN': .2,
'AMERICA': .2,
'NEWS': .2,
'TV': .2,
}
class PatternKey:
@property
def Confidence(self):
return (self._confidenceAffirm * self.ExactWeight) * self.ExactMatch \
or (self._confidenceAffirm * self.PartialWeight) * self.PartialMatch \
or self._confindenceDeny
@property
def Match(self):
return self.PartialMatch or self.ExactMatch
def __init__(self, key):
self.KeyName = key.strip(' ')
self.TargetIndex = []
self.TargetString = None
self.PartialMatch = False
self.ExactMatch = False
self.ExactWeight = 1.5
self.PartialWeight = .9
self._confidenceAffirm = .5
self._confindenceDeny = -.1
self.Uuid = uuid.uuid1()
self.MatchUuid = None
self.setConfidenceValue()
return
def setConfidenceValue(self):
if len(self.KeyName) <= 1:
self._confidenceAffirm = .1
v = globals()["confidence_levels"].get(self.KeyName.upper())
if v:
self._confidenceAffirm = v
return
def __call__(self, v):
obj = copy.deepcopy(self)
pattern = re.escape(self.KeyName)
obj.TargetString = v.strip(' ')
for s in re.split('[\s,-]',v.strip(' ')):
if re.fullmatch(f"({pattern})", s, re.IGNORECASE):
obj.ExactMatch = True
break
if re.search(f"({pattern})", s, re.IGNORECASE):
obj.PartialMatch = True
obj.MatchUuid = uuid.uuid1()
return obj
def to_df(self):
return pd.DataFrame(
{"Key": [self.KeyName],
"Match": [self.Match],
"Confidence": [self.Confidence],
"PartialMatch": [(self._confidenceAffirm * self.PartialWeight) * self.PartialMatch],
"ExactMatch": [(self._confidenceAffirm * self.ExactWeight) * self.ExactMatch]}
)[["Key","Match","Confidence","PartialMatch","ExactMatch"]]
def createRegexPattern(df):
def fn(r):
return pd.Series([r.index.to_list(), r["station_name"].str.split('[\s,-]').iat[0] + r["station_code"].to_list()],
index=["DrMetrix_index", "pattern"])
df["pattern"] = df["station_name"].str.split('[\s,-]')
return df.groupby(["station_name", "station_code"]).apply(fn)
df = dfMetrix.copy()
patterns = createRegexPattern(df)
df2 = patterns.explode("pattern")
df3 = df2.reset_index()["pattern"].drop_duplicates()
df4 = pd.concat([df3, df3.apply(lambda x: PatternKey(x)).rename("model")], axis=1)
def fn(x, pattern):
p = pattern.copy()
p["result"] = p.apply(lambda y: y.model(x), axis=1)
return p.loc[:,("pattern","result")].set_index("pattern")
df5 = dfCore.copy()
t = dfCore["Name"].apply(fn, args=(df4,))
t
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T03:49:18.223",
"Id": "466650",
"Score": "0",
"body": "There's no `station_code` in `dfCore`, do you mean `CoreCode`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T03:50:00.900",
"Id": "466651",
"Score": "1",
"body": "\"I have this here for now because it didn't seem appropriate to post the script on SO, and so I will update this to reflect the final version once my SO question is resolved.\" seems to conflict with \"You must not edit the code in the question, as that would violate the question-and-answer nature of this site. (An exception to that would be if a user wrote a comment saying that your code is completely broken, and needs to be fixed before it can be reviewed.)\" as stated [here](https://codereview.meta.stackexchange.com/a/1765/9555). Maybe you should delete and undelete if you have your answer..."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T03:18:42.603",
"Id": "237944",
"Score": "0",
"Tags": [
"python",
"regex",
"pandas"
],
"Title": "Script for matching regex matches between two lists"
}
|
237944
|
<p>From the last few days I have been studying scrapping webpages and for further development I challenge myself to transform the script I have created into a class which will receive inputs from a user.</p>
<p>The main reason I'm posting this is because I would like advices and insights on how should I approach and manipulete instance variables from given object. </p>
<p>It had quite the hard time to figure it out how should I start or initiate the flow of the program. I will give you briefly what the scrape script does and see for yourself if I make sense I have done in the later script.</p>
<p>Here's the scrapper.</p>
<p>It's to scrape all the jobs vacancies from given State or city.</p>
<p>The program receive the first page of a given url from a State/city and extract 3 main information. The last page, the total of jobs and how many jobs it has each page.</p>
<p>Then it use this information to build a loop to keep scrapping until it reaches the last page. I put the loop inside of CSV function in order to save the data into a file at the same time.</p>
<pre><code>require 'nokogiri'
require 'rest-client'
require 'csv'
url = 'https://www.infojobs.com.br/empregos-em-santa-catarina.aspx'
begin
html = RestClient.get(url)
rescue => e
puts "ERROR:#{e.message}"
next
parsed_html = Nokogiri::HTML(html)
total = parsed_html.css('.js_xiticounter').text.gsub('.', '')
page = 1
per_pagina = parsed_html.css('.element-vaga').count
last_page = (total.to_f / per_page).round
CSV.open('data_infojobsSC.csv', 'w') do |csv|
csv << ['Title', 'Company', 'City', 'Área']
until page >= last_page
current_url = "https://www.infojobs.com.br/empregos-em-santa-catarina.aspx?Page=#{page}"
begin
current_html = RestClient.get(current_url)
rescue => e
puts "ERROR: #{current_url}"
puts "Exception Message:#{e.message}"
next
end
parsed_current_html = Nokogiri::HTML(current_html)
jobs = parsed_current_html.css('.element-vaga')
jobs.each do |job|
title = job.css('div.vaga > a > h2').text.strip()
company = job.css('div.vaga-company > a').text.strip()
company = job.empty? ? "Confidential Company" : company
city = job.css('p.location2 > span > span > span').text
area = job.css('p.area > span').text
csv << [title, company, city, area]
end
puts "Registrados da página #{page} salvos com sucesso."
page+=1
end
end
</code></pre>
<p>Here's my POO code. This is the third version of the first functional code. Each time I try to make more modular.
This is my first POO ruby code. It was really hard to me grasp how it would work the class itself because all the previosly class I had written was simple as a dog class and bark function from beginners videos...</p>
<pre><code>require 'nokogiri'
require 'rest-client'
require 'csv'
class InfoJobs #this is the name of the website
attr_accessor :url, :parsed_html, :total, :per_page, :last_page, :list
attr_reader :city, :state
def city=(city)
@city = city.chomp.downcase.gsub(' ', '-')
end
def state=(state)
@state = state.chomp.downcase
end
def build_url
@url = 'https://www.infojobs.com.br/empregos-em-' + @city + ',-' + @state + '.aspx'
end
def parsing(url) #since I need to parse many urls I decided to make a function
begin
html = RestClient.get(url)
rescue => e
puts "ERROR on #{url}"
puts "Exception Class:#{e.class.name}"
puts "Exception Message:#{e.message}"
end
@parsed_html = Nokogiri::HTML(html)
end
def get_page_values #to the initial values to know how many pages to scrape and use these values to build a loop
self.parsing(@url)
@total = @parsed_html.css('.js_xiticounter').text.gsub('.', '')
@per_page = @parsed_html.css('.element-vaga').count
@last_page = (@total.to_f / @per_page).round
end
def scraping
@list = []
page = 1
@url = @url + "?Page="
until page >= @last_page
@url + page.to_s
jobs = self.parsing(@url).css('.element-vaga') #in this part of program, the instance variable @url is no longer that previosly page we sent to get_page_values method. Is ok to use in this way the same instance variable ? or the best practice is to create another instance variable called url_pagination?
jobs.each do |job|
company = job.css('div.vaga-company > a').text.strip()
company = company.empty? ? "Confidential Company" : company
data = {
title: job.css('div.vaga > a > h2').text.strip(),
company: company,
city: job.css('p.location2 > span > span > span').text,
area: job.css('p.area > span').text
}
@list << data
puts "The page #{page} was successfully saved."
page+=1
end
end
end
def writing
CSV.open("list_jobs.csv", "wb", {headers: list.first.keys} ) do |csv|
csv << ['Title', 'Company', 'City', 'Area']
list.each do |hash|
csv << hash
end
end
end
def run
self.build_url
self.parsing(@url)
self.get_page_values
self.scraping
self.writing
end
end
test = InfoJobs.new
puts "[ Type a city ] "
test.city = gets
puts "[ Type the state ]"
teste.state = gets
puts "Processing..."
test.run
</code></pre>
<p>The user input is to set a State and a city. And then built the url with these values.</p>
<p>Just a note...Previosly to call each class method I had something like this (below). In the code above I made a method 'run' to keep the object calling the methods inside the class. I really don't know if this is a correct approach or not...</p>
<pre><code>teste = InfoJobs.new
test = InfoJobs.new
puts "[ Type a city ] "
test.city = gets
puts "[ Type the state ]"
teste.state = gets
puts "Processing..."
teste.build_url
teste.get_page_values
teste.scraping
teste.writing
</code></pre>
<p>NOTE: Each code runs perfectly fine.</p>
|
[] |
[
{
"body": "<p>In general, your OOP approach looks good to me.<br>\nPlease check the comments to know more about the changes/details I found:</p>\n\n<pre><code>require 'nokogiri'\nrequire 'rest-client'\nrequire 'csv'\n\n# Just as a general reference, I changed all the code's indentation from 4 to 2\n# spaces as it's the most used way, also suggested by the ruby style guide\n# https://rubystyle.guide/#spaces-indentation , but it's up to you to use 4 if\n# you feel more comfortable with it.\nclass InfoJobs\n # If you're not really reading/writing object attributes when you create an\n # instance, like:\n #\n # test = InfoJobs.new(city, state)\n # test.total = 12345\n # puts test.parsed_html\n #\n # there's no need to expose them for the object's instance. That's why I\n # remove all `attr_accessor`s. I have the feeling `city` and `state` are the\n # only attributes should be accessible, but only read access. Another option\n # would be to declare attributes as private `attr_reader`s, but I leave that\n # to you.\n attr_reader :city, :state\n\n # city/state attributes should be initialized in the constructor. Also is more\n # like an OOP approach.\n def initialize(city, state)\n @city = city.chomp.downcase.tr(' ', '-')\n @state = state.chomp.downcase\n end\n\n def run\n # Removed:\n # - `build_url`, as `base_url` will be called from every method when be\n # required.\n # - `parsing(@url)` as it's later called in `initial_page_values`, where it\n # really do something with the received html.\n # - All `self.` definitions, in general `self.` is required only when you're\n # modifying a value of the instance, but it's not needed to read values or\n # call methods.\n initial_page_values\n scraping\n ensure\n # With `ensure`, in case you ctrl+c the process or fail for some reason, you\n # \"ensure\" the gathered info so far is saved.\n writing\n end\n\n # The only accessible method for the class instance is `.run`, so the rest of\n # them should be kept as private.\n private\n\n # Changed method `build_url` to memoized method `base_url`. More info in\n # https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Naming/MemoizedInstanceVariableName\n def base_url\n # Changes:\n # - Using ||= to set a value only when this is empty,\n # - Using already defined city/state attr_readers instead of accessing\n # directly to the global variables @city and @state\n # - Instead of using + to concatenate, I'm interpolating, which is the most\n # prefered way. https://rubystyle.guide/#string-interpolation\n @base_url ||= \"https://www.infojobs.com.br/empregos-em-#{city},-#{state}.aspx\"\n end\n\n def parsing(url)\n # No need of `begin` when `rescue` contemplates the whole method\n html = RestClient.get(url)\n # No sense to have html parsing out of begin/rescue block. For `rescue`\n # case, the parsing would fail, so moving html parsing before rescue.\n # Also the result of this operation should be returned, not kept in a global\n # variable `@parsed_html`.\n Nokogiri::HTML(html)\n rescue StandardError => e\n puts \"ERROR on #{url}\"\n puts \"Exception Class:#{e.class.name}\"\n puts \"Exception Message:#{e.message}\"\n end\n\n # Minor change, but `get_` and `set_` method names are discouraged in ruby.\n # More info in https://rubystyle.guide/#accessor_mutator_method_names\n def initial_page_values\n # Following what was described in the previous method, you're going to need\n # the result of the parsing method only for the scope of this method, so\n # there's no need to save it as a global variable.\n parsed_html = parsing(base_url)\n # You're only using @last page out of this method, so there shouldn't be\n # necessary to have @total and @per_page as global variables.\n total = parsed_html.css('.js_xiticounter').text.delete('.')\n per_page = parsed_html.css('.element-vaga').count\n @last_page = (total.to_f / per_page).round\n puts \"#{@last_page} pages found\"\n end\n\n def scraping\n @list = []\n page = 1\n # Removed\n # @url += '?Page='\n # as it should be better to handle it directly when the parsing is invoked.\n until page >= @last_page\n # This is wrong:\n # @url + page.to_s\n # as you're adding the page to @url in a void context, after this line,\n # @url will keep having the same value as before this line.\n # This should be the url to parse:\n jobs = parsing(\"#{base_url}?Page=#{page}\").css('.element-vaga')\n # Moving all the job parsing to its own method. Also to decrease ABC\n # metric https://en.wikipedia.org/wiki/ABC_Software_Metric and Cyclomatic\n # complexity https://en.wikipedia.org/wiki/Cyclomatic_complexity for this\n # `scraping` method.\n jobs.each { |job| @list.push(job_data(job)) }\n # Page increasing should be out of the jobs loop.\n puts \"The page #{page} was successfully saved\"\n page += 1\n end\n end\n\n def job_data(job)\n company = job.css('div.vaga-company > a').text.strip\n company = company.empty? ? 'Confidential Company' : company\n {\n title: job.css('div.vaga > a > h2').text.strip,\n company: company,\n city: job.css('p.location2 > span > span > span').text,\n area: job.css('p.area > span').text\n }#.tap { |jd| puts jd } # Uncomment if you need to debug values.\n end\n\n def writing\n # If you don't have values to save, simply return\n return unless @list && @list.any?\n\n puts \"saving #{@list.count} jobs.\"\n # Just a minor change to write to a different file every time you run this,\n # but feel free to remove it.\n filename = \"list_jobs_#{Time.now.to_i}.csv\"\n CSV.open(filename, 'wb', headers: @list.first.keys) do |csv|\n csv << %w[Title Company City Area]\n @list.each do |hash|\n csv << hash\n end\n end\n end\nend\n\nputs '[ Type a city ] '\ncity = gets\nputs '[ Type the state ]'\nstate = gets\nputs 'Processing...'\ntest = InfoJobs.new(city, state)\ntest.run\n</code></pre>\n\n<hr>\n\n<p>When I talk about void context, check the following example:</p>\n\n<pre><code># First definition of variable with a value\n@url = 'www.stackoverflow.com' # => \"www.stackoverflow.com\"\n# Then I'm adding a text, which is returning a value in a void context, in other\n# words, there's no context, like a variable or a method, which is receiving the\n# resulting value.\n@url + '/tags' # => \"www.stackoverflow.com/tags\"\n# If I access to the variable again, it has the same initial value\n@url # => \"www.stackoverflow.com\"\n# A different situation is when there's a context, in this case the same @url\n# variable, which it will receive the resulting value of the addition.\n@url = @url + '/tags' # => \"www.stackoverflow.com/tags\"\n@url # => \"www.stackoverflow.com/tags\"\n# Or also using the shorter += version\n@url += '?tab=name' # => \"www.stackoverflow.com/tags?tab=name\"\n@url # => \"www.stackoverflow.com/tags?tab=name\"\n</code></pre>\n\n<p>I'm far to be an OOP expert (I've forgotten most of theory learned in Uni.), but the idea is try to keep only the essential information of your object as attributes.<br>\nFor your case, I think city and state are essential to make all the object's functioning works as expected.<br>\nAlso, could be good to keep as attributes information to be accessed multiple times and that takes a while to get it. For your case, the jobs list was saved to be written later to a file (actually, rethinking the problem, maybe it wasn't necessary at all to have <code>@list</code> if after writing to a file isn't going to be used anymore).<br>\nFinally, you must to think that any created instance variable isn't garbage collected and will keep living in memory as long as your object's instance is alive. For your particular case, maybe this isn't a problem, but in the eventual case where you have thousands of those objects created, they should be as lightweight as possible or you could run out of memory.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T01:00:15.860",
"Id": "466778",
"Score": "0",
"body": "You have my sincere thanks. I really appreciate the break down you have done in my code. I could grasp most of all you wrote, but I couldn't understand what do you mean by \"void context\". Another thing, instance variables are the DNA of each object, right? So you don't keep changing their values like a did in the previously code right? like I was setting different values to my '@url' and '@parsed_html' variables each time the page changes."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T22:50:48.767",
"Id": "238010",
"ParentId": "237946",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "238010",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T05:03:18.167",
"Id": "237946",
"Score": "2",
"Tags": [
"ruby",
"web-scraping"
],
"Title": "Tentative to transform this scrape script into a class object program"
}
|
237946
|
<p>This is a simple GUI to display employee data stored in the database, with editing options that sync with the database and adjust display according to mouse clicks/ keyboard scrolling/add/delete ... and please do not mind pictures of dogs, I thought they might look cooler for the sake of demonstration. Awaiting your feedback/suggestions for improvements.</p>
<p>You can find the code repo here with necessary files <a href="http://bit.ly/3caE7sc" rel="nofollow noreferrer">http://bit.ly/3caE7sc</a></p>
<p><strong>Main interface:</strong> </p>
<p><a href="https://i.stack.imgur.com/nuSMb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nuSMb.png" alt="Main"></a></p>
<p><strong>Code:</strong></p>
<pre><code>#!/usr/local/bin/python3
from PyQt5.QtWidgets import (QWidget, QApplication, QDesktopWidget, QHBoxLayout, QFormLayout, QVBoxLayout,
QTableView, QPushButton, QLabel, QLineEdit, QTextEdit, QFileDialog, QMessageBox,
QAbstractItemView)
from PyQt5.QtGui import QPixmap, QFont, QImage
from PyQt5.QtCore import QAbstractTableModel, Qt
import pandas as pd
import numpy as np
import sqlite3
import sys
import cv2
import os
class _PandasModel(QAbstractTableModel):
"""
Sub-class of QAbstractTableModel, provides a standard interface for displaying a pandas DataFrame.
"""
def __init__(self, data):
"""
Initialize a pandas DataFrame for display.
Args:
data: pandas DataFrame.
"""
QAbstractTableModel.__init__(self)
self._data = data
def rowCount(self, parent):
"""
Return pandas DataFrame number of rows.
"""
return self._data.shape[0]
def columnCount(self, parent=None):
"""
Return pandas DataFrame number of columns.
"""
return self._data.shape[1]
def data(self, index, role=Qt.DisplayRole):
"""
Return pandas DataFrame data at a given index.
"""
if index.isValid():
if role == Qt.DisplayRole:
return str(self._data.iloc[index.row(), index.column()])
return None
def headerData(self, col, orientation, role):
"""
Return pandas DataFrame column name
"""
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self._data.columns[col]
return None
class _EmployeeBase(QWidget):
"""
Abstract base class for the employees app not for direct use,
to be sub-classed by by other employee app classes.
"""
def __init__(self, window_title, geometry=None, db='Employees.db', img_new_size=(200, 200)):
"""
Initialize database connection, dimensions and logistics.
Args:
window_title: Title to be displayed for the current interface.
geometry: int x, int y, int w, int h
db: Path to .db file.
img_new_size: new size to be fit inside all displayed windows.
"""
super().__init__()
self.image_size = img_new_size
self.place_holder = None
self.connection = sqlite3.connect(db)
self.cursor = self.connection.cursor()
if geometry:
self.setGeometry(*geometry)
self.setWindowTitle(window_title)
win_rectangle = self.frameGeometry()
center_point = QDesktopWidget().availableGeometry().center()
win_rectangle.moveCenter(center_point)
self.move(win_rectangle.topLeft())
self.setStyleSheet('QPushButton:!hover {color: yellow}')
self.icons = {'Person': 'Icons/person.png'}
self.image = QPixmap(self.icons['Person'])
self.binary_image = open(self.icons['Person'], 'rb').read()
def main_window(self):
"""
Display the main interface.
Return:
None
"""
self.place_holder = EmployeeMain()
self.close()
@staticmethod
def clear_cached_images():
"""
Cleanup cached images.
Return:
None
"""
current_dir = os.getcwd()
for item in os.listdir(current_dir):
if item.endswith('.png'):
os.remove(f'{current_dir}/{item}')
def closeEvent(self, event):
"""
Setup for closing event.
Args:
event: QCloseEvent.
Return:
None
"""
self.clear_cached_images()
event.accept()
class EmployeeMain(_EmployeeBase):
"""
Main window interface.
"""
def __init__(self, window_title='Employee Manager', left_ratio=4, right_ratio=6,
geometry=(0, 0, 1050, 500), db='Employees.db', img_new_size=(200, 200)):
"""
Initialize database connection, dimensions and logistics.
Args:
window_title: Title to be displayed for the current interface.
left_ratio: int, left main interface relative size.
right_ratio: int, right main interface relative size.
geometry: int x, int y, int w, int h
db: Path to .db file.
img_new_size: new size to be fit inside all displayed windows.
"""
_EmployeeBase.__init__(self, window_title, geometry, db, img_new_size)
self.left_ratio = left_ratio
self.right_ratio = right_ratio
self.main_layout = QHBoxLayout()
self.left_layout = QFormLayout()
self.right_main_layout = QVBoxLayout()
self.right_upper = QHBoxLayout()
self.right_lower = QHBoxLayout()
self.employee_data = QTableView()
self.employee_frame = None
self.right_widgets = {'New': (QPushButton('New'), self.create_employee),
'Update': (QPushButton('Update'), self.update_employee),
'Delete': (QPushButton('Delete'), self.delete_employee)}
self.left_widgets = {'Image': QLabel()}
self.adjust_layouts()
self.get_employees()
self.show()
def adjust_layouts(self):
"""
Setup main interface layouts.
Return:
None
"""
self.right_main_layout.addLayout(self.right_upper)
self.right_main_layout.addLayout(self.right_lower)
self.main_layout.addLayout(self.left_layout, self.left_ratio)
self.main_layout.addLayout(self.right_main_layout, self.right_ratio)
self.left_layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(self.main_layout)
self.adjust_widgets()
def adjust_widgets(self):
"""
Setup main interface widgets.
Return:
None
"""
self.right_upper.addWidget(self.employee_data)
self.employee_data.setStyleSheet('color: yellow')
for widget, widget_method in self.right_widgets.values():
self.right_lower.addWidget(widget)
widget.clicked.connect(widget_method)
for widget in self.left_widgets.values():
self.left_layout.addWidget(widget)
def get_employees(self):
"""
Fetch employee data from database and display the data.
Return:
None
"""
self.employee_frame = pd.read_sql_query('SELECT * FROM emp_data', self.connection)
model = _PandasModel(self.employee_frame.drop('image', axis=1))
self.employee_data.setModel(model)
self.employee_data.setSelectionBehavior(QAbstractItemView.SelectRows)
self.employee_data.selectRow(0)
self.display_selected()
self.employee_data.clicked.connect(self.display_selected)
self.employee_data.selectionModel().currentChanged.connect(self.display_selected)
@staticmethod
def clear_layout(layout):
"""
Clear a given layout.
Args:
layout: PyQt layout.
Return:
None
"""
items = [layout.itemAt(i) for i in range(1, layout.count())]
for item in items:
widget = item.widget()
widget.deleteLater()
def display_selected(self):
"""
Display selection from the right layout in the left display layout.
Return:
None
"""
self.clear_layout(self.left_layout)
indexes = self.employee_data.selectionModel().selectedRows()
if indexes:
selected = indexes[0].row()
values = self.employee_frame.iloc[selected].values
labels = ['ID: ', 'Name: ', 'Surname: ', 'Phone: ', 'e-mail: ', 'Address: ']
image_name = f'{values[0]}.png'
if image_name not in os.listdir():
with open(image_name, 'wb') as temp:
temp.write(values[5])
image = cv2.imread(image_name)
resized = cv2.resize(image, self.image_size)
height, width = self.image_size
self.image = QImage(resized, height, width, QImage.Format_RGB888)
self.left_widgets['Image'].setPixmap(QPixmap(self.image))
values = np.delete(values, 5)
for label, value in zip(labels, values):
self.left_layout.addRow(QLabel(label), QLabel(str(value)))
def create_employee(self):
"""
Shift to employee creation interface.
Return:
None
"""
self.place_holder = CreateEmployee()
self.close()
def update_employee(self):
"""
Update employee data, sync to database and shift to main interface.
Return:
None
"""
if not self.employee_data.selectedIndexes():
message = QMessageBox()
message.information(self, 'Information', 'You must select a row to delete')
return
indexes = self.employee_data.selectionModel().selectedRows()
if indexes:
selected = indexes[0].row()
self.place_holder = UpdateEmployee(self.employee_frame, selected)
self.close()
def delete_employee(self):
"""
Delete employee data sync to database and adjust display accordingly.
Return:
None
"""
if not self.employee_data.selectedIndexes():
message = QMessageBox()
message.information(self, 'Information', 'You must select a row to delete')
return
indexes = self.employee_data.selectionModel().selectedRows()
if indexes:
selected_row = indexes[0].row()
selected_id = self.employee_frame.iloc[selected_row]['id']
temp_image = f'{selected_id}.png'
if temp_image in os.listdir():
os.remove(temp_image)
name = self.employee_frame['name'].iloc[selected_row]
message = QMessageBox()
answer = message.question(self, 'Warning', f'Delete {name}, are you sure?')
if answer == QMessageBox.Yes:
delete_query = f'DELETE FROM emp_data WHERE id={selected_id}'
self.cursor.execute(delete_query)
self.connection.commit()
self.get_employees()
class CreateEmployee(_EmployeeBase):
"""
New employee data creation interface.
"""
def __init__(self, window_title='Create Employee', geometry=(0, 0, 500, 500),
db='Employees.db', img_new_size=(200, 200), employee_frame=None, selected=None):
"""
Initialize database connection, dimensions and logistics then display New/Edit interface.
Args:
window_title: Title to be displayed for the current interface.
geometry: int x, int y, int w, int h
db: Path to .db file.
img_new_size: new size to be fit inside all displayed windows.
employee_frame: pandas DataFrame with employee data to update.
selected: int, row of the selected employee to edit.
"""
_EmployeeBase.__init__(self, window_title, geometry, db, img_new_size)
self.employee_frame = employee_frame
self.selected_row = selected
emp_id, name, surname, phone, email, image, address = 7 * [None]
if isinstance(employee_frame, pd.DataFrame):
emp_id, name, surname, phone, email, image, address = employee_frame.iloc[self.selected_row].values
self.add_button = 'Update' if isinstance(self.employee_frame, pd.DataFrame) else 'Add'
self.main_layout = QVBoxLayout()
self.upper_layout = QVBoxLayout()
self.lower_layout = QFormLayout()
self.window_inner_title = 'Add Employee' if not isinstance(self.selected_row, int) else 'Edit Employee'
self.upper_widgets = {'Title': (QLabel(self.window_inner_title), None),
'Image': (QLabel(), None)}
self.lower_widgets = {'Back': (None, QPushButton('Back'), None, self.main_window),
'Name': (QLabel('Name :'), QLineEdit(name), 'Enter name', None),
'Surname': (QLabel('Surname :'), QLineEdit(surname), 'Enter surname', None),
'Phone': (QLabel('Phone: '), QLineEdit(phone), 'Enter phone number', None),
'e-mail': (QLabel('e-mail: '), QLineEdit(email), 'Enter e-mail', None),
'Image': (QLabel('Image: '), QPushButton('Browse'), None, self.upload_image),
'Address': (QLabel('Address: '), QTextEdit(address), 'Enter Address', None),
'Add': (None, QPushButton(self.add_button), None, self.add_employee),
}
self.adjust_layouts()
if isinstance(self.employee_frame, pd.DataFrame):
self.set_image(self.selected_row)
self.show()
def adjust_layouts(self):
"""
Setup layouts for employee editing interface.
Return:
None
"""
self.main_layout.addLayout(self.upper_layout)
self.main_layout.addLayout(self.lower_layout)
self.setLayout(self.main_layout)
self.adjust_widgets()
self.upper_layout.setContentsMargins(115, 0, 0, 0)
self.lower_layout.setContentsMargins(0, 0, 0, 0)
def adjust_widgets(self):
"""
Setup widgets for employee editing interface.
Return:
None
"""
self.upper_widgets['Image'][0].setPixmap(self.image)
self.upper_widgets['Title'][0].setFont(QFont('Arial', 20))
for widget, widget_method in self.upper_widgets.values():
self.upper_layout.addWidget(widget)
if widget_method:
widget.clicked.connect(widget_method)
for label, widget, place_holder, widget_method in self.lower_widgets.values():
self.lower_layout.addRow(label, widget)
if place_holder:
widget.setPlaceholderText(place_holder)
widget.setStyleSheet('color: orange')
if widget_method:
widget.clicked.connect(widget_method)
def set_image(self, selected):
"""
Display selected to edit employee image.
Args:
selected: selected row.
Return:
None
"""
values = self.employee_frame.iloc[selected].values
image_name = f'{values[0]}.png'
if image_name not in os.listdir():
with open(image_name, 'wb') as temp:
temp.write(values[5])
self.binary_image = open(image_name, 'rb').read()
image = cv2.imread(image_name)
resized = cv2.resize(image, self.image_size)
height, width = self.image_size
self.image = QImage(resized, height, width, QImage.Format_RGB888)
self.upper_widgets['Image'][0].setPixmap(QPixmap(self.image))
def upload_image(self):
"""
Browse and upload image, adjust display accordingly.
Return:
None
"""
file_dialog = QFileDialog()
file_name, _ = file_dialog.getOpenFileName(self, 'Upload Image')
try:
uploaded = cv2.imread(file_name)
self.binary_image = open(file_name, 'rb').read()
resized = cv2.resize(uploaded, self.image_size)
height, width = self.image_size
self.image = QImage(resized, height, width, QImage.Format_RGB888)
self.upper_widgets['Image'][0].setPixmap(QPixmap(self.image))
except (cv2.error, FileNotFoundError):
print(f'Image could not be loaded')
def add_employee(self):
"""
Add new employee to the database, adjust and display main interface accordingly.
Return:
None
"""
name = self.lower_widgets['Name'][1].text()
surname = self.lower_widgets['Surname'][1].text()
phone = self.lower_widgets['Phone'][1].text()
email = self.lower_widgets['e-mail'][1].text()
image = self.binary_image
address = self.lower_widgets['Address'][1].toPlainText()
items = [name, surname, phone, email, image, address]
if not all(items):
message = QMessageBox()
message.information(self, 'Failure', f'Cannot add with empty fields')
return
query = (f'INSERT INTO emp_data(name, surname, phone, email, image, address) '
f'Values(?, ?, ?, ?, ?, ?)')
self.cursor.execute(query, [name, surname, phone, email, image, address])
self.connection.commit()
message = QMessageBox()
message.information(self, 'Success', f'{surname}, {name} has been added')
self.main_window()
class UpdateEmployee(CreateEmployee):
"""
Update existing employee data interface.
"""
def __init__(self, employee_frame, selected, window_title='Update Employee', geometry=(0, 0, 500, 500),
db='Employees.db', img_new_size=(200, 200)):
"""
Initialize database connection, dimensions and logistics then display Edit interface.
Args:
window_title: Title to be displayed for the current interface.
geometry: int x, int y, int w, int h
db: Path to .db file.
img_new_size: new size to be fit inside all displayed windows.
employee_frame: pandas DataFrame with employee data to update.
selected: int, row of the selected employee to edit.
"""
CreateEmployee.__init__(self, window_title, geometry, db, img_new_size, employee_frame, selected)
self.employee_frame = employee_frame
self.selected_row = selected
self.show()
def add_employee(self):
"""
Update existing employee data, adjust and display main interface accordingly.
"""
name = self.lower_widgets['Name'][1].text()
surname = self.lower_widgets['Surname'][1].text()
phone = self.lower_widgets['Phone'][1].text()
email = self.lower_widgets['e-mail'][1].text()
image = self.binary_image
address = self.lower_widgets['Address'][1].toPlainText()
items = [name, surname, phone, email, image, address]
if not all(items):
message = QMessageBox()
message.information(self, 'Failure', f'Cannot add with empty fields')
return
selected_id = self.employee_frame.iloc[self.selected_row]['id']
delete_query = f'DELETE FROM emp_data WHERE id={selected_id}'
add_query = (f'INSERT INTO emp_data(id, name, surname, phone, email, image, address) '
f'Values(?, ?, ?, ?, ?, ?, ?)')
self.cursor.execute(delete_query)
self.cursor.execute(add_query, [int(selected_id), name, surname, phone, email, image, address])
self.connection.commit()
message = QMessageBox()
message.information(self, 'Success', f'{surname}, {name} has been updated')
self.main_window()
if __name__ == '__main__':
test = QApplication(sys.argv)
window = EmployeeMain()
sys.exit(test.exec_())
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T05:09:47.217",
"Id": "237947",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"gui",
"pyqt"
],
"Title": "Simple employee GUI database sync/display/edit"
}
|
237947
|
<p>As part of learning Vue and Vue Test Utils I develop some simple games. I made a simple version of craps. Because in many other games a die (or dice) is used, I decided to create a reusable component <code>GameDie</code>.</p>
<p><strong><code>GameDie.vue</code></strong></p>
<pre><code><template>
<span class="dice">{{ dice.icon }}</span>
</template>
<script>
export default {
name: 'GameDie',
data() {
return {
dieFaces: [
{
value: undefined,
icon: '',
},
{
value: 1,
icon: '⚀',
},
{
value: 2,
icon: '⚁',
},
{
value: 3,
icon: '⚂',
},
{
value: 4,
icon: '⚃',
},
{
value: 5,
icon: '⚄',
},
{
value: 6,
icon: '⚅',
},
],
value: undefined,
};
},
computed: {
dice() {
return this.dieFaces.filter((el) => el.value === this.value).shift();
},
},
methods: {
/**
* Generate a random number between 1 and 6.
* Assign it to the property value.
*/
throwDice() {
this.value = 1 + Math.floor(Math.random() * 6);
this.$eventBus.$emit('transmit-dice', this.value);
},
/**
* Reset the dice.
*/
resetDice() {
if (this.value) {
this.value = undefined;
}
},
},
created() {
this.$eventBus.$on('throw-dice', this.throwDice);
this.$eventBus.$on('reset-dice', this.resetDice);
},
};
</script>
<style scoped>
.dice {
font-size: 4em;
}
</style>
</code></pre>
<p>I use emojis for the dice. When the die is thrown the value is calculated with <code>Math.random</code>. The component relies on a global event bus.</p>
<p>My <code>main.js</code> looks like this:</p>
<pre><code>import Vue from 'vue';
import { BootstrapVue } from 'bootstrap-vue';
import App from './App.vue';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap-vue/dist/bootstrap-vue.css';
Vue.use(BootstrapVue);
Vue.config.productionTip = false;
Vue.prototype.$eventBus = new Vue();
new Vue({
render: (h) => h(App),
}).$mount('#app');
</code></pre>
<p>The <code>GameDie.vue</code> component can now be used for different games, for craps or backgammon you need two dices:</p>
<pre><code><template>
<div>
<game-die></game-die>
<game-die></game-die>
</div>
</template>
</code></pre>
<p>For yamb you would need for example 5 dice, for <em>Mensch ärgere Dich nicht</em> just one.</p>
<p>Since I didn't have any other idea I used a global event bus to trigger the throwing and resetting the die. If we include <code>GameDie.vue</code> as a child component then the parent should actually communicate with it by passing props. But I was not sure how could I implement this.</p>
<p>The unit tests are here:</p>
<pre><code>import { expect } from 'chai';
import sinon from 'sinon';
import mergeWith from 'lodash.mergewith';
import { shallowMount, createLocalVue } from '@vue/test-utils';
import Vue from 'vue';
import GameDie from '@/components/GameDie.vue';
/* eslint-disable no-param-reassign */
const GlobalPlugins = {
install(v) {
v.prototype.$eventBus = new Vue();
},
};
/* eslint-enable no-param-reassign */
const localVue = createLocalVue();
localVue.use(GlobalPlugins);
describe('GameDie.vue', () => {
function createWrapper(overrides) {
const options = {
mocks: {
$eventBus: {
$on: sinon.spy(),
$emit: sinon.spy(),
},
},
};
return shallowMount(GameDie, mergeWith(options, overrides));
}
it('should render the dice', () => {
const wrapper = createWrapper();
expect(wrapper.text()).to.equal('');
});
it('should render a die face', () => {
const data = () => ({
value: 2,
});
const wrapper = createWrapper({ data });
expect(wrapper.vm.value).to.equal(2);
expect(wrapper.text()).to.equal('⚁');
});
it('should listen to custom events', () => {
const wrapper = createWrapper();
expect(wrapper.vm.$eventBus.$on.calledTwice).to.equal(true);
expect(wrapper.vm.$eventBus.$on.calledWith('throw-dice')).to.equal(true);
expect(wrapper.vm.$eventBus.$on.calledWith('reset-dice')).to.equal(true);
});
it('should listen to custom event throw-dice', () => {
const throwDiceSpy = sinon.spy();
const wrapper = shallowMount(GameDie, {
localVue,
methods: {
throwDice: throwDiceSpy,
},
});
wrapper.vm.$eventBus.$emit('throw-dice');
expect(throwDiceSpy.called).to.equal(true);
});
it('should listen to custom event reset-dice', () => {
const resetDiceSpy = sinon.spy();
const wrapper = shallowMount(GameDie, {
localVue,
methods: {
resetDice: resetDiceSpy,
},
});
wrapper.vm.$eventBus.$emit('reset-dice');
expect(resetDiceSpy.called).to.equal(true);
});
it('should emit a custom event transmit-dice', () => {
const wrapper = createWrapper();
wrapper.vm.throwDice();
expect(wrapper.vm.$eventBus.$emit.called).to.equal(true);
});
});
</code></pre>
<p>What can be improved here? Is there a better way using props? Or maybe Vue.js is not an adequate tool for programming games?</p>
<p>For the unit tests I used the input from a <a href="https://stackoverflow.com/questions/60338721/how-to-test-a-global-event-bus-in-vuejs">question</a> I posted on StackOverflow. If the approach with the global event bus is good, how would you enhance the tests?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T09:15:18.517",
"Id": "466687",
"Score": "0",
"body": "Oh there's definitely nothing wrong with using Vue.js for programming games. I've done so myself for a few games."
}
] |
[
{
"body": "<p>First of all, communicating through father-son relation component-wise should be with the event bus and props whereas it is recommended to send events from father to son with props.</p>\n\n<p>I would use a prop to change the specific instance of the dice because you will be triggering a single event to a single die.\nIf you would indeed want this to happen, I would use a single data property to bind all the dice from the father component.</p>\n\n<p>With your implementation - all dice would reset/re-roll and you would get unknown behavior in the future if you would want to re-use your die.\nThis would be a bad practice and you want to implement components as a single monad with a designed functionality without side effects. (more on monads <a href=\"https://en.wikipedia.org/wiki/Monad_(functional_programming)\" rel=\"nofollow noreferrer\">here</a>)</p>\n\n<p>Secondly I would stick with 'die' or 'dice' for the sake of consistency and readability.</p>\n\n<p>Thirdly, Vue has $emit as a native prototype so there's no need to configure it in your main.js you probably already know it but here's the <a href=\"https://vuejs.org/v2/guide/components-custom-events.html\" rel=\"nofollow noreferrer\">resource</a>.\nAlso, a bit petty but alas, You're not using Bootstrap but you are importing it to your project.</p>\n\n<p><strong>PS</strong></p>\n\n<p>Another solution would be using <a href=\"https://vuex.vuejs.org/\" rel=\"nofollow noreferrer\">Vuex</a> for non father-son relation, perhaps holding an array of dice and changing their state that would trigger a single event for the responsible die</p>\n\n<p><strong>Edit</strong></p>\n\n<p>Here's a working git <a href=\"https://github.com/Natanhel/GameDiceExample\" rel=\"nofollow noreferrer\">example of using props with your code</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T19:36:51.933",
"Id": "476332",
"Score": "0",
"body": "Thank you very much for your answer. Unfortunately the GitHub repository seems to have just the boilerplate code for a Vue.JS app. Have you maybe forgotten to push the actual code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-22T13:44:31.173",
"Id": "476435",
"Score": "0",
"body": "Yes you are correct, no idea how that happened :S\nFixed that :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T11:51:02.260",
"Id": "242693",
"ParentId": "237953",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T07:33:52.203",
"Id": "237953",
"Score": "6",
"Tags": [
"javascript",
"game",
"unit-testing",
"dice",
"vue.js"
],
"Title": "Vue component for Game Die (dice)"
}
|
237953
|
<pre><code>const getSelectedItemsIds = selectedItemsList => {
let keys = Object.keys(selectedItemsList);
let selectedItems = [];
keys.map(k => {
selectedItemsList[k].map(id => {
if (k.includes("projectIds")) {
return selectedItems.push({ type: "PROJECT", id });
} else if (k.includes("subjectGroupIds")) {
return selectedItems.push({
type: "SUBJECT_GROUP",
id
});
} else if (k.includes("subjectIds")) {
return selectedItems.push({ type: "SUBJECT", id });
}
});
});
return selectedItems;
}
</code></pre>
<p>I have written my custom logic to get the desired result, if anyone can validate and tell me if there's a better way to do it. I'm adding input and expected out below:</p>
<pre><code>I/P:
{
projectIds: [2]
subjectGroupIds: [] // incase multiple subjects are grouped togehter
subjectIds: [4]
}
Expected format:
[{"type":"PROJECT","id":2},{"type":"SUBJECT","id":4}]
</code></pre>
<p>Thanks in advance!</p>
|
[] |
[
{
"body": "<p>Your code is not bad. You use functional style to loop through the data, which is good. But inside the loop you do not have to check with if-elseif-elseif, as this is not solid when it comes to many many cases. \nMaybe it would be better to use a map object to guide the process of matching data.</p>\n\n<pre><code>getSelectedItemsIds = selectedItemsList => {\n const keyNamesMap = {\n projectIds: \"PROJECT\",\n subjectGroupIds: \"SUBJECT_GROUP\", \n subjectIds: \"SUBJECT\"\n };\n let selectedItems = [];\n\n Object.keys(keyNamesMap).map( k => {\n selectedItemsList[k].map ( id => {\n selectedItems.push (\n {\n type: keyNamesMap[k],\n id: id\n }\n );\n }); \n });\n return selectedItems;\n}\n</code></pre>\n\n<p>This way it is more clear and more easy to add another type.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T08:57:31.393",
"Id": "237959",
"ParentId": "237954",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "237959",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T07:36:16.813",
"Id": "237954",
"Score": "0",
"Tags": [
"javascript",
"object-oriented",
"array",
"functional-programming",
"iteration"
],
"Title": "converting object of arrays to an array of objects in a desired format"
}
|
237954
|
<p>I will be inserting a new text line in a <code>setup.py</code> file, this new line will contain text, and is part of the <code>REQUIRED_PACKAGES</code>. I parsed the
file and look for <code>REQUIRED_PACKAGES</code> pattern (<code>REQUIRED_PACKAGES = [ ... ]</code>). Looking for alternatives during file insertion.</p>
<p>A sample <code>setup.py</code> file looks like this:</p>
<pre><code>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import fnmatch
import os
import re
import sys
from setuptools import Command
from setuptools import find_packages
from setuptools import setup
from setuptools.command.install import install as InstallCommandBase
from setuptools.dist import Distribution
DOCLINES = __doc__.split('\n')
_VERSION = '1.0.0'
REQUIRED_PACKAGES = [
'absl-py >= 0.7.0',
'astunparse == 1.6.3',
'backports.weakref >= 1.0rc1;python_version<"3.4"',
'enum34 >= 1.1.6;python_version<"3.4"',
'gast == 0.3.3',
'scipy == 1.2.2;python_version<"3"',
]
if sys.byteorder == 'little':
# grpcio does not build correctly on big-endian machines due to lack of
# BoringSSL support.
REQUIRED_PACKAGES.append('io >= 1.0.0')
...
</code></pre>
<p>After conversion it will look like this (adding a new line):</p>
<pre><code>...
REQUIRED_PACKAGES = [
'absl-py >= 0.7.0',
'astunparse == 1.6.3',
'backports.weakref >= 1.0rc1;python_version<"3.4"',
'enum34 >= 1.1.6;python_version<"3.4"',
'gast == 0.3.3',
'scipy == 1.2.2;python_version<"3"',
'test==1.0.0',
]
...
</code></pre>
<p>Python code</p>
<pre><code>import re
SEARCH_DICT = {
'required_packages': re.compile(
r'REQUIRED_PACKAGES = (?P<required_packages>.*)\n')
}
TEST_LIBRARY = '\t\t\'test==1.0.0\'\n'
def _parse_line(line):
"""
Do a regex search against all defined regexes and
return the key and match result of the first matching regex
"""
for key, rx in SEARCH_DICT.items():
match = rx.search(line)
if match:
return key, match
# if there are no matches
return None, None
def parse_file(filepath):
"""
Parse text at given filepath
Parameters
----------
filepath : str
Filepath for file_object to be parsed
Returns
-------
data : file contents
while True:
last_pos = fp.tell()
line = fp.readline()
new_line = line.upper()
fp.seek(last_pos)
fp.write(new_line)
print "Read %s, Wrote %s" % (line, new_line)
"""
data = [] # create an empty list to collect the data
line_index = -1
# open the file and read through it line by line
with open(filepath, 'r+') as file_object:
line = file_object.readline()
line_index+=1
while line:
# at each line check for a match with a regex
key, match = _parse_line(line)
if key == 'required_packages':
required_packages_start = match.group('required_packages')
if required_packages_start == '[':
print('Found REQUIRED_PACKAGES')
while line.strip():
library = line.rstrip()
if library == ']': # End of required packages
return line_index
line = file_object.readline()
line_index+=1
line = file_object.readline()
line_index+=1
file_object.readline()
line_index+=1
return line_index
line_index = parse_file('setup.py')
lines = None
if line_index != -1:
with open('setup.py', 'r+') as fd:
contents = fd.readlines()
contents.insert(line_index, TEST_LIBRARY) # new_string should end in a newline
fd.seek(0) # readlines consumes the iterator, so we need to start over
fd.writelines(contents) # No need to truncate as we are increasing filesize
</code></pre>
|
[] |
[
{
"body": "<p>Your code goes through the file twice - once to find the index where your new line is to be inserted, and again to actually perform the change.</p>\n\n<p>My approach to this problem would be to create a class that contains three variables:</p>\n\n<ol>\n<li>The lines in <code>setup.py</code> before <code>\"REQUIRED_PACKAGES = [\"</code></li>\n<li>The contents of the <code>REQUIRED_PACKAGES</code> list</li>\n<li>The lines in <code>setup.py</code> after the <code>REQUIRED_PACKAGES</code> list</li>\n</ol>\n\n<p>Your problem then splits nicely into three distinct sub-problems:</p>\n\n<ol>\n<li>Parsing <code>setup.py</code> and returning an instance of the class above</li>\n<li>Adding an element to the required packages list in your custom class (trivial)</li>\n<li>Writing a new <code>setup.py</code> file</li>\n</ol>\n\n<p>Looking at your code specifically, your docstring for <code>parse_file</code> does not match what the code is doing. It says that <code>data</code> is returned, but the code actually returns <code>line_index</code>, and the <code>data</code> member you initialise is unused.</p>\n\n<p>Your code comments in general could be improved. You comment some obvious things such as\"open the file and read through it line by line\" and \"if there are no matches\". These operations are immediately apparent from looking at the code, and do not require comments. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T10:04:52.267",
"Id": "237961",
"ParentId": "237956",
"Score": "4"
}
},
{
"body": "<p>Things I would do differently:</p>\n\n<ul>\n<li>make the function checking for the line where to insert accept any iterator which yields lines. This hoists the IO to a level above, and makes the function easier to test. I would also throw an exception if there is no place to insert the line, instead of returning <code>-1</code> as a sentinel value</li>\n<li>make the function inserting the line a generator that yields lines</li>\n<li>use a temporary file to write the new content, and when finished, copy this to the original file</li>\n</ul>\n\n<h1>Finding the insertion place</h1>\n\n<p>With some rearrangements, replacing the <code>while</code> for a <code>for</code>-loop and inversions of checks, I arrive at something like this</p>\n\n<pre><code>def find_insert_position(lines: typing.Iterator[str]) -> int:\n line_index = -1\n for line in lines:\n line_index += 1\n\n key, match = _parse_line(line)\n if key != \"required_packages\":\n continue\n required_packages_start = match.group(\"required_packages\")\n if required_packages_start != \"[\":\n continue\n logging.debug(\"Found REQUIRED_PACKAGES\")\n while True:\n library = line.rstrip()\n if library == \"]\": # End of required packages\n return line_index\n try:\n line = next(lines)\n line_index += 1\n except StopIteration:\n raise ValueError(\"No required packages found\")\n raise ValueError(\"No required packages found\")\n</code></pre>\n\n<p>I also started using the <code>logging</code> module instead of a <code>print</code>, and added type annotations.</p>\n\n<p>I also adapted the regex a bit to</p>\n\n<pre><code>SEARCH_DICT = {\n \"required_packages\": re.compile(\n r\"^REQUIRED_PACKAGES = (?P<required_packages>.*)$\"\n )\n}\n</code></pre>\n\n<p>This works in both your and this method.</p>\n\n<p>In your original method, I found no reason for the <code>while line.strip()</code>. On the contrary. If there is an empty line somewhere in the list of required packages, this does not work. I changed this to a <code>while True</code>.</p>\n\n<p>This code can be tested with a number of testcases, listed at the end of the answer</p>\n\n<pre><code>test_cases = {\n test_case_empty: None,\n test_case_no_req: None,\n test_case_empty_req: 2,\n test_case_one_line_req: None,\n test_case_req: 8,\n code: 27,\n test_case_req_empty_line: 9,\n}\n\nfor test_case, expected_result in test_cases.items():\n try:\n result = find_insert_position(test_case.split(\"\\n\"))\n assert result == expected_result\n except ValueError as e:\n assert expected_result is None\n</code></pre>\n\n<h1>inserting the line</h1>\n\n<p>This can be very easily done with a generator:</p>\n\n<pre><code>import itertools\ndef insert_line(lines: typing.Iterable[str], insert_position: int, line_to_insert: str):\n lines = iter(lines)\n for i, line in enumerate(itertools.islice(lines, insert_position)):\n yield line\n if insert_position > i + 1:\n raise ValueError(\"insert_position is beyond `lines`\")\n yield line_to_insert\n yield from lines\n</code></pre>\n\n<p>And tested as follows:</p>\n\n<blockquote>\n<pre><code>list(insert_line([\"a\"] * 10, 10, \"test\"))\n</code></pre>\n</blockquote>\n\n<pre><code>['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'test']\n</code></pre>\n\n<blockquote>\n<pre><code>list(insert_line([\"a\"] * 10, 11, \"test\"))\n</code></pre>\n</blockquote>\n\n<pre><code>Raises ValueError\n</code></pre>\n\n<p>So this is also a simple, easily testable unit.</p>\n\n<h1>tempfile</h1>\n\n<p>Instead of reading and writing to the same file, I would either create a temporary file (with <a href=\"https://docs.python.org/3/library/tempfile.html\" rel=\"nofollow noreferrer\">tempfile</a> and then replace the original with it, or concatenate the results into a string and then write that to the file</p>\n\n<pre><code>def write_result(lines, output_file: Path):\n with tempfile.TemporaryDirectory() as tempdir:\n my_tempfile : Path = Path(tempdir) / \"output.txt\"\n with my_tempfile.open(\"w\") as filehandle:\n for line in lines:\n filehandle.write(line)\n my_tempfile.replace(output_file)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>result = \"\\n\".join(lines)\nast.parse(result)\noutut_file.write_text(result)\n</code></pre>\n\n<p>The main difference is when the source is large, this will use more memory</p>\n\n<h2>verify the result</h2>\n\n<p>You can even use the <code>ast</code> or <code>py_compile</code> module to check whether you generated valid python by inserting a <code>py_compile.compile(my_tempfile)</code> before replacing the original with the generate file</p>\n\n<h1>putting it together:</h1>\n\n<pre><code>if __name__ == \"__main__\":\n source_file = Path(\"test.py\")\n TEST_LIBRARY = \" 'test,'\\n\"\n with source_file.open(\"r\") as filehandle:\n try:\n insert_location = find_insert_position(filehandle)\n except ValueError:\n insert_location = None\n print(f\"insert_location: {insert_location}\")\n if insert_location is not None:\n with source_file.open(\"r\") as filehandle:\n new_lines = list(insert_line(\n lines=filehandle,\n insert_position=insert_location,\n line_to_insert=TEST_LIBRARY,\n ))\n write_result(new_lines, source_file.with_suffix(\".new.py\"))\n</code></pre>\n\n<p>I've added the <code>.with_suffix(\".new.py\")</code> so during testing, you can check the results side by side.</p>\n\n<p>I've also replaced the <code>'</code> in <code>TEST_LIBRARY</code> with <code>\"</code> so you don't have to escape the <code>'</code>. I also see you use tabs to indent, better use 4 spaces.</p>\n\n<p>Also know that this approach might not work when the last line in the <code>REQUIRED_PACKAGES</code> does not end with a <code>,</code>. Python concatenates strings on different lines, so this will not be picked up by the <code>py_compile</code> either, so this will fail silently.</p>\n\n<hr>\n\n<h1>test cases</h1>\n\n<pre><code>test_case_empty = \"\"\"\n\n\n\"\"\"\ntest_case_no_req = \"\"\"\nno required packages\n\"\"\"\n\ntest_case_empty_req = \"\"\"\nREQUIRED_PACKAGES = [\n]\n\"\"\"\n\ntest_case_one_line_req = \"\"\"\nREQUIRED_PACKAGES = []\n\"\"\"\n\ntest_case_req = \"\"\"\nREQUIRED_PACKAGES = [\n 'absl-py >= 0.7.0',\n 'astunparse == 1.6.3',\n 'backports.weakref >= 1.0rc1;python_version<\"3.4\"',\n 'enum34 >= 1.1.6;python_version<\"3.4\"',\n 'gast == 0.3.3',\n 'scipy == 1.2.2;python_version<\"3\"',\n]\n\"\"\"\ntest_case_req_empty_line = \"\"\"\nREQUIRED_PACKAGES = [\n 'absl-py >= 0.7.0',\n 'astunparse == 1.6.3',\n 'backports.weakref >= 1.0rc1;python_version<\"3.4\"',\n 'enum34 >= 1.1.6;python_version<\"3.4\"',\n\n 'gast == 0.3.3',\n 'scipy == 1.2.2;python_version<\"3\"',\n]\n\"\"\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-08T18:42:12.013",
"Id": "488159",
"Score": "0",
"body": "The final copy of the temporary file could use `shutil` to make use of [platform-dependent fast copying](https://docs.python.org/3.8/library/shutil.html#platform-dependent-efficient-copy-operations) system calls on Python 3.8 (as I pointed out in my answer to a similar question [here](https://stackoverflow.com/a/62366144/2251982))."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T07:19:45.943",
"Id": "488194",
"Score": "0",
"body": "I don't copy the tempfile. `my_tempfile.replace(output_file)` moves [moves](https://docs.python.org/3/library/pathlib.html#pathlib.Path.replace) the temporary file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-09T19:47:48.747",
"Id": "488267",
"Score": "0",
"body": "Ah, that's indeed better than copying."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T14:53:34.277",
"Id": "238038",
"ParentId": "237956",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "237961",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T08:02:16.630",
"Id": "237956",
"Score": "5",
"Tags": [
"python",
"parsing"
],
"Title": "Python insert line in the middle of the file"
}
|
237956
|
<p>Basically I have written a matrix class for addition, multiplication and scalar multiplication.</p>
<p>I need your review of the class implementation below in terms of efficiency, memory consumption and new C++11/14/17 features that can be used. </p>
<p>Here goes the code: </p>
<p>Matrix.hpp</p>
<pre><code>// Created by prajwal.sapare on 2/18/2020.
//
#ifndef UNTITLED2_MATRIX_HPP
#define UNTITLED2_MATRIX_HPP
#include <vector>
#include <exception>
#include <iostream>
#include <algorithm>
#include "helper.h"
template<class T, uint m, uint n>
class Matrix;
template <class T, uint n>
using rowVector = Matrix<T, 1, n>;
template <class T, uint m>
using colVector = Matrix<T, m, 1>;
template<class T, uint m, uint n>
class Matrix {
public:
explicit Matrix();
explicit Matrix(const std::vector<T> matrixValue);
int getRows()const;
int getColoumns() const;
T& operator()(const uint row, const uint col);
Matrix<T,m,n> operator=(std::vector<T> matrixIntializationValue);
template<uint N>
Matrix<T,m,N> operator*(Matrix<T,n,N>& other);
template<uint a, uint b>
bool operator==(Matrix<T,a,b>& other);
Matrix<T,m,n> operator+(Matrix<T,m,n>& other);
Matrix<T,m,n> operator*(T scalar);
template<class T, uint m, uint n> friend std::ostream& operator<<(std::ostream& os, const Matrix<T,m,n>& matrix);
private:
uint rows;
uint cols;
std::vector<std::vector<T>> data;
};
template<class T, uint m, uint n>
Matrix<T,m,n>::Matrix(): rows(m), cols(n)
{
if(rows == 0 || cols == 0)
throw std::invalid_argument( "received zero as argument" );
data.resize(rows);
for (auto& colData : data)
colData.resize(cols);
}
template<class T, uint m, uint n>
Matrix<T,m,n>::Matrix(const std::vector<T> matrixValue): rows(m), cols(n)
{
if(rows == 0 || cols == 0)
throw std::invalid_argument( "received zero as argument" );
if(matrixValue.empty())
throw std::invalid_argument( "Empty vector" );
if(rows * cols != matrixValue.size())
throw std::runtime_error( "Total number of matrix values does not match with rows and coloumns provided" );
data.resize(rows);
for (auto& colData : data)
colData.resize(cols);
for (auto i = 0; i<rows; i++)
data[i] = {matrixValue.begin() + (i * cols), matrixValue.begin() + ((i+1) * cols)};
}
template<class T, uint m, uint n>
int Matrix<T,m,n>::getRows() const
{
return this->rows;
}
template<class T, uint m, uint n>
int Matrix<T,m,n>::getColoumns() const
{
return this->cols;
}
template<class T, uint m, uint n>
T& Matrix<T,m,n>::operator()(const uint row, const uint col)
{
return this->data[row][col];
}
template<class T, uint m, uint n>
Matrix<T,m,n> Matrix<T,m,n>::operator+(Matrix& other)
{
if ((this->rows == other.getRows()) && (this->cols == other.getColoumns()))
{
Matrix<T,m,n> resultantMatrix;
for(auto i = 0; i< this->rows; i++)
{
for(auto j = 0; j < this->cols; j++)
{
auto& valueFirst = this->data[i][j];
auto& valueSecond = other(i, j);
if((additionOverflow(valueFirst, valueSecond)) || (additionUnderflow(valueFirst, valueSecond)))
throw std::out_of_range("Resultant value of matrix is out of range");
else
resultantMatrix(i, j) = valueFirst + valueSecond;
}
}
return resultantMatrix;
}
else
throw std::runtime_error("Matrices cannot be added, sizes do not match");
}
template<class T, uint m, uint n>
template<uint N>
Matrix<T,m,N> Matrix<T,m,n>::operator*(Matrix<T,n,N>& other)
{
if ((this->cols == other.getRows()))
{
Matrix<T,m,N> resultantMatrix;
T temp = 0;
for (auto i = 0; i < this->rows; i++) {
for (auto j = 0; j < other.getColoumns(); j++) {
temp = 0.0;
for (auto k = 0; k < this->cols; k++) {
if(other(k, j) != 0)
{
if(multiplicationOverflow(this->data[i][k], other(k, j)) || multiplicationUnderflow(this->data[i][k], other(k, j)))
throw std::out_of_range("Resultant value of matrix is out of range");
}
auto tempMul = this->data[i][k] * other(k, j);
if((additionOverflow(temp, tempMul)) || (additionUnderflow(temp, tempMul)))
throw std::out_of_range("Resultant value of matrix is out of range");
temp = temp + tempMul;
}
resultantMatrix(i, j) = temp;
}
}
return resultantMatrix;
}
else
throw std::runtime_error("Matrices cannot be multiplied, invalid sizes");
}
template<class T, uint m, uint n>
Matrix<T,m,n> Matrix<T,m,n>::operator*(T scalar){
Matrix<T,m,n> resultantMatrix;
for (auto i = 0; i < this->rows; i++)
{
for (auto j = 0; j < this->cols; j++)
{
auto valueFirst = this->data[i][j];
if (scalar == 0)
resultantMatrix(i,j) = 0;
else if((multiplicationOverflow(valueFirst, scalar)) || (multiplicationUnderflow(valueFirst, scalar)))
throw std::out_of_range("Resultant value of matrix is out of range");
else
resultantMatrix(i,j) = this->data[i][j] * scalar;
}
}
return resultantMatrix;
}
template<class T, uint m, uint n>
Matrix<T,m,n> Matrix<T,m,n>::operator=(std::vector<T> matrixIntializationValue)
{
if (!matrixIntializationValue.empty())
{
if(rows * cols != matrixIntializationValue.size())
throw std::invalid_argument( "Total number of matrix values does not match with rows and coloumns provided" );
for (auto i = 0; i<rows; i++)
data[i] = {matrixIntializationValue.begin() + (i * cols), matrixIntializationValue.begin() + ((i+1) * cols)};
return *this;
}
else
throw std::runtime_error("Matrices cannot be multiplied, invalid sizes");
}
template<class T, uint m, uint n>
std::ostream& operator<<(std::ostream &os, const Matrix<T,m,n> &matrix)
{
if(!matrix.data.empty())
{
for (const auto& rowVal : matrix.data)
{
for(const auto& colVal : rowVal)
os << colVal << " ";
os << std::endl;
}
}
return os;
}
template<class T, uint m, uint n>
template<uint a, uint b>
bool Matrix<T,m,n>::operator==(Matrix<T,a,b>& other)
{
if( (m!=a) || (n!=b))
return false;
for(auto i =0; i< m ; i++)
{
for(auto j=0;j <n;j++)
{
if(this->data[i][j]!= other(i,j))
return false;
}
}
return true;
}
#endif //UNTITLED2_MATRIX_HPP
</code></pre>
<p>Helper.h</p>
<pre><code>//
// Created by prajwal.sapare on 2/22/2020.
//
#ifndef UNTITLED2_HELPER_H
#define UNTITLED2_HELPER_H
using uint = unsigned int;
#include <limits>
template <typename T>
constexpr bool additionOverflow(const T& x, const T& y) {
return (y >= 0) && (x > std::numeric_limits<T>::max() - y);
}
template <typename T>
constexpr bool additionUnderflow(const T& x, const T& y) {
return (y < 0) && (x < std::numeric_limits<T>::min() - y);
}
template <typename T>
constexpr bool multiplicationOverflow(const T& x, const T& y) {
return ((y >= 0) && (x >= 0) && (x > std::numeric_limits<T>::max() / y))
|| ((y < 0) && (x < 0) && (x < std::numeric_limits<T>::max() / y));
}
template <typename T>
constexpr bool multiplicationUnderflow(const T& x, const T& y) {
return ((y >= 0) && (x < 0) && (x < std::numeric_limits<T>::min() / y))
|| ((y < 0) && (x >= 0) && (x > std::numeric_limits<T>::min() / y));
}
#endif //UNTITLED2_HELPER_H
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T12:54:27.283",
"Id": "466710",
"Score": "0",
"body": "Have you read any of the other matrix classes posted for review? You'll likely pick up useful tips from most of them (the most important being to change the storage to a rasterised form, rather than vector-of-vector)."
}
] |
[
{
"body": "<p><strong>Correctness:</strong></p>\n\n<p>You are dividing by <code>0</code> here</p>\n\n<pre><code>((y >= 0) && (x >= 0) && (x > std::numeric_limits<T>::max() / y)\n</code></pre>\n\n<p>and here</p>\n\n<pre><code>((y >= 0) && (x < 0) && (x < std::numeric_limits<T>::min() / y))\n</code></pre>\n\n<p>Note that division can also underflow and overflow.</p>\n\n<hr>\n\n<p><strong>Efficiency:</strong></p>\n\n<p>Your code is about 1000 times slower than MKL for multiplying large <code>float</code> matrices, which is state-of-the-art, but there are other implementations that have similar performance to MKL, such as OpenBLAS.</p>\n\n<p>The reasons your code is hugely inefficient include</p>\n\n<ol>\n<li><p>The layout of your data requires extra indirection (one chunk of data is better)</p></li>\n<li><p>The loops are cache-unfriendly (The triple loop is inefficient for dot products)</p></li>\n<li><p>Division is much more expensive than multiplication, typically, and you are doing it twice to check that multiplying is \"OK\" (which this fails to do)</p></li>\n</ol>\n\n<hr>\n\n<p><strong>Some minor things I noticed:</strong></p>\n\n<p><code>constexpr</code> seems pointless here, since you don't know the arguments at compile time.</p>\n\n<p><code>this-></code> is unnecessary</p>\n\n<p>Matrix dimensions are <code>uint</code>, but the methods returning them return <code>int</code></p>\n\n<p>There is no need to store <code>rows</code> and <code>cols</code> in the class, since they are known to the compiler (template parameters)</p>\n\n<hr>\n\n<p><strong>Odd choice:</strong></p>\n\n<p>Your class can't handle arbitrary matrix sizes, unless they are known at compile time.</p>\n\n<p>But since you are doing that, you also should avoid throwing a <em>runtime</em> error, if matrix sizes do not match -- you should know this before the program runs.</p>\n\n<hr>\n\n<p><strong>Compilation errors:</strong></p>\n\n<p>Shadowing template parameters:</p>\n\n<pre><code>template<class T, uint m, uint n>\nclass Matrix {\n// ...\ntemplate<class T, uint m, uint n> friend std::ostream& operator<<(std::ostream& os, const Matrix<T,m,n>& matrix);\n// ...\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T18:13:49.620",
"Id": "466745",
"Score": "0",
"body": "Double plus on the know at compile time for matrix sizes. But you should show the OP how to do that test."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T18:36:31.323",
"Id": "466747",
"Score": "0",
"body": "@MartinYork There's `static assert`, but here there is no need for one. The relevant matices can just share a template parameter or both."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T12:03:05.890",
"Id": "237964",
"ParentId": "237962",
"Score": "5"
}
},
{
"body": "<h2>Overview</h2>\n\n<p>Potentially not very efficient.</p>\n\n<p>I have seen other Matrix libraries not do the actual computation until the value is needed. So what is passed around is a Matrix wrapper that contains references to the original matrixes and the operations on them. You can then delay the actual work till it is needed. Then if you multiply by the null matrix you can can optimize out all the numeric operations.</p>\n\n<p>I will assume you know how to do the basic maths of matrix manipulation. I will look at the interfaces and idioms.</p>\n\n<h2>Code Review</h2>\n\n<p>Nice:</p>\n\n<pre><code>template <class T, uint n>\nusing rowVector = Matrix<T, 1, n>;\n\ntemplate <class T, uint m>\nusing colVector = Matrix<T, m, 1>;\n</code></pre>\n\n<hr>\n\n<p>So the only way to initialize the matrix is via a vector?</p>\n\n<pre><code> explicit Matrix(const std::vector<T> matrixValue);\n ^^^^^^^^^^^^^^^^^^^^\n Note: passing by value.\n You are making a copy. Probably want to pass\n by const reference (see below) \n\n explicit Matrix(std::vector<T> const& matrixValue);\n explicit Matrix(std::vector<T>&& matrixValue); // don't forget move semantics.\n</code></pre>\n\n<p>I would have liked to be able to initialize it via iterators</p>\n\n<pre><code> template<typename I>\n explicit Matrix(I begin, I end);\n</code></pre>\n\n<p>That way I can simply read the data from a file:</p>\n\n<pre><code> std::ifstream file(\"Matrix.file\");\n Matrix<int, 5, 6> data(std::istream_iterator<int>{file}, std::istream_iterator<int>{});\n</code></pre>\n\n<hr>\n\n<p>I like this:</p>\n\n<pre><code> int getRows()const;\n int getColoumns() const;\n</code></pre>\n\n<p>But some people will complain that you should use unsigned int (i.e. std::size_t).</p>\n\n<hr>\n\n<p>Yes you need this:</p>\n\n<pre><code> T& operator()(const uint row, const uint col);\n</code></pre>\n\n<p>But you also need the const version. A lot of time you may pass a const reference of the matrix to a function. You should still be able to read data from the matrix.</p>\n\n<pre><code> T const& operator()(const uint row, const uint col) const;\n</code></pre>\n\n<p>If you want to fo whole hog you can add the <code>[]</code> operators. A tiny bit more work but doable.</p>\n\n<pre><code> // Define inside Matrix so the template stuff\n // Is already available.\n struct Row\n {\n Matrix& parent;\n int row;\n Row(Matrix& parent, int row) : parent(parent), row(row) {}\n T& operator[](int col) {return parent(row, col);}\n }\n Row operator[](int row){return Row(*this, row);}\n\n // Very similar for the const version.\n</code></pre>\n\n<hr>\n\n<p>Fair:</p>\n\n<pre><code> Matrix<T,m,n> operator=(std::vector<T> matrixIntializationValue);\n</code></pre>\n\n<p>But if you define this. Then you also need to define the standard assignment operator. Otherwise you can't do simple Matrix assignment.</p>\n\n<hr>\n\n<p>You don't need all this template stuff if you define this inside the class declaration. </p>\n\n<pre><code> template<class T, uint m, uint n> friend std::ostream& operator<<(std::ostream& os, const Matrix<T,m,n>& matrix);\n</code></pre>\n\n<p>By doing it inside the class you make everything much simpler to read.</p>\n\n<hr>\n\n<p>Why are you storing the data as a vector of vectors?</p>\n\n<pre><code>std::vector<std::vector<T>> data;\n</code></pre>\n\n<p>You have this wrapper class for managing all the interactions. You can use a more effecient storage method internally because you have wrapped the object and limit access to the implementation.</p>\n\n<p>Simply use a single vector of data.</p>\n\n<pre><code>std::vector<T> data;\n</code></pre>\n\n<p>It makes initialization easy. Access will be quicker (less look-ups and data locality will mean that data will already be in the processor cache).</p>\n\n<hr>\n\n<p>Since <code>m</code> and <code>n</code> are defined at compile time. This runtime check should not be required. You simply make the zero sized versions invalid and you get a compile time error.</p>\n\n<pre><code>template<class T, uint m, uint n>\nMatrix<T,m,n>::Matrix(): rows(m), cols(n)\n{\n // Compile time check.\n static_assert(m > 0 && n > 0);\n</code></pre>\n\n<hr>\n\n<p>No need for this loop:</p>\n\n<pre><code> data.resize(rows);\n for (auto& colData : data)\n colData.resize(cols);\n\n ----\n</code></pre>\n\n<p>Simply do the declaration in the initializer list:</p>\n\n<pre><code>template<class T, uint m, uint n>\nMatrix<T,m,n>::Matrix()\n : rows(m)\n , cols(n)\n , data(rows, std::vector<T>(cols))\n{}\n</code></pre>\n\n<hr>\n\n<p>Stop using: <code>this-></code></p>\n\n<pre><code> return this->rows;\n</code></pre>\n\n<p>Its not very C++. It also causes errors. Not for the compiler but for developers. The only reason you need <code>this-></code> is when you have shadowed a variable and need to distinguish between the local and the object variable. Unfortunately when you miss <code>this-></code> off the compiler can't tell you have made a mistake.</p>\n\n<p>But by using distinct names you know which variable you are using and the compiler can warn you about shadowed variables (turn on the warning and make it an error). This will reduce the number of programmer mistakes in your code.</p>\n\n<p>Well named and distinct variables will produce better code and less mistakes.</p>\n\n<hr>\n\n<p>You don't need this check:</p>\n\n<pre><code>template<class T, uint m, uint n>\nMatrix<T,m,n> Matrix<T,m,n>::operator+(Matrix& other)\n{\n</code></pre>\n\n<p>Did you not make sure that this addition can only happen with very specific types in the class definition? This means that Matrixes of the wrong size would generate a compile time error and thus you don't need a runtime error.</p>\n\n<pre><code> if ((this->rows == other.getRows()) && (this->cols == other.getColoumns()))\n {\n</code></pre>\n\n<hr>\n\n<pre><code>template<class T, uint m, uint n>\nstd::ostream& operator<<(std::ostream &os, const Matrix<T,m,n> &matrix)\n{\n</code></pre>\n\n<p>Can the data ever be empty? </p>\n\n<pre><code> if(!matrix.data.empty())\n</code></pre>\n\n<p>Don't you guarantee in the constructor that this never happens?</p>\n\n<hr>\n\n<p>Don't use <code>std::endl</code> when <code>\"\\n\"</code> will do.</p>\n\n<pre><code> os << std::endl;\n</code></pre>\n\n<p>The difference is that <code>endl</code> will force a stream flush. Manually flushing the stream is almost always (I say almost because somebody will point out an obscure situation were it would be nice) the wrong thing to do. You should never be using it until you can show with testing that it is worth the flush.</p>\n\n<p>When people complain about the speed of the C++ streams this is one of the main culprits. Excessive flushing of the stream is one of the main slowdown people see. When you stop doing it the C++ streams are about the same speed as C streams.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T12:32:49.603",
"Id": "466835",
"Score": "1",
"body": "Why use `std::vector<T>` when the size is known at compile-time? `std::array<T, m*n>` should definitely be preferred instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T12:34:35.287",
"Id": "466836",
"Score": "0",
"body": "Also, tangential nitpick: `this->` can also be necessary/useful to access members from a dependent base class (which unqualified name lookup won't find). Doesn't apply here, but maybe worth mentioning."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T17:23:24.403",
"Id": "466859",
"Score": "0",
"body": "@MaxLanghof, stack mught be hammered if std::array is used. 1024*1024 is already 1MB. Matrices these days are used for image dnn or cnn, and the dimensions are usually much bigger."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T18:07:35.870",
"Id": "466870",
"Score": "0",
"body": "@MaxLanghof I disagree. `std::array` is useful only for small(ish) arrays. Anything large really needs to be dynamically allocated. The main reason is to have useful move semantics which will come into play when doing any large scale matrix operations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T08:59:52.207",
"Id": "466946",
"Score": "0",
"body": "@MartinYork Move semantics (and stack restrictions when creating a matrix with automatic storage duration) are a valid reason not to use plain `std::array`, but that still favors `std::unique_ptr<std::array<T, m*n>>`. Why give up the compile-time size information?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T09:01:13.200",
"Id": "466947",
"Score": "0",
"body": "@Incomputable See above."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T10:23:33.983",
"Id": "466953",
"Score": "0",
"body": "@MartinYork : Thank You for valuable suggestions. I will make the necessary changes. I have not handled many points here, I will take care of it and make changes and post here again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T10:24:53.640",
"Id": "466954",
"Score": "0",
"body": "@MaxLanghof Thank You, I will make not of this"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T10:26:07.357",
"Id": "466955",
"Score": "0",
"body": "@Incomputable: Thank You, I will keep in mind."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T17:49:40.760",
"Id": "467025",
"Score": "0",
"body": "@MaxLanghof, I was thinking about allocating the memory and then throwing the pointer into `std::span` immediately (destructor will need to do deallocation manually). What do you think about it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-02T08:41:34.627",
"Id": "467207",
"Score": "0",
"body": "@Incomputable Why would you give up on the rule of zero?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-02T10:05:42.973",
"Id": "467214",
"Score": "0",
"body": "@MaxLanghof, I just wanted more of a value semantics than pointer semantics inside the class as well. But yes, the gains are negligible."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T18:54:54.647",
"Id": "237995",
"ParentId": "237962",
"Score": "9"
}
},
{
"body": "<p>I am not going to be nice. That's how bad it is. The design is terrible. You are greatly confused on so many levels.</p>\n\n<p>Internally, matrix stores runtime rows, cols, and dynamically the data in <code>std::vector<std:vector></code> - while the rows and cols are defined in the template arguments and thus compile time constants. It makes no sense at all.</p>\n\n<p>Generally there are two types of matrix implementations:</p>\n\n<p>(1) struct with fixed rows and cols and its data is stored in, say, <code>double mData[rows][cols];</code> - a static format.</p>\n\n<p>(2) dynamically allocated matrix with run-time chosen rows and cols with dynamically allocated data in, say, <code>std::vector<double> data;</code>.</p>\n\n<p>(Note: eigen linear algebra library also has more intermediate types for greater compatiability and efficiency.)</p>\n\n<p>Method (1) has the advantage that everything is known at compile time and data is allocated statically. Con: It requires compile time knowledge of the size of matrices and has to compile a new class for each size.\nThis is the preferred method for small sized matrices. </p>\n\n<p>Method (2) can serve all matrices of all sizes but it requires dynamic allocation of data and lack of compile time knowledge of sizes might infer with optimizations and some bugs will not be discoverable at compile time. This is the preferred method for large sized matrices and those when one lacks knowledge of matrix size at compile time.</p>\n\n<p>Your version has all the cons and none of the advantages. It requires compile time knowledge of the matrix's size and it requires run-time allocations and for some mysterious reasons it stores the size (compile-time defined) inside the matrix instance. Furthermore, you store data inside <code>std::vector<std::vector<double>></code> which is a horrible idea in as it requires <code>rows+1</code> allocations - it is slow on both initialization and usage and in addition results in memory fragmentation problems. This is how bad it is.</p>\n\n<p>Please, just use an open source matrix library. There are plenty.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T18:15:49.683",
"Id": "466874",
"Score": "1",
"body": "Not a very useful review. You don't explain what the OP could do to improve their code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T18:37:59.103",
"Id": "466878",
"Score": "0",
"body": "@MartinYork I believe I clearly stated how to improve the code: erase it and use available an open source library. Plus added several tips where he went wrong."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T21:36:46.933",
"Id": "238004",
"ParentId": "237962",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T11:00:27.460",
"Id": "237962",
"Score": "5",
"Tags": [
"c++",
"object-oriented",
"c++11",
"matrix",
"template"
],
"Title": "Template Matrix Class: implemented some basic functionalities"
}
|
237962
|
<pre class="lang-php prettyprint-override"><code>if ($v->getMedical()) {
$visitorHasMedical = $v->getMedical()->getMedCon() == true; // $visitorHasMedical will be false if "falsey" i.e. empty string or NULL
} else {
$visitorHasMedical = false;
}
</code></pre>
<p>Where <code>getMedical()</code> is a OneToOne Doctrine relationship that might not exist.</p>
<p>Does this snippet read OK? Firstly, I'm <strong>deliberately</strong> doing a loose == check as this could be NULL or empty string.</p>
<p>Secondly, is assigning $visitorHasMedical to what is essential an if statement OK?</p>
|
[] |
[
{
"body": "<p>Quite so. Except for the trailing comment getting beyond edge. But it can be written in much simpler way anyway.</p>\n\n<pre><code>$medical = $v->getMedical();\n$visitorHasMedical = ($medical && $medical->getMedCon());\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T12:31:09.560",
"Id": "237966",
"ParentId": "237965",
"Score": "3"
}
},
{
"body": "<p>First off, I semantically disagree about <code>$medical && $medical->getMedCon())</code>. Second I think that piece of code is worth wrapping up into a small method/function. To accomplish this, I'd go for:</p>\n\n<pre><code>private function hasMedical(SomeEntity $v): bool {\n if ($v->getMedical() === null) {\n return false;\n }\n return $v->getMedical()->getMedCon()\n}\n</code></pre>\n\n<p>However, there is some kind of smell over there that you need to check the null alongside with the bool value. \nProbably you could more cleanly implement it with annotations, mappings, etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-05T05:33:30.687",
"Id": "467528",
"Score": "0",
"body": "Except you got a possible return type error. And btw `getMedical` does not need to be called twice and if anything this should not be private method of who knows, but rather a public method of the visitor entity."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-04T23:56:15.490",
"Id": "238394",
"ParentId": "237965",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "237966",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T12:07:08.003",
"Id": "237965",
"Score": "3",
"Tags": [
"php"
],
"Title": "PHP - Deliberate loose == check and assigning to if statement"
}
|
237965
|
<p>I created this function it is looking for the html tag and replacing it with the ^value. It seems complicated wanted to know if there is a better way to do something like this.</p>
<blockquote>
<p>Will you review the syntax, structure, and logic of my code. It can be tested using the main.</p>
</blockquote>
<p>Output</p>
<pre><code>dsfsadfsad 5<sup>8</sup> dsfsadfsad
dsfsadfsad 5^8 dsfsadfsad
</code></pre>
<p>Code</p>
<pre><code>namespace Replacestring
{
class Program
{
static void Main(string[] args)
{
string source = "dsfsadfsad 5<sup>8</sup> dsfsadfsad";
Console.WriteLine(source);
source = superscriptRule(source);
Console.WriteLine(source);
}
protected static string superscriptRule(string source)
{
if (!string.IsNullOrEmpty(source) == true)
{
if (source.Contains("<sup>"))
{
Match m = Regex.Match(source, @"<sup>\s*(.+?)\s*</sup>", RegexOptions.IgnoreCase);
if (m.Success)
{
int i = 0;
string x = m.Groups[1].Value;
bool result = int.TryParse(x, out i);
if (result == true)
{
string replacestring = string.Format("<sup>{0}</sup>", x);
string newstring = string.Format("^{0} ", x);
source = source.Replace(replacestring, newstring);
return source;
}
else
{
return source;
}
}
return source;
}
}
return source;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T14:30:46.833",
"Id": "466717",
"Score": "0",
"body": "Won't a simple `return source.Replace(\"<sup>\", \"^\").Replace(\"<\\sup>\", string.Empty);` be enough?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T15:32:55.007",
"Id": "466722",
"Score": "0",
"body": "@Jefferson, also, you can compare to using String.Split(), might be faster"
}
] |
[
{
"body": "<ul>\n<li>Method names should be named using <code>PascalCase</code> casing. </li>\n<li><p>An <code>if</code> condition is just a boolean expression hence <code>if (!string.IsNullOrEmpty(source) == true)</code> is a little bit over the top. Either write </p>\n\n<pre><code>if (!string.IsNullOrEmpty(source))\n{\n\n}\n</code></pre>\n\n<p>or </p>\n\n<pre><code>if (string.IsNullOrEmpty(source)) { return source; } \n</code></pre>\n\n<p>which saves one level of indentation. </p></li>\n<li><p>Why is the method <code>protected</code> ? Doesn't make sense to me.</p></li>\n<li>The name of that method sounds rather like a class/object name than a method name. Methodnames should contain a verb or verb-phrase.</li>\n</ul>\n\n<p>Instead of the <code>Regex</code> stuff and <code>string.Contains()</code> etc your method could just look like so </p>\n\n<pre><code>private static string SuperscriptRule(string source)\n{\n if (string.IsNullOrEmpty(source)) { return source; }\n\n return source.Replace(\"<sup>\", \"^\").Replace(\"<\\sup>\", string.Empty);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T20:36:55.607",
"Id": "466760",
"Score": "0",
"body": "it could be also simplified to `return !string.IsNullOrEmpty(source) ? source.Replace(\"<sup>\", \"^\").Replace(\"<\\sup>\", string.Empty) : source;`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T14:40:22.163",
"Id": "237974",
"ParentId": "237968",
"Score": "2"
}
},
{
"body": "<p>There are a few major issues here. First, as already noted you could use <code>if (x) {...}</code> instead of <code>if (x == true) {...}</code>. Second the variable <code>result</code> is only used once so you can move the entire <code>int.TryParse(x, out i)</code> into the if condition: <code>if (int.TryParse(x, out i)) {...}</code>. Next you type <code>return source;</code> four times but you only need it once: at the end of the method. And fourth the first two conditions can be combined as C# uses shortcircuiting in evaluating if conditions. So <code>if (!string.isNullOrEmpty(source) || source.Contains(\"<sup>\")) {...}</code>.</p>\n\n<p>Also I'm not too familiar with regexes in C# but I suspect you can skip the <code>source.Contains(\"<sup>\")</code> command entirely as the regex call makes it redundant. And I suspect the <code>!string.IsNullOrEmpty(source)</code> can be replaced with <code>source != null</code> for the same reason.</p>\n\n<p>Also in the words of JetBrains: Invert 'if' statement to reduce nesting. That is instead of:</p>\n\n<pre><code>if (cond1) {\n doStuff();\n if (cond2) {\n doMoreStuff();\n }\n}\nreturn;\n</code></pre>\n\n<p>You have:</p>\n\n<pre><code>if (!cond1) {\n return;\n}\ndoStuff();\nif (cond2) {\n doMoreStuff();\n}\nreturn;\n</code></pre>\n\n<p>If you have nested if conditions it's probably a good idea. But it's pretty minor (some people may even disagree on this one).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T14:54:12.607",
"Id": "237977",
"ParentId": "237968",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "237974",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T14:12:28.110",
"Id": "237968",
"Score": "0",
"Tags": [
"c#"
],
"Title": "Check source contain replace string"
}
|
237968
|
<p>I am currently coding a tool for my work that modifies a textfile by removing unneeded parts of a string at specific spots in the file.
I would like to know if there are any obvious things I am missing or doing too complicated.
I know that some of the comments are considered too long for PEP8.</p>
<pre class="lang-py prettyprint-override"><code>class vis_file_tools:
def __init__(self):
pass
# Splits the input line into list (by a space), removes the last position, joins them with spaces and returns the modified line.
def remove_jedec_line(self, input_line):
input_line_split = input_line.split(" ") # splits the string that was input through the function into a list
del input_line_split[-1] # deletes the last line from the list (In this case it removes the jedec)
output_line = " ".join(input_line_split) # joins back the list to a string. Joins the list with a space
output_line = output_line + "\n"
return output_line # returns the finished string to the caller of the function
def remove_jedecs_file(self, path_input_file, path_output_file):
with open(path_input_file, "r") as file: # Opens the input file read only
temp_data = ""
comp_line_reached = False
for line in file: # "line" in this case is already a variable. Do not us file.readline() when using the "for line" loop.
if "COMP" in line: # Sets the bool "comp_line_reached" to "true" when the loop reaches the "COMP" in the .vis file which marks the start of the components
comp_line_reached = True
temp_data = temp_data + line
elif comp_line_reached is False: # Simply writes the lines from the file into a variable until the component part is reached.
temp_data = temp_data + line
else:
line_no_jedec = self.remove_jedec_line(line)
temp_data = temp_data + line_no_jedec
with open(path_output_file, "w") as write_file:
write_file.write(temp_data)
temp_data = "" # Empties memory
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T15:38:57.153",
"Id": "466725",
"Score": "1",
"body": "Your question seems fine, but you should change your title to be more of a general description of what your code does. Asking if it has any problems, like your title does, is implied in every question is not needed. For more info, check out the help center. (https://codereview.stackexchange.com/help/how-to-ask)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T16:07:04.587",
"Id": "466732",
"Score": "1",
"body": "I think I missunderstood the help beforehand. I tried to find a better title now. Thank you for the hint."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T16:37:39.917",
"Id": "466734",
"Score": "1",
"body": "Please put correct spaces on the code for the class methods."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T16:50:34.160",
"Id": "466737",
"Score": "0",
"body": "Done. The whitespace somehow got removed."
}
] |
[
{
"body": "<h1>PEP-8</h1>\n\n<p><code>ClassNames</code> should be <code>BumpyWords</code>; <code>snake_case</code> is used for things like <code>method_names</code> and <code>variable_names</code>. So you class should be:</p>\n\n<pre><code>class VisFileTools:\n ...\n</code></pre>\n\n<h1>Unnecessary <code>__init__</code> method</h1>\n\n<p>This method does nothing; it may safely be omitted.</p>\n\n<pre><code> def __init__(self):\n pass\n</code></pre>\n\n<h1>Public / Private</h1>\n\n<p><code>remove_jedec_line</code> looks like a private method, used by the <code>remove_jedecs_file</code> method. If <code>remove_jedec_line</code> is not supposed to be used by actors outside of the class, it should be prefixed with a leading underscore:</p>\n\n<pre><code> def _remove_jedec_line(self, inputline):\n ...\n</code></pre>\n\n<h1>Garbage Collection</h1>\n\n<pre><code>temp_data = \"\" # Empties memory\n</code></pre>\n\n<p>This is unnecessary. The variable is about to go out of scope, which will naturally release the memory it is holding.</p>\n\n<h1>Stop Writing Classes</h1>\n\n<p>See the video <a href=\"https://www.youtube.com/watch?v=o9pEzgHorH0\" rel=\"nofollow noreferrer\">Stop Writing Classes</a></p>\n\n<p>Your class is unnecessary. It has no data members. It has one public method. It should just be a function.</p>\n\n<h1>Simplified code</h1>\n\n<p>Here is a function version of your code (untested):</p>\n\n<pre><code>def remove_jedecs_file(path_input_file: str, path_output_file: str) -> None:\n \"\"\"\n Read `path_input_file`, copying each line to `path_output_file`.\n Once the start of components is reached (indicated by a line containing \"COMP\"),\n the last \"word\" (jedec) of each line is removed.\n \"\"\"\n\n def remove_jedec_line(input_line: str) -> str:\n return \" \".join(input_line.split(\" \")[:-1]) + \"\\n\"\n\n with open(path_input_file) as file, open(path_output_file, \"w\") as write_file:\n comp_line_reached = False\n\n for line in file:\n if comp_line_reached:\n line = remove_jedec_line(line)\n else:\n comp_line_reached = \"COMP\" in line\n\n write_file.write(line)\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>Type-hints (Python 3.6+) have been added to the function (<code>: str</code> and <code>-> None</code>)</li>\n<li>A <code>\"\"\"docstring\"\"\"</code> has been added to describe the function.</li>\n<li>A nested function is used for <code>remove_jedec_line()</code>, making it \"private\".</li>\n<li><code>[:-1]</code> returns all but the last element in a list, which is simpler than using <code>del input_line_split[-1]</code>.</li>\n<li>Lines are not being accumulated in <code>temp_data</code>. Instead, lines are written out immediately after being read in, which is a much lighter load on memory, and avoid <span class=\"math-container\">\\$O(N^2)\\$</span> string concatenation.</li>\n<li><code>\"COMP\" in line</code> is a \"slow\" search operation, looking for that substring in the <code>line</code> string. When found, it sets a flag. Here, once the flag is set, we can skip the slow substring search. But I'm introducing a slight change in behaviour: if subsequent lines also contain <code>\"COMP\"</code>, the OP version would not do the <code>remove_jedec_line()</code> transformation where as mine will. The assumption here is that <code>\"COMP\"</code> only appears once.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T20:13:41.397",
"Id": "466756",
"Score": "0",
"body": "Thanks a lot. I have to read up on the data members stuff for classes.\nComp in this case basically declares a part of the file that gets repeated for a specific amount of times. \nAfter that amount is done a new section of the text starts with comp.\nSo I have to recheck the appearence. I think.\nI will try the function when I am at work next time. Thank you for your help.\n\nI was planning on adding more functions to the class. But I dont know much about data members yet so I need to read up on that if its better to just create more functions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T18:36:01.397",
"Id": "237992",
"ParentId": "237971",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "237992",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T14:26:23.727",
"Id": "237971",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"file"
],
"Title": "Python file modifying script with focus on OOP"
}
|
237971
|
<p>I'm looking to improve my code writing in general by peer review.
I've followed the following exercise: <a href="https://edabit.com/challenge/dLnZLi8FjaK6qKcvv" rel="nofollow noreferrer">https://edabit.com/challenge/dLnZLi8FjaK6qKcvv</a>.</p>
<p>The exercise is to create an English version Shiritori Game. You can find an explanation by following the link but I'm going to explain below anyway.</p>
<p>The game is a word matching games where the last letter of the last word said must match the first letter of the next word. A word cannot be used again once it has been played in that game. If a word doesn't match these rules then it is game over and the game is restarted.</p>
<p>Please find the code below:</p>
<pre class="lang-py prettyprint-override"><code>#Exercise source = https://edabit.com/challenge/dLnZLi8FjaK6qKcvv
'''
Class Shiritori
Controls the action and state of the game
'''
class Shiritori:
'''
Set up an empty array to store the last words used.
Stores the currently used word for judging
Initiates the main game loop main()
'''
def __init__(self):
self.playedWords = []
self.currentWord = None
self.main()
'''
Determines if the current word's first letter matches the last word's letter
'''
def ruleOne(self):
lastWord = self.playedWords[-1]
if lastWord[-1] == self.currentWord[0]:
return True
return False
'''
Determines if the current word has already been played
'''
def ruleTwo(self):
if self.currentWord in self.playedWords:
return False
return True
'''
Adds the current word to the list of played words
'''
def addWord(self):
self.playedWords.append(self.currentWord)
'''
Play a turn
1. enters a word which is turned into lowercase and removes any additional spaces
2. checks if it is the first word to be played, add the word if no words have been played
3. checks the word against rule 1 and rule 2, adds the word if both rules are true
4. if 2 or 3 have not been done then activate the game over message and restart the game
'''
def play(self, word):
word = word.lower()
word = word.strip()
self.currentWord = word
if not self.playedWords:
self.addWord()
elif(self.ruleOne() and self.ruleTwo()):
self.addWord()
else:
self.gameOver()
'''
prints the game over message and restarts the game
'''
def gameOver(self):
print("You have lost. Game is being restarted.")
self.playedWords = []
self.currentWord = None
'''
The main loop of the game. Keeps accespting words from users and playing them in the games.
Exit the loop by entering in an empty string or just pressing enter.
'''
def main(self):
print("Enter a word or enter '' to exit the game")
while True:
word = input("Please enter your word>")
self.play(word)
if word == '':
break
print("Thank you for playing.")
game = Shiritori()
</code></pre>
<h2>Edit 1</h2>
<h3>Code Explanation</h3>
<p>Once run the code should run the main function of the class which will loop over until the user decided to quit by pressing enter (entering an empty string). Otherwise the program should accept a string of characters as words. Please note there is no parsing of the data except turning the word into lowercase and removing any additional spaces. The entered word will be checked against an array to see if the two rules match up, if the rules don't match then the game goes into the 'game over' function which resets the game automatically.</p>
<p>The game runs within the console.</p>
<h3>Unorthodox choices</h3>
<ol>
<li><p><code>array[-1]</code> and <code>string[-1]</code> last letter and last string retrieval</p>
<p>I originally used <code>len(string/array)-1</code> to retrieve the last letter/string. However this seems more visually appealing but it is questionable whether it is readable</p>
</li>
<li><p>Main inside or outside of class</p>
<p>I chose inside however maybe it should be outside of the class as it makes sense to have the main loop there and keep it separate from the object however it is the main controls so I am unsure.</p>
</li>
<li><p>play function <code>if,elif,else</code></p>
<p>the <code>if</code> and <code>elif</code> statement do the same thing, there should be a more efficient way of doing it without separating the action into the function and having both statements</p>
</li>
<li><p><code>if word == ''</code></p>
<p>Not sure if unorthodox but there should be a better comparison</p>
</li>
<li><p><code>word.lower()</code>, <code>word.strip()</code>, <code>self.currentWord = word</code></p>
<p>There might be a better way of combining this?</p>
</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T15:36:53.197",
"Id": "466723",
"Score": "1",
"body": "Could you add a short explanation for how you code works, and why you made any unorthodox choices if you did?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T16:19:52.673",
"Id": "466733",
"Score": "1",
"body": "@K00lman I added them in, please let me know if I should change anything else"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T18:53:18.513",
"Id": "466750",
"Score": "1",
"body": "No it all looks good now."
}
] |
[
{
"body": "<h1>Unorthodox choices</h1>\n\n<p>Before having a deeper look at the code, let's look at what the \"Unorthodox choices\" listed in the question</p>\n\n<ol>\n<li><p>Using <code>array[-1]</code> is perfectly valid Python and will very likely be considered much more readable and Pythonic than using <code>len(...)-1</code>.</p></li>\n<li><p><code>main</code> function</p>\n\n<p>Having the <code>main</code> function inside the class and call it directly when you create the object is IMHO much more unorthodox. I personally would discourage it, though it's probably not unheard of. What is usually used in Python is a separate <code>main()</code> function with the game loop as well as the infamous <code>if __name__ == \"main\":</code>, also known as <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"nofollow noreferrer\">top-level script environment in technical terms</a>. All code inside the body of this <code>if</code> is only run when you execute the file as a script, instead e.g. <code>import</code>ing something into another file.</p></li>\n<li><p><code>play</code> function, <code>if</code> statement</p>\n\n<p>It's easy combine both conditions: </p></li>\n</ol>\n\n<pre><code>if not self.playedWords or (self.ruleOne() and self.ruleTwo()): \n self.addWord()\nelse:\n self.gameOver()\n</code></pre>\n\n<p>It would also be possible to invert the condition:</p>\n\n<pre><code>if self.playedWords and not (self.ruleOne() or self.ruleTwo()): \n self.gameOver()\nelse:\n self.addWord()\n</code></pre>\n\n<ol start=\"4\">\n<li><p><code>if word == ''</code></p>\n\n<p>Python encourages you to be <a href=\"https://www.python.org/dev/peps/pep-0020/#the-zen-of-python\" rel=\"nofollow noreferrer\">explicit</a> in your code. Just for the sake of the argument, <code>if not word:</code> would have a similar effect.</p></li>\n<li><p><code>word.lower(), word.strip(), self.currentWord = word</code></p>\n\n<p>It's possible to chain those calls: <code>self.currentWord = word.lower().strip()</code>. Quick note here: <code>.strip()</code> <a href=\"https://docs.python.org/3/library/stdtypes.html#str.strip\" rel=\"nofollow noreferrer\">only removes trailing and leading whitespace</a>. If the user entered multiple words, the whitespace in between them will not be affected.</p></li>\n</ol>\n\n<h1>Style</h1>\n\n<p>I highly recommend having a look at the official <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> aka PEP 8 (again). Some key takeaways of that read should be:</p>\n\n<ul>\n<li>prefer to use <code>lowercase_with_underscores</code> for function and variable names.</li>\n<li><code>UpperCase</code> is \"reserved\" for class names (no issue in the code here)</li>\n<li>docstrings should be defined inside the function, i.e. after <code>def what_ever_name():</code>, not before. Otherwise Python's <code>help(...)</code> and also most IDEs will not pick it up correctly. There is more about <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings in PEP 257</a>.</li>\n</ul>\n\n<p>Fortunately, there is a wide variety of tools that can help with keeping a consistent style, even when projects grow larger. <a href=\"https://codereview.meta.stackexchange.com/a/5252/92478\">This list</a> on Code Review Meta provides you with a good starting point to get going.</p>\n\n<h1>Code</h1>\n\n<p>As I already said, I would not recommend starting the game immediately in <code>__init__</code>. even if you keep the main game loop inside the class, the user should have to trigger the game explicitly.</p>\n\n<p>The member variable <code>self.currentWord</code> is not strictly needed. By allowing a word as input for <code>ruleOne</code>, <code>ruleTwo</code>, and <code>addWord</code>, it would be easier to see what's going on.</p>\n\n<p>With a little bit of rewriting, a <a href=\"https://docs.python.org/3/tutorial/datastructures.html#sets\" rel=\"nofollow noreferrer\"><code>set</code></a> could be used. A <code>set</code> does not allow duplicate members and has faster membership tests compared to a list (constant time vs. linear time). However, <code>set</code>s don't preserve the order of elements, i.e. the class has to store the last word in a member variable.</p>\n\n<p>Having a <code>last_word</code> instead of <code>current_word</code>/<code>currentWord</code> would also be closer to what one might expect when looking at the game rules.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T17:28:41.613",
"Id": "237987",
"ParentId": "237972",
"Score": "4"
}
},
{
"body": "<p>I'm going to make all the easy improvements I can spot and call them out as I go; some of what I'm about to say will probably duplicate excellent points already raised by @AlexV.</p>\n\n<ol>\n<li><p>Running the game when you instantiate the object is an unusual interface. I'd rename that <code>main</code> method something like <code>run</code> and have the <code>__main__</code> function call that after creating the game object.</p></li>\n<li><p>Docstrings are conventionally marked with tripled double-quotes, not single-quotes. They also typically go inside the function they document rather than before it, and they should document the external behavior, not the internal implementation (use comments to explain internals where necessary).</p></li>\n<li><p>Avoid unnecessary state; your <code>currentWord</code> is only ever used in the context of a single turn, so there's no need to track it in your class.</p></li>\n<li><p>Variable and method name should be snake_case, not camelCase.</p></li>\n<li><p>Adding type annotations helps validate code correctness.</p></li>\n<li><p>Instead of:</p></li>\n</ol>\n\n<pre><code>if condition:\n return True\nreturn False\n</code></pre>\n\n<p>do:</p>\n\n<p><code>return condition</code></p>\n\n<p>(assuming <code>condition</code> is already a bool value; if you use type annotations, mypy will enforce this for you)</p>\n\n<ol start=\"7\">\n<li><p>I think it makes the <code>play</code> logic clearer to group the two \"valid\" conditions into a single <code>if</code> predicate. Another way to approach this would be to implement both <code>rule_one</code> and <code>rule_two</code> to return <code>True</code> when the list is empty so that you don't need to special-case it in the caller.</p></li>\n<li><p>Implicit \"truthy\" checks can lead to subtle bugs, so I usually prefer explicit boolean conditions, e.g. <code>is not None</code> or <code>len(...) > 0</code>.</p></li>\n</ol>\n\n<p>Here's the code I wound up with:</p>\n\n<pre><code>#Exercise source = https://edabit.com/challenge/dLnZLi8FjaK6qKcvv\nfrom typing import List\n\nclass Shiritori:\n \"\"\"\n Class Shiritori\n Controls the action and state of the game\n \"\"\"\n def __init__(self):\n self.played_words: List[str] = [] # words used so far\n\n def rule_one(self, word: str) -> bool:\n \"\"\"Determines if the word's first letter matches the last word's letter.\"\"\"\n return word[0] == self.played_words[-1][-1]\n\n def rule_two(self, word: str) -> bool:\n \"\"\"Determines if the word has not already been played\"\"\"\n return word not in self.played_words\n\n def add_word(self, word: str) -> None:\n \"\"\"Adds the current word to the list of played words\"\"\"\n self.played_words.append(word)\n\n def play(self, word: str) -> None:\n \"\"\"\n Play a word, validating it against the rules. \n If any rules are broken, end the game and restart.\n \"\"\"\n word = word.lower().strip()\n\n # If no words have been played yet, this play is automatically valid.\n # Otherwise, it must satisfy rules one and two.\n if (len(self.played_words) == 0\n or self.rule_one(word) and self.rule_two(word)):\n self.add_word(word)\n else:\n self.game_over()\n\n def game_over(self) -> None:\n \"\"\"prints the game over message and resets the game\"\"\"\n print(\"You have lost. Game is being restarted.\")\n self.played_words = []\n\n def run(self) -> None:\n \"\"\"\n The main loop of the game.\n Keeps accepting words from the user and playing them in the game.\n Exit the loop by entering an empty string.\n \"\"\"\n print(\"Enter a word or enter '' to exit the game\")\n while True:\n word = input(\"Please enter your word>\")\n self.play(word)\n if word == '':\n break\n print(\"Thank you for playing.\")\n\nif __name__ == '__main__':\n game = Shiritori()\n game.run()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T19:26:17.813",
"Id": "237998",
"ParentId": "237972",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "237987",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T14:28:41.247",
"Id": "237972",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"game"
],
"Title": "Python Shirtori Game Exercise"
}
|
237972
|
<p>Team,
I have a working script but when we upgraded some drivers on the GPU system it’s starting to cause zombie process and system is lowing down as script runs periodically as a crib job. </p>
<p>so I am trying to see is there a way I can have a graceful clean up after the Scripts run what is the best procedure to clean up after yourself when Scripts is done running? What wrong am I doing or what better could it be?</p>
<pre><code>gpu-health-check.sh: |
#!/bin/bash
# Do nothing if nvidia-smi is found. This is not a GPU node.
if ! [ -x "$(command -v nvidia-smi)" ]; then
echo "nvidia-smi not found. Ignoring"
exit 0
fi
# Check if there is any retired page. The query is copied from https://docs.nvidia.com/deploy/dynamic-page-retirement/index.html.
bad_gpus=$(nvidia-smi --query-retired-pages=gpu_uuid,retired_pages.address,retired_pages.cause --format=csv,noheader | cut -d, -f1| sort | uniq)
if [ -z "${bad_gpus}" ]; then
echo "No Single/Double Bit ECC Error found"
exit 0
fi
for bad_gpu in "{$bad_gpus}"; do
# Exit 1 if there is a pending page blacklist as we need to reboot the node to actually add the page to the blacklist.
nvidia-smi -i $bad_gpu -q -d PAGE_RETIREMENT | grep Pending| grep Yes > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo "Found pending blacklist on ${bad_gpu}"
exit 1
fi
echo "No pending blacklist on ${bad_gpu}"
done
exit 0
</code></pre>
<p>On gpu system I see </p>
<pre><code>741:19286 ? Z 0:00 [gpu-health-chec] <defunct>
757:30022 ? Z 0:00 [gpu-health-chec] <defunct>
761:31930 ? Z 0:00 [gpu-health-chec] <defunct>
762:31931 ? Z 0:00 [gpu-health-chec] <defunct>
794:37947 ? S 0:00 /bin/bash ./config/gpu-health-check.sh
795:37948 ? S 0:00 /bin/bash ./config/gpu-health-check.sh
796:37955 ? S 0:00 /bin/bash ./config/gpu-health-check.sh
803:37962 ? S 0:00 /bin/bash ./config/gpu-health-check.sh
816:50066 ? Z 0:00 [gpu-health-chec] <defunct>
817:50067 ? Z 0:00 [gpu-health-chec] <defunct>
</code></pre>
<p>All above are just piling up. How to avoid coz system is becoming irresponsible after hours. </p>
|
[] |
[
{
"body": "<blockquote>\n<pre><code> #!/bin/bash\n</code></pre>\n</blockquote>\n\n<p>Why not plain <code>/bin/sh</code>? I don't see any non-POSIX shell constructs in there.</p>\n\n<blockquote>\n<pre><code>sort | uniq\n</code></pre>\n</blockquote>\n\n<p>We could replace with <code>sort -u</code> (that's a standard option).</p>\n\n<blockquote>\n<pre><code> echo \"Found pending blacklist on ${bad_gpu}\"\n exit 1\n</code></pre>\n</blockquote>\n\n<p>That message should go to standard error stream: <code>>&2</code>. The same <em>may</em> be true of the other informational messages.</p>\n\n<blockquote>\n<pre><code> for bad_gpu in \"{$bad_gpus}\"; do\n</code></pre>\n</blockquote>\n\n<p>Really? <code>\"{$bad_gpus}\"</code> is a single token; I think you meant <code>$bad_gpus</code> there. Especially as we then expand <code>$bad_gpu</code> unquoted in the next line.</p>\n\n<blockquote>\n<pre><code>grep Pending| grep Yes > /dev/null 2>&1\n</code></pre>\n</blockquote>\n\n<p>If <code>Pending</code> and <code>Yes</code> always occur in the same order, we could simplify to a single command (and we don't need the redirection):</p>\n\n<pre><code>grep -q 'Pending.*Yes'\n</code></pre>\n\n<blockquote>\n<pre><code> if [ $? -eq 0 ]; then\n</code></pre>\n</blockquote>\n\n<p>That's an antipattern - it's a sign that you need to move the preceding statement into the <code>if</code>:</p>\n\n<pre><code>if nvidia-smi -i \"$bad_gpu\" ...\nthen\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T17:19:39.250",
"Id": "237985",
"ParentId": "237979",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T16:13:01.247",
"Id": "237979",
"Score": "0",
"Tags": [
"bash"
],
"Title": "Clean up after shell script that is run via k8s pod on a gpu node for health check"
}
|
237979
|
<pre><code>let date= new Date()
let day = date.getDay()
let weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
changeText = () => {
if(day === 1){
firstDay.textContent = weekday[2]
secondDay.textContent = weekday[3]
thirdDay.textContent = weekday[4]
fourthDay.textContent = weekday[5]
fifthDay.textContent = weekday[6]
}else if(day === 2){
firstDay.textContent = weekday[3]
secondDay.textContent = weekday[4]
thirdDay.textContent = weekday[5]
fourthDay.textContent = weekday[6]
fifthDay.textContent = weekday[0]
}
}
changeText();
</code></pre>
<p>this is for a weather app. I need to change the html text.content based on the current day so that the extended forecast stays accurate </p>
<p>This code repeats for each day of the week it works but seems very inefficient. the purpose is to change the text in my html so the extended weather forecast is consistent</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T17:41:06.360",
"Id": "466743",
"Score": "0",
"body": "You could use a (`for` or `while`) loop rolling over the `0` index and stopping when `day` is reached again. Just an idea, I am not an expert for javascript. But you should also give more detail what's your code exactly trying to achieve in the context to improve your question. Also the title needs improvement particularly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T17:50:25.870",
"Id": "466744",
"Score": "2",
"body": "Welcome to Code Review! We need to know *what the code is intended to achieve*. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436), rather than your concerns about the code."
}
] |
[
{
"body": "<p>You can do:</p>\n\n<pre><code>changeText = () => {\n firstDay.textContent = weekday[(day + 1) % 7]\n secondDay.textContent = weekday[(day + 2) % 7]\n thirdDay.textContent = weekday[(day + 3) % 7]\n fourthDay.textContent = weekday[(day + 4) % 7]\n fifthDay.textContent = weekday[(day + 5) % 7]\n}\n</code></pre>\n\n<p>Also I'd recommend passing <code>day</code> as a parameter. Just so that it's more clear.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T18:54:38.827",
"Id": "237994",
"ParentId": "237986",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "237994",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T17:23:53.513",
"Id": "237986",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "change html text based on date......JS"
}
|
237986
|
<p>I have two python libraries, let's call them <code>lib</code> and <code>extended_lib</code>, that provide a very similar public API. To be more specific, <code>extended_lib</code> enriches the API of <code>lib</code> with new features and functionality; it also modifies the behavior of some functions that are also provided in <code>lib</code> (e.g. <code>get_version()</code>).</p>
<p>I have a pair of classes <code>LibWrapper</code> and <code>ExtendedLibWrapper</code>, the latter being a sub-class of the former, that dynamically load the corresponding module and save its reference within an instance variable (i.e. <code>self._lib</code>).</p>
<p>I have a class <code>Base</code> that inherits from <code>LibWrapper</code> and a class <code>Derived</code> that inherits from both <code>Base</code> and <code>ExtendedLibWrapper</code>. The class <code>Base</code> exposes the functionalities provided by <code>lib</code>. The class <code>Derived</code> inherits all these functions and exposes also the functionalities provided by <code>extended_lib</code>.</p>
<p>This setup is meant to allow <code>Derived</code> to inherit, without code duplication, the functionality provided by <code>Base</code>.</p>
<p>I designed the <code>LibWrapper</code> and <code>ExtendedLibWrapper</code> as an independent hierarchy of classes because there are multiple <code>Base</code>/<code>Derived</code> pairs.</p>
<p><strong>Example:</strong></p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3
import importlib
class LibWrapper():
def __init__(self, *args, **kwargs):
self._lib = self.get_lib()
def get_lib(self):
return importlib.import_module("lib")
class ExtendedLibWrapper(LibWrapper):
def __init__(self, *args, **kwargs):
super(ExtendedLibWrapper, self).__init__(*args, **kwargs)
def get_lib(self):
return importlib.import_module("extended_lib")
class Base(LibWrapper):
def __init__(self, *args, **kwargs):
super(Base, self).__init__(*args, **kwargs)
def get_version(self):
return self._lib.get_version()
def print_version(self):
print("Base class:\n\t" + self.get_version())
class Derived(Base, ExtendedLibWrapper):
def __init__(self, *args, **kwargs):
super(Derived, self).__init__(*args, **kwargs)
def print_version(self):
print("Derived class:\n\t" + self.get_version())
if __name__ == '__main__':
base = Base()
base.print_version()
derived = Derived()
derived.print_version()
</code></pre>
<p>The output is:</p>
<pre class="lang-bsh prettyprint-override"><code>~$ ./test.py
Base class:
Lib Version
Derived class:
Extended Lib Version
</code></pre>
<p><strong>Question(s):</strong></p>
<ul>
<li>coming from a different software development experience (<code>c++</code>), I would like to ask: <em>is this pythonic?</em></li>
<li>is there a better, more robust or easily extensible, setup?</li>
</ul>
|
[] |
[
{
"body": "<p>Yes, this is definitely pythonic: implementing lib wrappers allows one to easily include additional features in wrapper classes, as a complement to pure import. So it is both concise and versatile.</p>\n\n<p>As you are working with Python 3 (according to the shebang), you may use the simplified form for <code>super()</code>:</p>\n\n<pre><code>super().__init__(*args, **kwargs)\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>super(ExtendedLibWrapper, self).__init__(*args, **kwargs)\n</code></pre>\n\n<p>It works even with multiple inheritance.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T17:53:45.853",
"Id": "238050",
"ParentId": "237989",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "238050",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T17:59:43.897",
"Id": "237989",
"Score": "2",
"Tags": [
"python",
"inheritance"
],
"Title": "Dynamic module import in a class hierarchy"
}
|
237989
|
<p>I made a formula retriever that works and allows importing of fractions.</p>
<p>This python code is meant for the fx-cg50 calculator's micropython, where there are a lot of functions that don't work including fractions, some mathematical functions such as <code>math.gcd</code> and <code>math.isclose</code>. So I really require some advice or coding tricks to simplify my program.</p>
<p>Disclaimer: I'm only an A-Level student of 16 years; consider me a beginner. I know <code>eval</code> is insecure, but I'm not planning on uploading this online; it's only for my personal use.</p>
<pre class="lang-py prettyprint-override"><code># just to make the input_checker function smaller and to eliminate repeated code
def three_variables_looper_arithmetic():
a = input("enter a1: ")
b = input("enter n: ")
c = input("enter d: ")
original = 0
count_list = [[a], [b], [c]]
loop = 0
for count in count_list:
if isinstance(count[0], str):
original = float(eval(count[0]))
count_list[loop][0] = original
loop += 1
return count_list[0][0], count_list[1][0], count_list[2][0]
# just to make the input_checker function smaller and to eliminate repeated code
def three_variables_looper_geometric():
a = input("enter a1: ")
b = input("enter r: ")
c = input("enter n: ")
original = 0
count_list = [[a], [b], [c]]
loop = 0
for count in count_list:
if isinstance(count[0], str):
original = float(eval(count[0]))
count_list[loop][0] = original
loop += 1
return count_list[0][0], count_list[1][0], count_list[2][0]
# loops through all the inputs of a given situation based on whether its arithmetic
# or not, and checks whether the input is string like "6/2" so it could evaluate it, allows input of fractions
def input_checker(arithmetic_1_geometric_2, formula_num, L):
if arithmetic_1_geometric_2 == 1:
if formula_num == 1:
return three_variables_looper_arithmetic()
elif formula_num == 2:
return three_variables_looper_arithmetic()
elif formula_num == 3:
a1 = input("enter a1: ")
b = input("enter n: ")
c = input("enter d: ")
original = 0
count_list = [[a1], [b], [c], [L]]
loop = 0
for count in count_list:
if isinstance(count[0], str):
original = float(eval(count[0]))
count_list[loop][0] = original
return count_list[0][0], count_list[1][0], count_list[2][0], count_list[3][0]
elif arithmetic_1_geometric_2 == 2:
if formula_num == 1:
return three_variables_looper_geometric()
elif formula_num == 2:
return three_variables_looper_geometric()
elif formula_num == 3:
a1 = input("enter a1: ")
b = input("enter n: ")
original = 0
count_list = [[a1], [b]]
loop = 0
for count in count_list:
if isinstance(count[0], str):
original = float(eval(count[0]))
count_list[loop][0] = original
return count_list[0][0], count_list[1][0]
# as this code is for a calculator the a and b buttons are right beside each other, so after you find your desired result
# you enter a to stop and b to continue
def stopper():
stop_flag = False
stop_or_continue = ""
while stop_or_continue != "a" or "b":
stop_or_continue = input("Stop?: ")
if stop_or_continue == "a":
stop_flag = True
break
if stop_or_continue == "b":
stop_flag = False
break
if stop_flag:
raise SystemExit
print("Sequence & Series Solver")
# asks whether you want to solve arithmetically or geometrically, depends on the sequence/series
while True:
choice = ""
choices = ["a", "b", "c", "d"]
while choice not in choices:
choice = input("a for arithmetic\nb for geometric\n>> ")
if choice == "a":
arithmetic_1_geometric_2 = 1
choice_2 = input("a for a_nth term\nb for sum\n>> ")
# the variable arithmetic_1_geometric_2 refers to whether the inputs are for arithmetic hence it is 1, or the inputs
# are for geometric hence 2
# formula_num refers to the types of formulas you'll use in sequences/series
if choice_2 == "a":
print("a_nth=a1+(n-1)d")
formula_num = 1
a1, n, d = input_checker(arithmetic_1_geometric_2, formula_num, 0)
result = a1+(n-1)*d
print(result)
elif choice_2 == "b":
print("Sn=(n/2)(2a1+(n-1)d)\nSn=(n/2)(a1+L)\nEnter x if L is unknown")
L = input("Enter L: ")
if L == "x":
formula_num = 2
a1, n, d = input_checker(arithmetic_1_geometric_2, formula_num, L)
result = (n/2)*(2*a1+(n-1)*d)
print(result)
else:
formula_num = 3
a1, n, d, L = input_checker(arithmetic_1_geometric_2, formula_num, L)
result = (n/2)*(a1+L)
print(result)
elif choice == "b":
arithmetic_1_geometric_2 = 2
choice_2 = input("a for a_nth term\nb for sum\nc for sum_to_inf")
if choice_2 == "a":
print("a_nth=a1(r)^(n-1)")
formula_num = 1
a1, r, n = input_checker(arithmetic_1_geometric_2, formula_num, 0)
result = a1*(r)**(n-1)
print(result)
elif choice_2 == "b":
print("Sn=(a1(1-(r)^n))/(1-r)")
formula_num = 2
a1, r, n = input_checker(arithmetic_1_geometric_2, formula_num, 0)
result = (a1(1-(r)**n))/(1-r)
print(result)
elif choice_2 == "c":
print("S_inf=a1/(1/r)")
formula_num = 3
a1, r = input_checker(arithmetic_1_geometric_2, formula_num, 0)
result = a1/(1-r)
print(result)
stopper()
</code></pre>
|
[] |
[
{
"body": "<p>For now I'll mostly pick on how you do user input.</p>\n\n<p>In your first two functions, and then again in your main code, you build a complicated data structure with nested lists, only to ever need the elements in the list. Just, don't use that complicated structure.</p>\n\n<p>It might make sense to write a function that asks the user for input and evaluates it if needed:</p>\n\n<pre><code>def get_input(message, type_=float, evaluate=False):\n \"\"\"Ask the user for input that will be cast to `type_`, (default: float).\n\n WARNING: If `evaluate` is `True`, `eval` will be called on the input\n before being cast to the type.\n \"\"\"\n x = input(message)\n if evaluate:\n x = eval(x)\n return type_(x)\n</code></pre>\n\n<p>Note that I made <code>evaluate</code> default to <code>False</code>. This way it is still always obvious that this is a potentially dangerous function and you actively need to enable it. I also added a warning regarding this in the <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstring</a>. Normally I would use <code>type_=str</code> as a default, but since you are mostly dealing with numerical inputs, using <code>float</code> might make more sense here.</p>\n\n<p>You can use this function like this, as a first step:</p>\n\n<pre><code>def three_variables_looper_geometric():\n a = get_input(\"enter a1: \", evaluate=True)\n b = get_input(\"enter r: \", evaluate=True)\n c = get_input(\"enter n: \", evaluate=True)\n return a, b, c\n</code></pre>\n\n<p>At this point you can realize that the function <code>three_variables_looper_arithmetic</code> is almost the same as the <code>three_variables_looper_geometric</code> function, and that this function has a lot of repetition, so it might make sense to make a generic function for this:</p>\n\n<pre><code>def get_variables(*names):\n return [get_input(f\"enter {name}: \", evaluate=True) for name in names]\n</code></pre>\n\n<p>Which you can then use like this:</p>\n\n<pre><code>def three_variables_looper_arithmetic():\n return get_variables(\"a1\", \"n\", \"d\")\n\ndef three_variables_looper_geometric():\n return get_variables(\"a1\", \"r\", \"n\")\n</code></pre>\n\n<p>Note that I used the relatively new <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"nofollow noreferrer\"><code>f-string</code></a> for easy building of the string. If your Python version does not support this, replace it with the slightly longer <code>\"enter {}: \".format(name)</code>.</p>\n\n<p>This now returns a <code>list</code> (since it uses a <a href=\"https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow noreferrer\">list comprehension</a>), instead of a <code>tuple</code>, which should not make any difference (you can still assign them via tuple unpacking, etc). It also uses tuple unpacking in the signature in order to <a href=\"https://www.geeksforgeeks.org/args-kwargs-python/\" rel=\"nofollow noreferrer\">take a variable number of arguments</a>.</p>\n\n<p>You can also use this directly in the <code>input_checker</code> function, making those two functions completely obsolete:</p>\n\n<pre><code>def input_checker(arithmetic_1_geometric_2, formula_num, L):\n if arithmetic_1_geometric_2 == 1:\n if formula_num in [1, 2]:\n return get_variables(\"a1\", \"n\", \"d\")\n elif formula_num == 3:\n return get_variables(\"a1\", \"n\", \"d\") + [L]\n elif arithmetic_1_geometric_2 == 2:\n if formula_num in [1, 2]:\n return get_variables(\"a1\", \"r\", \"n\")\n elif formula_num == 3:\n return get_variables(\"a1\", \"n\")\n</code></pre>\n\n<hr>\n\n<p>The input function can also be improved further if needed, for example by continuing to ask if the entered string cannot be cast to the required type, or if some validator function fails (very useful to e.g. enforce a value to lie in a certain range or be one of some choices):</p>\n\n<pre><code>from sys import stderr\n\n\ndef get_input(message, type_=float, validator=lambda x: True, evaluate=False):\n \"\"\"Ask the user for input that will be cast to `type_`, (default: float).\n\n WARNING: If `evaluate` is `True`, `eval` will be called on the input\n before being cast to the type.\n \"\"\"\n while True:\n x = input(message)\n if evaluate:\n x = eval(x)\n try:\n x = type_(x)\n except TypeError:\n print(x, \"cannot be cast to type\", type_, file=stderr)\n continue\n if not validator(x):\n print(x, \"is not valid.\", file=stderr)\n continue\n return x\n</code></pre>\n\n<p>Here are two use-cases for this, the latter of which actually appears in your code later on:</p>\n\n<pre><code>get_input(\"enter x\", validator=lambda x: 0 <= x < 100)\n\nchoices = {\"a\", \"b\", \"c\"}\nget_input(\"enter choice\", type_=str, validator=choices.__contains__)\n# Or, equivalently\nget_input(\"enter choice\", type_=str, validator=lambda x: x in choices)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T17:58:07.513",
"Id": "466867",
"Score": "0",
"body": "ahh interesting thank you for your time, really helpful!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T09:40:27.873",
"Id": "238029",
"ParentId": "237991",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "238029",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T18:32:21.267",
"Id": "237991",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"formatting",
"mathematics"
],
"Title": "A sequence/series formula solver"
}
|
237991
|
<p>I have a weather app that allows the user to save Cities (with nickname and zip) into a room database. I'm using mvvm and livedata to observe the list of cities and update the recyclerview accordingly. I then perform an API call for each item in the recyclerview, which to me seems wrong. It works but seems wrong.</p>
<p>I'd appreciate any reviews on things I could do to improve.</p>
<pre><code>public class RecyclerAdapter extends ListAdapter<MyCity, RecyclerAdapter.ViewHolder> {
private static final DiffUtil.ItemCallback<MyCity> DIFF_CALLBACK = new DiffUtil.ItemCallback<MyCity>() {
@Override
public boolean areItemsTheSame(@NonNull MyCity oldItem, @NonNull MyCity newItem) {
return oldItem.getId() == newItem.getId();
}
@Override
public boolean areContentsTheSame(@NonNull MyCity oldItem, @NonNull MyCity newItem) {
return oldItem.getZipCode() == newItem.getZipCode();
}
};
public RecyclerAdapter() {
super(DIFF_CALLBACK);
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_item_list, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
MyCity city = getItem(position);
WeatherApi weatherApi = RetrofitService.createService(WeatherApi.class);
weatherApi.getWeatherWithZip(city.getZipCode(), Constants.API_KEY).enqueue(new Callback<WeatherResponse>() {
@Override
public void onResponse(Call<WeatherResponse> call, Response<WeatherResponse> response) {
if (response.isSuccessful()) {
String zip = String.valueOf(city.getZipCode());
holder.zip.setText(zip);
holder.city.setText(response.body().getName());
holder.weather.setText(Conversions.kelvinToFahrenheit(response.body().getMain().getTemp()) + "°C");
}
}
@Override
public void onFailure(Call<WeatherResponse> call, Throwable t) {
}
});
}
public MyCity getCityAt(int position) {
return getItem(position);
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView zip, city, weather;
public ViewHolder(@NonNull View itemView) {
super(itemView);
zip = itemView.findViewById(R.id.tv_zip);
city = itemView.findViewById(R.id.tv_city);
weather = itemView.findViewById(R.id.tv_weather);
}
}
}
</code></pre>
<p>EDIT:
I just got an email from openweatherapi... I made 11791 calls in a minute. This is definitely not ideal.</p>
<p><img src="https://i.stack.imgur.com/CmKQJ.jpg" alt="This is what the final product looks like"></p>
|
[] |
[
{
"body": "<p><strong>First issue</strong></p>\n\n<p>You're calling the weather API on every <code>OnBindViewHolder()</code>, which means it will get called for each visible row, and on new rows entering, or re-entering the screen. So if you scroll the list a few times you will call the API for each city more than once.</p>\n\n<p><strong>Second issue</strong></p>\n\n<p>Your Adapter shouldn't make any API calls. In fact, it should only concern itself about displaying cities.</p>\n\n<p><strong>How can we solve this?</strong></p>\n\n<p>Your <code>MyCity</code> model should provide all information necessary to display the weather.</p>\n\n<p>So let's add city name and temperature to your model.</p>\n\n<p>Next we create a service which iterates over the cities and calls the API once for each city. This can be a regular Android <code>Service</code> for example, or something more advanced like <code>WorkManager</code>.</p>\n\n<p>This logic will be triggered from your ViewModel.</p>\n\n<p>Depending on how frequent you want the weather updates to be, you can call this each time you open the screen, or on certain intervals.</p>\n\n<p>In all cases, once you get the response back, you need to persist the new data to your database.</p>\n\n<p>Since you are observing the data, the adapter will be automatically notified of changes.</p>\n\n<p><strong>Note:</strong> when retrieving the cities to call the API you shouldn't use <code>LiveData</code> because when you update the city it will re-trigger the <code>LiveData</code> and you find yourself in an endless loop.</p>\n\n<p>Your Dao will look something like this:</p>\n\n<pre><code>@Dao\npublic interface CitiesDao {\n\n @Query(\"SELECT * FROM cities\")\n List<MyCity> getCities();\n\n @Query(\"SELECT * FROM cities\")\n LiveData<List<MyCity>> observeCities();\n\n // etc\n\n}\n</code></pre>\n\n<p>This is just the starting point.</p>\n\n<p>More things you can consider:</p>\n\n<ul>\n<li>Use different models for data and UI (e.g. MyCity and MyCityUiModel)</li>\n<li>Use the Repository pattern</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T22:40:24.033",
"Id": "238009",
"ParentId": "237993",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "238009",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T18:40:29.693",
"Id": "237993",
"Score": "7",
"Tags": [
"java",
"android"
],
"Title": "Recyclerview Adapter for weather app - Makes API calls for each item"
}
|
237993
|
<p>I asked this question on Stackoverflow, but thought it might be a better fit here.</p>
<p>I'm playing around with the titanic dataset, and wanted to create a custom imputer to fill in missing <code>age</code> values with predictions from a LinearRegression model. Please find the code below:</p>
<pre><code>import seaborn as sns
import pandas as pd
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LinearRegression
from sklearn.base import BaseEstimator, TransformerMixin
titanic = sns.load_dataset('titanic')
class AgeImputer(TransformerMixin, BaseEstimator):
def fit(self, x, y=None):
self.model = LinearRegression()
# just use two columns for this example
self.independent_columns = ['fare', 'pclass']
# split the null age values from rest of data
self.null_age_data = x[pd.isnull(x['age'])]
self.age_data = x[pd.isnull(x['age'])==False]
# fit the model on age_data
self.model.fit(self.age_data[self.independent_columns], self.age_data['age'])
return self
def transform(self, x):
""" make predictions and return the whole dataframe """
self.null_age_data['age'] = self.model.predict(self.null_age_data[self.independent_columns])
return self.null_age_data.append(self.age_data)
age_imputer = make_pipeline(
AgeImputer()
)
age_imputer.fit_transform(titanic)
</code></pre>
<p>The code does the following:</p>
<ol>
<li>during the <code>fit</code> phase, it saves the entire dataframe as a variable (after splitting it on whether or not the <code>age</code> column is null or not)</li>
<li>Fits a linear regression model on the dataset where <code>age</code> is not null</li>
<li>During the transform phase, it predicts the null values.</li>
<li>Finally, concatenates the two dataframe and output the result.</li>
</ol>
<p>I'm wondering if this is the best way to create an imputer like this. The reason being, passing in the whole dataframe and saving it as a class variables feels like a waste of memory. Is there a simpler solution than this where the memory usage might be more efficient? Thanks in advance!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T19:12:11.600",
"Id": "466753",
"Score": "0",
"body": "Could you add a short explanation for how you code works, and why you made any unorthodox choices if you did?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T20:29:38.887",
"Id": "466891",
"Score": "1",
"body": "@K00lman I did my best to add some explanation. Please check the edit, thanks!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T19:01:07.363",
"Id": "237996",
"Score": "2",
"Tags": [
"python",
"pandas",
"machine-learning"
],
"Title": "Sklearn Custom Imputer from prediction"
}
|
237996
|
<p>I want inputs on how I can square the sorted Array more efficiently in haskell. I wrote a very naive algorithm to solve the problem. What I am doing is comparing the head and the last element of list on absolute value and whichever is max I square the element and add it to accumulator.</p>
<p>But I think it is very slow. Is there any data structure that I can use to make it more efficient.</p>
<pre><code>import qualified Data.List as List
sqrarr:: [Int] -> [Int]
sqrarr xss = helper xss []
helper::[Int] -> [Int] -> [Int]
helper [] acc = acc
helper [x] acc = [(x^ 2)] ++ acc
helper (x:xss) acc = case abs x > abs (List.last xss) of
False -> helper (x: (List.init xss)) (((List.last xss)^2): acc)
True -> helper xss ((x ^ 2):acc)
</code></pre>
<p>The above code works and gives the desired input </p>
<pre><code>sqrarr [-7, -4, 2,5,8]
[4,16,25,49,64]
</code></pre>
<p>I have found another solution</p>
<pre><code>import Data.Array
sqrarr2::[Int] -> [Int]
sqrarr2 xss = helper2 0 (length xss -1)
(listArray (0,(length xss -1)) xss)
[]
helper2::Int -> Int -> Array Int Int -> [Int] -> [Int]
helper2 l r arr acc = case l > r of
True -> acc
False -> case abs (arr!l) > abs (arr!r) of
False -> helper2 l (r - 1) arr ((arr!r ^ 2):acc)
True -> helper2 (l + 1) r arr ((arr!l ^ 2):acc)
</code></pre>
|
[] |
[
{
"body": "<p>This looks needlessly convoluted: there is a lot happening, all at once, on top of each other.</p>\n\n<p>The way to think about this is: first square each number, then sort the resulting list. The way to transform each element of a list is <a href=\"https://www.stackage.org/haddock/lts-15.1/base-4.13.0.0/Prelude.html#v:map\" rel=\"nofollow noreferrer\"><code>map</code></a>. The way to sort is, well, <a href=\"https://www.stackage.org/haddock/lts-15.1/base-4.13.0.0/Data-List.html#v:sort\" rel=\"nofollow noreferrer\"><code>sort</code></a>. The way to compose two functions (i.e. pass the result of one as argument to the other) is <a href=\"https://www.stackage.org/haddock/lts-15.1/base-4.13.0.0/Prelude.html#v:.\" rel=\"nofollow noreferrer\"><code>.</code> (dot)</a></p>\n\n<p>So:</p>\n\n<pre><code>sqrarr = sort . map sq\n where\n sq x = x * x\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T20:29:48.720",
"Id": "466758",
"Score": "0",
"body": "Thank you for your time"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T20:01:22.807",
"Id": "238001",
"ParentId": "237999",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T19:32:16.000",
"Id": "237999",
"Score": "2",
"Tags": [
"haskell"
],
"Title": "Square the sorted array using haskell"
}
|
237999
|
<p>I am beginning to learn about object oriented programming in my programming class, and to make sure I had all the ideas down, I made a small palindrome checker program. It works by checking if the letter on the opposite side is the same.</p>
<pre class="lang-py prettyprint-override"><code>from time import sleep # To add readability delays
class PalindromeFinder:
# Makes the variables
def __init__(self):
self.letter_count = {}
self.loop = 0
def check_for_palindrome(self, base):
self.loop = 0
for letter in base:
# Checks if the letter in x position is the same as the letter in the -x position
if base[self.loop] != base[-(self.loop + 1)]:
return (f"{base} is not a palindrome")
self.loop += 1
return (f"{base} is a palindrome.")
def introduce_palindromes():
print("Palindromes are really cool!")
sleep(2)
print("It when a word or phrase is the same backwards and forwards!")
sleep(2)
print("For example", palindrome_checker.check_for_palindrome("racecar"))
sleep(2)
print("While", palindrome_checker.check_for_palindrome("alarm"))
sleep(2)
print("Now you enter some palindromes!")
palindrome_checker = PalindromeFinder()
introduce_palindromes()
while True:
sleep(1)
print(palindrome_checker.check_for_palindrome(input("Enter your palindrome: ").lower()))
</code></pre>
<p>Since I have no idea what I am doing, I just generally want to know if what I am doing is not violating any conventions. More specifically, I want to know if having both functions and classes are ok, as well as if putting the variables in <code>__init__</code> like I did is fine. Also, when initializing several instances at once, is there any documentation on were you do it? Do you do it between the class and functions or between the functions and the code?</p>
<p>Any other advice is welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T20:06:12.440",
"Id": "466755",
"Score": "1",
"body": "As you stated *\"I have no idea what I am doing\"*, all your effort is replaced with a short function `def is_palindrome(inp_text): return inp_text == inp_text[::-1]`. That's all"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T22:14:19.253",
"Id": "466766",
"Score": "3",
"body": "OOP isn't necessarily the best tool for every job, so this specific thing might not be a good example to learn with. Something that involves multiple steps and state that needs to be tracked between steps would be a better use case for an object."
}
] |
[
{
"body": "<p>As stated in the comments, this is not a good example for OO programming, because it can be solved with just a function. Sometimes you can still use classes to separate different functionality, but in Python this is not really required nor generally practiced (compared to e.g. Java where all code <em>must be</em> in a class - if we discount <code>default</code> methods in interfaces, static code blocks and such).</p>\n\n<p>Now you've put designated two variables as fields, while they <strong>should</strong> be local to the function. There is no need at all to use them as fields. This won't directly show up as a problem, but if you'd e.g. call the method <code>check_for_palindrome</code> in a concurrent fashion, you'd be in trouble, because the <code>loop</code> field will now be used by two different threads at once. <code>letter_count</code> on the other hand is secure, but only because it is simply not used.</p>\n\n<p>Only create fields for variable values that are intrinsic to the class (or are references that tie the class to another of which it is dependent). For instance, you might want to configure the checker to check for upper or lowercase, or maybe even mixed case. That kind of field would be logical for a palindrome checker class. All in all, you should try and <em>minimize the variables that make up the state</em> and thus number & complexity of the fields for a particular class.</p>\n\n<p>As you've already found out yourself, <code>PalindromeChecker</code> would be a better name for the class, as it doesn't <strong>search</strong> for palindromes, at least not at the moment. If you've got a method for a class, you don't need to repeat everything, just <code>PalindromeChecker.check</code> would be sufficient. I don't know why the input is called <code>base</code>, just <code>input</code> seems sufficient (edit: <code>word</code> would probably even be a better name).</p>\n\n<p>When it comes to functionality of a class, it is important to distinguish human interaction with actual output. I'd never create a checker that would return a string as response. In this case I'd expect a <code>bool</code> output instead. Then the program that uses the checker can create a user response if the result is <code>True</code> or <code>False</code>. At least didn't <em>print out</em> the result, which would have been the action of most starting developers.</p>\n\n<p>Finally, in the call to the class instance, you're trying to do too much at once:</p>\n\n<pre><code>print(palindrome_checker.check_for_palindrome(input(\"Enter your palindrome: \").lower()))\n</code></pre>\n\n<p>First assign the result to a variable and then print it out. Separate the input. You'll thank yourself if you have to startup a debugger and step through your program.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T02:26:08.810",
"Id": "238016",
"ParentId": "238000",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "238016",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T19:45:02.633",
"Id": "238000",
"Score": "4",
"Tags": [
"python",
"beginner",
"python-3.x",
"object-oriented"
],
"Title": "O.O. Style Palindrome Checker"
}
|
238000
|
<p>I'm new to Haskell, so I wrote a program to crack Caesar Ciphered text for practice. The program calculates the frequency of each letter in the input, and then checks to see which shift minimizes the Euclidean norm of the element-wise difference between the text's frequencies and pre-measured frequencies in the English language. The program prints the shift to stdio and writes the decrypted text to {<em>input file name</em>}_DECRYPTED.</p>
<p>While this isn't actually a great (let alone mediocre) decryption method, I'd appreciate any input about how to improve my code to make it more "Haskell-like" or idiomatic. Syntax and readability suggestions are also more than welcome.</p>
<p>Thank you!</p>
<pre class="lang-hs prettyprint-override"><code>import System.Environment (getArgs)
import System.IO
import Data.List (elemIndex)
import Data.Char (ord, chr, isUpper, isAlpha, toLower)
import Data.Bool (bool)
import Data.Map (fromListWith, toList)
-- English letter frequencies from A to Z
frequencies :: (Fractional a) => [a]
frequencies = [0.0812,
0.0149,
0.0271,
0.0432,
0.1202,
0.023,
0.0203,
0.0592,
0.0731,
0.001,
0.0069,
0.0398,
0.0261,
0.0695,
0.0768,
0.0182,
0.0011,
0.0602,
0.0628,
0.091,
0.0288,
0.0111,
0.0209,
0.0017,
0.0211,
0.0007]
main :: IO()
main = do
(filename: _) <- getArgs
handle <- openFile filename ReadMode
encrypted <- hGetContents handle
let shift_size = decrypt (map toLower $ filter isAlpha encrypted) in
do
print shift_size
writeFile (filename ++ "_DECRYPTED") (shift (negate shift_size) encrypted)
hClose handle
shift :: Int -> String -> String
shift s input = map (shiftLetter s) input
shiftLetter :: Int -> Char -> Char
shiftLetter offset c
| isAlpha c =
let i = ord $ bool 'a' 'A' (isUpper c)
in chr $ i + mod ((ord c - i) + offset) 26
| otherwise = c
decrypt :: String -> Int
decrypt text = let len = fromIntegral $ length text
(_, freq) = unzip $ toList $ fromListWith (+) [(c, 1.0) | c <- text]
in minShift frequencies $ map (flip (/) len) freq
minShift :: (Fractional a) => (Ord a) => [a] -> [a] -> Int
minShift freq1 freq2 = let norms = map (\x -> norm freq1 (shiftList freq2 x)) [0..25]
(Just num) = elemIndex (minimum norms) norms in num
shiftList :: (Fractional a) => [a] -> Int -> [a]
shiftList freq x = iterate oneCycle freq !! x
oneCycle :: (Fractional a) => [a] -> [a]
oneCycle (x:xs) = xs ++ [x]
norm :: (Fractional a) => [a] -> [a] -> a
norm xs ys = foldl (\acc -> \(x, y) -> acc + (x - y)^2) 0 $ zip xs ys
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T06:51:14.150",
"Id": "466802",
"Score": "1",
"body": "Welcome to CodeReview@SE! Add the [tag:beginner] tag. As in many SE sites, it is considered non-helpful to repeat tags in the title. Your post may catch more attention if you start the code with something more interesting than binding `frequencies` - is the sequence the functions are presented in deliberate?"
}
] |
[
{
"body": "<p>Let's start with the trivial stuff...</p>\n\n<p>A few minor stylistic points that are pretty much universal:</p>\n\n<ul>\n<li>The type <code>IO ()</code> is always written with a space between <code>IO</code> and <code>()</code>, never <code>IO()</code>.</li>\n<li><p>Similarly, multiple constraints are written as a comma-separated list:</p>\n\n<pre><code>(Fractional a, Ord a) => ...\n</code></pre>\n\n<p>rather than a chained list <code>(Fractional a) => (Ord a) => ...</code></p></li>\n<li><p>For do-blocks, even though the syntax permits:</p>\n\n<pre><code>do\nfirstLine\nsecondLine\n</code></pre>\n\n<p>they are almost never written this way. It's either:</p>\n\n<pre><code>do firstLine\n secondLine\n</code></pre>\n\n<p>or else:</p>\n\n<pre><code>do\n firstLine -- w/ your standard choice of indentation, usually 2 or 4\n secondLine\n</code></pre>\n\n<p>It's often considered acceptable to write:</p>\n\n<pre><code>someother expression $ do\n contentsOf\n theDoBlock\n</code></pre>\n\n<p>so the contents can be unindented or negatively indented with respect to the <code>do</code> keyword in this case.</p></li>\n</ul>\n\n<p>For the specific do-block in your <code>main</code> function, because a standalone <code>let</code> statement is permitted in do-notation, you don't need the nesting at all, so this would be more standard:</p>\n\n<pre><code>main = do\n ...\n let shift_size = decrypt (map toLower $ filter isAlpha encrypted)\n print shift_size\n writeFile (filename ++ \"_DECRYPTED\") (shift (negate shift_size) encrypted)\n hClose handle\n</code></pre>\n\n<p>(This is <em>despite</em> the fact that <code>shift_size</code> is only needed in the following two lines and not the last.)</p>\n\n<p>I find that idiomatic Haskell tends to use <code>where</code> in preference to <code>let ... in ...</code> statements, so for example:</p>\n\n<pre><code>decrypt :: String -> Int\ndecrypt text = minShift frequencies $ map (flip (/) len) freq\n where len = fromIntegral $ length text\n (_, freq) = unzip $ toList $ fromListWith (+) [(c, 1.0) | c <- text]\n</code></pre>\n\n<p>The motivation here is that the definition of <code>decrypt text</code> is given immediately following the <code>=</code>, and if the helper functions like <code>len</code> and <code>freq</code> have sufficiently self-evident names, the reader can mostly ignore the <code>where ...</code> details.</p>\n\n<p>More controversially, some people like to write the most general type signatures possible. In my opinion, unless you're writing a library or actually need the generality, I don't think there's much point. The polymorphic type signatures and <code>Fractional</code> constraints clutter up your code, and if you turned on <code>-Wall</code>, which you should be doing anyway, you'd see that GHC is defaulting your type to <code>Double</code>, a default that would be better to make explicit anyway. Personally, I'd replace most of the <code>Fractional a => ... a ...</code> with <code>Double</code>s. (Well, except <code>oneCycle</code> and <code>shiftList</code>, which are probably clearer with unconstrained type signatures.)</p>\n\n<p>Now to the less trivial stuff...</p>\n\n<p>In <code>minShift</code>, consider the definition of <code>norms</code>:</p>\n\n<pre><code>norms = map (\\x -> norm freq1 (shiftList freq2 x)) [0..25]\n</code></pre>\n\n<p>This calculates <code>shiftList freq2 x</code> for every <code>x</code> from 0 to 25, but <code>shiftList</code> works by generating the full list <code>iterate oneCycle freq</code> and then selecting element <code>x</code>, so you would have been better off writing:</p>\n\n<pre><code>norms = map (norm freq1) (take 26 $ iterate oneCycle freq2)\n</code></pre>\n\n<p>Actually, a more common way of calculating all \"cycles\" of a list is:</p>\n\n<pre><code>cycles :: [a] -> [[a]]\ncycles xs = zipWith (++) (tails xs) (inits xs)\n</code></pre>\n\n<p>which many Haskellers take great pride in writing using implicit reader monad/applicative:</p>\n\n<pre><code>cycles :: [a] -> [[a]]\ncycles = zipWith (++) <$> tails <*> inits\n</code></pre>\n\n<p>Also, finding the minimum with <code>minimum</code> and then getting its index with <code>elemIndex</code> would be frowned upon because it traverses the list twice (or, on average, one and a half times in the absence of duplicate minimums), and even though it's ridiculous to worry about performance on a 26-item list, I guess folks would be more likely to use a trick like:</p>\n\n<pre><code>minimumIndex :: (Ord a) => [a] -> Int\nminimumIndex xs = snd . minimum $ zip xs [0..]\n</code></pre>\n\n<p>Note that I'm breaking my own rule here about not overgeneralizing functions. In this case, it just \"feels\" right. Anyway, the way this works is by using <code>zip</code> to add an index, so that the list <code>xs = [5,4,6,1,8]</code> becomes:</p>\n\n<pre><code>[(5,0),(4,1),(6,2),(1,3),(8,4)]\n</code></pre>\n\n<p>Because tuples are sorted lexicographically, finding the minimum will pick up the element <code>(1,3)</code>, and we use <code>snd</code> to grab the index \"3\".</p>\n\n<p>So, now <code>minShift</code> looks like this:</p>\n\n<pre><code>minShift :: [Double] -> [Double] -> Int\nminShift freq1 freq2 = minimumIndex $ map (norm freq1) (cycles freq2)\n</code></pre>\n\n<p>with helpers <code>minimumIndex</code> and <code>cycles</code> as above.</p>\n\n<p>For the top-level <code>norm</code> function, your <code>foldl</code> is really a <code>sum</code>, and you can use <code>zipWith</code> to combine the <code>zip</code> with the calculation of the term:</p>\n\n<pre><code>norm :: [Double] -> [Double] -> Double\nnorm xs ys = sum $ zipWith (\\x y -> (x-y)^2) xs ys\n</code></pre>\n\n<p>With <code>-Wall</code> on, this warns you that <code>2</code> is defaulting to <code>Integer</code>. I'd probably write:</p>\n\n<pre><code>norm :: [Double] -> [Double] -> Double\nnorm xs ys = sum $ zipWith (\\x y -> (x-y)*(x-y)) xs ys\n</code></pre>\n\n<p>just to get rid of this warning.</p>\n\n<p>In <code>decrypt</code>, the <code>flip</code> can be replaced with a section:</p>\n\n<pre><code>decrypt text = minShift frequencies $ map (/ len) freq\n</code></pre>\n\n<p>However, there's a bug in your <code>freq</code> calculation. The map it builds will only have keys for the letters that actually appear in the input text, so the <code>freq</code> and <code>frequencies</code> lists won't generally line up. Anyway, I'd pull it out into a separate function:</p>\n\n<pre><code>{-# LANGUAGE TupleSections #-}\nimport qualified Data.Map.Strict as Map\n\nfreq :: String -> [Int]\nfreq inp\n = Map.elems $ Map.unionWith (+) initMap . Map.fromListWith (+) . map (,1) $ inp\n where initMap = Map.fromList . map (,0) $ ['a'..'z']\n</code></pre>\n\n<p>This uses <code>Map.unionWith</code> and an all-zeros map <code>initMap</code> to ensure the keys <code>'a'</code> through <code>'z'</code> will be in the map. It also uses <code>Map.elems</code> in place of <code>let (_, freq) = unzip $ Map.toList $ ...</code>.</p>\n\n<p>Finally, note that I've used <code>Data.Map.Strict</code>. This is good practice for \"counting\" maps, so that large inputs don't cause a memory leak.</p>\n\n<p>My <code>decrypt</code> now looks like:</p>\n\n<pre><code>decrypt :: String -> Int\ndecrypt text = minShift frequencies $ map (/ len) $ map fromIntegral $ freq text\n where len = fromIntegral $ length text\n</code></pre>\n\n<p>Also, <code>shiftLetter</code> would probably be clearer to write with separate cases and a helper in place of <code>bool</code>.</p>\n\n<pre><code>shiftLetter :: Int -> Char -> Char\nshiftLetter offset c\n | isAsciiLower c = go 'a'\n | isAsciiUpper c = go 'A'\n | otherwise = c\n where go a = chr $ (ord c - ord a + offset) `mod` 26 + ord a\n</code></pre>\n\n<p>Note that the <code>isAscii...</code> versions are safer than <code>isLower</code> and <code>isUpper</code> because these allow unicode letters.</p>\n\n<p>For <code>shift</code>, some typical simplifications are possible. So:</p>\n\n<pre><code>shift s input = map (shiftLetter s) input\n</code></pre>\n\n<p>can be rewritten (using \"eta reduction\") as:</p>\n\n<pre><code>shift s = map (shiftLetter s)\n</code></pre>\n\n<p>Some people might go farther and write:</p>\n\n<pre><code>shift = map . shiftLetter\n</code></pre>\n\n<p>though this isn't particularlyclear. Maybe this would be a nice compromise:</p>\n\n<pre><code>shift :: Int -> String -> String\nshift offset = map shift1\n where\n shift1 c\n | isAsciiLower c = go 'a' c\n | isAsciiUpper c = go 'A' c\n | otherwise = c\n go a c = chr $ (ord c - ord a + offset) `mod` 26 + ord a\n</code></pre>\n\n<p>allowing us to eliminate <code>shiftLetter</code> completely.</p>\n\n<p>In <code>main</code>, for quick-and-dirty argument parsing, you can write:</p>\n\n<pre><code>[filename] <- getArgs\n</code></pre>\n\n<p>This has the advantage over <code>filename:_ <- getArgs</code> of raising an exception if more than one argument is supplied.</p>\n\n<p>The <code>openFile</code> / <code>hClose</code> pairs is more properly written using a <code>withFile</code> clause. But, if you're opening a file just to read its contents, it's better to use <code>readFile</code> anyway.</p>\n\n<pre><code>encrypted <- readFile filename\n</code></pre>\n\n<p>so my final <code>main</code> looks like:</p>\n\n<pre><code>main :: IO ()\nmain = do\n [filename] <- getArgs\n encrypted <- readFile filename\n let shift_size = decrypt (map toLower $ filter isAlpha encrypted)\n print shift_size\n writeFile (filename ++ \"_DECRYPTED\") (shift (negate shift_size) encrypted)\n</code></pre>\n\n<p>The final thing that bothers me is that <code>freq</code> has to pass through the <code>String</code> once to calculate the counts, and then <code>decrypt</code> passes through it again to count the full text length. I'd like to do it in one pass, so I'd rewrite <code>freq</code> to calculate the full text length, too, and return the fractional frequencies directly. This also allows us to pull the filtering into <code>freq</code> which is safer, since the above version of <code>freq</code> will break if it gets fed input that isn't restricted to the characters from <code>'a'</code> to <code>'z'</code>.</p>\n\n<pre><code>freq :: String -> [Double]\nfreq str = let (tot', mp') = foldl' step (0::Int, initMap) . getLower $ str\n in divlist (Map.elems mp') tot'\n where\n -- get ASCII letters, converted to lowercase\n getLower = filter isAsciiLower . map toLower\n -- initial map of all-zero counts for 'a' to 'z'\n initMap = Map.fromList . map (,0::Int) $ ['a'..'z']\n -- for each `c`, add one to `tot` and count a `c`\n step (tot, mp) c = (tot+1, Map.insertWith (+) c 1 mp)\n -- divide each element of xs by n\n divlist xs n = map (/ fromIntegral n) (map fromIntegral xs)\n</code></pre>\n\n<p>This works with the following versions of <code>main</code> and <code>decrypt</code>:</p>\n\n<pre><code>main :: IO ()\nmain = do\n [filename] <- getArgs\n encrypted <- readFile filename\n let shift_size = decrypt encrypted\n print shift_size\n writeFile (filename ++ \"_DECRYPTED\") (shift (-shift_size) encrypted)\n\ndecrypt :: String -> Int\ndecrypt text = minShift frequencies (freq text)\n where len = fromIntegral $ length text\n</code></pre>\n\n<p>Note that <code>negate</code> can be written <code>-</code> as long as you stick in some parentheses. Some people hate this because this <code>-</code> is Haskell's only unary operator and looks weird, so they might stick with <code>negate</code> anyway.</p>\n\n<p>Finally, I think I'd rearrange <code>minShift</code> a bit to make things easier to test. Also, <code>Data.Char</code> and some others (<code>Data.List</code> and <code>Data.Foldable</code>) are commonly imported in full without explicit import lists, and <code>Data.Map.Strict</code> is commonly imported qualified without an explicit import list, so I'd probably write my imports as:</p>\n\n<pre><code>import System.Environment (getArgs)\nimport Data.List\nimport Data.Char\nimport qualified Data.Map.Strict as Map\n</code></pre>\n\n<p>This gives the final program:</p>\n\n<pre><code>{-# LANGUAGE TupleSections #-}\n{-# OPTIONS_GHC -Wall #-}\n\nimport System.Environment (getArgs)\nimport Data.List\nimport Data.Char\nimport qualified Data.Map.Strict as Map\n\nmain :: IO ()\nmain = do\n [filename] <- getArgs\n encrypted <- readFile filename\n let shift_size = decrypt encrypted\n print shift_size\n writeFile (filename ++ \"_DECRYPTED\") (shift (-shift_size) encrypted)\n\ndecrypt :: String -> Int\ndecrypt text = minimumIndex $ norms english (freq text)\n\n-- English letter frequencies from A to Z\nenglish :: [Double]\nenglish = [0.0812, 0.0149, 0.0271, 0.0432, 0.1202, 0.023, 0.0203, 0.0592, 0.0731, 0.001,\n 0.0069, 0.0398, 0.0261, 0.0695, 0.0768, 0.0182, 0.0011, 0.0602, 0.0628, 0.091,\n 0.0288, 0.0111, 0.0209, 0.0017, 0.0211, 0.0007]\n\nnorms :: [Double] -> [Double] -> [Double]\nnorms freq1 freq2 = map (norm freq1) (cycles freq2)\n\nnorm :: (Fractional a) => [a] -> [a] -> a\nnorm xs ys = sum $ zipWith (\\x y -> (x-y)*(x-y)) xs ys\n\nfreq :: String -> [Double]\nfreq str = let (tot', mp') = foldl' step (0::Int, initMap) . getLower $ str\n in divlist (Map.elems mp') tot'\n where\n -- get ASCII letters, converted to lowercase\n getLower = filter isAsciiLower . map toLower\n -- initial map of all-zero counts for 'a' to 'z'\n initMap = Map.fromList . map (,0::Int) $ ['a'..'z']\n -- for each `c`, add one to `tot` and count a `c`\n step (tot, mp) c = (tot+1, Map.insertWith (+) c 1 mp)\n -- divide each element of xs by n\n divlist xs n = map (/ fromIntegral n) (map fromIntegral xs)\n\nshift :: Int -> String -> String\nshift offset = map shift1\n where\n shift1 c\n | isAsciiLower c = go 'a' c\n | isAsciiUpper c = go 'A' c\n | otherwise = c\n go a c = chr $ (ord c - ord a + offset) `mod` 26 + ord a\n\nminimumIndex :: (Ord a) => [a] -> Int\nminimumIndex xs = snd . minimum $ zip xs [0..]\n\ncycles :: [a] -> [[a]]\ncycles = zipWith (++) <$> tails <*> inits\n</code></pre>\n\n<p>If I run <code>hlint</code> on this, I get one suggestion:</p>\n\n<pre><code>Caesar2.hs:43:20: Suggestion: Use map once\nFound:\n map (/ fromIntegral n) (map fromIntegral xs)\nPerhaps:\n map ((/ fromIntegral n) . fromIntegral) xs\n</code></pre>\n\n<p>In this case, I think the way I have it is clearer.</p>\n\n<p>In this form, it's pretty easy to test:</p>\n\n<pre><code>> freq \"It's pretty easy to test\"\n[5.263157894736842e-2,0.0,0.0,0.0,...]\n> norms english (freq \"It's pretty easy to test\")\n[8.694623493074792e-2,0.14473570861495846,0.17156728756232686,...]\n> minimumIndex $ norms english (freq \"It's pretty easy to test\")\n0\n> decrypt \"huk hjabhssf dvyrz xbpal dlss lclu vu zovya aleaz.\"\n7\n> shift (-7) \"huk hjabhssf dvyrz xbpal dlss lclu vu zovya aleaz.\"\n\"and actually works quite well even on short texts.\"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T01:48:02.867",
"Id": "239258",
"ParentId": "238005",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "239258",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T21:41:33.697",
"Id": "238005",
"Score": "5",
"Tags": [
"beginner",
"haskell"
],
"Title": "Cracking Caesar Cipher"
}
|
238005
|
<p>I've been practicing my folds and tail-call recursive programming, and I wanted to work on <code>unzip</code> for the general case as opposed to just pairs. This was very easy to do with standard tail call recursion. However, I was also told that any time you can use tail call recursion on a list, you could also use a fold. I was eventually able to figure out an algorithm that only uses folds, but it wasn't nearly as simple as, or even exactly a translation of, the tail recursive version. Are there any improvements or changes I could make to either of these algorithms?</p>
<p><strong>Tail-call recursive</strong></p>
<pre class="lang-lisp prettyprint-override"><code>; Unzip a list of equally lengthed lists
; Takes car of every list and conses it to acc, then reverses acc at the end
; (unzip '((1 4 7 10) (2 5 8 11) (3 6 9 12))) => '((1 2 3) (4 5 6) (7 8 9) (10 11 12)
(define (unzip lst [acc '()])
(if (or (empty? lst) (empty? (car lst)))
(reverse acc)
(unzip (map cdr lst) (cons (map car lst) acc))))
</code></pre>
<p><strong>Folds only</strong>:</p>
<pre class="lang-lisp prettyprint-override"><code>; Takes the last element and turns it into a list of singletons as a seed
; For each remaining element, it conses each element onto its respective list
(define (unzip lst)
(define (list->singletons lst)
(foldl (λ (x acc) (cons `(,x) acc)) '() (reverse lst)))
(define (cons* heads tails)
(foldr (λ (hd tl acc) (cons (cons hd tl) acc)) '() heads tails))
(if (empty? lst)
lst
(foldl (λ (x acc) (cons* x acc))
(list->singletons (car (reverse lst))) (cdr (reverse lst)))))
</code></pre>
|
[] |
[
{
"body": "<p>Doing it with folds pretty much begs you to create a custom accumulator and recursive function or fold within a fold like that. </p>\n\n<p>A couple notes. I don't think <code>foldr</code> is tail-recursive. Also <code>(λ (x acc) (cons* x acc))</code> is redundant. You can just use <code>cons*</code></p>\n\n<p>You're also using <code>(reverse lst)</code> in a few different places. You could create a separate definition here, or refactor. </p>\n\n<pre><code>(define (unzip lst)\n (define (template lst) ;;a list of null lists \n (if (null? lst) ;;of the proper length\n '()\n (foldl (λ (x acc) (cons '() acc)) '() (car lst))))\n (define (cons* heads tails)\n (reverse (foldl (λ (hd tl acc) \n (cons (cons hd tl) acc)) \n '() heads tails)))\n (reverse \n (foldl cons* template lst)))\n</code></pre>\n\n<p>Not much chage, but perhaps a bit easier to see what's going on. If your wanting to do it with a single fold, thats a bit tricker.</p>\n\n<pre><code>(define (unzip L)\n (define (mangle glob) \n (let loop ((news '()) (acc glob))\n (if (or (null? (car acc)) (pair? (car acc))) \n (cons (reverse news) (car acc))\n (loop (cons (car acc) news) (cdr acc)))))\n (reverse (apply foldl (lambda z (mangle z))'() L)))\n</code></pre>\n\n<p>Notice the lambda is just grabbing a list off all arguments, and we are <code>apply</code>ing foldl to the lists of lists, as if we are folding multiple lists. However arity is unknown so I've got to take all the arguments as a list, and figure out what is new and what was the accumulator on each round. As is this will choke on a list of lists of lists, but maybe an interesting approach.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-03T14:09:45.950",
"Id": "238312",
"ParentId": "238007",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "238312",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T22:04:29.270",
"Id": "238007",
"Score": "1",
"Tags": [
"scheme",
"racket",
"fold",
"tail-recursion"
],
"Title": "Implementations of unzip in Racket"
}
|
238007
|
<p>I have a javascript function that will accept an array of objects (from a database or websocket) and then spit out HTML <code><ul></code> lists. The code works -- but I am "self-taught" and always learning. I want to be producing professional looking/behaving code. I will be graduating from university, but job prospects in my field are low... Any insights into style or approach would be welcomed. Get the red marker out :)</p>
<p>The HTML output from the function is:</p>
<pre><code><ul class="prek">
<li class="firstName">Bobby</li>
<li class="lastName">Fisher</li>
<li class="guardian"><span>Mommy</span><span>Fisher</span></li>
<li class="checkIn">9:14am</li>
<li class="phone">ewqrqr3452</li>
<ul class="buttons">
<li class="pageButton">Page Mommy</li>
<li class="edit">Edit Bobby</li>
<li class="move">Move Bobby To Group</li>
<li class="checkOut">Check Out Bobby</li>
</ul>
</ul>
<ul class="grade1">
<li class="firstName">Anne</li>
<li class="lastName">Gables</li>
<li class="guardian"><span>Green</span><span>Gables</span></li>
<li class="checkIn">9:14am</li>
<li class="flag"><span class="peanuts"></span><span class="bees"></span></li>
<li class="phone">ewqrqr3452</li>
<ul class="buttons">
<li class="pageButton">Page Green</li>
<li class="edit">Edit Anne</li>
<li class="move">Move Anne To Group</li>
<li class="checkOut">Check Out Anne</li>
</ul>
</ul>
</code></pre>
<p>The input looks like this: </p>
<pre><code>children = [
{
group: "prek",
firstName: "Bobby",
lastName: "Fisher",
guardian: {firstName: "Mommy", lastName: "Fisher"},
checkIn: "9:14am",
phone: "ewqrqr3452",
},
{
group: "grade1",
firstName: "Anne",
lastName: "Gables",
guardian: { firstName: "Green", lastName: "Gables" },
checkIn: "9:14am",
notes: "",
flag: ["peanuts", "bees"],
phone: "ewqrqr3452",
}
];
for(const child of children) {
addChild(child);
}
</code></pre>
<p>And the Javascript looks like this:</p>
<pre><code>function addChild(child){
// Create child <ul>
const ul = document.createElement("ul");
document.getElementById("childList").appendChild(ul);
// Assign <ul> to a group
if(child.group) {
ul.classList.add(child.group);
delete child.group;
}
else {
ul.classList.add("unassigned");
}
// Add properties to the child as <li>
for(let property in child) {
// If the value is empty don't add the <li>
if(!child[property]) {
continue;
}
// Create <li> node and add class
const li = document.createElement("li");
li.classList.add(property);
// Add child properties to the li
if(typeof(child[property]) !== "object") {
// Add simple data to the li
li.innerText = child[property];
} else {
// If the data is an object go deeper put the elements into a span
for (const nestedKey in child[property]) {
// Don't go deeper -- it's just malformed data
if(typeof(child[property][nestedKey]) === "object") {
continue;
}
// Create the span with data in it
const span = document.createElement("span");
if(parseInt(nestedKey) >= 0) {
span.classList.add(child[property][nestedKey]);
} else {
span.innerText = child[property][nestedKey];
}
li.appendChild(span);
}
}
ul.appendChild(li);
}
// CHILD BUTTONS
const buttons = document.createElement("ul");
buttons.classList.add("buttons");
// Page guardian button
const page = document.createElement("li");
page.innerText = `Page ${child.guardian.firstName}`;
page.classList.add("pageButton");
buttons.appendChild(page);
page.addEventListener("click", function(){pageGuardian()});
// Edit child button
const edit = document.createElement("li");
edit.innerText = `Edit ${child.firstName}`;
edit.classList.add("edit");
buttons.appendChild(edit);
edit.addEventListener("click", function(){editChild()});
// Move child button
const move = document.createElement("li");
move.innerText = `Move ${child.firstName} To Group`;
move.classList.add("move");
buttons.appendChild(move);
move.addEventListener("click", function(){moveChild()});
// Checkout child button
const checkOut = document.createElement("li");
checkOut.innerText = `Check Out ${child.firstName}`;
checkOut.classList.add("checkOut");
buttons.appendChild(checkOut);
checkOut.addEventListener("click", function(){checkOutChild()});
ul.appendChild(buttons);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T22:40:53.763",
"Id": "466910",
"Score": "0",
"body": "Welcome to Code Review! Please stop editing your post - especially the code. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T22:42:27.077",
"Id": "466911",
"Score": "0",
"body": "Sᴀᴍ Onᴇᴌᴀ: I apologize. I was trying to add the edits based on the answer below. When I read the stack's instuctions about bounties it said \"be sure to edit your question as people leave answers\"... I unchecked the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T22:46:38.037",
"Id": "466914",
"Score": "0",
"body": "Okay I rolled it back to the edit before rotata's answer was posted. You could change the description if you feel there is something you really want to add. \"_I unchecked the answer._\" - why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T22:47:14.383",
"Id": "466915",
"Score": "0",
"body": "I unchecked the answer so that I could continue to get feedback on the changes as the document is so different."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T22:48:03.777",
"Id": "466916",
"Score": "0",
"body": "Okay- you have other options for continued feedback - see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T22:48:53.893",
"Id": "466917",
"Score": "0",
"body": "Also, because I wanted RoToRa to still get points I upvoted. Also I unchecked because I realized that having an answer probably meant I wouldn't get more feedback."
}
] |
[
{
"body": "<p>First some words about the created HTML/DOM:</p>\n\n<p>In HTML it is invalid for an <code>ul</code> element to directly contain another <code>ul</code>. An <code>ul</code> only may contain <code>li</code> elements, so you should wrap the inner <code>ul</code> in it's own <code>li</code>. Unfortunately the DOM API allows you to create invalid HTML and there is no good way to notice it. And it may not become noticeable until the browser has problems rendering it.</p>\n\n<p>Regarding the guardian names: You should have a space character between the <code>span</code> elements otherwise the browser will render it (or in case of screen readers/text-to-speech, may read it) as one one word. EDIT: Creating a space with CSS may not be recognized by a screen reader. An actual space will always be interpreted correctly. Another case were this could be a problem is copy and paste where it also will be copied without a space.</p>\n\n<p>A similar accessibility problem may be the way \"flag\" is being rendered: Even if you use CSS to display something, empty span elements with just a class name but no content may be ignored and not read out by screen readers.</p>\n\n<hr>\n\n<p>On to the JavaScript:</p>\n\n<p>Instead of calling <code>document.getElementById(\"childList\")</code> each time <code>addChild</code> is called it would be better to call it once outside and pass the reference into <code>addChild</code>.</p>\n\n<p>In a function such as <code>addChild</code> which purpose is to display the <code>child</code> object it's unexpected for it to modify that object with <code>delete child.group</code>, especially since that modification isn't relevant to the further logic of the function.</p>\n\n<p>At the event listener assignment it's unnecessary to wrap the listener function in an additional function. So</p>\n\n<blockquote>\n<pre><code>page.addEventListener(\"click\", function(){pageGuardian()});\n</code></pre>\n</blockquote>\n\n<p>Can be written as:</p>\n\n<pre><code>page.addEventListener(\"click\", pageGuardian);\n</code></pre>\n\n<p>BTW how to the listener functions determine which child they work with when called? </p>\n\n<p>Finally, the code for creating the buttons are basically identical for each button so it should be extracted into a separate function.</p>\n\n<hr>\n\n<p>EDIT: One more point I forgot before: You may want to look into using a template engine instead of building the HTML/DOM structure yourself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T14:09:23.133",
"Id": "466843",
"Score": "0",
"body": "HTML > Thank you for the <ul> catch! As for the span, I am using CSS to put a space between them. Will it still have screen reader problems?\nI'll move my image from CSS to the HTML. I guess that makes sense because it is content.\nJS > I use the delete child.group because I don't want to create another <li> element for it--I should have used `continue`. Thank you for that as well.\n`pageGuardian` is wrapped because I will pass the function some parameters. I just haven't coded that yet -- so it's a placeholder.\n**I appreciate your help!** I'll change the getElementById(\"childList\") for sure!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T14:21:37.937",
"Id": "466845",
"Score": "1",
"body": "I really appreciated the suggestion to not delete the property from the object -- I mean, what if I used it later (I'm not planning on it... but that's some horrible code to keep straight in your mind!)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T22:43:35.250",
"Id": "466912",
"Score": "0",
"body": "I edited the code in the question to reflect your changes. Additionally, it caused me to rethink some of my approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T07:56:47.963",
"Id": "466940",
"Score": "0",
"body": "I've added a few more details to the missing space in the guardian's name."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T08:10:55.997",
"Id": "466941",
"Score": "0",
"body": "And I've add one more point at the end."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T08:31:58.877",
"Id": "238025",
"ParentId": "238011",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "238025",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T23:29:19.667",
"Id": "238011",
"Score": "3",
"Tags": [
"javascript",
"beginner"
],
"Title": "Function To Add DOM Nodes"
}
|
238011
|
<p>I wanted to ask this here because what I wanted to originally do felt like a really Pythonic method. I want to be able to use the syntax:</p>
<pre><code>d = {'apple':{'cranberry':{'banana':{'chocolate':[1,2,3,4,5,6]}}},'b':2}
with d['apple']['cranberry']['banana']['chocolate'] as item:
for i in item:
print(i)
item.append('k')
</code></pre>
<p>but found that Python doesn't allow for using lists, dicts, etc. as context managers.</p>
<p>So I implemented my own:</p>
<pre><code>def context_wrap(target):
class ContextWrap:
def __init__(self, tgt):
self._tgt = tgt
def __enter__(self):
return self._tgt
def __exit__(self, type, value, traceback):
pass
return ContextWrap(target)
if __name__ == '__main__':
with context_wrap({'a':1}) as item:
print(item['a'])
with context_wrap([1,2,3,4,5]) as item:
print(item[1])
with context_wrap(3) as item:
print (item)
</code></pre>
<p>In the above code, you can take any random object and wrap it inside an object that acts as a context manager controlling the underlying object. This means that inside any <code>with</code> clause, you can simply use the object with it's alias. I feel like it looks a lot cleaner and clearer than something like:</p>
<pre><code>alias = d['apple']['cranberry']['banana']['chocolate']
for i in alias:
print(i)
alias.append('k')
</code></pre>
<p>I wanted to know if there was a more "Pythonic" way to do it. So the improvement that I'm looking for is in terms of better reliance on the standard Python library and/or in terms of my syntax.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T23:59:51.253",
"Id": "466772",
"Score": "3",
"body": "What's the advantage of this over just saying `item = d['a']`? Usually the purpose of a context manager is to do something in the `__exit__` (close a file, free a resource, etc) but your use case doesn't require anything like that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T00:23:44.893",
"Id": "466774",
"Score": "0",
"body": "Welcome to code review, the question might be better received if the title was something like `Context Manager Wrapper` and there was a paragraph explaining what the code does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T00:25:10.610",
"Id": "466775",
"Score": "1",
"body": "@pacmaninbw Let me amend my post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T00:25:59.453",
"Id": "466776",
"Score": "0",
"body": "@SamStafford This is going to be used for more complicated objects where you wouldn't want to just endlessly list the same parameters over and over.\nSomething like `d = {'a':{'b':{'c':{'d':'e'}}}}` where the object is complex/deeply nested."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T00:30:38.647",
"Id": "466777",
"Score": "0",
"body": "You might want to read the guidelines for good questions at https://codereview.stackexchange.com/help/how-to-ask."
}
] |
[
{
"body": "<p>I think what you are doing is crazy, but yes, you can use Python’s library functions to clean it up.</p>\n\n<pre><code>from contextlib import contextmanager\n\n@contextmanager\ndef context_wrap(target):\n yield target\n</code></pre>\n\n<p>Again, this is busy work.</p>\n\n<pre><code>alias = thing\n</code></pre>\n\n<p>is clearer, shorter and faster than</p>\n\n<pre><code>with context_wrap(thing) as alias:\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T16:55:00.070",
"Id": "466852",
"Score": "0",
"body": "Wow, this is extremely much cleaner than my solution. And I can see a few uses for it! Using a context manager doesn't leave a strong reference around in case something needs to be cleaned up by the garbage collector! I think it's especially useful for classes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T17:11:27.063",
"Id": "466858",
"Score": "0",
"body": "`alias` will still be equal to `thing` after the `with` statement exits. It doesn't remove the variable, so a strong reference will still exist!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T18:06:47.373",
"Id": "466869",
"Score": "0",
"body": "I think I have some more work to do then. But thanks for the help anyway!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T18:41:06.430",
"Id": "466880",
"Score": "0",
"body": "Trying to trick the Python garbage collector into cleaning things up at specific times is not going to be a fun game to play. Write it in Rust if object lifetimes are that important! :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T03:33:35.893",
"Id": "238019",
"ParentId": "238012",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "238019",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T23:30:22.680",
"Id": "238012",
"Score": "1",
"Tags": [
"python",
"python-3.x"
],
"Title": "More Pythonic Context Manager Wrapper"
}
|
238012
|
<p>Intrigued by the events chronicled <a href="https://www.reddit.com/r/ProgrammerHumor/comments/f6csjp/so_both_these_tools_copied_from_the_same_wrong/" rel="nofollow noreferrer">here</a> (also <a href="https://twitter.com/Foone/status/1229641258370355200" rel="nofollow noreferrer">here</a> and <a href="https://stackoverflow.com/questions/502303/how-do-i-programmatically-get-the-guid-of-an-application-in-net2-0/502327#comment106847159_502327">here</a>), I saw the inherent utility in having a program-specific GUID available. The SO answers that were correct seemed a bit tightly-coupled and verbose. So I set out to make my own for use. Looking for a critique on the idea itself as well as maintainability, performance, etc. Improvements welcome.</p>
<pre><code>public static class AssemblyExtensions
{
/// <summary>
/// The <see cref="GuidAttribute"/> for the entry assembly lazily gotten as a <see cref="Guid"/> if it exists,
/// <see cref="Guid.Empty"/> otherwise.
/// </summary>
private static readonly Lazy<Guid> _MyGuid = new Lazy<Guid>(() => Assembly.GetEntryAssembly().GetGuid());
/// <summary>
/// Lazily gets the <see cref="GuidAttribute"/> for the entry assembly as a <see cref="Guid"/> if it exists,
/// <see cref="Guid.Empty"/> otherwise.
/// </summary>
/// <returns>The <see cref="GuidAttribute"/> for the entry assembly as a <see cref="Guid"/> if it exists,
/// <see cref="Guid.Empty"/> otherwise.</returns>
public static Guid GetMyGuid() => _MyGuid.Value;
/// <summary>
/// Gets the <see cref="GuidAttribute"/> for the given assembly as a <see cref="Guid"/> if it exists,
/// <see cref="Guid.Empty"/> otherwise.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <returns>The <see cref="GuidAttribute"/> for the given assembly as a <see cref="Guid"/> if it exists,
/// <see cref="Guid.Empty"/> otherwise.</returns>
public static Guid GetGuid(this Assembly assembly) => Guid.TryParse(
((GuidAttribute)assembly?.GetCustomAttributes(typeof(GuidAttribute), false).SingleOrDefault())?.Value,
out Guid guid) ? guid : Guid.Empty;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T05:36:51.150",
"Id": "466800",
"Score": "1",
"body": "Thanks for sharing the reddit post."
}
] |
[
{
"body": "<p>Well, there isn't much to say here. But I still see some stuff I don't really like. </p>\n\n<p>The implementations of <code>Lazy<Guid> _MyGuid</code> and <code>Guid GetMyGuid()</code> are quite simple and easy to read and understand. What bothers me here is that for the variable, and both methods the documentation is almost the same. But, at least for me, more critical is the documentation of <code>Guid GetMyGuid()</code> which states \"Lazily gets ...\" which is clearly an implementation detail which I wouldn't show. </p>\n\n<p>The method <code>Guid GetGuid()</code> is another thing. IMO its very hard to read and understand by sprawling the <code>Guid.TryParse()</code> over 3 lines. </p>\n\n<p>The change I will suggest is a little bit longer but its more readable, at least for me </p>\n\n<pre><code>public static Guid GetGuid(this Assembly assembly)\n{\n var guidAttribute = (GuidAttribute)assembly?.GetCustomAttributes(typeof(GuidAttribute), false).SingleOrDefault();\n if(Guid.TryParse(guidAttribute?.Value, out Guid guid)) { return guid; }\n return Guid.Empty;\n} \n</code></pre>\n\n<p>which could also be written like so </p>\n\n<pre><code>public static Guid GetGuid(this Assembly assembly)\n{\n var guidAttribute = (GuidAttribute)assembly?.GetCustomAttributes(typeof(GuidAttribute), false).SingleOrDefault();\n Guid.TryParse(guidAttribute?.Value, out Guid guid); // If Guid.TryParse returns false the out Guid is Guid.Empty\n return guid;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T14:18:16.327",
"Id": "466844",
"Score": "0",
"body": "Thank you for the commentary. Understand and agree with all your points."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T05:36:12.447",
"Id": "238021",
"ParentId": "238014",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "238021",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T01:26:37.797",
"Id": "238014",
"Score": "2",
"Tags": [
"c#",
".net",
"extension-methods"
],
"Title": "Programmatically getting the GUID of an application"
}
|
238014
|
<p>The program was to turn an integer into exact change and uses a bunch of if statements. </p>
<p>Are there steps a beginner like me can do to remove some or is it just how it will be? I can't find anything on it. At least I'm not sure as I'm still in the basic course. </p>
<p>The program is turned in and was fine and this would be for my personal use. I know I may learn this in my classes in time, but I find more direct answers to help more.</p>
<pre><code>change = int(input('')) # receive input from the user
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# This code it so provide exact change using the least amount of coins possible #
# COMPUTER SCIENCE 161A #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
if change > 0: # checks if there is change to provide coins
if change >= 100: #checks if the amount is greater or equal to 100
if (change // 100) != 0: # this is to check if there is change at this point
if (change // 100) > 1: # provide the plural if more than 1
print('{} Dollars'.format(change // 100))
change = (change % 100)
else:
print('{} Dollar'.format(change // 100)) # prints the dollar amount without a float
change = (change % 100) # this leaves the remainder after calculating the amount of change
else: # if there is no change do this
change = (change % 100) # if there no change here there will be no output
if change <= 99: #checks if the amount is lower or equal to 99
if (change // 25) != 0: # this is to check if there is change at this point
if (change // 25) > 1:
print('{} Quarters'.format(change // 25))
change = (change % 25)
else:
print('{} Quarter'.format(change // 25))
change = (change % 25)
else:
change = (change % 25)
if change <= 24: #checks if the amount is lower or equal to 24
if (change // 10) != 0: # this is to check if there is change at this point
if (change // 10) > 1:
print('{} Dimes'.format(change // 10))
change = (change % 10)
else:
print('{} Dime'.format(change // 10))
change = (change % 10)
else:
change = (change % 10)
if change <= 9: #checks if the amount is lower or equal to 9
if (change // 5) != 0: # this is to check if there is change at this point
if (change // 5) > 1:
print('{} Nickels'.format(change // 5))
change = (change % 5)
else:
print('{} Nickel'.format(change // 5))
change = (change % 5)
else:
change = (change % 5)
if change <= 4: #checks if the amount is lower or equal to 4
if (change // 1) != 0: # this is to check if there is change at this point
if (change // 1) > 1:
print('{} Pennies'.format(change // 1))
else:
print('{} Penny'.format(change // 1))
else:
print('No change') # tells the user to fuck off if there is nothing to convert
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T07:02:37.490",
"Id": "466804",
"Score": "2",
"body": "Welcome to CodeReview@SE! Seeing you don't follow the [Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/#documentation-strings), if you are fairly new to Python, tag your question [tag:beginner]. (You may want to have a look at reviews for [Python stabs at the Change Making Problem](https://codereview.stackexchange.com/questions/tagged/change-making-problem+python).)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T09:55:54.763",
"Id": "466820",
"Score": "0",
"body": "@greybeard, You have provided excellent advice! Brought me right to what I was looking for. Thank you very much."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T20:47:06.453",
"Id": "466898",
"Score": "1",
"body": "@Traveler Hi! You did a good job posting your first question and yes, your post is a good fit here :) I edited your post to space the text a bit more and also, I changed your title. We want titles that reflect what the code does, not what we want in a review. I hope you will follow those guidelines in your next posts and welcome to the world of programming :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T20:53:13.317",
"Id": "466899",
"Score": "1",
"body": "@IEatBagels I was just looking over the corrections you made and was looking to thank you, since you are right here now, thank you. I will do my best in the future to use the correct formatting, I'm sure the block of text was not easy to read, and the simpler title is much more appealing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T20:55:03.820",
"Id": "466900",
"Score": "0",
"body": "@Traveler You're most welcome!"
}
] |
[
{
"body": "<p>Firstly, I think your overall approach is sensible. You work your way through the coin types, from highest to lowest, pulling out as many coins of that type as possible, and passing the remainder to the next stage. So, logically, you're on the right track.</p>\n\n<p>But as you've probably noticed, there's a lot of duplication in your code. You need to think about what you're doing the same for each coin type, and pull that logic into its own function. Which will yield something like the following:</p>\n\n<pre><code>def calculate_coins_of_denomination(change, denom):\n \"\"\"\n Returns a tuple where the first value is the number of coins of the given denomination,\n and the second is the remainder\n\n Examples:\n\n calculate_coins_of_denomination(105, 100) => (1, 5)\n calculate_coins_of_denomination(100, 25) => (4, 0)\n \"\"\"\n num_coins = change // denom\n return (num_coins, change - (num_coins * denom))\n</code></pre>\n\n<p>Once you've got this function in place, you can then call it repeatedly with each coin type, passing just the remainder to each successive function call:</p>\n\n<pre><code>(num_dollars, change) = calculate_coins_of_denomination(change, 100)\n(num_quarters, change) = calculate_coins_of_denomination(change, 25)\n(num_dimes, change) = calculate_coins_of_denomination(change, 10)\n(num_nickels, change) = calculate_coins_of_denomination(change, 5)\n(num_pennies, change) = calculate_coins_of_denomination(change, 1)\n</code></pre>\n\n<p>Now you've got the values for <code>num_dollars</code> etc, it's just a question of printing your output in the desired format.</p>\n\n<p>As a final note, avoid using profanity or insults in code comments, even for little experimental programs like these. The brief satisfaction that it yields does not justify the potential cost in terms of looking unprofessional or developing bad habits.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T11:41:15.113",
"Id": "466826",
"Score": "7",
"body": "Just a note: putting explicit parentheses around `num_X, change` is not necessary, and I would argue that they don't improve the readability here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T13:49:45.903",
"Id": "466841",
"Score": "7",
"body": "Also perhaps consider using the `divmod` function. Won't be available in every language, but it'll clean up your relatively ugly `return` line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T13:52:38.873",
"Id": "466842",
"Score": "3",
"body": "Keep in mind that these repeated calls to `calculate_coins_of_denomination` could also be rolled into a loop, like `num_coins = {}`, `for (denom, name) in [(100, \"dollars\"), (25, \"quarters\"), ... (1, \"pennies\")]:` `num_coins[name], change = calculate_coins_of_denomination(change, denom)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T14:43:26.810",
"Id": "466846",
"Score": "0",
"body": "@acdr Luckily other languages are not a major concern in that case and Python has [`divmod`](https://docs.python.org/3/library/functions.html#divmod) ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T17:10:56.763",
"Id": "466857",
"Score": "6",
"body": "In addition to avoiding profanity in comments, it is usually better to avoid comments altogether if it is obvious what the code is doing. I don't need a comment to tell me what `print('No change')` or `if change <= 4:` does. I can tell that by reading the code. You only need a comment if it may not be clear why it was done that way. I.e. don't use comments to explain what the code does, just why it's there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T20:29:19.990",
"Id": "466890",
"Score": "0",
"body": "@pete I appreciate the feedback very much, I will look more into using more functions. See how well I can do on my next way around. I have looked into them a few times, but did not see where or when to do it, that example you gave really helps me see it how it works first hand, and hope to nail it soon! I agree with the commenting, it was late at night when I did that, though not an excuse I will keep in mind to leave those bits out."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T11:08:36.507",
"Id": "238032",
"ParentId": "238020",
"Score": "18"
}
},
{
"body": "<p>Python is a somewhat terse language.<br>\nIt has what it calls <a href=\"https://docs.python.org/3/library/operator.html#in-place-operators\" rel=\"noreferrer\">In-place Operators</a>. It is unusual to see them not used: change the likes of<br>\n<code>change = (change % whatever)</code> to <code>change %= whatever</code></p>\n\n<p>There are places where (almost) the same code reoccurs. There is <em>procedural abstraction</em>: once you give a <em>procedure</em> a (telling) name, you can use it in a terse way, time and again.<br>\nIf differences in <em>value</em> are all that makes code ranges just <em>almost</em> the same, introduce a <em>parameter</em>.</p>\n\n<p>There are places where the same code appears once in every path in a nested conditional statement. Trivial fix if at the beginning or end: move before or after that statement.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> nickels = change // 5\n if nickels != 0: # this is to check if there is change at this point\n if nickels > 1:\n print('{} Nickels'.format(nickels))\n else:\n print('{} Nickel'.format(nickels))\n change %= 5\n</code></pre>\n\n<p>(Well, \"the\" <em>pythonic</em> way may be <code>coins, change = divmod(change, denominations[d]</code>.)<br>\n(Having been raised with %-formatting, if that, I don't have preferences re. <code>string.format()</code> vs. the misleadingly named <a href=\"https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals\" rel=\"noreferrer\">formatted string literals</a>.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T20:34:01.353",
"Id": "466894",
"Score": "2",
"body": "That is great advice you provided here! I cannot recall actually being taught to do things that way yet, though I could have easily missed it. I will do my best to remember this for the future."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T11:36:22.993",
"Id": "238033",
"ParentId": "238020",
"Score": "10"
}
},
{
"body": "<p>I noticed that you have a ton of comments in your code. Now don't get me wrong, comments are great, but there is such a thing as too many. Good code will be self-documenting, which means that you should be able to understand it well even without comments. Some of these comments are extremely unnecessary such as</p>\n\n<pre><code> if change <= 9: #checks if the amount is lower or equal to 9\n</code></pre>\n\n<p>Any programmer can tell what this is doing without the comment. You don't need it.</p>\n\n<p>Other than that I'd recommend more modularity. As others have pointed out there's a lot of repetition in your code. You can fix this by using functions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T16:54:48.700",
"Id": "466851",
"Score": "5",
"body": "+1 on this. My code tends to have a *lot* of comments - and none of them look like the OP's. Comments should always say **why** the code is doing what it's doing. As your answer says, **what** it's doing can be seen from the code, so the comments shouldn't mention that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T20:30:56.890",
"Id": "466892",
"Score": "1",
"body": "I understand the commenting is a bit excessive, for now, I'm doing that just to tell myself and nothing more. Just a way for me to put things in my head."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T15:14:51.320",
"Id": "238039",
"ParentId": "238020",
"Score": "15"
}
},
{
"body": "<p>A small trick I can give you is to do your \"exit conditions\" first.</p>\n\n<p>For example, you have</p>\n\n<pre><code>if change > 0 :\n ...\n</code></pre>\n\n<p>The issue is that you then have the majority of your code indented. If you invert the condition and return, you can do this :</p>\n\n<pre><code>if change <= 0:\n print('No change')\n return\nif change >= 100:\n ...\n</code></pre>\n\n<p>This would give you the advantage of having less indentation in your code. <strong>Indentation is really really bad for cognitive complexity</strong>.</p>\n\n<p>Failing fast also lets your code execute faster when it fails. In your case, this won't really apply, but if you were doing expensive calls in your conditions, you would want to fail as early as possible.</p>\n\n<p>Always check what inverting your conditions results in. In some cases, it can make the code a lot easier to read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T20:37:05.540",
"Id": "466895",
"Score": "3",
"body": "@Hugu-Viallon I really like this as it has not crossed my mind before to have an exit from the start and I can clearly understand why it would be great to use. Thank you very much for this!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T16:53:00.693",
"Id": "238045",
"ParentId": "238020",
"Score": "6"
}
},
{
"body": "<p>The key to programs like this (or, to be honest, to any program) is to think carefully about abstractions. When approaching any programming problem, the first step is to choose the level of abstraction at which you want to work. </p>\n\n<p>In this case, the obvious abstraction is the notion of \"coins\" to represent nickels, dimes, quarters, etc. That tells you two things:</p>\n\n<ul>\n<li>Data representation: You'll want some abstract way of representing\n\"coins\" as data.</li>\n<li>Functions/methods: Any functions or routines that you write should use this abstract \"coin\" representation when performing any calculations.</li>\n</ul>\n\n<p>There are many choices for how you actually do this. In his answer, Pete presented a good way to do the second bullet: a generic function that will work for any denomination of coin. Personally, I would do things in a different order and start by thinking about the first: how to represent a coin.</p>\n\n<p>One way, of course, is to use the full blown object-oriented approach in all its glory: create a \"coin\" class and write methods to do all the manipulation (to include printing the output). This is the approach emphasized in most computer programming classes, and there's nothing wrong with it except that it may be a bit overkill for such a simple application.</p>\n\n<p>Another approach is to use simpler data constructs, such as lists or dictionaries, to represent coins. You can then loop over the elements in the list to give you the correct change. An example of that approach using dictionaries is:</p>\n\n<pre><code>coinTypes = {'Dollars':100, 'Quarters':25, 'Dimes':10, 'Nickels':5, 'Pennies':1}\n\nmoney = int(input('')) \n\nfor name,denom in coinTypes.items():\n ncoins, money = divmod(money, denom)\n print('{}: {}'.format(name, ncoins))\n</code></pre>\n\n<p>Minor variations could use lists instead of dictionaries, or use a separate list/dictionary to keep track of the number of coins for future use. Again, there's no \"right\" design for the program, but (in my opinion) there is a right way to think about it, and that is to start by thinking about the abstractions you want to use. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T20:46:19.220",
"Id": "466897",
"Score": "1",
"body": "I like the way this looks and helps me understand how abstraction works in Python. Would a second dictionary be needed if I needed to output singular or plural as in the case here, it was asked to do so in my code? I believe I actually left that part out :/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T21:23:00.163",
"Id": "466904",
"Score": "1",
"body": "Good question; there are different approaches. For singular/plural, you might have to go to a separate structure to store the singular/plural names, or make a more complex dictionary (so something like \"coinTypes = {100: ['dollar', 'dollars'], ...\" or such). But the important thing is to have the definitions stored in the data structure(s), so that you just have to change the values in order to switch systems (pounds and shillings, for example, or if you can't use dimes)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T21:25:32.620",
"Id": "466905",
"Score": "1",
"body": "Another important thing is not to have duplicate information that can become inconsistent. If you make a change, design it so you need to make the change only in one place. So, for example, you don't want to do something like manually write two dictionaries with the same keys. That could cause problems if you made a change to one, but not the other."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T05:16:41.707",
"Id": "466930",
"Score": "1",
"body": "That seems like a very clean approach, I still don't understand fully the capabilities of dictionaries and the likes but can see they are very great at what they can do. I do understand what you mean by using duplicates and hopefully can grasp the entire function tree to use this for the better now!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T13:37:21.597",
"Id": "466975",
"Score": "1",
"body": "I'd also separate the output from the computation. I'd fill in a dictionary in the cycle with the coin amounts and then iterate over it to print the results. Only this second cycle will need the coin names and need to deal with pluralization."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T18:39:57.960",
"Id": "238059",
"ParentId": "238020",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "238032",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T05:00:03.693",
"Id": "238020",
"Score": "13",
"Tags": [
"python",
"beginner",
"python-3.x",
"change-making-problem"
],
"Title": "Transform dollars in exact change"
}
|
238020
|
<p>This was part of a code challenge. I use them to help me learn c++/c# along with tutorials and guides. Basically I was taking a string...</p>
<blockquote>
<p>The quick brown fox jumps over the lazy dog.</p>
</blockquote>
<p>...and reversing the words in the string like this.</p>
<blockquote>
<p>ehT kciuq nworb xof spmuj revo eht yzal .god</p>
</blockquote>
<p>The following code works and compiles. However, I feel like this was a verbose way to achieve the objective.</p>
<blockquote>
<p>split</p>
</blockquote>
<p>This function was a copy paste from another Stack Overflow page. I'm not sure if this is idiomatic in c++, but it feels like an overkill. I just used it because it worked when I tested it on single word strings.</p>
<blockquote>
<p>vector_to_string</p>
</blockquote>
<p>I came up with this function because I had forgotten how to do this in c++. I recall a built in function somewhere in its library.</p>
<blockquote>
<p>reverse_words</p>
</blockquote>
<p>This was the provided function for the challenge. Everything inside of the {} is what I came up with.</p>
<p>Everything in the int main() I came up as well for testing. Test are provided, but I haven't quite learned how to implement this offline yet. Following is my code, with the test after that.</p>
<pre><code>#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<string> split(string s, string delimiter)
{
size_t pos_start = 0, pos_end, delim_len = delimiter.length();
string token;
vector<string> res;
while ((pos_end = s.find(delimiter, pos_start)) != string::npos)
{
token = s.substr(pos_start, pos_end - pos_start);
pos_start = pos_end + delim_len;
res.push_back(token);
}
res.push_back(s.substr(pos_start));
return res;
}
string vector_to_string(vector<string> v)
{
string s;
for (auto &e : v)
{
reverse(e.begin(), e.end());
s += e + " ";
}
return s;
}
string reverse_words(string str)
{
vector<string> v = split(str, " ");
string s = vector_to_string(v);
return s.substr(0, s.length() - 1);
}
int main()
{
cout << reverse_words("The quick brown fox jumps over the lazy dog.") << endl;
cout << reverse_words("apple") << endl;
cout << reverse_words("a b c d") << endl;
cout << reverse_words("") << endl;
cout << reverse_words("ab ba cd") << endl;
}
</code></pre>
<p>I was provided with these tests:</p>
<blockquote>
<pre><code>Describe(Tests)
{
It(Sample_Test_Cases)
{
Assert::That(reverse_words("The quick brown fox jumps over the lazy dog."), Equals("ehT kciuq nworb xof spmuj revo eht yzal .god"));
Assert::That(reverse_words("apple"), Equals("elppa"));
Assert::That(reverse_words("a b c d"), Equals("a b c d"));
Assert::That(reverse_words("double spaced words"), Equals("elbuod decaps sdrow"));
Assert::That(reverse_words(""), Equals(""));
Assert::That(reverse_words("ab ba cd"), Equals("ba ab dc"));
}
};
</code></pre>
</blockquote>
<p>Anyhow, any advice on this is much appreciated and thank you for your help. Again, I feel like this is a verbose way to solve this problem and I suspect it can be greatly optimized as well.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T12:24:30.187",
"Id": "466833",
"Score": "2",
"body": "Which test framework is that? Making it clear could help those who want to reproduce the results. BTW, kudos for including the tests - that puts you a cut above a vast majority of Code Review questions!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T21:03:26.817",
"Id": "466901",
"Score": "0",
"body": "@TobySpeight I don't know, which is part of the problem for myself in learning how to do that offline. It was what the website gives you. I assume its partially there because the rest of what is needed is hidden."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-02T09:46:14.893",
"Id": "467211",
"Score": "0",
"body": "Ah, I didn't realise that you didn't write the tests yourself. I've made an edit that should clarify that."
}
] |
[
{
"body": "<h1>The <code>split</code> function</h1>\n\n<blockquote>\n<pre><code>vector<string> split(string s, string delimiter)\n{\n size_t pos_start = 0, pos_end, delim_len = delimiter.length();\n string token;\n vector<string> res;\n\n while ((pos_end = s.find(delimiter, pos_start)) != string::npos)\n {\n token = s.substr(pos_start, pos_end - pos_start);\n pos_start = pos_end + delim_len;\n res.push_back(token);\n }\n\n res.push_back(s.substr(pos_start));\n return res;\n}\n</code></pre>\n</blockquote>\n\n<p><code>delim_len</code> should be declared as <code>const</code>, because it doesn't change. Or simply drop it; it is only used in one place.</p>\n\n<p>This function forces all substrings to be first copied into the <code>token</code> variable and then copied into the vector — that's two copies. It can be reduced to one copy by using <a href=\"https://en.cppreference.com/w/cpp/utility/move\" rel=\"noreferrer\"><code>std::move</code></a> (defined in <a href=\"https://en.cppreference.com/w/cpp/header/utility\" rel=\"noreferrer\"><code><utility></code></a>) on the argument to <code>push_back</code>, or by simply dropping the <code>token</code> variable.</p>\n\n<p>The function should have <a href=\"https://en.cppreference.com/w/cpp/string/basic_string_view\" rel=\"noreferrer\"><code>std::string_view</code></a> (defined in <a href=\"https://en.cppreference.com/w/cpp/header/string_view\" rel=\"noreferrer\"><code><string_view></code></a>) parameters instead of <code>std::string</code> parameters for efficiency.</p>\n\n<p>Putting everything together:</p>\n\n<pre><code>auto split(std::string_view s, std::string_view delimiter)\n{\n std::vector<std::string> result;\n\n std::size_t pos_start = 0, pos_end;\n while ((pos_end = s.find(delimiter, pos_start)) != s.npos) {\n res.push_back(s.substr(pos_start, pos_end - pos_start));\n pos_start = pos_end + delimiter.size();\n }\n\n res.push_back(s.substr(pos_start));\n return res;\n}\n</code></pre>\n\n<h1><code>vector_to_string</code></h1>\n\n<blockquote>\n<pre><code>string vector_to_string(vector<string> v)\n{\n string s;\n\n for (auto &e : v)\n {\n reverse(e.begin(), e.end());\n s += e + \" \";\n }\n\n return s;\n}\n</code></pre>\n</blockquote>\n\n<p><code>vector_to_string</code> is a non-descriptive name — <code>reverse_join</code> may be better. The delimiter should be an argument rather than hard coded.</p>\n\n<p>This function should strip the last space instead of letting its caller do so. Note that this function performs two operations logically (reverse and join).</p>\n\n<p>Copying the whole vector takes a lot of space; consider copying one string at a time.</p>\n\n<p>And yes, there is a simpler way to do this using <a href=\"https://en.cppreference.com/w/cpp/algorithm/accumulate\" rel=\"noreferrer\"><code>std::accumulate</code></a> (defined in <a href=\"https://en.cppreference.com/w/cpp/header/numeric\" rel=\"noreferrer\"><code><numeric></code></a>):</p>\n\n<pre><code>auto result = std::accumulate(v.begin(), v.end(), std::string{},\n [](std::string lhs, std::string_view rhs) {\n lhs += rhs;\n lhs += ' ';\n return lhs;\n });\nresult.pop_back();\n</code></pre>\n\n<h1><code>reverse_words</code></h1>\n\n<blockquote>\n<pre><code>string reverse_words(string str)\n{\n vector<string> v = split(str, \" \");\n string s = vector_to_string(v);\n return s.substr(0, s.length() - 1);\n}\n</code></pre>\n</blockquote>\n\n<p>Again, <code>std::string_view</code> parameter. Even if the stripping happens here, it should be done using <code>pop_back</code> to avoid copying the string and enable <a href=\"https://stackoverflow.com/q/12953127/9716597\">named return value optimization</a>.</p>\n\n<h1>Simplification</h1>\n\n<p>Here's a simplification, using streams to do the split job:</p>\n\n<pre><code>#include <cassert>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <string_view>\n\nstd::streamsize read_spaces(std::istream& is)\n{\n std::streamsize count = 0;\n while (is.peek() == ' ') {\n is.get();\n ++count;\n }\n return count;\n}\n\n// const std::string& because std::istringstream is constructed from a std::string\nstd::string reverse_words(const std::string& string)\n{\n std::istringstream iss{string};\n std::ostringstream oss{};\n\n for (std::string word; iss >> word;) {\n std::reverse(word.begin(), word.end());\n oss << word << std::string(read_spaces(iss), ' ');\n }\n return oss.str();\n}\n\nint main()\n{\n assert(reverse_words(\"The quick brown fox jumps over the lazy dog.\") == \"ehT kciuq nworb xof spmuj revo eht yzal .god\");\n assert(reverse_words(\"apple\") == \"elppa\");\n assert(reverse_words(\"a b c d\") == \"a b c d\");\n assert(reverse_words(\"double spaced words\") == \"elbuod decaps sdrow\");\n assert(reverse_words(\"\") == \"\");\n assert(reverse_words(\"ab ba cd\") == \"ba ab dc\");\n}\n</code></pre>\n\n<p>(<a href=\"https://wandbox.org/permlink/a8plELDQUvH8IsTI\" rel=\"noreferrer\">live demo</a>)</p>\n\n<h1>Miscellaneous</h1>\n\n<blockquote>\n<pre><code>#include <string>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n</code></pre>\n</blockquote>\n\n<p>Sort the <code>#include</code>s in alphabetical order to each navigation.</p>\n\n<blockquote>\n<pre><code>using namespace std;\n</code></pre>\n</blockquote>\n\n<p>Avoid global <code>using namespace std;</code>. It brings in many common identifiers from the <code>std</code> namespace and causes name clashes. Although it doesn't matter too much for a small program, get into the habit of explicitly qualifying names with <code>std::</code> instead. An alternative is using declarations (<code>using std::string, std::vector;</code>), which only pulls in the specified names. See <a href=\"https://stackoverflow.com/q/1452721/9716597\">Why is <code>using namespace std;</code> considered bad practice?</a> for more information.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T13:28:56.477",
"Id": "466840",
"Score": "0",
"body": "Your `reverse_words()` could accept string by value, and then `std::move()` it to the string stream's constructor. That avoids copying a temporary (e.g. in every test case here, where a `std::string` is constructed from a string literal)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T02:18:04.870",
"Id": "466926",
"Score": "1",
"body": "@TobySpeight The `std::string&&` constructor of `std::istringstream` is added in C++20 according to [cppreference](https://en.cppreference.com/w/cpp/io/basic_istringstream/basic_istringstream); the C++17 version only accepted a `const std::string&` and copied it, so `std::move` won't help. I don't think it's possible to construct directly into the stream ... Anyway, your approach is much better than mine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T09:59:16.847",
"Id": "466949",
"Score": "0",
"body": "\"`delim_len` should be declared as const, because it doesn't change. Or simply drop it; it is only used in one place.\" <-- While, yes, it is used in 1 place, it is used in every iteration of the `while` loop. Wouldn't it (slightly) hurt performance to just drop it? In Python, it doesn't matter, but on PHP and JavaScript it matters a lot. I think it does in C/C++ too, but I'm not sure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T10:09:56.100",
"Id": "466950",
"Score": "0",
"body": "@IsmaelMiguel [libstdc++](https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/bits/basic_string.h#L167) stores the length of the string. [libc++](https://github.com/llvm-mirror/libcxx/blob/master/include/string#L946-L947) does test `__is_long()` in `size()`, so you're probably right, but I don't think the overhead will be noticeable (especially given that the implementation itself uses `size()` all over the place). C is another story - different languages handle strings differently."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T10:19:40.090",
"Id": "466952",
"Score": "0",
"body": "Well, if C++ stores the length, then probably it will be a micro-optimization to keep the length precalculated somewhere."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T08:53:12.303",
"Id": "238026",
"ParentId": "238022",
"Score": "10"
}
},
{
"body": "<h1>Test coverage</h1>\n\n<p>We don't have any test inputs that begin or end with a space, or that contain spaces but no letters. Also, in each test, all spaces are the same length; there are no tests with single and double spaces in the same input.</p>\n\n<p>These should be tested, as they are all candidates for making an error in the algorithm.</p>\n\n<h1>A different approach</h1>\n\n<p>The code makes several copies of strings, and creates and copies a temporary vector. With judicious use of standard algorithms, we can work completely <em>in-place</em>, without any extra allocations.</p>\n\n<p>We can use <code>std::find_if()</code> and <code>std::find_if_not()</code> with a suitable predicate to find start and end of each word as iterators:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> --+---+---+---+---+---+---+--\n . | | w | o | r | d | | .\n --+---+---+---+---+---+---+--\n ▲ ▲ \n start end\n</code></pre>\n\n<p>Then we can simply pass those iterators to <code>std::reverse()</code>, which will reverse that substring.</p>\n\n<p>In C++, that looks like this:</p>\n\n<pre><code>#include <algorithm>\n#include <cctype>\n#include <string>\n\nstd::string reverse_words(std::string s)\n{\n auto is_space = [](unsigned char c) { return std::isspace(c); };\n\n auto word_start = s.begin();\n while ((word_start = std::find_if_not(word_start, s.end(), is_space)) != s.end()) {\n auto word_end = std::find_if(word_start, s.end(), is_space);\n std::reverse(word_start, word_end);\n word_start = word_end;\n }\n\n return s;\n}\n</code></pre>\n\n<p>This way, there's no copying if the caller doesn't want to re-use the passed string (e.g. if it's passed using <code>std::move()</code>), and only the single copy into the argument otherwise.</p>\n\n<p>I provided the <code>is_space()</code> adapter for two reasons:</p>\n\n<ol>\n<li>If we want to change it to recognise only spaces, or perhaps also count punctuation as word separators, then we need to change only one place in the code, rather than two.</li>\n<li><code>std::isspace()</code> accepts a non-negative integer as its argument, so we need to convert <code>char</code> to <code>unsigned char</code> before it's widened to <code>int</code>.</li>\n</ol>\n\n<hr>\n\n<p>For completeness, here's a slightly different <code>main()</code> that I used when testing:</p>\n\n<pre><code>#include <cassert>\n#include <iostream>\nint main(int argc, char **argv)\n{\n if (argc <= 1) {\n // no arguments: self test\n assert(reverse_words(\"The quick brown fox jumps over the lazy dog.\") == \"ehT kciuq nworb xof spmuj revo eht yzal .god\");\n assert(reverse_words(\"apple\") == \"elppa\");\n assert(reverse_words(\"a b c d\") == \"a b c d\");\n assert(reverse_words(\"double spaced words\") == \"elbuod decaps sdrow\");\n assert(reverse_words(\"\") == \"\");\n assert(reverse_words(\"ab ba cd\") == \"ba ab dc\");\n assert(reverse_words(\" ab ba \") == \" ba ab \");\n } else {\n // transform and print each argument\n for (int i = 1; i < argc; ++i) {\n std::cout << '\\'' << reverse_words(argv[i]) << \"'\\n\";\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T13:18:19.887",
"Id": "238035",
"ParentId": "238022",
"Score": "9"
}
},
{
"body": "<p>The other two answers have done a good job.<br>\nI will present a slightly alternative solution.</p>\n\n<p>One of the slowest things about strings is duplicating them. So where possible it is nice to re-use the same space (i.e. do it inplace). You can then use wrapper functions to do copying when you need to:</p>\n\n<pre><code>// Lets start with a generic way of reversing words in any container.\ntemplate<typename I>\nvoid reverse_words(I begin, I end)\n{\n // Credit to Toby Speight\n // Stolen basically verbatim.\n auto is_space = [](unsigned char c) { return std::isspace(c); };\n\n auto word_start = begin;\n while ((word_start = std::find_if_not(word_start, end, is_space)) != end) {\n auto word_end = std::find_if(word_start, end, is_space);\n std::reverse(word_start, word_end);\n word_start = word_end;\n }\n}\n\n// Reverse in place for any container.\ntemplate<typename C>\nvoid reverse_words_in_container(C& container)\n{\n reverse_words(std::begin(container), std::end(container));\n}\n\n// Reverse a container into another container (usually a string).\ntemplate<typename C, typename S = std::string>\nS reverse_words_in_container(C const& container)\n{\n S result(std::begin(container), std::end(container))\n reverse_words_in_container(result);\n return result;\n}\n</code></pre>\n\n<p>Then just for fun. As it is an interesting code interview question. Reverse the words in a string:</p>\n\n<pre><code>std::string reverseWordsInAString(std::string const& value)\n{\n // Notice we reverse the whole string here.\n result(std::rbegin(container), std::rend(container))\n\n // So now the whole string is reversed.\n // We now go through and reverse each word so it is\n // the correct way around.\n reverse_words_in_container(result);\n\n return result;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T18:26:07.167",
"Id": "238055",
"ParentId": "238022",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "238026",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T05:40:16.793",
"Id": "238022",
"Score": "8",
"Tags": [
"c++",
"strings",
"c++17",
"vectors"
],
"Title": "Reverse each word in the string. All spaces in the string should be retained"
}
|
238022
|
<p>So I needed to represent by objects in terms in ini format and change their values from the ini as well, so I thought why don't implement a property system for this. I want it to be bit fast so I would really like if anyone can remove the std::function if possible but its not necessary. The target application is GUI so small performance should not be a big issue, but still, I think this can be done in a faster way but I can't think of any. no one likes lag. Also, the properties are around 100 or more</p>
<pre><code>#include <functional>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <variant>
#include <QDebug>
template <typename C> class PropertySet {
public:
using PropertyValue = std::variant<bool, int, float, std::string>;
void set(const std::string &prop, PropertyValue v) {
auto p = m_properties.find(prop);
if (p == m_properties.end()) {
throw std::runtime_error("Invalid property key");
}
// p.value().setter(v);
p->second.setter(v);
}
void set(const std::string &prop, const std::string &v) {
auto p = m_properties.find(prop);
if (p == m_properties.end()) {
throw std::runtime_error("Invalid property key");
}
// p.value().setter(p.value().fromStr(v));
p->second.setter(p->second.fromStr(v));
}
std::unordered_map<std::string, std::string> getAllValues() {
std::unordered_map<std::string, std::string> r;
qDebug() << m_properties.size();
for (const auto &p : m_properties) {
// r[p.key()] = p.value().toStr();
r[p.first] = p.second.toStr();
}
return r;
}
private:
struct Payload {
std::function<std::string()> toStr;
std::function<PropertyValue(const std::string &)> fromStr;
std::function<PropertyValue()> getter;
std::function<void(PropertyValue)> setter;
};
std::unordered_map<std::string, Payload> m_properties;
protected:
template <typename T> static auto fromStr(const std::string &s) {
if constexpr (std::is_same<T, int>::value) {
return std::stoi(s);
} else if constexpr (std::is_same<T, bool>::value) {
return s == "true" || s == "1";
}
static_assert("Error");
}
template <typename T, typename Getter, typename Setter>
void add(const std::string &name, Getter getter, Setter setter) {
auto cptr = static_cast<C *>(this);
Payload p;
p.toStr = [getter, cptr]() { return std::to_string(std::invoke(getter, cptr)); };
p.fromStr = [](const std::string &s) { return PropertySet::fromStr<T>(s); };
p.getter = [getter, cptr]() { return PropertyValue(std::invoke(getter, cptr)); };
p.setter = [setter, cptr](PropertyValue v) { std::invoke(setter, cptr, std::get<int>(v)); };
m_properties[name] = p;
}
};
</code></pre>
<p>Also, I'm using Qt, so I was thinking of replacing <code>std::string</code> with <code>QString</code> or <code>QByteArray</code> and <code>std::unordered_map</code> with <code>QHash</code>.</p>
|
[] |
[
{
"body": "<p>There are several ways to approach this.</p>\n\n<p>The classic object oriented way is to make <code>Payload</code> be a simple interface class</p>\n\n<pre><code>class IPayload {\n virtual ~IPayload() = default;\n virtual std::string toStr() = 0;\n virtual PropertyValue fromStr(const std::string &) = 0;\n virtual PropertyValue get() = 0;\n virtual void set(PropertyValue) = 0;\n}; \n</code></pre>\n\n<p>And just create for each property its own instance of an implementation of the interface - depending on what kind of property one uses. This can be helpful when you need variety updating mechanisms to work simultaneously. Say, one Payload that stores the field only in memory, one that stores into both in memory and in a file, and one that forwards it to GUI - or a combination of these. This can be also helpful when you require specialized treatment for some properties - like time input property - that upon receiving <code>std::string</code> input it processes it according to some time conversion, i.e., read double and then converts it to seconds depending on the time unit specification, e.g., \"5min\" converts to 300 (seconds). The only issue is that you ought to instantiate a treatment for each property - which can be a hassle and make the class unsuitable for some trivial basic usages.</p>\n\n<p>I don't see any circumstances when the <code>std::function</code> approach would better - unless one has to runtime change setters or something - which is kinda odd honestly.</p>\n\n<p>Also you can try going in the opposite direction and detach the storage class from the \"customized actions\". Say, make a simple multipurpose ini file parser wrapping <code>std::unordered_map<std::string,std::string></code> - or use an existing one like <code>boost::ptree</code> that can read and write xml and json in addition. While in the GUI simply call the right functions when user sets the fields. Whether it is viable / not viable / preferred option depends a lot on your development platform for the GUI as well as other nuances.</p>\n\n<p>You can in fact combine the two methods. Use the <code>boost::ptree</code> for storing / parsing and for internal usage whilst <code>class PropertySet</code> make responsible for the GUI handling and just instantiate one from each other upon loading / saving / updating.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-14T09:32:47.193",
"Id": "468460",
"Score": "0",
"body": "I'm finding std::function release build faster, but debug bit slower, maybe debug std::function does some unnecessary checking"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-14T09:55:35.227",
"Id": "468467",
"Score": "1",
"body": "@bluedragon `std::function` performs a virtual call itself. Only that each of these std::functions has its own vtable - so it is very surpring that `std::function` performs faster. Not only that, but it makes a call that calls the actual function. Consider asking for another review and ask to compare these two implementations. I can't tell much beyond as I don't see the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-14T11:04:40.320",
"Id": "468472",
"Score": "0",
"body": "my guess is std::function does small function optimization and doesn't do dynamic allocation while my every payload was dynamically allocated here is my implementaion https://pastebin.com/vEjvPF3B"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-14T11:16:48.397",
"Id": "468476",
"Score": "0",
"body": "I changed my implementation according to my need and was running tests million times to see the difference"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-14T13:04:32.567",
"Id": "468477",
"Score": "0",
"body": "i tested with \"real\" code, they're both almost equal"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-17T01:58:31.073",
"Id": "468777",
"Score": "1",
"body": "@bluedragon I am confused about the implementation you wrote. Why `std::shared_ptr<IPayLoad>` inside a two layered unordered map? If you shared all instances inside the map then I could understand but no - you create a single instance for each of the shared pointer. ... Second - probably more important part. Each virtual function get/set calls some getter/setter - this is a double function call - not ideal. Unless your getter/setter is an optimazable lambda you are unlikely to see any performance improvement from this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-17T02:06:19.683",
"Id": "468778",
"Score": "1",
"body": "@bluedragon I have some doubts about the double `unordered_map`. I am not 100% sure but I believe that it would've worker better if it was a single `undordered_map` and you accessed value at `(group_name,name)` via a single string `group_name/name`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-17T05:57:24.867",
"Id": "468790",
"Score": "0",
"body": "you're right my bad, std::shared_ptr is actually useless there, I had something in mind when wrote it but ended up taking a different route, will try with single unordered_map"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T19:10:42.993",
"Id": "238129",
"ParentId": "238023",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T07:44:18.813",
"Id": "238023",
"Score": "1",
"Tags": [
"c++",
"template",
"c++17",
"qt",
"properties"
],
"Title": "Minimal Property system in c++17"
}
|
238023
|
<pre><code> id: "1"
email: "TEST@TREST.COM"
selection1: "2"
race1: "1"
selection2: "4"
race2: "1"
selection3: "3"
race3: "0"
selection4: "2"
race4: "0"
selection5: "1"
race5: "0"
selection6: "1"
race6: "0"
selection7: "1"
race7: "0"
</code></pre>
<p>This is 1 on the objects in the Json array. so if race1=1 the class .race1 innerhtml = the email.</p>
<p>if Json.race2 = 1 .class race2 = the email and so on. if the race(number) = 0 dont write it</p>
<pre><code> const app = (() => {
let race1 = document.querySelector('.race1');
let race2 = document.querySelector('.race2');
let race3 = document.querySelector('.race3');
let race4 = document.querySelector('.race4');
let race5 = document.querySelector('.race5');
let race6 = document.querySelector('.race6');
let xt=[]
const returnAll = () => {
fetch('/php/index.php')
.then((response) => {
return response.json();
})
.then((myJson) => {
for (var i = 0; i < myJson.length; i++) {
if (myJson[i].race1 == 1) {race1.innerHTML += `<div>${myJson[i].email} </div>`}
if (myJson[i].race2 == 1) {race2.innerHTML += `<div>${myJson[i].email} </div>`}
if (myJson[i].race3 == 1) {race3.innerHTML += `<div>${myJson[i].email} </div>`}
if (myJson[i].race4 == 1) {race4.innerHTML += `<div>${myJson[i].email} </div>`}
if (myJson[i].race5 == 1) {race5.innerHTML += `<div>${myJson[i].email} </div>`}
if (myJson[i].race6 == 1) {race6.innerHTML += `<div>${myJson[i].email} </div>`}
}
});
}
return {
init: () => {
returnAll();
}
}
})();
app.init();
</code></pre>
<p>All the information above is correct and works occordingly. I just need a better way to code this rather than multiple if statements, Switch would pretty much the same! Any suggestions? I find multple If statements are easy to read, however I've been told this is bad coding.
I've tried Object.key which works fine for the html part, the issue is comparing myJson.race1 =1, myJson.race2 = 1.
i've tried myJson[i].race[i] but that then returns [object,object].race0 (up to race5).</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T09:19:38.000",
"Id": "466812",
"Score": "4",
"body": "Welcome to Code Review! We need to know *what the code is intended to achieve*. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436), rather than your concerns about the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T09:23:49.520",
"Id": "466814",
"Score": "0",
"body": "You'll need to show us what the JSON looks like you are working with."
}
] |
[
{
"body": "<p>We can start by building an object containing our race elements rather than having 6 different objects</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const racePrefix = 'race';\nconst raceElements = {};\nconst numRaceElements = 6;\n\nfor (let i = 1; i <= numRaceElements; i++) {\n numRaceElements[racePrefix + i] = document.querySelector('.' + racePrefix + i);\n}\n</code></pre>\n\n<p>then when we loop over the JSON we can check each key in turn:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>for (const jsonRow of myJson) {\n for (const fieldName in jsonRow) {\n if (raceElements[fieldName] instanceof HTMLElement && jsonRow[fieldName] == 1) {\n raceElements[fieldName].innerHTML += `<div>${jsonRow.email} </div>`;\n }\n }\n}\n</code></pre>\n\n<p>Now if in future you ever need to change anything like adding new races, or changing the class name it's easy to do in a single place without breaking anything.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T09:51:34.510",
"Id": "238030",
"ParentId": "238027",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T09:10:28.647",
"Id": "238027",
"Score": "-2",
"Tags": [
"javascript"
],
"Title": "Updating multiple HTML elements based on a JSON response from an API"
}
|
238027
|
<p>I want to achieve different animation for many elements on scroll, so instead of using window.scroll i'm using intersection observer api, but i want to know if my approach is effective and won't cause performance drop, basically what i did is make a single function to hold the entire animation of the website and check if the target has specific class then do something like so :</p>
<pre><code>const one = document.querySelector('.one')
const two = document.querySelector('.two')
const three = document.querySelector('.three')
function animation (entires) {
entires.forEach(entry => {
if(entry.isIntersecting) {
if(entry.target.classList.contains('text')) {
entry.target.style.transform = 'translateY(0)'
}
if(entry.target.classList.contains('one')) {
entry.target.style.transform = 'translateX(100px)'
}
if(entry.target.classList.contains('two')) {
entry.target.style.transform = 'translateY(0)'
}
if(entry.target.classList.contains('three')) {
entry.target.style.transform = 'skew(10deg)'
}
}
})
}
const observer = new IntersectionObserver(animation)
</code></pre>
<p>i'm not experienced enough but i feel like it's spaghetti code and not efficient and how can i observe multiple elements ? do i have to repeat observer.observe for each element i want to observe ?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T15:35:19.043",
"Id": "238040",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "intersection observer multiple animation"
}
|
238040
|
<p>My code as a whole works for me without issues, but what I want to improve is a small part right out of the middle of it. I hope it's ok to post a simplified snippet here that just shows the structure (it's not something you can copy paste and it works), but I'll try to explain what it is about. If this is against the rules, let me know. </p>
<hr>
<p>I have a workbook that functions as a database (<code>wbDB</code>). I look for the number of an object (<code>objectNumber</code>) and, if found, add it to a sheet (<code>wsTest</code>) in another workbook via <code>Sub AddObject</code>. </p>
<pre><code>Option Explicit
Public Const fRowType As Long = 4
Public Const fRowClosing As Long = fRowType + 1
Public Const fRowLoan As Long = fRowType + 4
'[there are about 30 of those fRow variables; they are needed in another _
module, that's why they are public]
Dim wbDB As Workbook
Dim wsDB As Worksheet, wsTest As Worksheet
Dim lColTest As Long
Sub AddObject(ByVal objectNumber As String, ByVal rngObjects As Range)
Const colType As String = "A"
Const colClosing As String = "BN"
Const colLoan As String = "CD"
'[same as fRows, I have over 30 of these "col"-variables]
Dim rowObject As Long
Dim foundCell As Range
Set wbDB = Application.Workbooks("Database.xlsx")
Set wsDB = wbDB.Sheets(2)
Set wsTest = ActiveSheet
'---Find object in rngObjects and set rowObject to respective row
Set foundCell = rngObjects.Find(What:=objectNumber, LookAt:=xlWhole)
If foundCell Is Nothing Then
MsgBox "Object " & objectNumber & "wasn't found and will be skipped."
Exit Sub
Else
rowObject = foundCell.Row
End If
lColTest = wsTest.Cells(12, wsTest.Columns.Count).End(xlToLeft).Column
'Type
Call ImportData(rowObject, colType, fRowType)
'Closing
Call ImportData(rowObject, colClosing, fRowClosing)
'Loan
Call ImportData(rowObject, colLoan, fRowLoan)
'[again, there are 30+ of these calls]
End Sub
Sub ImportData(ByVal rowDB As Long, ByVal colDB As String, ByVal fRowSection As Long)
wsTest.Cells(fRowSection, lColTest + 1).Value = wsDB.Cells(rowDB, colDB).Value
End Sub
</code></pre>
<p>If you look at <code>Sub ImportData</code>: It requires <code>lColTest</code>, a module-wide variable, which I initialize in <code>Sub AddObject</code>. On the other hand, <code>rowObject</code> is needed just as often, but I put it as one of the parameters of <code>ImportData</code>. What is better practice? From what I've read is that the wider the scope of a variable, the less desirable it is. However, if it is one of the parameters, I currently copy paste it about 30 times with every <code>Call</code> and every additional parameter makes it a little less readable too. </p>
<p>My idea as the "cleanest" solution would be: put it in as parameter and instead of typing out every <code>Call</code>, I loop through it. Would you agree with that? If the answer is yes, I'd need an array or something similar. </p>
<ol>
<li><p>What's the best option here since I need always need a pair of values (column and first row)? </p></li>
<li><p>Is there an efficient or readable way to fill the array with all these variables? </p></li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T23:04:45.627",
"Id": "466918",
"Score": "1",
"body": "Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 2 → 1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T23:44:59.167",
"Id": "466923",
"Score": "1",
"body": "FWIW a simplified snippet isn't against the rules per se, but makes you needlessly walk a thin blurry line between actual code and pseudocode, the latter being off-topic. Best include the 30+ constants instead of just saying \"there are 30 more like this\" - code that's not in the post isn't reviewable, and you generally get better feedback when you simply include your code exactly as you have it. Don't worry about making a long post, we're used to that on this site (and the post length limit is *twice* that of [so] for a reason!)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T08:47:54.343",
"Id": "466944",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ Thank you, I'll keep that in mind in the future."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T08:52:38.623",
"Id": "466945",
"Score": "0",
"body": "@MathieuGuindon Thank you for the tips. In this case, if I were to include everything and not at least simplify it, the code would be fairly long and, more importantly, without both the workbooks/data structure you can't get it to run. So what is the best thing to do in this case? Upload the file somewhere? Because that was my issue - I thought if you can't run it anyway, removing the clutter might make it more understandable."
}
] |
[
{
"body": "<pre><code>Public Const fRowType As Long = 4\nPublic Const fRowClosing As Long = fRowType + 1\nPublic Const fRowLoan As Long = fRowType + 4\n'[there are about 30 of those fRow variables; they are needed in another _\n module, that's why they are public]\n</code></pre>\n\n<p>First of all, they're not \"variables\" they're \"constants\".</p>\n\n<p>Second, that's screaming for an array or <code>scripting.dictionary</code> to hold them instead of a hoard of <code>Const</code>. They could even be pulled into a class that can easily be initialized provided with <code>Get</code>ter properties (if the values are as fixed as <code>Const</code> would indicate) then the class can be passed around wherever it's needed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T16:45:37.867",
"Id": "466850",
"Score": "0",
"body": "Fixed the constant/variable mix up. I have to look into classes, I don't have experience with them. As for an array: I get that it makes sense to store them in there, but to make sure I'm not missing something very basic: It wouldn't save lines of code, I'd still have to initiliaze them the same way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T17:55:35.537",
"Id": "466865",
"Score": "2",
"body": "@Alex \"Saving lines of code\" is a pointless exercise, though, actually it will. You'll have one `Dim rowClosing(30) as Long` statement, _et voila_ 30 variables declared. Yes, you'll have to populate them, but that can now be done in a loop instead of 1 by 1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T17:56:26.537",
"Id": "466866",
"Score": "1",
"body": "[here](https://rubberduckvba.wordpress.com/2020/02/27/vba-classes-gateway-to-solid/) is a great, basic intro to classes and OOP in VBA."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T09:02:35.360",
"Id": "466948",
"Score": "0",
"body": "I'm gonna read up on that, I have come in touch with OOP a few times, but always kind of shied away from it. To make sure I get what you mean by \"you'll have to populate them, but that can now be done in a loop \": obviously an array will allow me to do the `Call ImportData` in one loop, but initializing the variables would still need to be one by one (`Public Const fRowType As Long = 4` etc and populalting the array would then be `arrayRows = (fRowType, fRowClosing...)`. I still see the advantage, but I wanna make sure I understand you correctly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T12:35:11.643",
"Id": "466969",
"Score": "1",
"body": "@Alex perhaps if you provide more of your code (in particular the initialization code) I could rewrite it into a loop for you. At this point, all I know is one fixed value and a couple of minor variations on it. I'd need to see how the different values vary in order to know how to build the loop."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T15:57:50.857",
"Id": "238042",
"ParentId": "238041",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T15:43:18.630",
"Id": "238041",
"Score": "1",
"Tags": [
"vba"
],
"Title": "VBA: Calling one sub repeatedly and scope of variables"
}
|
238041
|
<p>I would like to show the tree-like structure contained in a multi-dimensional tuple by using the set of graphical glyphs that exist in Unicode fonts (e.g. \u2500, \u2502, \u2514 and others). Here is an example of the kind of output, I'm talking about:</p>
<pre><code>>>> showtree('(01, (02, 03, 04), 05, ((06, 07), 08), (09, (10, 11), (12, 13), 14), 15)')
┬─01
├─┬─02
│ ├─03
│ └─04
├─05
├─┬─┬─06
│ │ └─07
│ └─08
├─┬─09
│ ├─┬─10
│ │ └─11
│ ├─┬─12
│ │ └─13
│ └─14
└─15
</code></pre>
<p>Ideally, empty items, multi-words items, extra spaces around commas or parenthesis, as well as unbalanced parenthesis should be managed correctly, as in the following example:</p>
<pre><code>>>> showtree('( A, B multi-word item , (C,D), ( E , , F ), G )'))
┬─A
├─B multi-word item
├─┬─C
│ └─D
├─┬─E
│ ├─
│ └─F
└─G
</code></pre>
<p>I came up with a solution that works quite well (the examples above have been generated with it) but the implemented algorithm is not very elegant, and the code not very pythonic :</p>
<pre><code>def showtree(string):
"""display multidimensional tuple as a tree"""
glyphs = ['\u252C\u2500','\u251C\u2500','\u2514\u2500','\u2502 ']
tree, glyph, item = [], [], []
for char in string:
if char in ',)' and item: # add glyph prefix and current item to tree
tree.append(glyph + [''.join(item).strip()]); item = []
if char == ',': # update glyph prefix for new item in sublist
glyph = [glyphs[3]] * (len(glyph)-1) + [glyphs[1]]
elif char == ')': # update glyph prefix for last item in sublist
tree[-1][-2] = glyphs[2]; glyph = glyph[:-1]
elif char == '(': # update glyph prefix for first item in sublist
glyph.append(glyphs[0])
else: # other chars are simply added to current item
item.append(char)
return '\n'.join(''.join(node) for node in tree)
</code></pre>
<p>So I would like to get some ideas for an improved implementation, maybe using regular expressions or other advanced parsing techniques. Thank you very much for any hint...</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T16:56:26.713",
"Id": "466854",
"Score": "0",
"body": "when i hear \"tree\" i think recursion... (don't know yet if it's useful in this case...) btw. you have a function named 'tree' and a variable also named 'tree', that is confusing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T17:01:24.183",
"Id": "466855",
"Score": "0",
"body": "@JanKuiken: Recursion was my first attempt, but I couldn't manage it properly, so I came back to a solution where the glyph stack is managed by hand, with a standard Python list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T17:07:28.363",
"Id": "466856",
"Score": "0",
"body": "@JanKuiken: I renamed the actual name of the function when I pasted the code here, and didn't notice the name collision. I've edited the OP to remove collision. Thanks."
}
] |
[
{
"body": "<p>I'm still thinking about recursion, but i think you nailed it with your solution!</p>\n\n<p>However to better understand your code I have made some cosmetically changes:</p>\n\n<ul>\n<li>removed the <code>glyphs</code> list and used string literals when <code>glyphs</code> was used</li>\n<li>changed variable name <code>tree</code> to <code>display_rows</code></li>\n<li>changed variable name <code>glyph</code> to <code>prefix</code></li>\n<li>changed the type of <code>item</code> to string</li>\n<li>added more 'air' to the code by using empty lines and replacing comments to keep them within the 80 characters limit</li>\n</ul>\n\n<p>This led to:</p>\n\n<pre><code>def tree_string_to_display_string(tree_string):\n \"\"\"change 'tuple-tree-string' to a string for display\"\"\"\n\n display_rows = []\n prefix = []\n item = ''\n\n for char in tree_string:\n\n if char in ',)' and item:\n\n # add glyph prefix and current item to tree\n display_rows.append(prefix + [item.strip()])\n item = ''\n\n if char == ',':\n\n # update glyph prefix for new item in sublist\n prefix = ['│ '] * (len(prefix)-1) + ['├─']\n\n elif char == ')':\n\n # update glyph prefix for last item in sublist\n display_rows[-1][-2] = '└─'\n prefix = prefix[:-1] \n\n elif char == '(':\n\n # update glyph prefix for first item in sublist\n prefix.append('┬─')\n\n else:\n\n # other chars are simply added to current item\n item += char\n\n return '\\n'.join(''.join(node) for node in display_rows)\n\n\ns = '( A, B multi-word item , (C,D), ( E , , F ), G )'\nprint(tree_string_to_display_string(s))\n\ns = '(01, (02, 03, 04), 05, ((06, 07), 08), (09, (10, 11), (12, 13), 14), 15)'\nprint(tree_string_to_display_string(s))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T19:38:28.447",
"Id": "466887",
"Score": "0",
"body": "**Oops:** found a bug (/issue), string '( A, (B,C) , D)' gives desired result, however string '( A, (B,C))' does not..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T18:50:07.333",
"Id": "238060",
"ParentId": "238043",
"Score": "1"
}
},
{
"body": "<p>Neither the code provided in the question or the top voted answer work correctly. This is as you're making unreasonable assumptions on how the data is formed.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>>>> print(showtree('(A)'))\n└─A\n>>> print(showtree('(1, ((2)), (3, 4, (5)))'))\n┬─1\n├─┬─└─2\n├─┬─3\n│ ├─4\n│ ├─└─5\n>>> print(tree_string_to_display_string('(1, ((2)), (3, 4, (5)))'))\n┬─1\n├─┬─└─2\n├─┬─3\n│ ├─4\n│ ├─└─5\n</code></pre>\n\n<p>Your code is also doing two things at once, parsing a string and building a tree. And so I will only take a tuple as input. If you need to take a string then you can build the parser separately.</p>\n\n<ol>\n<li><p>Make the code work with one item.</p>\n\n<p>To do this should be fairly simple, we take the tuple <code>('1',)</code> and return <code>──1</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def build_tree(root):\n return '\\n'.join(_build_tree(root))\n\n\ndef _build_tree(node):\n yield '──' + node[0]\n</code></pre>\n\n<pre class=\"lang-py prettyprint-override\"><code>>>> print(build_tree(('1',)))\n──1\n</code></pre></li>\n<li><p>Make the code work with 1, 2 or more items.</p>\n\n<p>This is fairly simple, we check <code>node</code>'s length and use the above code if it's 1. Otherwise we make:</p>\n\n<ul>\n<li>The first item start with <code>┬─</code>.</li>\n<li>The last item start with <code>└─</code>.</li>\n<li>All other items start with <code>├─</code>.</li>\n</ul>\n\n<p>This is as simple as using tuple unpacking, and then iterating over the middle.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def _build_tree(node):\n if len(node) == 1:\n yield '──' + node[0]\n return\n\n start, *mid, end = node\n yield '┬─' + start\n for value in mid:\n yield '├─' + value\n yield '└─' + end\n</code></pre>\n\n<pre class=\"lang-py prettyprint-override\"><code>>>> print(build_tree(('1',)))\n──1\n>>> print(build_tree(('1', '2')))\n┬─1\n└─2\n>>> print(build_tree(('1', '2', '3')))\n┬─1\n├─2\n└─3\n</code></pre></li>\n<li><p>Get the code to work if you only enter a value, no tuples.</p>\n\n<p>This is simple, since we're only allowing tuples as the nesting datatype, then we can just add an <code>if not isinstance(node, tuple)</code>. We will convert this to a string now to help our future selves.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def _build_tree(node):\n if not isinstance(node, tuple):\n yield str(node)\n return\n\n if len(node) == 1:\n yield '──' + node[0]\n return\n\n start, *mid, end = node\n yield '┬─' + start\n for value in mid:\n yield '├─' + value\n yield '└─' + end\n</code></pre>\n\n<pre class=\"lang-py prettyprint-override\"><code>>>> print(build_tree('1'))\n1\n</code></pre></li>\n<li><p>Get the code to work recursively with the same input as (2). To check this we will change the input to integers.</p>\n\n<p>This is simple. We run <code>_build_tree</code> on all the values in <code>node</code>, if it's a tuple. From here we only work on these values. We know these values are going to be iterators with only one value. This means we can just use <code>next</code> for now.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def _build_tree(node):\n if not isinstance(node, tuple):\n yield str(node)\n return\n\n values = [_build_tree(n) for n in node]\n if len(values) == 1:\n yield '──' + next(values[0])\n return\n\n start, *mid, end = values\n yield '┬─' + next(start)\n for value in mid:\n yield '├─' + next(value)\n yield '└─' + next(end)\n</code></pre>\n\n<pre class=\"lang-py prettyprint-override\"><code>>>> print(build_tree((1,)))\n──1\n>>> print(build_tree((1, 2)))\n┬─1\n└─2\n>>> print(build_tree((1, 2, 3)))\n┬─1\n├─2\n└─3\n</code></pre></li>\n<li><p>Get the code working recursively.</p>\n\n<p>We know all the current <code>yield</code>s work the same way, and so this calls for a new function. This should take three values:</p>\n\n<ol>\n<li>The value to add to the first item. (This is what we're doing right now)</li>\n<li>The value to add on all other items.<br>\nThis is important as if a node is only one large. But has nested data that is larger than one value then we will add <code>' '</code> to the output.</li>\n<li>The nested data.</li>\n</ol>\n\n<p>This is really simple to build:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def build_lines(first, other, values):\n yield first + next(values)\n for value in values:\n yield other + value\n</code></pre>\n\n<p>Finally we adjust the current <code>yields</code> so they are <code>yield from</code> functions.</p></li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>def build_tree(root):\n return '\\n'.join(_build_tree(root))\n\n\ndef _build_tree(node):\n if not isinstance(node, tuple):\n yield str(node)\n return\n\n values = [_build_tree(n) for n in node]\n if len(values) == 1:\n yield from build_lines('──', ' ', values[0])\n return\n\n start, *mid, end = values\n yield from build_lines('┬─', '│ ', start)\n for value in mid:\n yield from build_lines('├─', '│ ', value)\n yield from build_lines('└─', ' ', end)\n\n\ndef build_lines(first, other, values):\n yield first + next(values)\n for value in values:\n yield other + value\n</code></pre>\n\n<pre class=\"lang-py prettyprint-override\"><code>>>> print(build_tree(('01', ('02', '03', '04'), '05', (('06', '07'), '08'), ('09', ('10', '11'), ('12', '13'), '14'), '15')))\n┬─01\n├─┬─02\n│ ├─03\n│ └─04\n├─05\n├─┬─┬─06\n│ │ └─07\n│ └─08\n├─┬─09\n│ ├─┬─10\n│ │ └─11\n│ ├─┬─12\n│ │ └─13\n│ └─14\n└─15\n>>> print(build_tree(('A', 'B multi-word item', ('C', 'D'), ('E', '', 'F'), 'G')))\n┬─A\n├─B multi-word item\n├─┬─C\n│ └─D\n├─┬─E\n│ ├─\n│ └─F\n└─G\n>>> print(build_tree((1, ((2,),), (3, 4, (5,)))))\n┬─1\n├─────2\n└─┬─3\n ├─4\n └───5\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T20:49:06.370",
"Id": "467043",
"Score": "1",
"body": "Woow ! This is the first time that I submit some unsatisfactory code of mine to CodeReview, and the result is brilliant.Tuple unpacking with the *-op in the middle is exactly what I was seeking for. And using a recursive generator seems so obvious, once you see it on screen. By the way, I need this tree-like display in a context where I don't want the user to enclose all items in quotes to create well-formed strings. But as you suggested, it's much easier to convert the loose syntax string into a well-formed tuple, then call your recursive fonction. Thanks a lot for this (master)piece of code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T12:00:46.417",
"Id": "238106",
"ParentId": "238043",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "238106",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T16:44:14.393",
"Id": "238043",
"Score": "5",
"Tags": [
"python"
],
"Title": "Pythonic solution to display multi-dimensional tuple as a tree"
}
|
238043
|
<p>I have a file that i use as database. It has the records and in the row 1 several cells used as buttons, (open folder, copy text, send mail, ecc.) At any change on any column of any record the file register the time in one column in order to have the last change of that record. It also change the color of the row if that row is selected.
Here an image:
<a href="https://i.stack.imgur.com/n91pW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n91pW.png" alt="The first buttons are just for email. "Aggiorna tutto" button do a code to refresh the database saving and changing some records from one worksheet to another depending on status, folder button is for open the folder of that specific person on server; mail button is to open an outlook message for that specific record, H1 and I1 are just text that are ready to copy and J1 and K1 are the paths for open directly the files related to that record "></a></p>
<p>The first buttons are just to send an specific email. "Aggiorna tutto" button do a code to refresh the database saving and changing some records from one worksheet to another depending on status, folder button is for open the folder of that specific person on server; mail button is to open an outlook message for that specific record, H1 and I1 are just text that are ready to copy and J1 and K1 are the paths for open directly the files related to that record.</p>
<p>My problem is that it is very slow to navigate trough the cells. Here my code in the worksheet:</p>
<pre><code>Private Sub Worksheet_Change(ByVal Target As Range)
'This code is to register the date and time of any change in any column in every record. This in order to have only the last change of that record.
Select Case Target.Column
Case 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40
Application.EnableEvents = False
Cells(Target.Row, 25).Value = Date + Time
Application.EnableEvents = True
End Select
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'I copy in first row the content that i need of every record that i navigate throug, except for the first rows where there are not records. The content is not visible is just used to feed formulas in H1, I1, J1 and K1 the folder and email button.
If ActiveCell.Row > 2 Then
Dim rw As Long
rw = ActiveCell.Row
Range("z1") = "=c" & rw
Range("b1") = "=b" & rw
Range("c1") = "=c" & rw
Range("d1") = "=d" & rw
Range("e1") = "=e" & rw
Range("f1") = "=f" & rw
Range("q1") = "=aa" & rw
Range("o1") = "=o" & rw
Range("g1") = "=i" & rw
Range("u1") = "=u" & rw
Range("x1") = "=y" & rw
If Application.CutCopyMode = False Then
Application.Calculate
End If
End If
If Selection.Count = 1 Then
If Not Intersect(Target, Range("h1")) Is Nothing Then
Call nomefile
End If
If Not Intersect(Target, Range("i1")) Is Nothing Then
Call nomefile2
End If
If Not Intersect(Target, Range("j1")) Is Nothing Then
Call nomefile3
End If
If Not Intersect(Target, Range("k1")) Is Nothing Then
Call nomefile4
End If
End If
End Sub
</code></pre>
<p>Here the codes that are called: </p>
<pre><code>
Sub cartella()
'Open the folder of the student of the record
Dim cartella As String
If IsError(Range("i1").Value) Then
GoTo fin
Else
cartella = Range("i1")
Call Shell("explorer.exe " & cartella, vbNormalFocus)
End If
fin:
End Sub
Sub nomefile()
'copy the text to save the certificate with that specific text
Dim nomefile As String
On Error GoTo fin
nomefile = Range("h1").Value
Range("h1").Select
Selection.Copy
CreateObject("WScript.Shell").Popup nomefile, 1, "Testo copiato: "
fin:
End Sub
Sub nomefile2()
'copy the path to save that certificate on server
Dim nomefile2 As String
On Error GoTo fin
nomefile2 = Range("i1").Value
Range("i1").Select
Selection.Copy
CreateObject("WScript.Shell").Popup nomefile2, 1, "Testo copiato: "
fin:
End Sub
Sub nomefile3()
'Open the file previously saved. If the file does not exit open the student's folder
Dim nomefile3 As String
On Error GoTo fin
nomefile3 = Range("j1").Value & ".pdf"
If Dir(nomefile3) <> "" Then
ActiveWorkbook.FollowHyperlink nomefile3
Else
cartella
End If
fin:
End Sub
Sub nomefile4()
'Open a file. If the file does not exit open the student's folder
Dim nomefile4 As String
On Error GoTo fin
nomefile4 = Range("k1").Value & ".pdf"
If Dir(nomefile4) <> "" Then
ActiveWorkbook.FollowHyperlink nomefile4
Else
cartella
End If
fin:
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T16:55:09.657",
"Id": "466853",
"Score": "3",
"body": "Could you add a short explanation for how you code works, and why you made any unorthodox choices if you did?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T17:27:44.033",
"Id": "466860",
"Score": "2",
"body": "@K00lman Thanks for your reply. I have explained a little more. I hope it is more clear now."
}
] |
[
{
"body": "<p>You're already declaring your variables :+1:. But I'll still mention that <code>Option Explicit</code> should be turned on. From the menu at the top Tools>Options>Editor tab>Code Settings group>Require Variable Declaration needs a check mark. That will then add <code>Option Explicit</code> to every new module mandating that <code>Dim variableName As String</code> needs to be added before any variable can be used. Again, it looks like you're already doing this but it wasn't explicitly shown in your code.</p>\n\n<hr>\n\n<p>Naming in VBA is PascalCase for Subs/Function where <code>TheFirstLetterOfEveryWordIsCapitalized</code>. Variables is camelCase where <code>theSecondAndSubsequentWordsAreCapitalized</code>.</p>\n\n<hr>\n\n<p>For the <a href=\"https://docs.microsoft.com/en-us/office/vba/Language/Reference/User-Interface-Help/select-case-statement\" rel=\"nofollow noreferrer\">Select Case statement</a> want to replace <code>1, 2, ... , 23, 24</code> and <code>26, 27, ... , 39, 40</code> with a range of values. \nBelow it immediately apparent that 25 is intentionally omitted. All too easy to miss that 25 is not in your original code.</p>\n\n<pre><code>Select Case Target.Column\n Case 1 To 24, 26 To 40\n</code></pre>\n\n<hr>\n\n<p>In <code>Cells(Target.Row, 25).Value = Date + Time</code> you're implicitly accessing the whatever-happens-to-be-active-sheet by not qualifying your <code>Cells</code> access with a worksheet. Because the code is within a worksheets event handler you can qualify with the identifier <code>Me.Cells(...)</code>. Otherwise if you're in a standard module explicitly qualify with the sheet you want to work with <code>Sheet1.Cells(...)</code>. Always make it explicit which worksheet you want to use so there's no guessing as to your intention.</p>\n\n<p>That line is also using the <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/date-function\" rel=\"nofollow noreferrer\">Date function</a> and the <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/time-function\" rel=\"nofollow noreferrer\">Time function</a> when you can use the <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/now-function\" rel=\"nofollow noreferrer\">Now function</a>. <code>Me.Cells(Target.Row, 25).Value = Now</code></p>\n\n<hr>\n\n<p>Within <code>Worksheet_SelectionChange</code> you are implicitly accessing the default member with <code>Range(\"z1\") = \"assignValue\"</code>. <code>Range(\"z1\").[_Default] = \"assignValue\"</code> is what's occurring. As stated above be explicit about member access by stating <code>Range(\"z1\").Value2 = \"assignValue\"</code>. Charles William already explained <a href=\"https://fastexcel.wordpress.com/2011/11/30/text-vs-value-vs-value2-slow-text-and-how-to-avoid-it/\" rel=\"nofollow noreferrer\">TEXT vs VALUE vs VALUE2</a> if you're interested.</p>\n\n<hr>\n\n<p>You can consolidate </p>\n\n<pre><code>Range(\"b1\") = \"=b\" & rw\nRange(\"c1\") = \"=c\" & rw\nRange(\"d1\") = \"=d\" & rw\nRange(\"e1\") = \"=e\" & rw\nRange(\"f1\") = \"=f\" & rw\n</code></pre>\n\n<p>into a single assignment</p>\n\n<pre><code>Me.Range(\"b1\", \"f1\").Formula = \"=b\" & rw\n</code></pre>\n\n<p>In addition to that you can turn off <code>Application.EnableEvents</code> until the last assignment since it's overwriting the same cell. This will increase speed a bit.</p>\n\n<pre><code>If ActiveCell.Row > 2 Then\n Dim rw As Long\n rw = ActiveCell.Row\n\n Application.EnableEvents = False\n\n Me.Range(\"z1\").Value2 = \"=c\" & rw\n Me.Range(\"b1\", \"f1\").Formula = \"=b\" & rw\n Me.Range(\"q1\").Value2 = \"=aa\" & rw\n Me.Range(\"o1\").Value2 = \"=o\" & rw\n Me.Range(\"g1\").Value2 = \"=i\" & rw\n Me.Range(\"u1\").Value2 = \"=u\" & rw\n\n Application.EnableEvents = True\n\n Me.Range(\"x1\").Value2 = \"=y\" & rw\n\n If Application.CutCopyMode = False Then\n Application.Calculate\n End If\nEnd If\n</code></pre>\n\n<hr>\n\n<p>The <a href=\"https://docs.microsoft.com/en-us/office/vba/Language/Reference/User-Interface-Help/call-statement\" rel=\"nofollow noreferrer\">Call statement</a> isn't needed. It's there for legacy purposes.</p>\n\n<hr>\n\n<p>You can conosolidate <code>nomefile</code> and <code>nomefile2</code> by paramaterizing the Sub. This is because only \"h1\" and \"i1\" are different. Refactor your code so that it accepts the arguments you need. Below you're supplying the <code>singleCell</code> variable which describes what you require of it along with how long you want the popup to display for. You can keep the Sub within the same code behind for the worksheet since, as far Is I can tell, its working on the same sheet. This goes back to qualifying your Range references to make it explicitly clear which sheet they come from.</p>\n\n<p>You also don't need or want to <code>Range(...).Select</code> followed by <code>Selection.Copy</code>. <a href=\"https://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba\">How to avoid using Select in Excel VBA</a> answered this already.</p>\n\n<pre><code>Private Sub DisplayPopupForCopiedCell(ByVal singleCell As Range, ByVal secondsToDisplayWindow)\n singleCell.Copy\n CreateObject(\"WScript.Shell\").Popup singleCell.Value2, secondsToDisplayWindow, \"Testo copiato: \"\nEnd Sub\n</code></pre>\n\n<p>Now when you need to use it <code>DisplayPopupForCopiedCell Me.Range(\"h1\"), 1</code> and <code>DisplayPopupForCopiedCell Me.Range(\"i1\"), 1</code> are used. This eliminates copied code and when you have to make a change you only need to do so in a single location.</p>\n\n<p>Do the same for <code>nomefile3</code> and <code>nomefile4</code></p>\n\n<hr>\n\n<p>The Sub for Cartella has no need for the label <code>fin:</code>. Replace that with the Exit statement. Also you can rename the sub. Forgiveness on my lack of Italian but a rough tranlsate results in <code>AprireCartellaDeiStudenti</code>.</p>\n\n<pre><code>Public Sub OpenStudentRecordFolder(ByVal folderPath As String)\n If IsError(folderPath) Then\n Exit Sub\n End If\n\n Shell \"explorer.exe \" & folderPath, vbNormalFocus\nEnd Sub\n</code></pre>\n\n<hr>\n\n<p>The static cell references \"h1\", \"i1\" are ticking time bombs and will break if the cells are shifted by adding a row above or column to the left. Using a named range so that you have <code>Sheet1.Range(\"StudentRecordFolder\")</code> or <code>Sheet1.Range(\"CartellaRegistrazioneStudente\")</code> won't break with a shifting cell.</p>\n\n<hr>\n\n<p>The above will help clarify your code. Ultimately I'm not sure how much faster it will make it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-05T20:39:11.503",
"Id": "238447",
"ParentId": "238044",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T16:49:05.533",
"Id": "238044",
"Score": "-1",
"Tags": [
"vba",
"excel"
],
"Title": "Worksheet change and worksheet selection change slowing down my file"
}
|
238044
|
<p>I am relatively new to C language and Linux systems I would like some feedback/review. The main function of the code is to read the dhcpcd file looking for the 3 lines and then either adding/removing to the new file. It works and the Pi can switch from AP to client without a reboot, but I feel like it is more of a hack than a proper solution.</p>
<pre><code>#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct word {
int linenumber;
char *value;
};
struct words {
int wordcount;
struct word wordlist[3];
};
int main(void) {
FILE *fp;
FILE *temp;
char filename[] = "/etc/dhcpcd.conf";
char tempname[] = "/etc/temp.conf";
char *line = NULL;
size_t len = 0;
ssize_t read;
int linecount = 0;
int index = 0;
int shouldSkip = 0;
struct words searchlist;
struct word wordA;
struct word wordB;
struct word wordC;
wordA.value = "interface wlan0";
wordA.linenumber = -1;
wordB.value = "static ip_address=192.168.4.1/24";
wordA.linenumber = -1;
wordC.value = "nohook wpa_supplicant";
wordC.linenumber = -1;
searchlist.wordcount = 3;
searchlist.wordlist[0] = wordA;
searchlist.wordlist[1] = wordB;
searchlist.wordlist[2] = wordC;
fp = fopen(filename, "r");
temp = fopen(tempname, "w");
if (fp == NULL || temp == NULL) {
printf("Unable to open file!\n");
exit(-1);
}
while ((read = getline(&line, &len, fp)) != -1) {
struct word *xword = &searchlist.wordlist[index];
if(strstr(line, xword->value) != NULL) {
xword->linenumber = linecount;
if(index > 0 && index != searchlist.wordcount - 1) {
if ((linecount - searchlist.wordlist[index - 1].linenumber) != 1) {
for (int i = 0; i < searchlist.wordcount; i++) {
struct word *wd = &searchlist.wordlist[i];
wd->linenumber = -1;
index = 0;
}
}
}
index = (index == (searchlist.wordcount - 1)) ? index : index + 1;
}
linecount++;
}
linecount = 0;
//AP is on so toggle off
if (fseek(fp, 0L, SEEK_SET) == 0) {
while ((read = getline(&line, &len, fp)) != -1) {
for(int i = 0; i < searchlist.wordcount; i++) {
if(linecount == searchlist.wordlist[i].linenumber && strstr(line, searchlist.wordlist[i].value) != NULL) {
shouldSkip = 1;
}
}
if(!shouldSkip)
fputs(line, temp);
shouldSkip = 0;
linecount++;
}
}
if (index != searchlist.wordcount - 1) {
for(int i = 0; i < searchlist.wordcount; i++) {
fputs(searchlist.wordlist[i].value, temp);
fputs("\n", temp);
}
}
fclose(fp);
fclose(temp);
remove(filename);
rename(tempname, filename);
if(line)
free(line);
if (index == searchlist.wordcount - 1) {
printf("Turning WIFI on\n");
} else {
printf("Turning Access Point on\n");
}
system("sudo service hostapd stop");
system("sudo service dhcpcd restart");
system("sudo service hostapd start");
exit(0);
}
</code></pre>
|
[] |
[
{
"body": "<p>There are a few compiler errors that may not have show up for you, the first major compiler problem is that <code>read</code> is a basic function in C input and output so the variable declaration <code>ssize_t read;</code> should be changed to something like <code>size_t readsize</code>. It might be good if you compiled with the -w flags to add warnings to the compiler error messages.</p>\n\n<p>The second problem I see is that you might have compiled this with a C++ compiler rather than a C compiler, a strict C compiler will not recognize the function <code>readline()</code> in a strict C compiler <a href=\"http://www.cplusplus.com/reference/cstdio/fgets/\" rel=\"nofollow noreferrer\">fgets()</a> should be used instead. You will have to make the variable <code>line</code> an array of characters.</p>\n\n<pre><code>char line[BUFSIZ];\n</code></pre>\n\n<p>The symbolic constant BUFSIZ is defined in the include file <code>stdio.h</code>.</p>\n\n<pre><code> fgets(line, BUFSIZ, fp);\n</code></pre>\n\n<p>Overall it would be better if <code>main()</code> was a short function that called other functions, it is currently too complex (does too much).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T23:44:47.983",
"Id": "466922",
"Score": "0",
"body": "Thank you for the feedback. Good catch on the read variable naming. Using fgets method, would I have to parse for ‘\\n’ to get track the line count?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T05:25:02.663",
"Id": "466931",
"Score": "0",
"body": "No, fgets gets only one line at a time. If it is still there and you want to remove it just one of the reverse string searches to start from the back rather than the front."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T13:56:30.070",
"Id": "466977",
"Score": "0",
"body": "`read` is not standard, but then on the other hand neither is `getline`. If one of them is available, the other is likely as well. Similarly, there is nothing called `BUFSIZE` in standard C."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T14:11:07.417",
"Id": "466979",
"Score": "0",
"body": "@Lundin My mistake it should be BUFSIZ"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T19:02:33.517",
"Id": "238061",
"ParentId": "238046",
"Score": "1"
}
},
{
"body": "<p>A few minor remarks:</p>\n<ul>\n<li><p>All pointers to string literals should be <code>const</code> qualified to prevent accidental bugs. That is <code>const char*</code>.</p>\n</li>\n<li><p><code>if(line) free(line);</code> is pointless, just call <code>free(line)</code>. It is well-defined to call <code>free</code> with a null pointer as parameter, in which case it will do nothing. This is handy when you know that all your pointers that may point at stuff that needs to be freed were originally initialized to point at <code>NULL</code>.</p>\n<p>(And similarly, it is good practice to assign the pointer to <code>NULL</code> after calling <code>free()</code>, if you plan to re-use that same pointer again.)</p>\n</li>\n<li><p><code>exit(0);</code> at the end of main is pointless and potentially confusing. You are using C99 so you actually don't need to write anything at all there. Not writing anything in C99 is identical to writing <code>return 0;</code>, which in turn is the same thing as calling <code>exit(0);</code>.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T14:09:23.540",
"Id": "238113",
"ParentId": "238046",
"Score": "1"
}
},
{
"body": "<blockquote>\n<pre><code>fclose(fp);\nfclose(temp);\n</code></pre>\n</blockquote>\n\n<p>Ignoring the return value from these (specifically the latter) is not a good idea. Closing a buffered file stream is when the last of the data are written - we want to know if that fails.</p>\n\n<blockquote>\n<pre><code>remove(filename);\nrename(tempname, filename);\n</code></pre>\n</blockquote>\n\n<p>Again, return value ignored when it's actually quite important.</p>\n\n<blockquote>\n<pre><code>if(line)\n free(line);\n</code></pre>\n</blockquote>\n\n<p>The test is unnecessary, as <code>free()</code> already performs the same test.</p>\n\n<blockquote>\n<pre><code>system(\"sudo service hostapd stop\");\nsystem(\"sudo service dhcpcd restart\");\nsystem(\"sudo service hostapd start\");\n</code></pre>\n</blockquote>\n\n<p>More return values ignored when they shouldn't be.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-02T09:39:58.047",
"Id": "238228",
"ParentId": "238046",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T17:21:32.733",
"Id": "238046",
"Score": "3",
"Tags": [
"c",
"raspberry-pi"
],
"Title": "Raspberry PI switching from Soft Access Point to WIFI client"
}
|
238046
|
<p>This code is to have a dictionary of names and birthdays.</p>
<p>It will ask who's birthday it is that you're looking for. Then if it is in the dictionary, it will print back what that birthday is. If not, it will ask if you want to add it then have you insert the birthday as the value and use the name that you input before as the key. Then finally print the full dictionary. </p>
<p>I am pretty new to coding in Python and feel like there is a better way to type this code. Was thinking I could use return but I'm still not quite sure what the difference between return and print is. Is there a way to make this shorter or more efficient? </p>
<pre><code>birthdays = {'Jon': 'July 17', 'Shauna': 'Jan 27', 'Lynette': 'July 10'}
while True:
print("Who's birthday is it that you are looking for? To cancel, press enter!")
name = input()
if name == '':
break
if name in birthdays:
print(birthdays[name] + ' is the birthday of ' + name)
else:
print("I don't have that person's name in my archives. Would you like to add it? Press Y or N")
answer = input()
if answer == 'Y':
new_name = name
print("Please enter their birthday")
new_birthday = input()
birthdays[name] = new_birthday
print('It has been added')
print(new_name + "'s birthday has been added as " + new_birthday)
print('Here is a list of birthdays you have saved...')
print(birthdays)
else:
print('Alrighty Then')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T17:28:16.570",
"Id": "466861",
"Score": "1",
"body": "_\"Was thinking I could use return but I'm still not quite sure what the difference between return and print is.\"_ Huh, what please? You can use `return birthdays` in the context of a function which is called elsewhere and print's the result. Other function won't have access to what's printed on the screen from your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T16:45:30.780",
"Id": "467011",
"Score": "1",
"body": "@πάνταῥεῖ: While that question immediately identifies the OP as a beginner not only in Python but in programming in general, it seems to be a common enough cause of confusion, in my experience."
}
] |
[
{
"body": "<p><code>return</code> returns the value, in this case the dictionary <code>birthdays</code>, whereas <code>print</code> just prints the value to the terminal. Your printing might be improved by using <a href=\"https://docs.python.org/3.8/reference/lexical_analysis.html#f-strings\" rel=\"nofollow noreferrer\">f-strings</a>. This is usually a bit easier than having to use \"+\" inside your print statements. So for example, instead of </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(new_name + \"'s birthday has been added as \" + new_birthday)\n</code></pre>\n\n<p>You could write:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(f\"{new_name}'s birthday has been added as {new_birthday}\")\n</code></pre>\n\n<p>This combined with a generator could also make your dictionary printing a little neater:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(\"\\n\".join([f\"{name}'s birthday is {bday}\" for name,bday in birthdays.items()]))\n</code></pre>\n\n<p>The generator creates a list of strings for each item in the <code>birthdays</code> dictionary, so in this case, it would generate the list <code>[\"Jon's birthday is July 17\",\"Shauna's birthday is Jan 27\", \"Lynette's birthday is July 10\"]</code>. The <code>join()</code> function is used to combine each element of this list into a new string, separated by the newline character <code>\\n</code>. So the final result would produce:\n<code>\nJon's birthday is July 17\nShauna's birthday is Jan 27\nLynette's birthday is July 10\n</code></p>\n\n<p>If you want to further extend this code, I'd recommend representing the birthday as a <code>date</code> object, from the Python built-in library <a href=\"https://docs.python.org/3.8/library/datetime.html\" rel=\"nofollow noreferrer\"><code>datetime</code></a>. Then you could also add the functionality of easily telling how many days until someone's birthday and other features like that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T19:45:34.883",
"Id": "466888",
"Score": "1",
"body": "Ah, thank you so much! This is incredibly helpful. I didn't know that library existed. I'll have to check it out and I also didn't know f-strings were a thing. Looks like a great way to condense part of the code. I appreciate it!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T18:35:51.677",
"Id": "238058",
"ParentId": "238047",
"Score": "4"
}
},
{
"body": "<p>If this were a real program (i.e. not simply something you are playing and learning with), it would need a lot more error checking.</p>\n\n<p>E.g. If this happens:</p>\n\n<blockquote>\n <p>Would you like to add it? Press Y or N<br>\n yes<br>\n Alrighty Then</p>\n</blockquote>\n\n<p>The program's ambiguous response will mislead the user into thinking that his answer has been accepted, and then the user will get confused about what happens next.</p>\n\n<p>It would be better to have a function that prompts the user and indicates whether a positive or negative response was entered. E.g.</p>\n\n<pre><code>if positive_response(\"I don't have that person's name. Would you like to add it?\"):\n</code></pre>\n\n<p>Where <code>positive_response(prompt)</code> can have long lists of possible positive and negative responses and can loop until it gets a definite hit.\nThe function can be reused later in other parts of the program that need a confirmation.</p>\n\n<p>Similarly nothing checks the entered birthday (e.g. \"<em>today</em>\" or \"<em>last Wednesday</em>\").\nAgain, a self-contained function that loops until it gets a date that it can understand would be appropriate:</p>\n\n<pre><code>birthdays[name] = get_date(\"Please enter their birthday\")\n</code></pre>\n\n<p>The function should also convert the date into a standard format.\nAnd again, the function can be reused elsewhere if a date is required from input.</p>\n\n<p>This code is simpler, easier to read, and far less likely to contain bugs:</p>\n\n<pre><code>if positive_response(\"I don't have that person's name. Would you like to add it?\"):\n birthdays[name] = get_date(\"Please enter their birthday\")\n display_birthdays(\"Updated list of birthdays\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-02T14:58:24.003",
"Id": "238250",
"ParentId": "238047",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T17:26:06.567",
"Id": "238047",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Dictionary of names and birthdays"
}
|
238047
|
<p>So I made a Python program to solve some of my A-level binomial questions or just to let me check my answer overall. I need advice on how to make it more compact and simplify it.</p>
<p>This Python code is meant for the fx-cg50 calculator's micropython, where there are a lot of functions that don't work including fractions, some mathematical functions such as <code>math.gcd</code> and <code>math.isclose</code>. So I really require some advice or coding tricks to simplify my program.</p>
<p>Disclaimer: I'm only an A-Level student of 16 years; consider me a beginner. I know <code>eval</code> is insecure, but I'm not planning on uploading this online; it's only for my personal use.</p>
<pre class="lang-py prettyprint-override"><code>print("Factorial Calculator: ")
term = []
# loops through the terms to print them
def term_list_looper(num):
for i in range(num):
print(term[i])
# finds the factorial of a certain number (!)
def factorial(num):
result = 1
if type(num) == str:
num = int(eval(num))
else:
pass
for i in range(1, num+1):
result *= i
return result
# find the combination of a nth and r (nCr)
def combination(nth, rth):
coefficient = (factorial(nth) / (factorial(rth) * factorial(nth - rth)))
return coefficient
# finds a certain entry of the pascal's triangle using rows and columns
def pascal_triangle_c_entry(nth, rth):
coefficient = (factorial(nth-1)/(factorial(rth-1)*factorial((nth-1)-(rth-1))))
return int(coefficient)
# finds the working and and coefficent of a term in (a+bx)^n
def binomial_term_coefficient_finder(nth, rth, a, b_coefficient, output):
diff_nth_rth = nth - rth
comb = combination(nth, rth)
a_result = a**diff_nth_rth
b_result = b_coefficient**rth
resultant_coefficient = comb * a_result * b_result
group = str("("+str(nth)+"C"+str(rth)+") ("+str(a)+")^"+str(diff_nth_rth)+" ("+str(b_coefficient)+"x)^"+str(rth))
if output == 0:
return group
elif output == 1:
print("work: ("+str(nth)+"C"+str(rth)+") ("+str(a)+")^"+str(diff_nth_rth)+" ("+str(b_coefficient)+"x)^"+str(rth))
print("Coefficient of x^"+str(rth)+"\n:", resultant_coefficient)
elif output == 2:
if rth == 0:
return resultant_coefficient
else:
return ("("+str(resultant_coefficient)+")"+'x^'+str(rth))
def first_count_terms(nth, count, a, b_coefficient):
for r in range(count):
term.insert(r, binomial_term_coefficient_finder(nth, r, a, b_coefficient, 0))
print(str(count)+" Terms are:")
term_list_looper(count)
def first_terms_with_coefficients(nth, count, a, b_coefficient):
terms = []
terms = [binomial_term_coefficient_finder(nth, rth, a, b_coefficient, 2) for rth in range(count)]
print(terms)
def stopper():
stop_flag = False
stop_or_continue = ""
while stop_or_continue != "a" or "b":
stop_or_continue = input("Stop?: ")
if stop_or_continue == "a":
stop_flag = True
break
if stop_or_continue == "b":
stop_flag = False
break
if stop_flag:
raise SystemExit
while True:
print("Choose a for Pas_Tri entry(C)\nChoose b for term coefficient finder\nChoose c for first nth terms\nChoose d for c but with coeff")
choice = input(">> ")
while choice != "a" or choice != "b" or choice != "c" or choice != "d":
if choice == "a":
nth = int(input("Enter nth: "))
rth = int(input("Enter rth: "))
print(pascal_triangle_c_entry(nth, rth))
elif choice == "b":
nth = int(input("Enter nth: "))
rth = int(input("Enter rth: "))
a = int(input("Enter a: "))
b_coefficient = input("Enter b's coeff: ")
if type(b_coefficient) == str:
b_coefficient = eval(b_coefficient)
binomial_term_coefficient_finder(nth, rth, a, b_coefficient, 1)
elif choice == "c":
nth = int(input("Enter nth: "))
count = int(input("Enter first nth term num: "))
a = int(input("Enter a: "))
b_coefficient = input("Enter b's coeff: ")
if type(b_coefficient) == str:
b_coefficient = eval(b_coefficient)
first_count_terms(nth, count, a, b_coefficient)
elif choice == "d":
nth = int(input("Enter nth: "))
count = int(input("Enter first nth term num: "))
a = int(input("Enter a: "))
b_coefficient = input("Enter b's coeff: ")
if type(b_coefficient) == str:
b_coefficient = eval(b_coefficient)
first_terms_with_coefficients(nth, count, a, b_coefficient)
stopper()
print("Choose a for Pas_Tri entry(C)\nChoose b for term coefficient finder\nChoose c for first nth terms\nChoose d for c but with coeff")
choice = input(">> ")
</code></pre>
|
[] |
[
{
"body": "<p>there.</p>\n\n<p>This is my first answer, so If I screw up or some of my suggestion are 'too strong', let me know. I'll try to correct it.</p>\n\n<p>I'm just renaming 'nth' and 'rth' to 'n' and 'r' at some places in my code, please keep that in mind.</p>\n\n<p>One more thing, I can't add a comment yet (not enough rep), so could you tell me what purpose 'eval' servers in your code, I couldn't figure it out.</p>\n\n<pre><code> if type(num) == str:\n num = int(eval(num))\n\n if type(b_coefficient) == str:\n b_coefficient = eval(b_coefficient)\n</code></pre>\n\n<p>Are you consider to take expressions as input? If you are even then you can move 'eval' out of functions (like you did in the second example) to the input, (as soon as you input), so functions and the rest of code is streamlined.</p>\n\n<p>Also, you don't need to check <code>if type(num) == str</code> . In python3, the input is 'str' by default. So, if there's an expression you can evaluate it directly.</p>\n\n<p>Now, coming to the code, I'll try to simplify things I'm able to.</p>\n\n<hr>\n\n<h1>Simple Optimization</h1>\n\n<p>Solving 'Combinations' as a factorial needs unnecessary computations when they could be avoided. You are calculating three factorials, then the result. But, it could be simplified. (Considering r <= (n-r) and the fact that nCr = nC(n-r))</p>\n\n<p><a href=\"https://i.stack.imgur.com/cYCXi.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cYCXi.png\" alt=\"enter image description here\"></a></p>\n\n<p>So, if you modify you factorial and combination functions, you'll save some computation.</p>\n\n<pre><code>def factorial(n, end_point=1) :\n result = 1\n for i in range(end_point, n+1):\n result *= i\n return result\n\ndef combination(n, r) :\n r = min(r, n - r)\n c = factorial(n, n-r+1) // factorial(r)\n return c\n</code></pre>\n\n<p>And if you didn't know, '//' is integer division in python 3. So, if you do this then you won't need to convert output to and integer.</p>\n\n<h1>Don't repeat yourself</h1>\n\n<p>You can simplify pascal's triangle by doing this</p>\n\n<pre><code>def pascal_triangle_c_entry(n, r):\n return combination(n-1, r-1)\n</code></pre>\n\n<hr>\n\n<h1>Streamline Stuff</h1>\n\n<p>You can break your 'binomial_term_coeff_finder' function in smaller functions. A start would be to make a new 'group' output formatter funtion. It would be called whenever you called 'binomial_term_coeff_finder' with 'output = 0'.</p>\n\n<pre><code>def output_formatter(nth, rth, a, b_coeff) :\n d = n - r\n return \"(\"+str(nth)+\"C\"+str(rth)+\") (\"+str(a)+\")^\"+str(d)+\" (\"+str(b_coeff)+\"x)^\"+str(rth) \n # You don't need the outermost str\n</code></pre>\n\n<p>Now you don't need the choice (output) 0 and you can delete that.\nFor choice 1 and 2, you can merge them so the function will only return 'resultant_coefficient' and format the output as desired, because the choice 1 and 2 are doing the same thing.\nThe only time you use choice 1 is in choice 'b' of your main function i.e. 'term coefficient finder'.</p>\n\n<pre><code>b_coefficient = input(\"Enter b's coeff: \")\nif type(b_coefficient) == str:\n b_coefficient = eval(b_coefficient)\nbinomial_term_coefficient_finder(nth, rth, a, b_coefficient, 1)\n</code></pre>\n\n<p>So, replace this by - </p>\n\n<pre><code>b_coefficient = input(\"Enter b's coeff: \")\nb_coefficient = eval(b_coefficient) # Again idk why you'd need that\nresultant_coeff = binomial_term_coefficient_finder(nth, rth, a, b_coefficient)\nprint(output_formatter(nth, rth, a, b_coefficient))\nprint(\"Coefficient of x^\"+str(rth)+\"\\n:\", resultant_coeff)\n</code></pre>\n\n<hr>\n\n<h1>Don't complicate</h1>\n\n<p>In your 'first_count_terms' function, I don't know why you're using 'insert' method. If I'm missing something, let me know. Also, you don't need to print first 'count' terms, since you're only generating 'count' terms. imo, this would be better - </p>\n\n<pre><code>def first_count_terms(n, count, a, b_coefficient):\n print(count, \"Terms are:\") # Same as print(str(count)+\" Terms are:\")\n for r in range(count):\n print(output_formatter(n, r, a, b_coefficient))\n# I used output_formatter call here, which is equivalent to binomial_fun call with choice 0\n</code></pre>\n\n<hr>\n\n<p>In your following function, ditch the second line. You don't need a predefined list when using list comprehension.</p>\n\n<pre><code>def first_terms_with_coefficients(nth, count, a, b_coefficient):\n terms = [] # This line is unnecessary\n terms = [binomial_term_coefficient_finder(nth, rth, a, b_coefficient, 2) for rth in range(count)]\n # don't forget to remove '2' from the arguments if you consolidated the function earlier.\n print(terms)\n</code></pre>\n\n<hr>\n\n<p>Your 'stopper' function is unnecessarily complicated. You can just do,</p>\n\n<pre><code>def stopper():\n choice = input('Stop? (y/n) : ')\n if choice == 'y' :\n raise SystemExit\n</code></pre>\n\n<p>However, I can't comment on whether you need a stopper function at all, because I don't know how your calculator exits from a code. </p>\n\n<hr>\n\n<p>The inner while loop in the below code serves no purpose you can just remove it and the last two lines of your code and it'll behave the same.</p>\n\n<pre><code>while True:\n print(\"Choose a for Pas_Tri entry(C)\\nChoose b for term coefficient finder\\nChoose c for first nth terms\\nChoose d for c but with coeff\")\n choice = input(\">> \")\n while choice != \"a\" or choice != \"b\" or choice != \"c\" or choice != \"d\":\n if choice == \"a\":\n nth = int(input(\"Enter nth: \"))\n rth = int(input(\"Enter rth: \"))\n.\n.\n.\n b_coefficient = eval(b_coefficient)\n first_terms_with_coefficients(nth, count, a, b_coefficient)\n\n stopper()\n print(\"Choose a for Pas_Tri entry(C)\\nChoose b for term coefficient finder\\nChoose c for first nth terms\\nChoose d for c but with coeff\")\n choice = input(\">> \")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T17:55:09.447",
"Id": "467026",
"Score": "0",
"body": "idk what micropython is but in desktop python > 3.6 you can use [f-strings](https://realpython.com/python-f-strings/#f-strings-a-new-and-improved-way-to-format-strings-in-python) . These simply formatting your output quite a bit, `return \"(\"+str(nth)+\"C\"+str(rth)+\") (\"+str(a)+\")^\"+str(d)+\" (\"+str(b_coeff)+\"x)^\"+str(rth)` would be `return f'({nth}C{rth}) ({a})^{d} ({b_coeff}x)^{rth}'`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T23:40:07.353",
"Id": "467048",
"Score": "0",
"body": "im afraid f'strings dont work in micropython, a bummer indeed, and for your question about the eval statements, recall the fact that this program is for a calculator, as a result, the only way to enter fractions is like this \"5/7\", this will be originally in string, so i have to evaluate it before further processing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T23:51:54.740",
"Id": "467049",
"Score": "0",
"body": "so i ran into a bug with your program at your factorial and combination function, apparently when i try to calculate the 7th row and 2th entry it gives me a value of 0"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T00:07:52.630",
"Id": "467050",
"Score": "0",
"body": "ahh update: i fixed your bug by removing the max(rth, nth-rth) function and replacing factorial(r) with factorial(rth) as the combination function removes the nth-rth part so only the rth part remains to be divided."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T03:20:09.697",
"Id": "467055",
"Score": "0",
"body": "I couldn't replacate your bug. For me combination (6,1) = 6 and combination (7,2) =21. Idk, how you're getting '0'. There is however a problem with that function, the 'max' function should've been a 'min' funtion so it lessens the calculation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T23:37:44.193",
"Id": "467109",
"Score": "0",
"body": "oh i was doing comb(n-1, r-1) and i somehow got a 0 when its not supposed to be 0"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T11:43:51.207",
"Id": "467142",
"Score": "0",
"body": "If you say, you figured it out then no worries. But it was already working for me, [code_result](https://imgur.com/8lx4oVQ)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T17:11:53.663",
"Id": "238122",
"ParentId": "238051",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "238122",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T18:10:57.027",
"Id": "238051",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"mathematics"
],
"Title": "Binomial Expander"
}
|
238051
|
<p>I wrote a Python script to generate a video file of typing the contents of any program file. It works, but I'm really not very happy with how it works. I have several issues with it.</p>
<ol>
<li>In order to generate the video file I had to generate an image for every character in the file. As you can imagine, this is extremely time consuming, especially for longer files of code. I had originally wanted to only obtain the <code>numpy</code> array or bytes rather than having to save it to a file, but I didn't find an efficient way to generate the video file from this, nor how to obtain the array from the Pygments function <code>highlight</code>. I tried saving the value returned from the function into a variable and found it to be a list of bytes, but when I tried to use the Pillow <code>Image</code> function <code>from_bytes()</code>, it returned an error saying something to the effect of the bytes array being too small or not having enough data or something like that. I assume this is because the initial image saved is a blank image. I did this because I needed to get the size of the final image that would be generated so that I could keep all preceding images at the same size. Otherwise, if all the images produced at differing sizes, the output video would turn into a garbled mess. I haven't thought of a better solution to generating the frames of the video but I know there has to be one.</li>
</ol>
<p><a href="https://i.stack.imgur.com/1TDaJ.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/1TDaJ.gif" alt="GIF animation of output video"></a></p>
<ol start="2">
<li>I noticed that the quality of the output video produced from this script decreases with each frame. It gets worse and worse quality over time. I am pretty sure this is due to each frame overlapping the last one. Since each frame is identical to the frame before it with the addition of another character, I believe the overlapping of the frames on top of each other creates the unpleasant blurriness (I don't know if that's the right way to describe it) that is seen in the output video. It's a subtle effect that is more noticeable when the font size is smaller. I've provided a GIF to show what I mean, with the font size set to 14. Are the frames overlapping each other? Would this issue be fixed by generating the video from the collection of image files? </li>
<li>I know I made extensive use of <code>property</code> in this program. I have a feeling I used them at times when I shouldn't have. I was pretty happy with myself for using the <code>property</code> feature for the progress bar, since it allowed me to generate the progress bar just by incrementing <code>self.progress</code>. I probably don't need the other two properties, and I think I ended up not even using one of them in the end. I used the property method for updating the progress bar because I found it simpler to use and because when I tested two versions of the code, one which used <code>property</code> and the other which used <code>threading.Thread</code> and output the runtime for each, the version which used <code>property</code> ended up running faster than the multithreading one. Granted, I didn't extensively test this, so this may not be true in all cases.</li>
<li>I am also aware that it would have been more efficient and better practice for me to use <code>**kwargs</code> and pass along the dictionary of values that way instead of just saving the dictionary itself as <code>self.args</code>. To be honest, I only found out about <code>**kwargs</code> a couple days ago and I haven't had the chance to go back and change this. I would still appreciate advice on implementing that though.</li>
<li>I'm also unhappy with having to use both OpenCV and Pillow to generate the video. I feel like this is redundant and I could accomplish the same task with just one of these libraries rather than depending on both.</li>
</ol>
<p>Overall, I'm unhappy with how excruciatingly slowly this script is. I am confident that there are better design choices I could make in order to improve both the runtime and the quality of the output produced.</p>
<pre class="lang-py prettyprint-override"><code>class Typewriter:
def __init__(self,args):
self.args = args
if not args.language is None:
self.lexer = get_lexer_by_name(args.language)
else:
self.lexer = get_lexer_for_filename(args.textfile)
logger.debug(f'Assigned value to lexer object {self.lexer}')
self.formatter = self.__get_formatter()
logger.debug(f'Assigned value to formatter object {self.formatter}')
self._image_paths = []
self._progress=0
self._impath=''
self.images = []
self.total=0
self.total_size=0
try:
with open(args.textfile,'r') as f:
self._content = f.read()
except FileNotFoundError as err:
logger.error(err)
sys.exit(-1)
def __get_formatter(self):
return ImageFormatter(line_numbers=True,style=self.args.style,line_number_bg=None,font_size=self.args.font_size)
def __get_lexer(self,content):
if not args.language is None:
lexer = get_lexer_by_name(self.args.language)
else:
lexer = guess_lexer(content)
return lexer
def __update_progress(self):
'''
Adapted into fewer lines from the following gist:
https://gist.github.com/vladignatyev/06860ec2040cb497f0f3
'''
sys.stdout.write(f'[{"="*int(round(50*self.progress/float(self.total)))+"-"*(50-int(round(50*self.progress/float(self.total))))} {round(100.0*self.progress/float(self.total),1)}%]\r')
sys.stdout.flush()
def __make_dir(self):
choice=''
if not os.path.exists('tmp'):
os.makedirs('tmp')
else:
while not choice == 'y':
logger.warning('There is already a directory named "tmp" here. Please make sure you are okay with everything in this "tmp" folder getting deleted before continuing.')
choice=input('Continue? y/n\n')
if choice == 'y':
break
elif choice == 'n':
sys.exit(-1)
else:
logger.warning('Invalid choice. Please type "y" or "n".\n')
continue
@property
def content(self):
return self._content
@content.setter
def content(self,val):
self._content=val
self.__get_lexer(self._content)
self.__get_formatter()
@property
def progress(self):
return self._progress
@progress.setter
def progress(self,val):
self._progress=val
self.__update_progress()
@property
def impath(self):
return self._impath
@impath.setter
def impath(self,val):
self._impath=val
self._image_paths.append(self._impath)
old = Image.open(self._impath)
new=Image.new('RGBA',self.total_size)
new.paste(old)
new.save(self._impath)
self.images.append(new)
@property
def image_paths(self):
return self._image_paths
@image_paths.setter
def image_paths(self,val):
self._image_paths=val
self.images=[Image.open(f) for f in self._image_paths]
def generate_images(self,content=None):
'''
Generate Images
---------------
Description: Creates a list of image data given text content
'''
if content is None:
content=self.content
else:
self.content = content
self.__make_dir()
self.total=len(content)
code = ''
logger.info('Generating images...')
# self.total_size=self.formatter._get_image_size(80,len(content.splitlines()))
blank='\n'.join([' '*len(line) for line in content.splitlines()])
last_impath=os.path.join('tmp',f'tmp_{str(len(content)).zfill(5)}.png')
highlight(blank,self.lexer,self.formatter,outfile=last_impath)
im=Image.open(last_impath).convert('RGBA')
self.total_size=im.size
self.images.append(im)
os.remove(last_impath)
for line in content:
for ch in line:
self.progress+=1
impath=os.path.join('tmp',f'tmp_{str(self.progress).zfill(5)}.png')
highlight(code,self.lexer,self.formatter,outfile=impath)
self.impath=impath
code += ch
print()
return self.image_paths
def generate_movie(self,image_paths=None,fps=10,moviename='movie.avi'):
'''
Generate Movie
--------------
Description: Creates an animation of the images generated above,
and then cleans up the tmp files by removing everything
in the tmp directory that was generated.
'''
# If it's run without a list of images and we haven't generated any images yet,
# then generate the images and set the var to that
logger.info('Generating movie...')
if image_paths is None and not self.image_paths:
image_paths=self.generate_images(self.content)
# If we have already generated the images then set the var to that
elif image_paths is None:
image_paths=self.image_paths
# If they gave us the list of images, put out something to make sure
# user knows to keep the content matching
else:
logger.info('Make sure the content of the images matches the content var in this class!')
frame=cv2.imread(self.image_paths[0])
h,w,l=frame.shape
v=cv2.VideoWriter(moviename,0,fps,(w,h))
self.progress=0
self.total=len(self.image_paths)+1
for im in self.image_paths:
v.write(cv2.imread(im))
os.remove(im)
self.progress += 1
os.rmdir('tmp')
self.progress+=1
print()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-07T17:49:43.540",
"Id": "477971",
"Score": "1",
"body": "The code, as is, doesn't run."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T15:39:12.403",
"Id": "481653",
"Score": "0",
"body": "Just to confirm, you want to record a video of code as you are typing. What's the objective? Can you please elaborate more on why you want to do this? Also are you using this code to capture a code editor's window as you type?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-15T19:53:39.103",
"Id": "482191",
"Score": "3",
"body": "Do you have a usage example showing how to actually get the result you show with the class provided? Please don't forget to mention relevant imports as well. Your question has gone unanswered so far while I think it's perfectly answerable provided you add the aforementioned items."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T18:14:02.553",
"Id": "238053",
"Score": "11",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Generate a video of typing the contents of a file"
}
|
238053
|
<h1>Introduction</h1>
<p>I'm working on a Statistics Library that can record observations and produce a Summary of the statistics when there's enough observations. Right now, it's at its early stages and is expected to change a lot as I develop it gradually. </p>
<h1>Minimal Example</h1>
<p>Suppose I want to record the run time of a particular piece of code and generate some of the common Statistics about it. At the current state of my project, the following approach is the way to go:</p>
<pre class="lang-java prettyprint-override"><code> SampleBuilder builder = new SampleBuilder("Runtimes", "s");
for (int i = 0; i < ITERATION_LIMIT; i++) {
long timeStart = System.currentTimeMillis();
// The code to be timed goes here.
new BigInteger(1024, 2048, new Random());
long timeEnd = System.currentTimeMillis();
builder.addObservation((timeEnd - timeStart) / 1000.0);
}
Sample runtimes = builder.buildSample();
System.out.println(runtimes);
</code></pre>
<p>The output is something like:</p>
<pre class="lang-none prettyprint-override"><code>0.121 s
0.147 s
0.22 s
0.115 s
0.084 s
0.025 s
0.353 s
0.209 s
0.021 s
0.223 s
...
0.015 s
0.521 s
0.03 s
0.017 s
0.036 s
Summary Statistics for Sample: Runtimes
Count : 50 s
Sum : 4.757 s
Mean : 0.095 s
Variance: 0.011 s
Std Dev : 0.106 s
</code></pre>
<h1>The Code</h1>
<h2>Sample.java (and Summary.java)</h2>
<pre class="lang-java prettyprint-override"><code>package in.hungrybluedev.statistics;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* A Sample is an immutable collection of observations. There are statistics
* associated with every Sample, such as mean, variance and standard
* deviation. This class implements various methods to access these
* desired statistics and also presents them in an organised manner
* through the Summary subclass.
* <p>
* Note that the minimum number of elements in a Sample must be {@value #DEFAULT_THRESHOLD}
* (or whatever the threshold is set to). This is because the formulas
* implemented do not adjust for the decrease in degree of freedom.
*
* @author Subhomoy Haldar (@HungryBlueDev)
* @noinspection WeakerAccess, unused
*/
public class Sample {
/* Statically accessible parameters */
/**
* The threshold is the minimum number of elements that a Sample
* must have to ensure accurate statistical analysis. The implementation
* allows for some flexibility by providing methods to change the
* threshold. However, some minimum restrictions apply.
*/
public static final int DEFAULT_THRESHOLD = 40;
/**
* This is the minimum threshold value allowed for the Sample size. Any
* lower, and we cannot guarantee the accuracy of the Summary Statistics
* generated.
*/
public static final int MINIMUM_THRESHOLD = 30;
private static int threshold = DEFAULT_THRESHOLD;
/**
* Update the minimum sample size to the new minimum value. Note that
* the new minimum must be at least {@value MINIMUM_THRESHOLD}.
*
* @param newThreshold The new proposed threshold value.
* @throws IllegalArgumentException If the value is lesser than the minimum acceptable value.
*/
public static void setThreshold(final int newThreshold)
throws IllegalArgumentException {
if (newThreshold < MINIMUM_THRESHOLD) {
throw new IllegalArgumentException("Value of threshold is too low.");
}
threshold = newThreshold;
}
/**
* @return The current threshold value.
*/
public static int getThreshold() {
return threshold;
}
/**
* The precision is the number of significant digits that are accurately portrayed
* in the results. The default precision is chosen arbitrarily. Users are
* recommended to set the precision (within the capacity of double) to change
* the way the summary is generated.
*/
public static final int DEFAULT_PRECISION = 3;
private static int precision = DEFAULT_PRECISION;
/**
* Update the precision value to the new proposed value, provided that the
* String format method and the size of double support it.
*
* @param newPrecision The proposed value to the set the precision to.
* @throws IllegalArgumentException If the new precision is not valid.
*/
public static void setPrecision(final int newPrecision)
throws IllegalArgumentException {
if (newPrecision < 1 || newPrecision > 15) {
throw new IllegalArgumentException("Invalid precision value");
}
precision = newPrecision;
}
/**
* @return The current precision.
*/
public static int getPrecision() {
return precision;
}
/*
* These are helper methods that make use of the precision value to
* determine the output of the statistics generated.
*/
private static String format(final double value) {
return String.format("%." + precision + "f", value);
}
private static String format(final int value) {
return String.valueOf(value);
}
private static boolean stringIsEmpty(final String text) {
return text == null || text.isEmpty();
}
// Immutable fields
private final String name;
private final String unit;
private final double[] values;
// Lazily initialized fields:
private Summary summary;
private Double sum;
private Double squaredSum;
/**
* This is the constructor for Sample and requires a name and the array
* of observations for the sample. Unit of measurement is optional.
* It is recommended to use a SampleBuilder to generate a Sample.
* If the name is not provided, the default result of super.toString() is used.
* <p>
* Note: It is important to ensure that the observations are equal to or
* greater than the threshold value. See {@linkplain #getThreshold()} and
* {@link #DEFAULT_THRESHOLD}
*
* @param name The name of the sample.
* @param unit The unit of measurement for all
* @param observations The array of observations in the sample.
* @throws IllegalArgumentException If any of the parameters are empty, or invalid.
*/
Sample(final String name, final String unit, double[] observations)
throws IllegalArgumentException {
if (observations == null) {
throw new IllegalArgumentException("Empty value array");
}
if (observations.length < threshold) {
throw new IllegalArgumentException(
"The sample size is the less than the threshold: "
+ observations.length + " < " + threshold
);
}
this.name = stringIsEmpty(name) ? super.toString() : name;
this.unit = stringIsEmpty(unit) ? "" : unit;
this.values = observations;
summary = null;
sum = null;
squaredSum = null;
}
/**
* @return The name of the Series (if non-empty).
*/
public String getName() {
return name;
}
/**
* @return The unit of measurement for the Observations (if non-empty).
*/
public String getUnit() {
return unit;
}
/**
* Generates the summary statistics for the Sample. For a regular Sample, the
* guaranteed statistics calculated are:
* <ol>
* <li>Count</li>
* <li>Sum</li>
* <li>Mean</li>
* <li>Variance</li>
* <li>Standard Deviation</li>
* </ol>
* The Summary is generated lazily. Therefore, the getSummary() function can be
* used more than once without any degradation of performance. In fact, the
* {@linkplain #toString()} method relies on this.
*
* @return A Sample.Summary object with at least the guaranteed statistics mentioned.
*/
public Summary getSummary() {
if (summary != null) {
return summary;
}
// Add the basic summary statistics that are generally required.
// These do not require the Sample observations to be sorted.
summary = new Summary(this);
summary.addStatistic("Count", format(getCount()));
summary.addStatistic("Sum", format(getSum()));
summary.addStatistic("Mean", format(getMean()));
summary.addStatistic("Variance", format(getVariance()));
summary.addStatistic("Std Dev", format(getStdDev()));
return summary;
}
/**
* @return The size of this Sample, or the number of Observations in this Sample.
*/
public int getCount() {
return values.length;
}
/**
* @return The sum of all the observations in the Sample.
*/
public double getSum() {
if (sum != null) {
return sum;
}
double value = 0;
for (double item : values) {
value += item;
}
sum = value;
return value;
}
/**
* @return The arithmetic mean (average) of all the observations in the Sample.
*/
public double getMean() {
return getSum() / getCount();
}
/**
* The variance in the sample. It is calculated in a manner like (but not exactly):
*
* <pre>
* <code>
* double mean = // mean of observations
* double result = 0;
* for (double obs: observations) {
* result += Math.pow(obs - mean, 2);
* }
* return result / count;
* </code>
* </pre>
* <p>
* Mathematically, {@code var X = sum((x - avg)^2)} where X is the sample, x is an individual
* observation, avg is the arithmetic mean.
* <p>
* NOTE: There is no adjustment made for the decrease in degree of freedom. The effect
* should be negligible because the Sample size is appropriate (at least {@value #MINIMUM_THRESHOLD}.
*
* @return Returns the variance of the all the observations in the Sample.
*/
public double getVariance() {
if (squaredSum != null) {
return squaredSum / getCount();
}
double mu = getMean();
double accumulator = 0;
for (double item : values) {
accumulator += Math.pow(item - mu, 2);
}
squaredSum = accumulator;
return accumulator / getCount();
}
/**
* The Standard Deviation in the Sample. It can be usually calculated in the following manner:
*
* <pre>
* <code>
* double mean = // mean of observations
* double result = 0;
* for (double obs: observations) {
* result += Math.pow(obs - mean, 2);
* }
* return Math.sqrt(result / count);
* </code>
* </pre>
* <p>
* Mathematically, it is the square root of the variation. It is advantageous (and often
* referred to as the Standard Error) because it has the same units as the observations.
* <p>
* NOTE: The formula is not adjusted for the decrease in degree of freedoms. However,
* it should not make a significant difference because the Sample size is guaranteed
* to be at least {@value MINIMUM_THRESHOLD}.
*
* @return The standard deviation of all the observations in the Sample.
*/
public double getStdDev() {
return Math.sqrt(getVariance());
}
public String toString() {
StringBuilder builder = new StringBuilder();
String unitString = stringIsEmpty(unit) ? "" : " " + unit;
for (double observation : values) {
builder.append(observation)
.append(unitString)
.append("\n");
}
return builder.toString() + "\n" + getSummary().toString();
}
/**
* A Summary is a collection of Statistics and their corresponding values. Internally
* it is a {@link Map} that stores the name of the Statistics as keys and the value
* of that Statistic as the value in the Key-Value pair.
*/
static class Summary {
private final Sample owner;
private final Map<String, String> map;
private int maxKeyLength;
private int maxValueLength;
/**
* Create a new Summary. Statistics and their values (as Strings) can be
* added using the {@link #addStatistic(String, String)} method.
*
* @param owner The Sample for which this Summary contains Statistics.
*/
Summary(final Sample owner) {
this.owner = owner;
map = new LinkedHashMap<>();
maxKeyLength = 0;
maxValueLength = 0;
}
/**
* Adds a statistics and its corresponding value to this Summary.
*
* @param statistic The statistic (like mean, median, etc).
* @param value The value corresponding to the statistic.
*/
void addStatistic(final String statistic, final String value) {
String unit = owner.getUnit();
String updatedValue = unit.isEmpty() || statistic.equals("Count")
? value
: value + " " + unit;
map.putIfAbsent(statistic, updatedValue);
maxKeyLength = Math.max(maxKeyLength, statistic.length());
maxValueLength = Math.max(maxValueLength, updatedValue.length());
}
/**
* @param statistic The statistic whose value is sought.
* @return The value of the statistic if it is saved in this Summary, or "Unknown".
*/
String getStatistic(final String statistic) {
return map.getOrDefault(statistic, "Unknown");
}
private static String fitString(final String text, final int width, final boolean left) {
final String prefix = left ? "%-" : "%";
return String.format(prefix + width + "s", text);
}
/**
* @return A String form of the Statistics added to this summary and their values.
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Summary Statistics for Sample: ")
.append(owner.name)
.append("\n\n");
for (Map.Entry<String, String> entry : map.entrySet()) {
builder.append(fitString(entry.getKey(), maxKeyLength, true))
.append(": ")
.append(fitString(entry.getValue(), maxValueLength, false))
.append("\n");
}
return builder.toString();
}
}
}
</code></pre>
<h2>SampleBuilder.java</h2>
<pre class="lang-java prettyprint-override"><code>package in.hungrybluedev.statistics;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
/**
* A Utility class for easy construction of Samples. Observations
* can be added one by one, or all at once. Once a sufficient number
* of observations are entered (see {@linkplain Sample#getThreshold()}
* a sample can be generated.
* <p>
* Generating a sample does not invalidate the previous observations.
* More entries can be added and the consequent samples will contain
* all the observations (new as well as old ones). In such a scenario,
* it is recommended to use the {@linkplain #setName(String)} method
* to create Sample with different names (for the sake of easy organization).
*
* @author Subhomoy Haldar (@HungryBlueDev)
* @noinspection unused, WeakerAccess, UnusedReturnValue
*/
public class SampleBuilder {
private final List<Double> observationList;
private String name;
private String unit;
/**
* Default constructor that creates an internal storage list of
* default size and the name of the sample is set to {@code null}.
* If you want to change the name of the Sample, use the
* {@linkplain #setName(String)} method.
*
* @see Sample#DEFAULT_THRESHOLD
* @see Sample#getThreshold()
*/
public SampleBuilder() {
observationList = new ArrayList<>(Sample.getThreshold());
name = null;
unit = null;
}
/**
* Creates a SampleBuilder and sets the (current) name of the
* Sample to the proposed value. The internal list is of the default size.
*
* @param name The desired name of the Sample.
* @see Sample#DEFAULT_THRESHOLD
* @see Sample#getThreshold()
*/
public SampleBuilder(final String name) {
observationList = new ArrayList<>(Sample.getThreshold());
this.name = name;
}
/**
* Creates a SampleBuilder and sets the (current) name of the
* Sample to the proposed value. The internal list is of the default size.
*
* @param name The desired name of the Sample.
* @param unit The unit of measurement for all the observations in the Sample.
* @see Sample#DEFAULT_THRESHOLD
* @see Sample#getThreshold()
*/
public SampleBuilder(final String name, final String unit) {
observationList = new ArrayList<>(Sample.getThreshold());
this.name = name;
this.unit = unit;
}
/**
* Constructor that takes the desired name of the Sample as well
* as the tentative size of the Sample. This ensures that the value
* of count is at least equal to the threshold value.
*
* @param name The desired name of the Sample.
* @param unit The unit of measurement for all the observations in the Sample.
* @param count The proposed size of the Sample.
* @throws IllegalArgumentException If the count is lower than the threshold.
* @see Sample#DEFAULT_THRESHOLD
* @see Sample#getThreshold()
*/
public SampleBuilder(final String name, final String unit, final int count) {
if (count < Sample.getThreshold()) {
throw new IllegalArgumentException("The count is lower than the threshold.");
}
observationList = new ArrayList<>(count);
this.name = name;
this.unit = unit;
}
/**
* Sets the name of the Sample being built to the proposed value.
*
* @param name The name to be given to the next Sample that is generated.
* @return This SampleBuilder to facilitate chaining of method calls.
*/
public SampleBuilder setName(final String name) {
this.name = name;
return this;
}
/**
* Sets the unit of measurement for the observations in the Sample.
*
* @param unit The unit of measurement for all the observations in the Sample.
* @return This SampleBuilder to facilitate chaining of method calls.
*/
public SampleBuilder setUnit(final String unit) {
this.unit = unit;
return this;
}
/**
* Adds an observation value to the list. The requirement is that the
* value must be finite (not infinite or NaN).
*
* @param observation The observation to add to the current Sample.
* @return This SampleBuilder to facilitate chaining of method calls.
* @throws IllegalArgumentException If the observation is not finite.
* @see Double#isFinite(double)
*/
public SampleBuilder addObservation(final double observation)
throws IllegalArgumentException {
if (!Double.isFinite(observation)) {
throw new IllegalArgumentException("Observations must be finite.");
}
observationList.add(observation);
return this;
}
/**
* Adds a chunk of observations to the current Sample. The criterion for individual
* observations holds: only finite values (no infinite or NaN).
*
* @param observationChunk The chunk of observations to add to the current Sample.
* @return This SampleBuilder to facilitate chaining of method calls.
* @throws IllegalArgumentException If any of the observations are not finite.
*/
public SampleBuilder addObservations(final double[] observationChunk)
throws IllegalArgumentException {
for (double observation : observationChunk) {
addObservation(observation);
}
return this;
}
/**
* Adds a {@link Collection} of observations to the current Sample. The criteria
* for valid observations include:
* <ol>
* <li>Must be non-null</li>
* <li>Must be finite (not infinite or NaN)</li>
* </ol>
*
* @param observationsCollection The collections of elements to be added.
* @return This SampleBuilder to facilitate chaining of method calls.
* @throws IllegalArgumentException If any of the items is null, infinite or NaN.
*/
public SampleBuilder addObservations(final Collection<Double> observationsCollection)
throws IllegalArgumentException {
for (Double observation : observationsCollection) {
Objects.requireNonNull(observation);
addObservation(observation);
}
return this;
}
/**
* @return The current count of observations in the internal list.
*/
public int getCount() {
return observationList.size();
}
/**
* @return A Sample instance from the observations collected thus far.
* @throws IllegalStateException If the sample size does not exceed the minimum required threshold.
* @see Sample#DEFAULT_THRESHOLD
* @see Sample#getThreshold()
*/
public Sample buildSample()
throws IllegalStateException {
final int count = getCount();
if (count < Sample.getThreshold()) {
throw new IllegalStateException("The sample does not contain enough observations.");
}
Double[] rawOutput = observationList.toArray(new Double[count]);
double[] observations = new double[count];
for (int i = 0; i < count; i++) {
observations[i] = rawOutput[i];
}
return new Sample(name, unit, observations);
}
}
</code></pre>
<h2>SampleTest.java</h2>
<pre class="lang-java prettyprint-override"><code>package in.hungrybluedev.statistics;
import java.util.Arrays;
import java.util.Random;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertThrows;
public class SampleTest {
private static final int TEST_COUNT = 100;
private static final int RANDOM_MAX = 1000;
private static final double EPSILON = 1e-10;
private static Random random = new Random();
private static int getRandomSampleSize() {
return random.nextInt(RANDOM_MAX) + Sample.getThreshold();
}
/**
* Implementation of the classic Fischer-Yates shuffle algorithm.
*
* @param observation The array of observations to be shuffled.
*/
private static void shuffle(final double[] observation) {
for (int i = observation.length - 1; i >= 1; i--) {
int j = random.nextInt(i);
swap(observation, i, j);
}
}
private static void swap(double[] observation, int i, int j) {
double temp = observation[i];
observation[i] = observation[j];
observation[j] = temp;
}
@org.testng.annotations.Test
public void testThreshold() {
int[] testThresholds = {30, 20, 10, 40, 100, 2};
for (int threshold : testThresholds) {
// The point is to ensure that the sample size is never below
// the minimum threshold. If it is lower, then an exception
// should be thrown. Otherwise everything should work.
if (threshold < Sample.MINIMUM_THRESHOLD) {
assertThrows(IllegalArgumentException.class, () -> Sample.setThreshold(threshold));
} else {
Sample.setThreshold(threshold);
assertEquals(Sample.getThreshold(), threshold);
}
}
Sample.setThreshold(Sample.DEFAULT_THRESHOLD);
}
@org.testng.annotations.Test
public void testGetSummary() {
String expected = "Summary Statistics for Sample: Test sample\n" +
"\n" +
"Count : 50\n" +
"Sum : 1225.000 km\n" +
"Mean : 24.500 km\n" +
"Variance: 208.250 km\n" +
"Std Dev : 14.431 km\n";
SampleBuilder builder = new SampleBuilder("Test sample", "km");
for (int i = 0; i < 50; i++) {
builder.addObservation(i);
}
Sample sample = builder.buildSample();
assertEquals(sample.getSummary().toString(), expected);
}
@org.testng.annotations.Test
public void testGetCount() {
for (int i = 1; i <= TEST_COUNT; i++) {
final int n = getRandomSampleSize();
final double[] observations = new double[n];
Sample sample = new Sample("Sample number " + i, null, observations);
assertEquals(sample.getCount(), n);
}
}
@org.testng.annotations.Test
public void testGetSum() {
for (int i = 1; i <= TEST_COUNT; i++) {
final int n = getRandomSampleSize();
final double[] observations = new double[n];
for (int j = 0; j < n; j++) {
observations[j] = (j + 1);
}
shuffle(observations);
Sample sample = new Sample("Sample number " + i, "cm", observations);
assertEquals(sample.getSum(), n * (n + 1.0) / 2, EPSILON);
}
}
@org.testng.annotations.Test
public void testGetMean() {
for (int i = 1; i <= TEST_COUNT; i++) {
final int n = getRandomSampleSize();
final double[] observations = new double[n];
for (int j = 0; j < n; j++) {
observations[j] = (j + 1);
}
shuffle(observations);
Sample sample = new Sample("Sample number " + i, "A", observations);
assertEquals(sample.getMean(), (n + 1.0) / 2, EPSILON);
}
}
@org.testng.annotations.Test
public void testZeroVariance() {
for (int i = 1; i <= TEST_COUNT; i++) {
final int n = getRandomSampleSize();
final double[] observations = new double[n];
final double constant = random.nextInt(RANDOM_MAX);
Arrays.fill(observations, constant);
Sample sample = new Sample("Sample number " + i, "J", observations);
assertEquals(sample.getVariance(), 0, EPSILON);
assertEquals(sample.getStdDev(), 0, EPSILON);
}
}
@org.testng.annotations.Test
public void testStdDev() {
for (int i = 1; i <= TEST_COUNT; i++) {
final int n = getRandomSampleSize() * 2;
final double[] observations = new double[n];
double mean = random.nextDouble();
double error = random.nextDouble();
int factor = -1;
for (int j = 0; j < n; j++) {
observations[j] = mean + error * factor;
factor *= -1;
}
Sample sample = new Sample("Gaussian Sample #" + i, null, observations);
assertEquals(sample.getMean(), mean, EPSILON);
assertEquals(sample.getStdDev(), error, EPSILON);
}
}
@org.testng.annotations.Test
public void testTestSampleToString() {
String expectedResult = "0.0 km\n" +
"1.0 km\n" +
"2.0 km\n" +
"3.0 km\n" +
"4.0 km\n" +
"5.0 km\n" +
"6.0 km\n" +
"7.0 km\n" +
"8.0 km\n" +
"9.0 km\n" +
"10.0 km\n" +
"11.0 km\n" +
"12.0 km\n" +
"13.0 km\n" +
"14.0 km\n" +
"15.0 km\n" +
"16.0 km\n" +
"17.0 km\n" +
"18.0 km\n" +
"19.0 km\n" +
"20.0 km\n" +
"21.0 km\n" +
"22.0 km\n" +
"23.0 km\n" +
"24.0 km\n" +
"25.0 km\n" +
"26.0 km\n" +
"27.0 km\n" +
"28.0 km\n" +
"29.0 km\n" +
"30.0 km\n" +
"31.0 km\n" +
"32.0 km\n" +
"33.0 km\n" +
"34.0 km\n" +
"35.0 km\n" +
"36.0 km\n" +
"37.0 km\n" +
"38.0 km\n" +
"39.0 km\n" +
"40.0 km\n" +
"41.0 km\n" +
"42.0 km\n" +
"43.0 km\n" +
"44.0 km\n" +
"45.0 km\n" +
"46.0 km\n" +
"47.0 km\n" +
"48.0 km\n" +
"49.0 km\n" +
"\n" +
"Summary Statistics for Sample: Test sample\n" +
"\n" +
"Count : 50\n" +
"Sum : 1225.000 km\n" +
"Mean : 24.500 km\n" +
"Variance: 208.250 km\n" +
"Std Dev : 14.431 km\n";
SampleBuilder builder = new SampleBuilder("Test sample", "km");
for (int i = 0; i < 50; i++) {
builder.addObservation(i);
}
Sample sample = builder.buildSample();
assertEquals(sample.toString(), expectedResult);
}
}
</code></pre>
<h1>Specific Requests</h1>
<ol>
<li>You are free to critique any part of the code. Don't hold back.</li>
<li>At this stage, the library is (obviously) feature incomplete. What could I add to extend its capabilities?</li>
<li>Are there any long-term concerns that might require significant alterations to fix? If so, I'd like to consider them sooner rather than later.</li>
<li>Any unit tests that are a <em>must</em>? Or would be nice to have?</li>
</ol>
|
[] |
[
{
"body": "<p>I have some suggestions for you.</p>\n\n<h1>Code Review</h1>\n\n<h2>Sample class</h2>\n\n<p>In my opinion, the variables and the constants declarations should be moved to the top of the class / block.</p>\n\n<h3>format(double) method</h3>\n\n<p>Instead of using the <code>java.lang.String#format</code> to format the double value, I suggest that you use the <code>java.text.NumberFormat</code>. This class will allow you to set the required precision by calling the <code>java.text.NumberFormat#setMaximumFractionDigits</code> method.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>double value = 0.123456;\nint precision = 3;\n\nNumberFormat nf = NumberFormat.getInstance();\nnf.setMaximumFractionDigits(precision);\n\n\nSystem.out.println(nf.format(value));\nSystem.out.println(String.format(\"%.\" + precision + \"f\", value));\n</code></pre>\n\n<h3>getSum, getMean, getVariance and getStdDev methods</h3>\n\n<p>In my opinion, those methods are a bit confusing, since they do more than returning the value and can be confused with traditional getters. I suggest that you pick a name that explain the action, example <code>updateAndFetchSum</code>.</p>\n\n<h3>toString method</h3>\n\n<p>I suggest that you add the <code>java.lang.Override</code> annotation when overriding the method, since I think it's easier to spot the inheritance when reading the code.</p>\n\n<h1>Unit Tests</h1>\n\n<p>In my opinion, the biggest issues to make the unit tests will be the uses of the static methods and variables in your code, since they will keep their states between tests. In your place, I would try to replace them with <code>composition</code> and a class for the utils, it will make the code more mockable and easier to test.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T07:03:51.423",
"Id": "467061",
"Score": "0",
"body": "I agree with NumberFormat. I seemed to have forgotten about how useful it is. I'll definitely fix that. Also, I'll try to make the Sample immutable and decouple the threshold and precision from the main class. Thanks for the great answer! I'll post a follow-up soon."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T02:54:48.720",
"Id": "238079",
"ParentId": "238062",
"Score": "3"
}
},
{
"body": "<h2>Threshold</h2>\n\n<p>Having static variables can cause issues with reusability and threading. I think having a default minimum threshold is reasonable. However, I'd consider removing the ability to change this default and make it possible to set a threshold when constructing the builder. This gives more control to the point that a sample is being constructed. It also makes it easier to use the class from different locations within the same application that may have different requirements around the number of observations needed.</p>\n\n<h2>Streams</h2>\n\n<p>Your buildSample creates a copy of observations as an array of <code>Double</code>, then copies it into an array of <code>double</code> in order to pass it to your sample class. Rather than doing that, you might want to consider using the stream api to simplify the code. Instead of:</p>\n\n<blockquote>\n<pre><code>Double[] rawOutput = observationList.toArray(new Double[count]);\ndouble[] observations = new double[count];\n\nfor (int i = 0; i < count; i++) {\n observations[i] = rawOutput[i];\n}\n</code></pre>\n</blockquote>\n\n<p>You end up with:</p>\n\n<pre><code>double[] observations = observationList.stream().mapToDouble(d->d).toArray();\n</code></pre>\n\n<h2>Boxing</h2>\n\n<p>Your builder is based around a reference type <code>Double</code>, however the way that you add to the list is based around a native type <code>double</code>. Combine this with an <code>addObservations</code> that allows a collection of reference types and you're iterating through a list of <code>Double</code> converting it to <code>double</code> to process it for adding then back to <code>Double</code> again to put it in the list. This feels wrong to me, I'd code the addObservation around the type it needs for storage, or provide an overload so that you can call to reduce the amount of boxing/unboxing, particularly from within a loop.</p>\n\n<h2>Builder responsibility / Constructor responsibility</h2>\n\n<p>Your <code>Sample</code> class has a package private constructor, so my assumption is that your intention is to always use the <code>SampleBuilder</code> for construction. If this is the case then it's unclear which class is responsible for the sample size. The <code>buildSample</code> method throws an exception:</p>\n\n<blockquote>\n<pre><code>if (count < Sample.getThreshold()) {\n throw new IllegalStateException(\"The sample does not contain enough observations.\");\n}\n</code></pre>\n</blockquote>\n\n<p>In the <code>Sample</code> constructor throws a different exception: </p>\n\n<blockquote>\n<pre><code>if (observations.length < threshold) {\n throw new IllegalArgumentException(\n \"The sample size is the less than the threshold: \"\n + observations.length + \" < \" + threshold\n );\n}\n</code></pre>\n</blockquote>\n\n<p>This seems like unnecessary confusion. Personally, I'd consider moving the constructor validation out of the <code>Sample</code> class, so that the complexity of validating the number of samples / creating a valid unit / name sits within the builder class and the <code>Sample</code> can assume it's being used correctly, since it's internal. If your intention is to reuse the <code>Sample</code> class with other things in the same package, then I'd remove all of the validation from the builder and just let the <code>Sample</code> constructor handle it. I would however try to avoid doing the same validation twice in different places, particularly with different outcomes.</p>\n\n<h2>Unit Tests</h2>\n\n<p>Generally you want to unit tests to be fast, isolated and repeatable. Your manipulation of the shared static threshold can break the isolation. </p>\n\n<p>Your use of random to generate your samples can break the repeatability of your tests. Whilst sending in a random sample and getting out the right answer can be comforting, if you do find an issue, you're going to want to investigate and fix it. At the moment, you'll get an assertion error, telling you for example that two means don't match. Without information about the sample, it's going to be very difficult for you to repeat the test, you'll just know there's <em>something</em> wrong in an unknown scenario. So, if you do want to use random samples, make sure that if an error occurs you feedback what sample you were using.</p>\n\n<p>A lot of your tests run 100 times, with different sample sizes. This is obviously going to be slower than running each test case a lower number of times. If I run an operation against sample sizes of 101 and 102, I'd expect them both to work, however I wouldn't usually write a unit test for both values, I'd focus on areas that I think might be relevant (for example, empty sample, below threshold, at threshold, just over threshold, well over threshold, possibly a really large sample). This means less wasted cycles and again, improved repeatability.</p>\n\n<p><strong>assertEquals(expected, actual)</strong></p>\n\n<p>You're using assert the wrong way round, which will be misleading if you encounter any errors, it should be the expected argument first.</p>\n\n<p><strong>Builder / no builder</strong></p>\n\n<p>Some of your tests use builders, some directly create a sample. If the intention is for the builder to always be used from client code, then it should be used for all of your unit tests, you shouldn't short-cut it and create a <code>Sample</code> class without the builder because the test becomes unrealistic, it's on a par with calling private methods. There's little point testing a class in a state that clients can't get it into.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T07:01:21.107",
"Id": "467060",
"Score": "0",
"body": "I'll definitely take your suggestions into consideration. All the points suggested are great, especially the Stream solution. I need to refactor now when there's relatively less work invested, rather than later. Thanks for such a great answer! I'll post a follow-up soon."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T08:22:28.090",
"Id": "238091",
"ParentId": "238062",
"Score": "3"
}
},
{
"body": "<p>I'm concentrating only on the API design.</p>\n\n<pre><code>final long timeStart = System.currentTimeMillis();\n...\nfinal long timeEnd = System.currentTimeMillis();\nbuilder.addObservation((timeEnd - timeStart) / 1000.0);\n</code></pre>\n\n<p>This code is IMHO a bit too cumbersome for the user and allows for programming errors to mess up the statistics. The user has to remember to do the logging exactly the same way every time. I would like to see the time keeping offloaded to the statistics library itself.</p>\n\n<p>For example with an observation token that has an internal callback to the builder. This would have the benefit that if you don't want to gather statistics, you could control it with a config switch and just return a common dummy token that does nothing (zero memory footprint, practically no processor time wasted).</p>\n\n<pre><code>final Observation observation = builder.startObservation();\n...\nobservation.finish();\n</code></pre>\n\n<p>Possibly with a Runnable:</p>\n\n<pre><code>builder.observe(() -> {\n ...\n});\n</code></pre>\n\n<p>Once this is implemented, the recording of the time stamps should be made with a <code>Supplier<Long></code> if the user wants to log a specific time source other than <code>System.currentTimeMillis()</code>. This feature would also allow efficient unit testing.</p>\n\n<pre><code>private Supplier<Long> timeSupplier = () -> System.currentTimeMillis();\n\npublic void setTimeSupplier(Supplier<Long> timeSupplier) {\n this.timeSupplier = timeSupplier;\n}\n</code></pre>\n\n<p>Instead of fractions of seconds as <code>double</code>s I would just log the smallest available time units (millis) and convert them to human readable format during formatting.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T14:22:23.873",
"Id": "466984",
"Score": "1",
"body": "I think that 'time' was really just an example of how the library might be used. It could be used for other things, such as transaction amount, distance ran etc, which is why one of the tests seems to do some analysis on km."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T06:58:10.250",
"Id": "467058",
"Score": "0",
"body": "I think the custom mechanism for easy runtime measurement is definitely very helpful. However, @forsvarir is right because I want my library to be as general as possible. I might implement your suggestions in a separate class or package though; it's too cool to ignore."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T21:28:10.300",
"Id": "467102",
"Score": "0",
"body": "The Supplier<Long> can return anything, not just time. And it can be a double instead of long if you think it's more flexible."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T11:22:43.803",
"Id": "238104",
"ParentId": "238062",
"Score": "4"
}
},
{
"body": "<h1>1) Persistant Data Structure</h1>\n\n<p>I think this could be a good use case for a <a href=\"https://en.wikipedia.org/wiki/Persistent_data_structure\" rel=\"nofollow noreferrer\">Persistant Data Structure</a>.</p>\n\n<h3>1.1) The Reason</h3>\n\n<p>The builder gives you some flexibility to observe at multiple locations</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>SampleBuilder builder = new SampleBuilder(\"Runtimes\", \"s\");\n\n// observe\nfor (...) { / * ... */ }\n\nSample runtimes = builder.buildSample();\nSystem.out.println(runtimes);\n\n// observe again\nfor (...) { / * ... */ }\n\nSample moreRuntimes = builder.buildSample();\nSystem.out.println(moreRuntimes);\n</code></pre>\n</blockquote>\n\n<p>The down sight of the two inconspicuous <code>System.out.println(...)</code> is that you calculate everything multiple times. In the following <em>sum</em> and <em>mean</em> will calculate the first time:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>Sample runtimes = builder.buildSample();\nSystem.out.println(runtimes);\n</code></pre>\n</blockquote>\n\n<p>Now you calculate again <em>sum</em> and <em>mean</em> and <strong>can't reuse the previous calculation</strong> from the first calculation because you create with <code>builder.buildSample()</code> a new <code>Sample</code> instance:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>Sample moreRuntimes = builder.buildSample();\nSystem.out.println(moreRuntimes);\n</code></pre>\n</blockquote>\n\n<h3>1.2) Possible Solution with a Persistant Data Structure</h3>\n\n<p>I created an <a href=\"https://repl.it/repls/ViciousRareSearch\" rel=\"nofollow noreferrer\">executable example on repl.it</a>, where a <code>Sample</code> can be <code>Empty</code> or <code>NonEmpty</code>. Please excuse that I ignored the threshold.. </p>\n\n<p>For an <code>Empty</code> Sample we know that the sum, mean and count would be 0. If we add a new observation to an <code>Empty</code> Sample the sum will be the observation, the count will be 1 and the mean is 0: </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public Sample add(double observation) {\n return new NonEmptyBuilder().withIncrementedCount(0)\n .withSum(observation)\n .withMean(0)\n .build();\n}\n</code></pre>\n\n<p>Adding a new observation to a <code>NonEmpty</code> Sample we need to increment the count, add the previous sum with the new observation and calculate the mean: </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public Sample add(double observation) {\n return new NonEmptyBuilder().withIncrementedCount(count)\n .withSum(sum + observation)\n .withMean(mean / count)\n .build();\n}\n</code></pre>\n\n<p>Since we calculate always the sum based on the previous sum we do not calculate observation multiple times:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>// ...\nSystem.out.println(sample.sum());\n\nsample = sample.add(...);\n\n// reuses previous sum and does not need to loop through all observations\nSystem.out.println(sample.sum()); \n</code></pre>\n\n<h1>2) Separate the Summary from the Sample</h1>\n\n<p>Beside the fact that it violates the <a href=\"https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle\" rel=\"nofollow noreferrer\">Open-Close-</a> and the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single-Responsibility-Principle</a> you limit the client to print a summary in a prescribed format to the console.</p>\n\n<p>It would be nice to choose the output and the format of the output.</p>\n\n<h1>3) Sample has a low cohesion</h1>\n\n<p>This point is related to the previous. </p>\n\n<p>In general a class should have a <a href=\"https://en.wikipedia.org/wiki/Cohesion_(computer_science)#High_cohesion\" rel=\"nofollow noreferrer\">high cohesion</a>.</p>\n\n<p>When we look into <code>Sample</code> we can see the following methods:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>private static String format(final double value) {\n return String.format(\"%.\" + precision + \"f\", value);\n}\n\nprivate static String format(final int value) {\n return String.valueOf(value);\n}\n\nprivate static boolean stringIsEmpty(final String text) {\n return text == null || text.isEmpty();\n}\n</code></pre>\n</blockquote>\n\n<p>All are private because they don't belong to an API of a <code>Sample</code> and they are only used maximal at two spots which is a sign that they maybe don't belong into <code>Sample</code>. </p>\n\n<h1>4) No Independent Samples</h1>\n\n<p>The client cant have different instances of a <code>Sample</code> with different <code>threshold</code> and <code>precision</code> what limits the client in his/her possibilities. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T07:07:11.133",
"Id": "467062",
"Score": "0",
"body": "This is a neat idea to use Persistent Data Structures! I like the simple implementation that you provided too. I'll use this and even decouple the threshold and precision from the main class. Maybe delegate them to different classes. I'll post a follow-up soon!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T18:42:09.250",
"Id": "238126",
"ParentId": "238062",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T19:23:52.670",
"Id": "238062",
"Score": "4",
"Tags": [
"java",
"unit-testing",
"statistics",
"library"
],
"Title": "Statistics Library with Sample, SampleBuilder and Tests"
}
|
238062
|
<p>I have a class that needs to provide access to an internal <code>List<int></code> member. The functions that use this class need to be able to work with that list, mutating the contents and sorting/filtering the list etc, without changing the internal list in the class object. Having a method that provides a copy of the list instead of a getter seems like the logical solution.</p>
<p>I know that the following code works, but as this seems like a somewhat common design pattern I wanted to know if there was a better or more standard way to design the signature or body of this type of function to inform/enforce its use. Perhaps it should use <code>ref</code> or <code>out</code>? Would it be better to just return a copy instead of doing it via a parameter?</p>
<pre><code>private List<int> integerList = new List<int>();
public void CopyReportsList(List<int> outList)
{
outList = this.integerList.ToList();
}
</code></pre>
|
[] |
[
{
"body": "<p>Take it on its readability deference : </p>\n\n<p>Example 1 (Current Usage): </p>\n\n<pre><code>CopyReportsList(outList);\n</code></pre>\n\n<p>Example 2 (Common):</p>\n\n<pre><code>var outList = GetIntegerList();\n</code></pre>\n\n<p>Example 3 (Common): </p>\n\n<pre><code>CopyReportsList(source, out outList);\n</code></pre>\n\n<p>if you compare them, you'll see that anyone would read example 1 at first would think it's meant to copy <code>outList</code> into another collection, which means, there is some other process going. While example 2 and 3 would be read as having an identical copy of current stored list.</p>\n\n<p>So, no one would ever use example 1, because it's unclear, confusing, and not a good practice. </p>\n\n<p>Example 2 would be clearer, and it's most used. </p>\n\n<p>Example 3 would be also used in some cases, but mostly, its most known uses for <code>TryParse</code> and <code>Copy</code> functionalities. </p>\n\n<p>For your case, example 2 would be fine, but you would need to use a <code>Property</code> instead. </p>\n\n<pre><code>public IEnumerable<int> Integers \n{\n get { return integerList; }\n}\n</code></pre>\n\n<p>usage : </p>\n\n<pre><code>var data = new SomeClass();\n\nvar list = data.Integers;\n</code></pre>\n\n<p>But you have to name your property to something that would be related to your logic functionality. Also, for returning type, if the return type is type of collection or array, try to use <code>IEnumerable</code> interface it would be better. (same as I did in the property example). The reason is that <code>IEnumerable</code> interface is implemented on all collections types including arrays. So, this would give your implementation more flexibility by providing the minimal understanding of the returning type which would be easier to extend to other collections types for current and long term running. </p>\n\n<p>another note on this line : </p>\n\n<pre><code>outList = this.integerList.ToList();\n</code></pre>\n\n<p><code>integerList</code> is a <code>List<int></code>, so there is no need to use <code>ToList()</code>, what are you doing is converting a list to a list ! which is redundant and unnecessary. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T21:35:33.857",
"Id": "466906",
"Score": "0",
"body": "Thanks for the input. The reason i was calling ToList() is so that it makes a copy of the list instead of returning a references to the list. I don't want the internal list to be changed by external function, but those function need to be able to freely work with their own \"copy\" of the list they are given."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T21:41:11.427",
"Id": "466907",
"Score": "1",
"body": "@user3776749 it won't change the source for the current context. It'll return a copy of the source. So, if you do this `return integerList;` or `var outList = this.integerList;` it'll make an identical copy, any changes on `outList` won't be applied on `integerList`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-02T13:52:22.833",
"Id": "467240",
"Score": "0",
"body": "@iSR5 that is not true at all, lists are reference types, returning wont make any copy you need to call `ToList()` or reinitialize the list with `new List<>(IEnumerable<>)` if you want to avoid this behavior. Furthermore, if your values were also reference type you would need to make a deep copy, to avoid any external changes being reflected on the collection. But for this case the aforementioned suggestions will do the job."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T21:13:58.710",
"Id": "238064",
"ParentId": "238063",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "238064",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T19:34:57.407",
"Id": "238063",
"Score": "-1",
"Tags": [
"c#"
],
"Title": "Copy a C# list into an out Parameter for better encapsulation"
}
|
238063
|
<h2>The problem:</h2>
<p>I have some text that I go through line-by-line, if I find a line containing the keyword <code>DATA_TYPE_1</code> and/or <code>DATA_TYPE_2</code>, I know all the following values are that data type. What I do right now is keep track of if the last keyword I saw was <code>DATA_TYPE_1</code> or <code>DATA_TYPE_2</code> (or in the case where I see both in the same line, I stop checking to see if the other data type keyword has come up, I just keep track of the order the keywords came up from left to right)</p>
<pre><code>ALL VALUES BELOW ARE DATA_TYPE_1
1
2
3
4
NOW ALL VALUES ARE DATA_TYPE_2
5
6
7
8
</code></pre>
<p>data_type_1 values = 1, 2, 3, and 4</p>
<p>data_type_2 values = 5, 6, 7, and 8</p>
<pre><code>ALL VALUES ARE DATA_TYPE_2
1
2
3
NOW VALUES ARE DATA_TYPE_1
4
5
6
</code></pre>
<p>data_type_2 values = 1, 2, and 3</p>
<p>data_type_1 values = 4, 5, 6</p>
<pre><code>ALL VALUES BELOW ARE DATA_TYPE_2 AND DATA_TYPE_1, RESPECTIVELY
1 2
3 4
5 6
7 8
</code></pre>
<p>data_type_1 values = 2, 4, 6, and 8</p>
<p>data_type_2 values = 1, 3, 5, and 7</p>
<hr>
<h2>The approach</h2>
<p>Essentially, I look at a given line and use regular expressions to identify <code>DATA_TYPE_1</code> and <code>DATA_TYPE_2</code>. If both are present, I want to know what order they are in. <strong>I want to clean up some of the logic statements if possible of the following function <code>determine_data_type</code></strong>:</p>
<p><strong>edit</strong>: did not realize I should include the regexes -- for explaining what I am trying to so I referred to the two keywords I am looking for as <code>data_type_1</code> and <code>data_type_2</code> but they are actually <code>achiral</code> and <code>chiral</code>; I've included the regexes below</p>
<pre class="lang-py prettyprint-override"><code>import re
REGEX_1 = re.compile(r'(?i)(\bachiral\b)')
REGEX_2 = re.compile(r'(?i)(\bchiral\b)')
def determine_data_type(text, type_array):
'''
Determines which keywords are present in a given string
Parameters:
text: str
Line of text to examine for DATA_TYPE_1 and DATA_TYPE_2
type_array: List[bool]
Initial type of data
Returns:
type_array: List[bool]
Updated type_array
A list of bools: [type_1, type_2, both_types]
If only type_1 is present: [True, False, False]
If only type_2 is present: [False, True, False]
If type_1 and type_2 appear: [True, False, True] or [False, True, True]
depending on which appears first
'''
type_1, type_2, both_types = type_array
# only see if data type needs updating if
# (1) haven't found data type keywords yet or
# (2) I expect the data type to switch from 1 to 2 or vice versa
if not both_types:
if not type_1 and not type_2:
if re.search(REGEX_1, text):
type_1 = True
if re.search(REGEX_2, text):
type_2 = True
if type_1 and type_2:
both_types = True
# get the positions of both words
type_1_pos = re.search(REGEX_1, text).start()
type_2_pos = re.search(REGEX_2, text).start()
if type_1_pos > type_2_pos:
# type_1 is not first
type_1 = False
else:
type_2 = False
elif type_1 and not type_2:
if re.search(REGEX_2, text):
type_2 = True
if not re.search(REGEX_1, text):
type_1 = False
else:
both_types = True
elif type_2 and not type_1:
if re.search(REGEX_1, text):
type_1 = True
if not re.search(REGEX_2, text):
type_1 = False
else:
both_types = True
return type_array
if __name__ == '__main__':
text = ["blah, blah blah",
"OTHER COLUMN HEADER achiral chiral",
"blah blah blah"]
# at first we don't know what type of data we are looking at
data_type = [False, False, False] # [type_1, type_2, both_types]
for line in text:
data_type = determine_data_type(line, data_type)
print(data_type) #[True, False, True]
</code></pre>
<hr>
<h2>Advice needed</h2>
<p>As you can see, I repeat a lot of the code above - like when I search twice for both <code>type_1</code> and <code>type_2</code> in order to get the position of each word when they appear on the same line. Also, in the cases where only <code>type_1</code> is <code>True</code> or only <code>type_2</code> is <code>True</code>, I was trying to think of a way to only search for the "Falsey" one, and if it's found, quickly check if the "Truthy" one happens to be there as well</p>
<p>I am using Python 3.6</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T02:24:46.437",
"Id": "466927",
"Score": "0",
"body": "What version of Python are you using? Add the “Python-2.x” or “Python-3.x” tag to your question. But also, please tell us what the exact version is: 2.7, 3.4, 3.8"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T02:35:37.057",
"Id": "466928",
"Score": "0",
"body": "`regex_1` and `regex_2` are not included in your code. You are also missing the `import re` which you must be using. Include your entire code or your question may be put on hold."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T03:55:55.157",
"Id": "466929",
"Score": "0",
"body": "@AJNeufeld thanks, updated with all relevant information (including that I am using Python 3.6)"
}
] |
[
{
"body": "<h1>Data Representation</h1>\n\n<p>I think <code>[False, True, True]</code> is a very confusing representation of both data types in \"reverse\" order. Let's revisit that.</p>\n\n<p>You have 2 types, and a line which may contain none, one, or both types.</p>\n\n<pre><code>types = {'DATA_TYPE_1', 'DATA_TYPE_2'}\n\nline = \"ALL VALUES BELOW ARE DATA_TYPE_2 AND DATA_TYPE_1, RESPECTIVELY\";\n</code></pre>\n\n<p>Let's use a regex that will split the <code>line</code> up into individual words. </p>\n\n<pre><code>import re\nword_re = re.compile(r'\\w+')\n</code></pre>\n\n<p>Now, what we want to do is extract all the words from the <code>line</code>, keeping only the ones that represent the <code>types</code> we are looking for, keeping the words in the order they were in the <code>line</code>:</p>\n\n<pre><code>order = [word for word in word_re.findall(line) if word in types]\n\n>>> order\n['DATA_TYPE_2', 'DATA_TYPE_1']\n</code></pre>\n\n<p>Or, with your updated question, it looks like there aren't commas or other punctuation to get in the way of a simple <code>line.split()</code>, so we can omit the regular expression:</p>\n\n<pre><code>types = {\"achiral\", \"chiral\"}\nline = \"OTHER COLUMN HEADER achiral chiral\"\norder = [word for word in line.split() if word in types]\n\n>>> order\n['achiral', 'chiral']\n</code></pre>\n\n<p>If you produced this, it is quite clear what the field order is. If you also maintained a <code>list</code> of all the types which have been found, adding new types as they are found, when the list size reaches the number of types (2) then you've encountered all (both) of the types.</p>\n\n<pre><code>def determine_data_type(text, found):\n found.extend(word for word in text.split() if word in types)\n return len(found) == len(types)\n\ntypes = {\"achiral\", \"chiral\"}\nline = \"OTHER COLUMN HEADER achiral chiral\"\nfound = []\nall_found = determine_data_type(line, found)\n\n>>> found\n['achiral', 'chiral']\n>>> all_found\nTrue\n</code></pre>\n\n<hr>\n\n<h1>Enums</h1>\n\n<p>Using strings to represent data types is awkward. When you have a finite set of named items, <code>enum</code> should be the tool you reach for.</p>\n\n<pre><code>from enum import Enum\n\nType = Enum('Type', 'ACHIRAL CHIRAL')\n\ndef determine_data_type(text, found):\n found.extend(Type[word] for word in text.upper().split() if word in Type.__members__)\n return len(found) == len(Type)\n\nline = \"OTHER COLUMN HEADER achiral chiral\"\nfound = []\nall_found = determine_data_type(line, found)\n\n>>> found\n[<Type.ACHIRAL: 1>, <Type.CHIRAL: 2>]\n>>> all_found\nTrue\n</code></pre>\n\n<p>Being able to use <code>Type.ACHIRAL</code> or <code>Type.CHIRAL</code> as named constants in your program, instead of using strings which can be mistyped, will result in safer and faster programs.</p>\n\n<hr>\n\n<p>From comment:</p>\n\n<blockquote>\n <p>Let's say that the keywords I am looking for are not exactly always the same. Instead of just chiral and achiral the words I am looking for could also be chirality and achirality or chiral and not chiral or chiral and a-chiral. With these two keywords it's hard to come up with examples, but in the case where maybe it's more difficult to keep a list of finite set of words to look for but the keywords all have a similar 'root' word, how would you modify your approach?</p>\n</blockquote>\n\n<p>With <code>chiral</code>/<code>chirality</code> and <code>achiral</code>/<code>achirality</code>, you could just use the <code>Enum</code> type's ability to have type-aliases.</p>\n\n<pre><code>from enum import Enum\n\nclass Type(Enum):\n CHIRAL = 1\n ACHIRAL = 2\n CHIRALITY = 1\n ACHIRALITY = 2\n\ndef determine_data_type(text, found):\n found.extend(Type[word] for word in text.upper().split() if word in Type.__members__)\n return len(found) == len(Type)\n\nline = \"OTHER COLUMN HEADER achiral chirality\"\nfound = []\nall_found = determine_data_type(line, found)\n\n>>> found\n[<Type.ACHIRAL: 2>, <Type.CHIRAL: 1>]\n>>> all_found\nTrue\n</code></pre>\n\n<p><code>len(Type) == 2</code> because there are only two enum values, but <code>len(Type.__members__) == 4</code> because there are 4 names for those two values, so you can safely use variants of the name.</p>\n\n<p>For <code>not chiral</code> or <code>a-chiral</code>, you'll have to use a regex that detects the whole term, with spaces and/or special characters.</p>\n\n<pre><code>regex = re.compile(r\"(?i)\\b(not |a-|a)?chiral(ity)?\\b\")\n\nfor term in regex.findall(text):\n ...\n</code></pre>\n\n<p>You can't use <code>Type[term]</code> to map those terms to the <code>Type(Enum)</code> directly, since the enum identifiers can't have spaces or special characters. But you could create your own dictionary to map the terms to the enum types.</p>\n\n<pre><code>Types = {'not chiral': Type.ACHIRAL,\n 'a-chiral': Type.ACHIRAL,\n ...\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T15:29:17.970",
"Id": "467001",
"Score": "0",
"body": "I learned a lot from this. Thank you!\n\nI have a follow up question - let's say that the keywords I am looking for are not exactly always the same. Instead of just `chiral` and `achiral` the words I am looking for could also be `chirality` and `achirality` or `chiral` and `not chiral` or `chiral` and `a-chiral`. With these two keywords it's hard to come up with examples, but in the case where maybe it's more difficult to keep a list of finite set of words to look for but the keywords all have a similar 'root' word, how would you modify your approach?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T06:16:15.567",
"Id": "238086",
"ParentId": "238065",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "238086",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T21:36:47.627",
"Id": "238065",
"Score": "2",
"Tags": [
"python",
"performance",
"beginner",
"algorithm",
"python-3.x"
],
"Title": "Looking for specific words in a string and noting the order"
}
|
238065
|
<p>I have two closely related questions:</p>
<p>1) I have a mixed PHP array. Not mixed in that it contains strings, floats, booleans etc. but mixed in that it is a hybrid indexed / associative array. Most of its entries look like they are from an indexed array while the very last entry looks like it's from an associative array:</p>
<pre><code>$myFruit = [
'apple',
'banana',
'cherry',
'Other_Fruit' => ['Damson', 'Elderberry', 'Fig', 'Grapefruit']
];
</code></pre>
<p>It strikes me that this is a <strong>bad idea</strong>, but I need to confirm that first... Is it a bad idea to have an array in PHP which is a hybrid between an indexed array and an associative array? Or is this not entirely uncommon practice in PHP?</p>
<p>2) If it <strong><em>is</em></strong> a bad idea (as I suspect), what is the best way to tidy it up, given that I want to preserve the entry <code>['Other_Fruit']</code> exactly as it is.</p>
<p>At present I am using the following:</p>
<hr>
<h2>Code to Review:</h2>
<pre><code>$myFruit2 = [];
$myFruit2['Fruitbowl'] = $myFruit;
$myFruit2['Other_Fruit'] = $myFruit2['Fruitbowl']['Other_Fruit'];
unset($myFruit2['Fruitbowl']['Other_Fruit']);
$myFruit = $myFruit2;
</code></pre>
<hr>
<p>This leaves me with:</p>
<pre><code>$myFruit = [
'Fruitbowl' => ['apple', 'banana', 'cherry'],
'Other_Fruit' => ['Damson', 'Elderberry', 'Fig', 'Grapefruit']
];
</code></pre>
<p>which is <em>exactly</em> what I want... only I'm not sure I'm getting there the most efficient / fastest / best practice way.</p>
<p>Ultimately, I am looking to maximise speed, efficiency and process optimisation and minimise garbage collection or other processes which might slow the operation down. I want to tidy up the array as quickly as possible. I am uncertain, for example, if there are any (much faster) native functions that I ought to be using instead.</p>
<p><em>(Subsequent thought: Maybe I can achieve this via <strong>destructuring</strong>...?)</em></p>
<hr>
<p><strong>Addendum:</strong></p>
<p>If I understand correctly, some users are objecting to the fact that in my code to be reviewed (above), I have used example variable names above instead of the actual variable names I am using.</p>
<p><em>I cannot comprehend the nature of this objection</em>, but nevertheless, in response to it, here is the example (again):</p>
<pre><code>$myFruit2 = [];
$myFruit2['Fruitbowl'] = $myFruit;
$myFruit2['Other_Fruit'] = $myFruit2['Fruitbowl']['Other_Fruit'];
unset($myFruit2['Fruitbowl']['Other_Fruit']);
$myFruit = $myFruit2;
</code></pre>
<p>And here is the actual code:</p>
<pre><code>$Codesheets = [];
$Codesheets['Static'] = $moduleBlock['Codesheets'];
$Codesheets['Dynamic'] = $moduleBlock['Static']['Dynamic'];
unset($Codesheets['Static']['Dynamic']);
$moduleBlock['Codesheets'] = $Codesheets;
</code></pre>
<p>It will be apparent that the example I gave above is a 1:1 representation of the actual code.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T00:39:16.103",
"Id": "467051",
"Score": "1",
"body": "Reason off-topic: `Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site.` You have provided generic data and asking for general best practice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T01:01:00.897",
"Id": "467052",
"Score": "1",
"body": "How can anyone propose to accurately advise on \"_maximise speed, efficiency and process optimisation and minimise garbage collection or other processes which might slow the operation down_\" when you haven't shown realistic sample data nor how you intend to process it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T08:49:26.893",
"Id": "467126",
"Score": "1",
"body": "Providing clear sample data is one requirement here. A missing requirement is how you intend to use the data. The fact that you are satisfied by slepic's answer is not a factor in deciding if your question is on-topic. How can anyone confidently advise on the best data structure if we don't know how it will be used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T09:06:15.953",
"Id": "467130",
"Score": "4",
"body": "This is where you are failing to understand my motivations. I am not here to put anyone down, I am here to help CodeReview up. Data structures are best designed by considering how the data will be used. You are taking offense to my feedback, but what you should do is pay attention to what I am asking for and improve your question by telling us all the ways you intend to use the data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T09:26:19.897",
"Id": "467133",
"Score": "0",
"body": "Additionally, tell us where this data is coming from. I assume that you are not hardcoding all this data, since you are favoring `unset()` in your answer. Why is the data initially structured the way that it is? We should probably inform you about how to handle the data when it is declared at the very earliest point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-02T12:10:29.930",
"Id": "467226",
"Score": "0",
"body": "_\"You are taking offense to my feedback.\"_ No, I am communicating to you that it looks like you are more concerned with referee-ing the question than trying to answer it. And yet several others have already endeavoured to answer the question and one of those answers has been accepted. So, it might be worth contemplating if the question is in need of being refereed? We can see that the question has now been shut down. If it had been shut down before being answered, so that it had neither answers nor an accepted answer, would that make this document more useful either to myself or anyone else?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-02T17:46:37.807",
"Id": "467267",
"Score": "1",
"body": "I've reviewed enough code to know that `foo`/`bar` and other bogus-names \"my real code is just like it\", never, never, never ends well. Reviewers aren't here to answer specific questions about best practices illustrated with sample code, they're here to review *real*, working code with a purpose, and tell you if best practices are taking a beating. The difference, is that in that latter scenario, the code to be reviewed becomes *central*, not just an illustration of a situation encountered in code that needs an \"answer\" - CR doesn't do \"answers\", we do *reviews*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T08:41:50.443",
"Id": "467687",
"Score": "1",
"body": "I cannot post an answer until the question is reopened and I cannot vote to reopen without knowing 1. What is producing these arrays to be begin with (can they be improved)? and 2. How do you intend to use the data going forward? Are you making a `<select>`? two `<select>`'s? are you using it as a lookup / validator / white/black list? In the absence of all of this completely relevant information, I could only _guess_ would be most appropriate for your project."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T11:04:02.260",
"Id": "467703",
"Score": "0",
"body": "I think we must be coming at this from different angles @mickmackusa (hence the initial conflict, which I am sorry for). Your position (if I understand it correctly) is that you need information which you currently don't have. My struggle is trying to understand what difference such information could possibly make. eg. In answer to your question: _\"What is producing these arrays to begin with?\"_ the answer is _\"A function.\"_ I (genuinely) don't understand how this moves things along. Can I rewrite the function? Of course. Do I want to? No. Why not? Visual aesthetic / usability etc. [1/3]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T11:06:28.600",
"Id": "467704",
"Score": "0",
"body": "Then, to be honest, I don't really understand some of the following questions: `<select>`, `lookup`, `validator`, `white/black list` - I don't understand what any of these are, so, initially, at least, I would say: _\"No, I don't want to use the array for any of these, I just want a conventional array structure for future general purpose use.\"_ [2/3]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T11:08:31.820",
"Id": "467706",
"Score": "0",
"body": "So, while you're asking me _\"Where is the array coming from?\"_ and _\"Where is the array going?\"_, I'm thinking: _\"I don't care about any of that. I just want to ensure I'm building a robustly structured, future-proofed array.\"_ [3/3]"
}
] |
[
{
"body": "<p>What you are doing here is denoting metadata about the fruit entries through the data structure. If it works for you then it’s certainly an acceptable solution. However, it will make the code much more readable and meaningful if you can get that metadata out of the structure and represent it directly. Someone unfamiliar with it (which might well be you a few months from now :)) is going to be able to figure out what everything means much more quickly. </p>\n\n<p>To do that, you need to answer the question “what make fruit belong in the ‘other fruit’ array”? Making a guess based on the example data, is it a question of the ‘Other Fruit’ being less common? </p>\n\n<p>If so, you could potentially use more meaningful names in your example last array. </p>\n\n<pre><code>$myFruit = [\n 'common' => [\n 'apple',\n 'banana',\n 'cherry',\n ],\n'rare' => [\n 'Damson',\n 'Elderberry',\n 'Fig',\n 'Grapefruit',\n ],\n];\n</code></pre>\n\n<p>A few notes in comparing this with what you have:</p>\n\n<ol>\n<li><code>array()</code> and <code>[]</code> do the exact same thing and are interchangeable. There is no reason to use <code>array()</code> at the very top level. </li>\n<li>Doing <code>array([‘Fruitbowl’] => […])</code> make the key an array, which I don’t think you want. Rather, you likely want <code>array(‘Fruitbowl’=>[…])</code>, which is the same as <code>[‘fruitbowl’ => […]]</code></li>\n</ol>\n\n<p>All of this said, any multidimensional array is a good opportunity to think about writing a class to represent the data and incorporate an object. Something to keep in mind if any more complexity creeps into this array. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T23:38:40.640",
"Id": "466920",
"Score": "0",
"body": "My apologies, I didn't make it sufficiently clear which part of my question was the Code to Review. I have edited the question to indicate it much more clearly. To restate my two questions: 1) Is a hybrid associative / indexed array a bad idea; and 2) what is the best approach to transform the former into a \"non-mixed\" associative (or even an indexed) array?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T23:08:40.890",
"Id": "238070",
"ParentId": "238066",
"Score": "3"
}
},
{
"body": "<p>Aha. Cracked it.</p>\n\n<p>What I was looking for ultimately wasn't so much <em>destructuring</em>, but might be termed <em>\"restructuring\"</em>.</p>\n\n<p><strong>Input:</strong></p>\n\n<pre><code>$myFruit = [\n 'apple',\n 'banana',\n 'cherry',\n 'Other_Fruit' => ['Damson', 'Elderberry', 'Fig', 'Grapefruit']\n];\n</code></pre>\n\n<p><strong>Operation:</strong></p>\n\n<pre><code>$myFruit = [\n 'Fruitbowl' => $myFruit,\n 'Other_Fruit' => $myFruit['Other_Fruit']\n];\n\nunset($myFruit['Fruitbowl']['Other_Fruit']);\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<pre><code>$myFruit = [\n 'Fruitbowl' => ['apple', 'banana', 'cherry'],\n 'Other_Fruit' => ['Damson', 'Elderberry', 'Fig', 'Grapefruit']\n];\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T01:02:21.280",
"Id": "467053",
"Score": "3",
"body": "I don't see this post as a _Review_."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T10:01:19.410",
"Id": "238099",
"ParentId": "238066",
"Score": "-1"
}
},
{
"body": "<p>It is often not very useful to have such a mix. It could make sense if you really wanted it to be associative array, but it just so happens that you can have the key strings contain numbers and even consecutive numers starting at zero which make it look like vector because php converts integer string keys to ints.</p>\n\n<p>For example:</p>\n\n<pre><code>$robotsByName = [\n \"0\" => [\"id\" => 0, \"name\" => \"0\"],\n \"1\" => [\"id\" => 1, \"name\" => \"1\"],\n \"2\" => [\"id\" => 2, \"name\" => \"2\"],\n \"johnny5\" => [\"id\" => 3, \"name\" => \"johnny5\"],\n];\n</code></pre>\n\n<p>If you have to deal with the input structure as is because it is not under your control, you could simplify your conversion like this:</p>\n\n<pre><code>$myFruit = [\n 'Fruitbowl' => \\array_slice($myFruit, 0, \\count($myFruit)-1),\n 'Other_Fruit' => $myFruit['Other_Fruit'],\n];\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T10:15:03.423",
"Id": "466951",
"Score": "1",
"body": "`array_slice()` - perfect. Thank you. Also you've introduced me to _PHP Namespacing_."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T10:02:13.517",
"Id": "238100",
"ParentId": "238066",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "238100",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T21:48:54.190",
"Id": "238066",
"Score": "-5",
"Tags": [
"php",
"array"
],
"Title": "What's the best way to tidy up a PHP array with both indexed entries and associative entries?"
}
|
238066
|
<p>I prepared a method to make possible to select elements of the array except for some indexes.</p>
<pre><code>def array_except(array, *indexes)
indexes =
indexes
.flat_map { |e| e.is_a?(Range) ? e.to_a : e }
.map { |e| e.negative? ? e + array.length : e }
array.values_at(*((0...array.length).to_a - indexes))
end
</code></pre>
<p>It works in such a way:</p>
<pre><code>> a = ["a", "b", "c", "d", "e", "f", "g", "h"]
array_except(a, 1, -1, 2..3, -4..-2)
=> ["a"]
> array_except(a, 1, 2)
=> ["a", "d", "e", "f", "g", "h"]
> array_except(a, -2..-1)
=> ["a", "b", "c", "d", "e", "f"]
</code></pre>
<p>I feel like it might be done with a lower level of complexity.
I spent a day playing with <code>#each_with_object([])</code> but can't find the proper way.
Maybe someone has any thoughts?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T21:43:27.427",
"Id": "467046",
"Score": "0",
"body": "Welcome to Code Review! Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 5 → 3"
}
] |
[
{
"body": "<p>The main concern with this implementation is not its complexity but the fact that you transform ranges into arrays of indices. It works fine for basic cases, but what if the range is huge? For example,</p>\n\n<pre><code>array_except(a, 1..100000000)\n</code></pre>\n\n<p>works with the significant delay on my laptop already, and infinite range will obviously cause your implementation to never terminate.</p>\n\n<p>But you don't need to iterate over all the numbers within the range to check if the index belongs to it, right? It's enough to just check the boundaries. So, my suggestion is</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>def array_except(array, *indexes)\n array.reject.with_index do |_, i|\n indexes.any? do |index|\n index.is_a?(Range) ? index.cover?(i) : index == i\n end\n end\nend\n\npry(main)> array_except(a, 1..Float::INFINITY) # => [\"a\"]\n</code></pre>\n\n<p>UPD. Please, note: it doesn't work with the negative ranges as is, but can be adjusted if you decide to go in this direction - for example, via converting ranges with the negative boundaries into \"equivalent\" ones with the proper positive boundaries:</p>\n\n<pre><code>def array_except(array, *indexes)\n array.reject.with_index do |_, i|\n indexes.any? do |index|\n if index.is_a?(Range)\n start = index.begin > 0 ? index.begin : array.length + index.begin\n stop = index.end > 0 ? index.end : array.length + index.end\n start <= i && i <= stop \n else\n index == i\n end\n end\n end\nend\n</code></pre>\n\n<p>The final version is more verbose than your initial implementation, but its performance doesn't depend on the size of the ranges provided as an input...</p>\n\n<p>UPD2. If you don't care about the predictable performance and is just interested in a concise implementation, it can be made as short as</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>def array_except(array, *indexes)\n array.reject.with_index { |_, i| indexes.any? { |ind| Array(ind).include?(i) } }\nend\n</code></pre>\n\n<p>UPD3. Good point raised in the comment. The second implementation works terribly bad in the cases when <code>indexes</code> parameter is a huge list of something (integers or ranges) applied to a large list. In this case we get stuck with O(m*n)... To beat this we need something more sophisticated. For example, we can first iterate over all indexes and fill some auxiliary data structure (with O(1) read access) with some \"flags\" (defining what to keep/delete) and then iterate over the array itself and clean it up. Very dirty implementation:</p>\n\n<pre><code>def array_except4(array, *indexes)\n to_delete = Array.new(array.size)\n\n indexes.each do |index|\n case index\n when Range\n start, stop = [index.begin, index.end].sort\n start = start < 0 ? [0, start + array.length].max : [start, array.length - 1].min\n stop = stop < 0 ? [stop + array.length, array.length - 1].min : [stop, array.length - 1].min\n\n (start..stop).each { |k| to_delete[k] = true }\n else\n to_delete[index] = true\n end\n end\n\n array.reject.with_index { |_, i| to_delete[i] }\nend\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T15:06:17.983",
"Id": "466997",
"Score": "0",
"body": "Hey, thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T15:14:06.470",
"Id": "466998",
"Score": "0",
"body": "The main problem that your suggestions is cool for big ranges but a bit slow for a big amount of indices :( You can check UPD"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T16:12:38.987",
"Id": "467006",
"Score": "0",
"body": "Yeah, good point. Updated the answer too."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T09:06:02.920",
"Id": "238096",
"ParentId": "238067",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "238096",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T22:12:19.320",
"Id": "238067",
"Score": "2",
"Tags": [
"beginner",
"array",
"ruby"
],
"Title": "Remove multiple array elements by indices"
}
|
238067
|
<p>I would appreciate feedback especially <strong>if you would be embarrassed</strong> by this code, or if I was on your team and you would expect better and/or you would mention something.</p>
<p>This code was derived from comments made on <a href="https://codereview.stackexchange.com/questions/238011/function-to-add-dom-nodes">Function To Add DOM Nodes</a> (it also lead to new ideas that are unique to this post).</p>
<p>If there are things that could improve performance definitely suggest them (as this code will be called frequently and there will be a lot of data in the browser).</p>
<p>If there is code that should be reused just point it out for me!</p>
<p>This is a javascript function that will accept an array of objects (from a database or websocket) and then spit out HTML <code><ul></code> lists.</p>
<p>I also tried to make the code more robust by allowing an array of objects or a single object to be sent and the object(s) properties to be sent in any order but still maintain order for the HTML output.</p>
<p>The code works -- but I am "self-taught" and always learning. I want to be producing professional looking/behaving code and the feedback here will inform all my projects. </p>
<p>Any insights into style or approach would be welcomed. Get the red marker out!</p>
<h3>Javascript Code</h3>
<pre><code>function addChildren(children) {
// Add a single child to the DOM (if array not passed)
if (!Array.isArray(children)) {
addChildToDOM(children);
return;
}
// Add children to the DOM
for (const child of children) {
addChildToDOM(child);
}
}
// Order the child's DOM elements
/* Places the properties in the correct order -- but you can override the default order.
Noteably if there are missing properties they will appear at the end of the object (to improve code maintainability) */
function orderChildObject(child, propertyOrder= ["group","flags","firstName","lastName","guardian","checkIn","notes","phone"]) {
let objectOrder = new Object();
propertyOrder.forEach(function(value, index, array) {
objectOrder[value] = null;
});
objectOrder = Object.assign(objectOrder, child);
return objectOrder;
}
function addChildToDOM(child) {
// Ensure that required properties exist or stop
if (!(child.hasOwnProperty("firstName") || child.hasOwnProperty("lastName"))
|| !child.hasOwnProperty("phone")) {
// @TODO add warning to user interface
console.log("Child missing required data and could not be displayed");
return;
}
// Ensure properties are ordered properly in the DOM
child = orderChildObject(child);
// Function variables
const childList = document.getElementById("childList"); // Top-level DOM node for child nodes
const childId = child.firstName + child.lastName + child.phone;
let ul; // Top-level of this child's node on the DOM
// Delete child from DOM if overwriting
if(document.getElementById(child.id)){
ul = document.getElementById(child.id);
ul.remove();
}
// Add ul child to DOM
ul = document.createElement("ul"); // Top-level of child on DOM
ul.id = childId;
childList.appendChild(ul);
// Assign <ul> to a group
if (child.group) {
ul.classList.add(child.group);
} else {
ul.classList.add("unassigned");
}
// Add the properties to the child as <li>s
let childKeys = Object.keys(child);
for (let property in childKeys) {
const key = childKeys[property];
const value = child[childKeys[property]];
if(key === "id") continue; // Skip adding the id as an <li> (added as #id on <ul>)
const li = assignChildProperty(key, value);
ul.appendChild(li);
}
function assignChildProperty(key, value) {
// If child property value is an object
if (typeof (value) === "object") {
// Add <li> to child's <ul> node and create a <ul> for this property
const outerli = document.createElement("li");
outerli.classList.add(key);
const ul = document.createElement("ul");
// Run through each of the nested objects and add <li>
for (let property in value) {
const li = document.createElement("li");
li.innerText = value[property]; // the object's value
li.classList.add(key); // the outer object's class key
// if the object is an array, don't add the array index to class
if (!Array.isArray(value)) {
li.classList.add(property); // the object's key
}
// add the <li> to the <ul>
ul.appendChild(li);
}
// add the <ul> to the outer <li> to be returned to the outer <ul>
outerli.appendChild(ul);
return outerli;
}
// If child property is a simple value (ie. string)
const li = document.createElement("li");
li.classList.add(key);
li.innerText = value;
return li;
}
}
</code></pre>
<h3>The input from an AJAX call or a websocket push:</h3>
<pre><code>// example use of data from AJAX database call being implemented
addChildren([
{
group: 'prek',
firstName: "Bobby",
lastName: "Fisher",
group: "prek",
checkIn: "9:14am",
phone: "ewqrqr3452",
},
{
group: "grade1",
firstName: "Anne",
lastName: "Gables",
guardian: {firstName: "Green", lastName: "Gables"},
flags: ['peanuts','bees'],
checkIn: "9:14am",
phone: "ewqrqr3452",
test: "this is a test",
}
]);
// example use of data from a websocket push that would overwrite a node
addChildToDOM( {
id: "BobbyFisherewqrqr3452",
group: "grade1",
firstName: "Bobby",
lastName: "Fisher",
guardian: {firstName: "Green", lastName: "Gables"},
checkIn: "9:14am",
phone: "ewqrqr3452",
test2: "this is a second test",
});
</code></pre>
<h3>HTML Output</h3>
<pre><code><main id="childList"><!-- where the output hooks on to the HTML -->
<ul id="BobbyFisherewqrqr3452" class="prek">
<li class="group">prek</li>
<li class="firstName">Bobby</li>
<li class="lastName">Fisher</li>
<li class="guardian">
<ul>
<li class="guardian firstName">Green</li>
<li class="guardian lastName">Gables</li>
</ul>
</li>
<li class="checkIn">9:14am</li>
<li class="phone">ewqrqr3452</li>
</ul>
</main>
</code></pre>
<p><strong>Note:</strong> I am using Babel for transpiling (added)</p>
|
[] |
[
{
"body": "<p>You have a big problem in your code: Object properties by definition don't have an intrinsic order. What you are doing in <code>orderChildObject</code> may not work. (Strictly speaking the most recent specifications do define an order, but it isn't necessarily insertion order, nor is it used in all cases, nor can you know if the JavaScript engine actually implements it.)</p>\n\n<p>(I don't have time to write more right now. Maybe I can back later.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T11:03:01.670",
"Id": "466959",
"Score": "0",
"body": "I look forward to it!\nI should mention that all the JS code runs through Bable transpiler. Does that make a difference?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T11:20:26.963",
"Id": "466961",
"Score": "0",
"body": "I had been under the impression that using a transpiler might preserver string insertion order -- because of newer JS. However: `Note: Since ECMAScript 2015, objects do preserve creation order for string and Symbol keys. In JavaScript engines that comply with the ECMAScript 2015 spec, iterating over an object with only string keys will yield the keys in order of insertion.` (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T11:21:19.040",
"Id": "466962",
"Score": "0",
"body": "Perhaps I should become more familiar with Maps."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T16:32:50.867",
"Id": "467008",
"Score": "0",
"body": "Just a note: There is 97%+ (93% globably) estimated browser compatibility with the Object.assign() method (which guarantees string keys to be in the order of insertion) and ES6 specifications for the North American market. Most notably is that there is no compatibility with IE. If you're using a different browser and it has been updated in the last 3+ years: it works (except Opera Mini). Each developer will need to decide basd on their project -- this project probably doesn't need > 93% but I will look into maps because: afterall, it's learning! (and can become part of my own best practice)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T09:47:57.793",
"Id": "238098",
"ParentId": "238072",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T23:16:16.973",
"Id": "238072",
"Score": "2",
"Tags": [
"javascript",
"html"
],
"Title": "JS Object In --> HTML Out (from a Noob/hobbyist)"
}
|
238072
|
<p>After watching <a href="https://www.youtube.com/watch?v=QPZ0pIK_wsc" rel="nofollow noreferrer">this video by Tom Scott</a>, I decided to make a program that follows that idea. This is what I came up with:</p>
<pre class="lang-py prettyprint-override"><code># If a number is divisible by the key, add the value
RULES = {
3: "Fizz",
5: "Buzz"
}
def is_divisible(num: int) -> list:
output = []
for divider in RULES:
if (num % divider) == 0:
output.append(RULES[divider])
return output
for num in range(100):
output = is_divisible(num + 1) # Increment num by 1 so it is 1-100 not 0-99
if not output:
print(num + 1)
else:
print("".join(output))
</code></pre>
<p>My whole idea behind the way I made this is because I wanted it to be as expandable as possible. That way if you wanted to change the code to do something different (like the examples at the end of the above video), you could just add it. I would like to know if there is anything I could do to improve its changeableness and if there are any glaring problems that when fixed doesn't affect the changeability of the code.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T20:18:33.527",
"Id": "467041",
"Score": "0",
"body": "`def is_divisible(n: int) -> list: return [RULES[d] for d in RULES if n % d == 0]` :)"
}
] |
[
{
"body": "<p>The name <code>is_divisible</code> could be better.<br>\nAs is, the leading <code>is_</code> makes it look like something that you would use as a test.<br>\ne.g. <code>if is_divisible(…):</code></p>\n\n<hr>\n\n<p>Why is <code>output</code> a list? Wouldn't a string be easier?</p>\n\n<hr>\n\n<p>The multiple <code>num +1</code> looks awkward.</p>\n\n<p>Normally I'd suggest assigning the result to another variable, but in this case the problem is with the <code>range(100)</code>. Instead, say <code>range(1,101)</code>, and then use just <code>num</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T01:37:13.500",
"Id": "238076",
"ParentId": "238073",
"Score": "4"
}
},
{
"body": "<p>In addition to Ray Butterworth’s comments:</p>\n\n<p>The parenthesis are unnecessary in <code>if (num % divider) == 0:</code></p>\n\n<p>The <code>is_divisible</code> function has too much code. Creating a list, then appending to the list in a loop, is an antipattern in Python. Python uses list comprehension to simplify and speed up this operation:</p>\n\n<pre><code>def is_divisible(num: int) -> list:\n return [value for divider, value in RULES.items() if num % divider == 0]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T16:03:55.903",
"Id": "467005",
"Score": "0",
"body": "+1 for list comprehension. It's valuable to have language-agnostic points in answers, but it's also valuable to encourage mastery of the features specific to whichever language is at hand."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T02:16:10.207",
"Id": "238078",
"ParentId": "238073",
"Score": "3"
}
},
{
"body": "<p>You do not provide a testable function that performs the task of returning the desired answer for a specific test case. It is the 'normal number' handling that you intermangled with your test code. The main structure of your program structure should look somewhat like</p>\n\n<pre><code>def fizzbuzz(int):\n #[...]\n return answer\n\nfor num in range(1, 101):\n print(fizzbuzz(num))\n</code></pre>\n\n<p>You are free to do helper functions but you should always provide a complete testable solution.\nCompletely separate the functionality you want to provide from the tests. even split into different files.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T14:29:54.247",
"Id": "466985",
"Score": "1",
"body": "This is actually the best answer, and just got my vote. It targets the most fundamental problem in the original code, which the rest of our answers missed. The only addition I'd make is to give it two parameters, `fizbuzz(num, rules)`, providing an even more general function that could be used in the same program with different sets of rules."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T08:40:54.210",
"Id": "238094",
"ParentId": "238073",
"Score": "9"
}
},
{
"body": "<p>When order of <code>RULES</code> matter, prefer a list of tuples instead of a dict as a dict's order might change depending of the version. You can iterate through the tuple with <code>for divider, value in RULES</code></p>\n\n<p>If all <code>value</code>s have to be capitalized, use <code>str.capitalize</code> in case you don't provide proper capitalization by mistake.</p>\n\n<p>Prefer <code>for num in range(1, 100 + 1):</code> instead of using <code>num + 1</code> each time. It's really easy to forget the <code>+ 1</code> and <code>num + 1</code> is confusing.</p>\n\n<p>As @RayButterworth mentioned, <code>is_divisible</code> is a bit awkward. You aren't exactly checking if a number is divisible. You are checking the rules. So use a name like <code>check_rules</code></p>\n\n<p>Instead of using <code>\"\".join(output)</code> each time you use <code>check_rules</code>, convert <code>output</code> to a string inside the <code>check_rules</code> function.</p>\n\n<p>This can be done using the idea @AJNeufeld mentioned.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>return \"\".join(value for divider, value in RULES if num % divider == 0)\n</code></pre>\n\n<p>Use all the parts you wouldn't want to run if imported inside a <code>if __name__ == '__main__'</code> statement.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>output = check_rules(num)\n\nif not output:\n print(num)\nelse:\n print(output)\n</code></pre>\n\n<p>This part can be a bit simplified with</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>output = check_rules(num)\n\nif not output:\n output = num\n\nprint(output)\n</code></pre>\n\n<p>Here's the final code:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># The case is weird to emphasize the use of str.capitalize\nRULES = [\n (3, \"FiZz\"),\n (5, \"buzz\"),\n (7, \"MUZZ\")\n]\n\n\ndef check_rules(num: int) -> str:\n return \"\".join(value.capitalize() for divider, value in RULES if num % divider == 0)\n\n\nif __name__ == '__main__':\n END = 120\n\n for num in range(1, END + 1):\n output = check_rules(num)\n\n if not output:\n output = num\n\n print(output)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T10:06:07.737",
"Id": "238102",
"ParentId": "238073",
"Score": "7"
}
},
{
"body": "<p>Further to @AJNeufeld's answer, I'll show another Python trick (an empty string is <a href=\"https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-how-is-it-different-from-true-and-false\">Falsy</a> so <code>'' or 4</code> is <code>4</code>), and I suggest you use a list of tuples instead of a dictionary, since its order is guaranteed. All you need is</p>\n<pre><code>RULES = [(3, 'Fizz'), (5, 'Buzz')]\n\ndef fizzbuzz(n):\n output = ''.join([value for factor, value in RULES if n%factor==0])\n return output or n\n\nfor n in range(1, 101): print(fizzbuzz(n))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T16:24:57.770",
"Id": "238118",
"ParentId": "238073",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "238102",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T00:02:44.343",
"Id": "238073",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"fizzbuzz"
],
"Title": "Small FizzBuzz program"
}
|
238073
|
<p>Here is my solution for <a href="https://www.codeabbey.com/index/task_view/blackjack-counting" rel="nofollow noreferrer">CodeAbbey - Blackjack Counting</a></p>
<p>My code passes all tests on Code Abbey but I think I have some poor implementation specifically with my handling of the Aces in the score but otherwise I think I overall used good practices and design. </p>
<pre class="lang-py prettyprint-override"><code>def calculate_player_hand(player_hand_input):
"""Return the score of a player hand"""
# Variable to hold score for a hand
total_player_hand_score = 0
# Dictionary mapping cards to their score value
card_values = {"2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "T": 10, "J": 10, "K": 10, "Q": 10}
# Find score of cards except Aces
for card in player_hand_input:
if card == "A":
continue
else:
total_player_hand_score += card_values[card]
# Return player_hand_score not including Ace card(s)
return total_player_hand_score
# Return the total amount of Aces in a player's hand
def get_aces_count(player_hand_input):
"""Return the count of Aces"""
return player_hand_input.count("A")
# Read in test cases
test_cases = int(input())
# List to hold all total scores
total_scores = []
# Iterate through test cases
for i in range(test_cases):
# Read in player hand
player_hand = input().split()
# Variable to hold number of Aces in player hand
player_score_without_aces = calculate_player_hand(player_hand)
for j in range(get_aces_count(player_hand)):
if 21 - player_score_without_aces < 11:
player_score_without_aces += 1
else:
player_score_without_aces += 11
# Rename variable since value of Aces were added
total_player_score = player_score_without_aces
# Add total score to total_scores list
if total_player_score > 21:
total_scores.append("Bust")
else:
total_scores.append(total_player_score)
# Output all total scores
for total_score in total_scores:
print(total_score, end=" ")
</code></pre>
<p>Thank you. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T12:24:40.713",
"Id": "466968",
"Score": "0",
"body": "What's the score of ace + ace + ten?"
}
] |
[
{
"body": "<p>You do not provide a testable function that performs the task of returning the desired answer for a specific test case. It is the ace handling that you intermangled with your test code. The main structure of your program structure should look somewhat like</p>\n\n<pre><code>def calculate_player_hand(player_hand_input):\n #[...]\n return score\n\ndef read_tests():\n #[...]\n return testcases, answers\n\nfor test, answer in zip(read_tests()):\n assert answer == calculate_player_hand(test)\n</code></pre>\n\n<p>Completely separate the functionality you want to provide from the tests. even split into different files.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T12:42:14.707",
"Id": "466971",
"Score": "0",
"body": "The separation of responsibilities is really elegant to look at. I will try to do this more in the future."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T08:28:34.643",
"Id": "238092",
"ParentId": "238077",
"Score": "5"
}
},
{
"body": "<p>As was mentioned - always do separation of implementation and test cases. </p>\n\n<p>For a better/optimized functionality consider the following actions:</p>\n\n<p><strong><code>calculate_player_hand</code></strong> <em>function</em></p>\n\n<ul>\n<li><p><code>card_values = {\"2\": 2, \"3\": 3, ...}</code> is better defined as top-level constant called <strong><code>CARDS</code></strong>:</p>\n\n<pre><code># Dictionary mapping cards to their score value\nCARDS = {\"2\": 2, \"3\": 3, \"4\": 4, \"5\": 5, \"6\": 6, \"7\": 7, \"8\": 8, \"9\": 9, \"T\": 10, \"J\": 10, \"K\": 10, \"Q\": 10}\n</code></pre></li>\n<li><p>instead of going through redundant variable <code>total_player_hand_score</code> and <code>for</code> loop + <code>continue</code> flow - the entire function can be replaced with concise <code>sum</code> + <em>generator</em> expression approach:</p>\n\n<pre><code>def calculate_player_hand(player_hand_input):\n \"\"\"Return the score of a player hand except Ace card(s)\"\"\"\n # Variable to hold score for a hand\n return sum(CARDS.get(card) for card in player_hand_input if card != 'A')\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p><em>Iterating through test cases</em></p>\n\n<ul>\n<li><p>the condition <code>if 21 - player_score_without_aces < 11:</code> can be replaced with a shorter equivalent <strong><code>if score_without_aces >= 11:</code></strong> (<code>player_score_without_aces</code> renamed to <code>score_without_aces</code>):</p>\n\n<pre><code> for j in range(get_aces_count(player_hand)):\n score_without_aces += 1 if score_without_aces >= 11 else 11\n</code></pre></li>\n<li><p>no need to rename the variable <code>total_player_score = score_without_aces</code> as <strong><code>score_without_aces</code></strong> will contain the last resulting value from the upper <code>for</code> loop:</p>\n\n<pre><code>total_scores.append(\"Bust\" if score_without_aces > 21 else score_without_aces)\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T12:51:14.023",
"Id": "466972",
"Score": "1",
"body": "The optimizations you added are much more desirable. Will try to emulate that in the future. Thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T17:47:54.227",
"Id": "467023",
"Score": "0",
"body": "Adding a comment for the constant CARDS is an indication that your variable name can be improved. Even something simple like CARD_SCORE would make the code more readable."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T09:09:28.150",
"Id": "238097",
"ParentId": "238077",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "238097",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T02:01:52.967",
"Id": "238077",
"Score": "4",
"Tags": [
"python",
"programming-challenge"
],
"Title": "CodeAbbey - Blackjack Counting"
}
|
238077
|
<p>I'm still a beginner, so I'm still learning. I'm trying to take test scores for 3 different students, enter them in an array, then display the name, test scores and the average. Trying to also have reusable code for the average. I'm not even sure I'm going about it the right way. This is what I've got so far. It works, but its probably sloppy. I'm sure there are other ways of doing it, but some constructive criticism would be nice.</p>
<pre><code>static void Main(string[] args)
{
const int STUDENTS = 3;
string[] names = new string[STUDENTS];
names[0] = "Morgan";
names[1] = "Bowie";
names[2] = "Ananya";
Console.WriteLine("Enter test scores for " + names[0]);
const int MORGAN_TEST = 3;
int[] morganScores = new int[MORGAN_TEST];
morganScores[0] = int.Parse(Console.ReadLine());
morganScores[1] = int.Parse(Console.ReadLine());
morganScores[2] = int.Parse(Console.ReadLine());
int sumMorgan = morganScores.Sum();
Console.WriteLine("Enter test scores for " + names[1]);
const int BOWIE_TEST = 5;
int[] bowieScores = new int[BOWIE_TEST];
bowieScores[0] = int.Parse(Console.ReadLine());
bowieScores[1] = int.Parse(Console.ReadLine());
bowieScores[2] = int.Parse(Console.ReadLine());
bowieScores[3] = int.Parse(Console.ReadLine());
bowieScores[4] = int.Parse(Console.ReadLine());
int sumBowie = bowieScores.Sum();
Console.WriteLine("Enter test scores for " + names[2]);
const int ANANYA_TEST = 4;
int[] ananyaScores = new int[ANANYA_TEST];
ananyaScores[0] = int.Parse(Console.ReadLine());
ananyaScores[1] = int.Parse(Console.ReadLine());
ananyaScores[2] = int.Parse(Console.ReadLine());
ananyaScores[3] = int.Parse(Console.ReadLine());
int sumAnanya = ananyaScores.Sum();
double[] average = { MORGAN_TEST, BOWIE_TEST, ANANYA_TEST };
Console.WriteLine(names[0] + " " + morganScores[0] + " " + morganScores[1] + " " + morganScores[2] + " Average score: {0:N2}", sumMorgan / average[0]);
Console.WriteLine(names[1] + " " + bowieScores[0] + " " + bowieScores[1] + " " + bowieScores[2] + " " + bowieScores[3] + " " + bowieScores[4] + " Average score: {0:N2}", sumBowie / average[1]);
Console.WriteLine(names[2] + " " + ananyaScores[0] + " " + ananyaScores[1] + " " + ananyaScores[2] + " " + ananyaScores[3] + " " + " Average score: {0:N2}", sumAnanya / average[2]);
Console.Read();
}
</code></pre>
|
[] |
[
{
"body": "<p>You've got students and their scores here. I assume that student without scores is meaningless, as well as scores without students. It would be nice to combine that data into single object:</p>\n<pre><code>public class StudentScores {\n \n // Auto-property guarantees that student name defined once in constructor\n // and will not accidentally change.\n public string Name { get; }\n \n // Scores count can be different for different students.\n // Private field guarantees that scores will not be messed up by other classes.\n // Otherwise some student could access scores and change them, \n // which would lead to errors.\n private readonly List<int> scores = new List<int>();\n\n public StudentScores(string name) {\n Name = name;\n }\n\n // We still need a method to add scores to our encapsulated list.\n // We could implement Clear() or RemoveAt() public methods later.\n public void AddScore(int score) {\n scores.Add(score);\n }\n\n public double Average() {\n if (scores.Count > 0)\n return scores.Average();\n else\n return 0;\n\n // Or simple: return scores.Count > 0 ? scores.Average() : 0;\n }\n\n // Nicer way to print data: student name and all scores separated by empty space.\n public override string ToString() {\n return $"{Name} {string.Join(" ", scores)}";\n }\n}\n</code></pre>\n<p>Without comments it's only 20 lines long:</p>\n<pre><code>public class StudentScores\n{\n public string Student { get; }\n\n private readonly List<int> scores = new List<int>();\n\n public StudentScores(string student)\n => Student = student;\n\n public void AddScore(int score)\n => scores.Add(score);\n\n public double Average()\n => scores.Count > 0 ? scores.Average() : 0;\n\n public override string ToString()\n => $"{Student} {string.Join(" ", scores)}";\n}\n</code></pre>\n<p>Now your syntax in Main is much nicer:</p>\n<pre><code>static void Main(string[] args) {\n\n string[] names = {"Morgan", "Bowie", "Ananya"};\n\n var morgan = new StudentScores(names[0]);\n\n // Determine how much scores has student.\n Console.WriteLine("Enter number of test scores for " + names[0]);\n int count = int.Parse(Console.ReadLine());\n \n for (int i = 0; i < count; i++) {\n morgan.AddScore(int.Parse(Console.ReadLine()));\n }\n\n var bowie = new StudentScores(names[1]);\n // ...\n \n var ananya = new StudentScores(names[2]);\n // ...\n\n Console.WriteLine(morgan.ToString() + " Average score: {0:N2}", morgan.Average());\n Console.WriteLine(bowie.ToString() + " Average score: {0:N2}", bowie.Average());\n Console.WriteLine(ananya.ToString() + " Average score: {0:N2}", ananya.Average());\n}\n</code></pre>\n<p>You could improve your Main() further creating single loop for all students:</p>\n<pre><code>static void Main(string[] args) {\n\n string[] names = {"Morgan", "Bowie", "Ananya"};\n List<StudentScores> scores = new List<StudentScores>();\n\n foreach(var name in names) \n {\n var student = new StudentScores(name);\n Console.WriteLine($"Enter number of test scores for {name}");\n int count = int.Parse(Console.ReadLine());\n for (int i = 0; i < count; i++)\n student.AddScore(int.Parse(Console.ReadLine()));\n scores.Add(student);\n }\n\n foreach(var score in scores)\n Console.WriteLine($"{score.ToString()}, Average score: {score.Average():N2}");\n</code></pre>\n<p>You could remove Average() method and move calculations directly to ToString(), but I think it's nice to have methods for such things.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T11:26:33.183",
"Id": "466963",
"Score": "1",
"body": "For demonstration purpose, it would be nice if you use block body instead of expression body. Also, it would better if you add a way to expose the scores to be reusable. Also, suggesting of `IEnumerable<int>` over `List<int>` would be a plus."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T08:34:49.293",
"Id": "238093",
"ParentId": "238080",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "238093",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T02:55:01.717",
"Id": "238080",
"Score": "5",
"Tags": [
"c#",
"beginner",
"array"
],
"Title": "Averaging students' scores"
}
|
238080
|
<p>This has been done a thousand times on here already, but here's another binary heap implementation. The implementation is generic in terms of heap elements, allows for injection of any type of comparison strategy via the constructor, and has an extra internal lookup scheme to achieve element removal in O(log(n)) time.</p>
<p>I am looking for overall tips to better utilize the (C#) language, design ideas to improve the structure/performance of this class, or any other feedback. Thanks!</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
namespace GenericHeap
{
/// <summary>
/// A generic heap implementation that allows injection of custom comparison strategies for
/// determining element priority
/// </summary>
/// <typeparam name="T">Type of element that will be stored in the heap</typeparam>
public class Heap<T> where T : IComparable
{
/// <summary>
/// The heap's internal elements
/// </summary>
protected readonly List<T> elements;
/// <summary>
/// A lookup for mapping each heap element value/instance to one or more indices in the internal array
/// </summary>
protected readonly Dictionary<T, HashSet<int>> elementIndexLookup;
private readonly IComparer<T> comparer;
/// <summary>
/// Returns true if there are no elements in the heap, otherwise returns false
/// </summary>
public bool IsEmpty => elements.Count == 0;
/// <summary>
/// Returns the number of elements in the heap
/// </summary>
public int Count => elements.Count;
/// <summary>
/// Constructs a <see cref="Heap{T}"/> with default comparer for type <see cref="T"/>
/// </summary>
public Heap() : this(Comparer<T>.Default)
{
}
/// <summary>
/// Constructs a <see cref="Heap{T}"/> with custom comparer for type <see cref="T"/>
/// </summary>
/// <param name="comparer">The custom comparer to use when determining priority order</param>
public Heap(IComparer<T> comparer)
{
this.comparer = comparer;
this.elements = new List<T>();
this.elementIndexLookup = new Dictionary<T, HashSet<int>>();
}
/// <summary>
/// Removes the highest priority element from the heap and returns it to the caller of <see cref="Poll"/>
/// </summary>
/// <returns>The highest priority element</returns>
/// <exception cref="InvalidOperationException">Thrown when there are no elements in the heap</exception>
public T Poll()
{
if (this.IsEmpty)
{
throw new InvalidOperationException("There are no elements in the heap to poll");
}
var rootIndex = 0;
var lastElementIndex = this.elements.Count - 1;
var root = this.elements[rootIndex];
this.elements[rootIndex] = this.elements[lastElementIndex];
this.elements.RemoveAt(lastElementIndex);
this.BubbleDown(rootIndex);
return root;
}
/// <summary>
/// Inserts an element into the heap
/// </summary>
/// <param name="newElement">The element to insert</param>
public void Insert(T newElement)
{
this.elements.Add(newElement);
var lastIndex = this.elements.Count - 1;
this.AddIndexToLookup(newElement, lastIndex);
this.BubbleUp(this.elements.Count - 1);
}
/// <summary>
/// Gets the highest priority element from the heap without removing it
/// </summary>
/// <returns>The highest priority element</returns>
/// <exception cref="InvalidOperationException">Thrown when there are no elements in the heap</exception>
public T Peek()
{
if (this.IsEmpty)
{
throw new InvalidOperationException("There are no elements in the heap to peek");
}
return this.elements[0];
}
/// <summary>
/// Checks if an element exists in the heap
/// </summary>
/// <param name="element">The element to search for</param>
/// <returns>True if element exists in the heap, otherwise false</returns>
/// <remarks>
/// This method is an O(1) operation due to the usage of an internal element lookup
/// </remarks>
public bool Contains(T element)
{
return this.elementIndexLookup.ContainsKey(element);
}
/// <summary>
/// Removes the first instance of <paramref name="elementToRemove"/> found in the heap
/// </summary>
/// <param name="elementToRemove">The element to remove from the heap</param>
/// <remarks>
/// This method is an O(log(n)) operation due to the usage of an internal lookup for
/// identifying element indices
/// </remarks>
/// <exception cref="ArgumentException">Thrown when <paramref name="elementToRemove"/> does not exist in the heap</exception>
public void Remove(T elementToRemove)
{
if (!this.elementIndexLookup.ContainsKey(elementToRemove))
{
throw new ArgumentException("Element does not exist in the heap");
}
var index = this.elementIndexLookup[elementToRemove].First();
var lastIndex = this.elements.Count - 1;
this.SwapElements(index, lastIndex);
this.RemoveIndexFromLookup(this.elements[lastIndex], lastIndex);
this.elements.RemoveAt(lastIndex);
this.BubbleDown(index);
}
private void BubbleDown(int parentIndex)
{
var leftChildIndex = this.GetIndexOfLeftChild(parentIndex);
var rightChildIndex = this.GetIndexOfRightChild(parentIndex);
var maxIndex = this.elements.Count - 1;
if (leftChildIndex > maxIndex)
{
return;
}
if (rightChildIndex > maxIndex)
{
if (this.IsChildHigherPriority(parentIndex, leftChildIndex))
{
this.SwapElements(parentIndex, leftChildIndex);
}
return;
}
var highestPriorityElementIndex = this.GetHighestPriorityElementIndex(parentIndex, leftChildIndex, rightChildIndex);
if (highestPriorityElementIndex == parentIndex)
{
return;
}
this.SwapElements(parentIndex, highestPriorityElementIndex);
this.BubbleDown(highestPriorityElementIndex);
}
private void BubbleUp(int childIndex)
{
if (childIndex == 0)
{
return;
}
var parentIndex = this.GetParentIndex(childIndex);
if (IsChildHigherPriority(parentIndex, childIndex))
{
this.SwapElements(parentIndex, childIndex);
this.BubbleUp(parentIndex);
}
}
private bool IsChildHigherPriority(int parentIndex, int childIndex)
{
return this.comparer.Compare(this.elements[childIndex], this.elements[parentIndex]) > 0;
}
private int GetHighestPriorityElementIndex(int parentIndex, int leftChildIndex, int rightChildIndex)
{
var isLeftChildHigherPriority = this.IsChildHigherPriority(parentIndex, leftChildIndex);
var isRightChildHigherPriority = this.IsChildHigherPriority(parentIndex, rightChildIndex);
if (isLeftChildHigherPriority && isRightChildHigherPriority)
{
return this.GetHigherPriorityElementIndex(leftChildIndex, rightChildIndex);
}
else if (isLeftChildHigherPriority)
{
return leftChildIndex;
}
else if (isRightChildHigherPriority)
{
return rightChildIndex;
}
return parentIndex;
}
private int GetHigherPriorityElementIndex(int leftElementIndex, int rightElementIndex)
{
if (this.comparer.Compare(this.elements[leftElementIndex], this.elements[rightElementIndex]) > 0)
{
return leftElementIndex;
}
else
{
return rightElementIndex;
}
}
private void SwapElements(int firstIndex, int secondIndex)
{
if (firstIndex == secondIndex)
{
return;
}
var firstElement = this.elements[firstIndex];
var secondElement = this.elements[secondIndex];
this.elements[firstIndex] = secondElement;
this.elements[secondIndex] = firstElement;
this.RemoveIndexFromLookup(firstElement, firstIndex);
this.RemoveIndexFromLookup(secondElement, secondIndex);
this.AddIndexToLookup(this.elements[firstIndex], firstIndex);
this.AddIndexToLookup(this.elements[secondIndex], secondIndex);
}
private void RemoveIndexFromLookup(T element, int index)
{
this.elementIndexLookup[element].Remove(index);
}
private void AddIndexToLookup(T element, int index)
{
if (this.elementIndexLookup.ContainsKey(element))
{
this.elementIndexLookup[element].Add(index);
}
else
{
this.elementIndexLookup.Add(element, new HashSet<int> { index });
}
}
private int GetParentIndex(int childIndex)
{
if (childIndex % 2 == 0)
{
return (childIndex - 2) / 2;
}
else
{
return (childIndex - 1) / 2;
}
}
private int GetIndexOfLeftChild(int currentIndex)
{
return 2 * currentIndex + 1;
}
private int GetIndexOfRightChild(int currentIndex)
{
return 2 * currentIndex + 2;
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T06:33:52.283",
"Id": "466933",
"Score": "2",
"body": "Welcome to Code Review! Nice question."
}
] |
[
{
"body": "<ul>\n<li>The code in question is easy to read and understand. </li>\n<li>You have named your variables and methods well, using the recommended naming and casing styles.</li>\n<li>The code in question is well documented as well. </li>\n<li>You are using braces <code>{}</code> althought they might be optional which <strong>is good</strong> because it prevents hidden and therfor hard to find bugs. </li>\n</ul>\n\n<p>That had been the good news about your code, now we talk about the bad news, but fortunately there aren't any, at least I don't see any. </p>\n\n<p>What bothers me a little and what I wouldn't do is using the <code>this</code> keyword that extensively all over the class.<br>\nThe <code>this</code> keyword is usually used to distinguish methods parameters from local variables/fields. One don't use it everywhere and for sure one shouldn't use it for calling methods. </p>\n\n<p>If you don't plan to inherit/extend this class I don't see any sense for declaring <code>elements</code> and <code>elementIndexLookup</code> as <code>protected</code>. Usually one should choose composition over inheritance. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T13:16:18.227",
"Id": "466973",
"Score": "0",
"body": "the same thoughts when I read the code. specially `this`, its extremely used which is uneeded, but in the other hand, I felt it's just a code habit ! which is understandable, but it gives the attention of an existing of another object with the same name."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T23:10:45.727",
"Id": "467107",
"Score": "0",
"body": "Thanks for the feedback @Heslacher! Definitely went overboard with the `this` keyword for this class, especially since the methods are mostly small. The reason I have this habit is at my workplace, code review is done via Azure DevOps, which shows pull request updates in a manner very similar to here at Code Review Stack Exchange. Our production code is not always concise, so having enforcing a `this` keyword in front of all members prevents any need for mind mapping class members to the current block of code being looked at."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T23:14:25.923",
"Id": "467108",
"Score": "0",
"body": "O and with regards to the `protected` members, I haven't given the full picture here (my bad!). [Here](https://github.com/Alvin-Leung/GenericHeap/blob/master/UnitTests/HeapMock.cs) is the repo containing the rest of the code. I wanted to test the internal array of the `Heap` class by overriding it with a test mock."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T06:48:50.457",
"Id": "238087",
"ParentId": "238085",
"Score": "7"
}
},
{
"body": "<p>I like the idea of the <code>elementIndexLookup</code> but you should be aware of the following:</p>\n\n<blockquote>\n<pre><code> private void RemoveIndexFromLookup(T element, int index)\n {\n this.elementIndexLookup[element].Remove(index);\n }\n</code></pre>\n</blockquote>\n\n<p>When you remove the last index from an elements lookup entry, you should remove the entry from <code>elementIndexLookup</code> else this:</p>\n\n<blockquote>\n<pre><code> public bool Contains(T element)\n {\n return this.elementIndexLookup.ContainsKey(element);\n }\n</code></pre>\n</blockquote>\n\n<p>will be wrong if <code>elementIndexLookup[element].Count == 0</code></p>\n\n<p>and this:</p>\n\n<blockquote>\n <p><code>var index = this.elementIndexLookup[elementToRemove].First();</code></p>\n</blockquote>\n\n<p>will fail with an exception.</p>\n\n<hr>\n\n<p>This</p>\n\n<blockquote>\n<pre><code> private void AddIndexToLookup(T element, int index)\n {\n if (this.elementIndexLookup.ContainsKey(element))\n {\n this.elementIndexLookup[element].Add(index);\n }\n else\n {\n this.elementIndexLookup.Add(element, new HashSet<int> { index });\n }\n }\n</code></pre>\n</blockquote>\n\n<p>can be simplified to:</p>\n\n<pre><code> private void AddIndexToLookup(T element, int index)\n {\n if (!elementIndexLookup.TryGetValue(element, out var indices))\n elementIndexLookup[element] = indices = new HashSet<int>();\n\n indices.Add(index);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T23:02:41.107",
"Id": "467106",
"Score": "1",
"body": "Thanks for finding those bugs. And the refactor to `AddIndexToLookup` is beautifully concise, cheers!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T08:09:03.133",
"Id": "238089",
"ParentId": "238085",
"Score": "10"
}
},
{
"body": "<p>Nice Code!</p>\n\n<p>One simple suggestion. Add a constructor with capacity and initialize the List with that capacity.\nIf you don't have the capacity preinitialize everytime you Add a new element to the list it has to do a resize and that has a time complexity of O(N) so you are losing the O(log N).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T21:21:16.780",
"Id": "467101",
"Score": "0",
"body": "This is especially good advice because because if one uses [Floyd's heap construction](https://en.wikipedia.org/wiki/Heapsort#Variations) it only takes `O(n)` for the initial elements."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T15:57:54.637",
"Id": "238117",
"ParentId": "238085",
"Score": "7"
}
},
{
"body": "<p>Small non-C# side note from me: The code seems over-documented.</p>\n\n<p>Properties like <code>elements</code>, <code>Count</code> or <code>IsEmpty</code> don't need a documentation, in my opinion. They are self-explanatory.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T21:06:21.213",
"Id": "238138",
"ParentId": "238085",
"Score": "2"
}
},
{
"body": "<p>This function can be simplified:</p>\n\n<blockquote>\n<pre><code>private int GetParentIndex(int childIndex)\n{\n if (childIndex % 2 == 0)\n {\n return (childIndex - 2) / 2;\n }\n else\n {\n return (childIndex - 1) / 2;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>This implementation explicitly takes care to divide only even numbers by two, but there is no problem dividing an odd number by two, that will round towards zero. In the case that <code>childIndex</code> is even, <code>(childIndex - 1) / 2</code> would still work. Hypothetically there would be a difference if <code>childIndex</code> is even and non-positive, but that means the parent of the root is being calculated (which does not happen, <code>BubbleUp</code> stops at the root) or that an invalid index (negative) is passed in which would be a bug elsewhere.</p>\n\n<p>Or to summarize, the implementation could be:</p>\n\n<pre><code>private int GetParentIndex(int childIndex)\n{\n return (childIndex - 1) / 2;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T15:07:28.497",
"Id": "238159",
"ParentId": "238085",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "238089",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T06:13:01.393",
"Id": "238085",
"Score": "11",
"Tags": [
"c#",
"object-oriented",
"design-patterns",
"generics",
"heap"
],
"Title": "Generic Heap Implementation in C#"
}
|
238085
|
<p>I'm in need of a simple wrapper for a fixed-size <code>std::vector</code> that can ensure atomic insertion.</p>
<p>Since my only real problem is with atomic insertion and I know beforehand the amount of entries it will have, I don't need any other parallelism related feature.</p>
<p>I am happy to have the initial allocation (<code>std::vector::resize</code>) run from the main thread, so it shouldn't need anything fancy.</p>
<p>Although there are great, free to use parallel vectors available, I think that my particular use case, being fixed size shouldn't require any fancy library (e.g. TBB).</p>
<p>I was thinking about something along these lines:</p>
<pre><code>template <typename T>
class AtomicFixedSizeVector {
public:
// a bunch of passthrough methods here...
inline void reserve(size_t count) {
m_data.resize(count);
//m_data.reserve(count);
}
inline void push_back(const T& entry) {
size_t index = m_count.fetch_add(1, std::memory_order_relaxed);
m_data[index] = entry;
}
// I don't think I need this at all, but just in case
inline size_t size()const {
return m_count.load(std::memory_order_relaxed);
}
private:
std::vector<T> m_data;
std::atomic<size_t> m_count;
};
</code></pre>
<p>It needs to be a wrapper to <code>std::vector</code> since the other parts of code take one.</p>
<p>I thought I'd ask this question as my knowledge of atomics is rather limited, and although it seems ok when executed, it's hard to tell if it's actually going well or I'm being lucky multiple times in a row.</p>
<p>Another question that I have is if I can trust <code>std::vector::reserve</code> to do the allocation on the spot or if it's implementation-dependent. I'm asking because if it allocates on the spot I don't need to override the behavior of <code>std::vector::size</code> and can use a passthrough wrapper there, too.</p>
<p>Please note that this is not a premature optimization but rather a post-mortem one, my insertion could be parallelized but only if it ends up adding onto a single block of entries.</p>
<p>This <code>std::vector</code> block of entries will only store <code>uint32_t</code> in case it helps.</p>
<hr>
<p>Edit: </p>
<p>The current use case is to insert from multiple threads, but this was designed knowing beforehand that by the time the data is accessed, the threads will have been joined.</p>
<p>There is an upper limit on the amount of values to be inserted so the vector will be preallocated before insertion.</p>
|
[] |
[
{
"body": "<p>This thing will work as long as one doesn't <code>push_back</code> beyond the capacity.</p>\n\n<p>I wouldn't call it <code>AtomicFixedSizedVector</code> - I think it's better to name it <code>AtomicFixedCapacityBackInserter</code> or something and let it wrap an iterator of the vector - or pointer towards base of the vector - plus the very same atomic size. That's because this way its name states more clearly and precisely what it does and aims to do.</p>\n\n<p><code>std::vector::reserve</code> is ought to make the allocation and you can access the size of the total allocated amount via <code>capacity</code> function.</p>\n\n<p>However, you should be aware that this is just a safety mechanism and unlikely to be an optimization. It might and probably will perform slower than a single threaded insertion. That's due to cacheline size and mechanism of syncronization of the said cachelines. The efficiency or lackthereof is surely hardware dependant and requires testing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T17:13:03.183",
"Id": "238123",
"ParentId": "238090",
"Score": "2"
}
},
{
"body": "<p>You haven't shown how you intend to use this thing, so it's impossible to say for sure whether it \"works correctly.\" For example, obviously it doesn't work if you're planning to use it like this:</p>\n\n<pre><code>AtomicFixedSizeVector<int> v;\nv.reserve(100);\nstd::thread t1([&]() {\n while (v.size() < 10) v.push_back(42);\n});\nstd::thread t2([&]() {\n while (v.size() < 10) std::this_thread::sleep_for(1ms);\n std::cout << v.m_data[0] << \"\\n\"; // DATA RACE!\n});\n</code></pre>\n\n<hr>\n\n<p>Obviously it won't compile if your type <code>T</code> isn't default-constructible. You could address that idiomatically by adding</p>\n\n<pre><code>static_assert(std::is_default_constructible_v<T>);\n</code></pre>\n\n<p>to the top of the class body — thus hopefully reassuring the client-programmer that the crazy template error message they just got was <em>intended</em>, and not a bug.</p>\n\n<hr>\n\n<p>Your <code>reserve</code> method can only be called once, and <code>m_count</code> increases monotonically. Think about whether to implement a <code>clear()</code> method, and what it might do. Think about whether <code>reserve()</code> should reset <code>m_count</code> to zero or not.</p>\n\n<p>My kneejerk reaction is that <code>reserve</code> shouldn't exist at all, and that you should force the user to construct the container with the right capacity to begin with:</p>\n\n<pre><code>explicit AtomicFixedSizeVector(int capacity);\n</code></pre>\n\n<hr>\n\n<p>ALX23z is right that what you mean is <code>FixedCapacity</code>, not <code>FixedSize</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T17:35:27.690",
"Id": "467175",
"Score": "0",
"body": "Thanks, I will be sure to remove the reserve as you mentioned and take a note on the static_assertion too. Both answers were equally useful for me, I hope you don't mind I accepted the first one, I don't think I can accept both. :("
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T20:06:22.517",
"Id": "238133",
"ParentId": "238090",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "238123",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T08:13:15.567",
"Id": "238090",
"Score": "4",
"Tags": [
"c++",
"c++11",
"multithreading",
"thread-safety",
"atomic"
],
"Title": "Atomic fixed-size parallel std::vector wrapper"
}
|
238090
|
<p>This is the function I've wrote to filter a two-dimension array.
I use it mainly on forms with user-defined filter (categories, dates, search bar, etc).
It works fine, but it's ugly.
Do you have any advice?</p>
<pre><code>Function FilterArray(ByVal originalArray As Variant, _
Optional arrayOfColumnToReturn As Variant, _
Optional firstExactMatchColumn As Integer = -1, Optional firstExactMatchValue As Variant, _
Optional secondExactMatchColumn As Integer = -1, Optional secondExactMatchValue As Variant, _
Optional thirdExactMatchColumn As Integer = -1, Optional thirdExactMatchValue As Variant, _
Optional firstColumnToExclude As Integer = -1, Optional firstValueToExclude As Variant, _
Optional secondColumnToExclude As Integer = -1, Optional secondValueToExclude As Variant, _
Optional thirdColumnToExclude As Integer = -1, Optional thirdValueToExclude As Variant, _
Optional firstColumnIsBetween As Integer = -1, Optional firstLowValue As Variant, Optional firstHighValue As Variant, _
Optional secondColumnIsBetween As Integer = -1, Optional secondLowValue As Variant, Optional secondHighValue As Variant, _
Optional thirdColumnIsBetween As Integer = -1, Optional thirdLowValue As Variant, Optional thirdHighValue As Variant, _
Optional partialMatchColumnsArray As Variant = -1, Optional partialMatchValue As Variant) As Variant
FilterArray = -1
If Not IsArray(originalArray) Then Exit Function
Dim firstRow As Long
Dim lastRow As Long
Dim firstColumn As Long
Dim lastColumn As Long
Dim row As Long
Dim col As Long
Dim filteredArrayRow As Long
Dim partialCol As Long
firstRow = LBound(originalArray, 1)
lastRow = UBound(originalArray, 1)
firstColumn = LBound(arrayOfColumnToReturn)
lastColumn = UBound(arrayOfColumnToReturn)
' If the caller don't pass the array of column to return I create an array with all the columns and I preserve the order
If Not IsArray(arrayOfColumnToReturn) Then
ReDim arrayOfColumnToReturn(LBound(originalArray, 2) To UBound(originalArray, 2))
For col = LBound(originalArray, 2) To UBound(originalArray, 2)
arrayOfColumnToReturn(col) = col
Next col
End If
' If the caller don't pass an array for partial match check if it pass the spacial value 1, if true the partial macth will be performed on values in columns to return
If Not IsArray(partialMatchColumnsArray) Then
If partialMatchColumnsArray = 1 Then partialMatchColumnsArray = arrayOfColumnToReturn
End If
ReDim tempFilteredArray(firstColumn To lastColumn, firstRow To firstRow) As Variant
filteredArrayRow = firstRow - 1
For row = firstRow To lastRow
' Start Exact Match check
If firstExactMatchColumn > -1 Then
If LCase(originalArray(row, firstExactMatchColumn)) <> LCase(firstExactMatchValue) Then GoTo SkipRow
End If
If secondExactMatchColumn > -1 Then
If LCase(originalArray(row, secondExactMatchColumn)) <> LCase(secondExactMatchValue) Then GoTo SkipRow
End If
If thirdExactMatchColumn > -1 Then
If LCase(originalArray(row, thirdExactMatchColumn)) <> LCase(thirdExactMatchValue) Then GoTo SkipRow
End If
' End Exact Match check
' Start Negative Match check
If firstColumnToExclude > -1 Then
If LCase(originalArray(row, firstColumnToExclude)) = LCase(firstValueToExclude) Then GoTo SkipRow
End If
If secondColumnToExclude > -1 Then
If LCase(originalArray(row, secondColumnToExclude)) = LCase(secondValueToExclude) Then GoTo SkipRow
End If
If thirdColumnToExclude > -1 Then
If LCase(originalArray(row, thirdColumnToExclude)) = LCase(thirdValueToExclude) Then GoTo SkipRow
End If
' End Negative Match check
' Start isBetween check
If firstColumnIsBetween > -1 Then
If originalArray(row, firstColumnIsBetween) < firstLowValue Or originalArray(row, firstColumnIsBetween) > firstHighValue Then GoTo SkipRow
End If
If secondColumnIsBetween > -1 Then
If originalArray(row, secondColumnIsBetween) < secondLowValue Or originalArray(row, secondColumnIsBetween) > secondHighValue Then GoTo SkipRow
End If
If thirdColumnIsBetween > -1 Then
If originalArray(row, thirdColumnIsBetween) < thirdLowValue Or originalArray(row, thirdColumnIsBetween) < thirdHighValue Then GoTo SkipRow
End If
' End isBetween check
' Start partial match check
If IsArray(partialMatchColumnsArray) Then
For partialCol = LBound(partialMatchColumnsArray) To UBound(partialMatchColumnsArray)
If InStr(1, originalArray(row, partialMatchColumnsArray(partialCol)), partialMatchValue, vbTextCompare) > 0 Then
GoTo WriteRow
End If
Next partialCol
GoTo SkipRow
End If
' End partial match check
WriteRow:
' Writing data in the filtered array
filteredArrayRow = filteredArrayRow + 1
ReDim Preserve tempFilteredArray(firstColumn To lastColumn, firstRow To filteredArrayRow) As Variant
For col = firstColumn To lastColumn
tempFilteredArray(col, filteredArrayRow) = originalArray(row, arrayOfColumnToReturn(col))
Next col
SkipRow:
Next row
If filteredArrayRow > firstRow - 1 Then
FilterArray = Application.Transpose(tempFilteredArray)
End If
Erase originalArray
Erase arrayOfColumnToReturn
If IsArray(partialMatchColumnsArray) Then Erase partialMatchColumnsArray
If IsArray(tempFilteredArray) Then Erase tempFilteredArray
End Function
</code></pre>
|
[] |
[
{
"body": "<p>I have two solutions for your problem. The first is how I would have tackled the problem before I found the free and fantastic RubberDuck addin for VBA and read all of the really helpful and informative blog articles on OOP.</p>\n\n<p>The second is an OOP solution which allowed me to have some nice fun (on a wet a dismal winter afternoon) with the OOP learnings I've gained from the RubberDuck community. I'll put the OOP solution in a second answer if I have the time.</p>\n\n<p>I suspect that you do not use Option Explicit at the start of your modules as there are undeclared variables in your code. I'd strongly recommend putting Option Explicit at the start of every Module and Class.</p>\n\n<p>Generally your code is quite good in the sense that you have used informative names and have modularised actions. This meant it was pretty easy to refactor.</p>\n\n<p>The issue that is preventing you simplifying your code is that you have a lot of dependencies within the function so moving 'modules' to separate activities would involve a lot of parameter passing, and multiple returns.</p>\n\n<p>A bad point is that you have some gnarly gotos which does obscure what is going on even though I can see the logic behind why you have used gotos in the way you have. Gotos are not necessarily bad but it is always better if we can replace naked gotos with structured gotos (i.e. exit for, exit function etc).</p>\n\n<p>To remove dependencies within the function you need to move from 'Operating with' to 'Operating On'. To do this you need to move the parameters and internal variables to outside of the function. The safest and most helpful way of doing this is to capture the parameters and variables in their own UDTs which will be at module scope and which, because they are encapsulated in a Type variable, will not interfere with any other code you have.</p>\n\n<p>This was done by creating the UDTs called FilterParameters and FilterState their respective module level variables of p and s respectively (to minimise typing). I then went through and renamed everything inside the function so that it was prefixed with either p. or s. as appropriate. Some variables were not needed in the State UDT because they were essentially local to the 'module'.</p>\n\n<p>It was then very simple to break down your function into a number of smaller subs and functions.</p>\n\n<p>The refactored code is below.</p>\n\n<pre><code>Option Explicit\n\nPrivate Type FilterParameters\n\n originalArray As Variant\n arrayOfColumnToReturn As Variant\n firstExactMatchColumn As Long\n firstExactMatchValue As Variant\n secondExactMatchColumn As Long\n secondExactMatchValue As Variant\n thirdExactMatchColumn As Long\n thirdExactMatchValue As Variant\n firstColumnToExclude As Long\n firstValueToExclude As Variant\n secondColumnToExclude As Long\n secondValueToExclude As Variant\n thirdColumnToExclude As Long\n thirdValueToExclude As Variant\n firstColumnIsBetween As Long\n firstLowValue As Variant\n firstHighValue As Variant\n secondColumnIsBetween As Long\n secondLowValue As Variant\n secondHighValue As Variant\n thirdColumnIsBetween As Long\n thirdLowValue As Variant\n thirdHighValue As Variant\n partialMatchColumnsArray As Variant\n partialMatchValue As Variant\n\nEnd Type\n\nPrivate p As FilterParameters\n\n\nPrivate Type FilterState\n\n ' Items here are used in multiple methods.\n ' otherwise the state member was demoted to a local variabel\n firstRow As Long\n lastRow As Long\n firstColumn As Long\n lastColumn As Long\n filteredArrayRow As Long\n tempFilteredArray As Variant\n\nEnd Type\n\nPrivate s As FilterState\n\nPublic Sub SetupFilterParameters()\n\n ' replace your_value with a value or comment out the line to prevent\n ' compile errors for an undeclared variable.\n With p\n\n .originalArray = your_value\n .arrayOfColumnToReturn = your_value\n\n .firstExactMatchColumn = -1\n .firstExactMatchValue = your_value\n .secondExactMatchColumn = -1\n .secondExactMatchValue = your_value\n .thirdExactMatchColumn = -1\n .thirdExactMatchValue = your_value\n\n .firstColumnToExclude = -1\n .firstValueToExclude = your_value\n .secondColumnToExclude = -1\n .secondValueToExclude = your_value\n .thirdColumnToExclude = -1\n .thirdValueToExclude = your_value\n\n .firstColumnIsBetween = -1\n .firstLowValue = your_value\n .firstHighValue = your_value\n .secondColumnIsBetween = -1\n .secondLowValue = your_value\n .secondHighValue = your_value\n .thirdColumnIsBetween = -1\n .thirdLowValue = your_value\n .thirdHighValue = your_value\n\n .partialMatchColumnsArray = your_value\n .partialMatchValue = your_value\n\n End With\n\nEnd Sub\n\nPublic Function FilterArray() As Variant\n\n FilterArray = -1\n\n If Not IsArray(p.originalArray) Then Exit Function\n\n s.firstRow = LBound(p.originalArray, 1)\n s.lastRow = UBound(p.originalArray, 1)\n s.firstColumn = LBound(p.arrayOfColumnToReturn)\n s.lastColumn = UBound(p.arrayOfColumnToReturn)\n\n InitialiseReturnColumns\n InitialisePartialCheck\n\n ReDim s.tempFilteredArray(s.firstColumn To s.lastColumn, s.firstRow To s.firstRow) As Variant\n s.filteredArrayRow = s.firstRow - 1\n\n Dim myRow As Long\n For myRow = s.firstRow To s.lastRow\n\n WriteRow myRow\n\n Next\n\n ' This nextaction seems incomplete as at this point FilterArray is still -1\n ' so we might expect to see an else clause in the test below\n ' where an untransposed array is passed to FilterArray.\n If s.filteredArrayRow > s.firstRow - 1 Then\n FilterArray = Application.WorksheetFunction.Transpose(s.tempFilteredArray)\n End If\n\n p.originalArray = Empty\n p.arrayOfColumnToReturn = Empty\n If IsArray(p.partialMatchColumnsArray) Then p.partialMatchColumnsArray = Empty\n If IsArray(s.tempFilteredArray) Then s.tempFilteredArray = Empty\n\nEnd Function\n\nPublic Sub InitialisePartialCheck()\n ' If the caller don't pass an array for partial match check if it pass the spacial value 1,\n ' if true the partial macth will be performed on values in columns to return\n If Not IsArray(p.partialMatchColumnsArray) Then\n\n If p.partialMatchColumnsArray = 1 Then p.partialMatchColumnsArray = p.arrayOfColumnToReturn\n\n End If\n\nEnd Sub\n\nPublic Sub InitialiseReturnColumns()\n\n ' If the caller don't pass the array of column to return\n ' I create an array with all the columns and I preserve the order\n If Not IsArray(p.arrayOfColumnToReturn) Then\n\n ReDim p.arrayOfColumnToReturn(LBound(p.originalArray, 2) To UBound(p.originalArray, 2))\n\n Dim col As Long\n For col = LBound(p.originalArray, 2) To UBound(p.originalArray, 2)\n\n p.arrayOfColumnToReturn(col) = col\n\n Next col\n\n End If\n\nEnd Sub\n\nPublic Sub WriteRow(ByVal ipRow As Long)\n\n If Not RowValidates(ipRow) Then Exit Sub\n ' Start partial match check\n If IsArray(p.partialMatchColumnsArray) Then\n\n Dim partialCol As Long\n For partialCol = LBound(p.partialMatchColumnsArray) To UBound(p.partialMatchColumnsArray)\n\n If InStr(1, p.originalArray(ipRow, p.partialMatchColumnsArray(partialCol)), p.partialMatchValue, vbTextCompare) > 0 Then\n\n WriteFilteredArrayRow ipRow\n Exit Sub ' Was goto SkipRow\n\n End If\n\n Next\n\n End If\n ' End partial match check\n\nEnd Sub\n\nPublic Sub WriteFilteredArrayRow(ByVal ipRow As Long)\n\n ' WriteRow:\n ' Writing data in the filtered array\n s.filteredArrayRow = s.filteredArrayRow + 1\n ReDim Preserve s.tempFilteredArray(s.firstColumn To s.lastColumn, s.firstRow To s.filteredArrayRow) As Variant\n\n Dim myCol As Long\n For myCol = s.firstColumn To s.lastColumn\n\n s.tempFilteredArray(myCol, s.filteredArrayRow) = p.originalArray(ipRow, p.arrayOfColumnToReturn(myCol))\n\n Next\n\nEnd Sub\n\nPublic Function RowValidates(ByVal ipRow As Long) As Boolean\n ' Start Exact Match check\n RowValidates = False\n If p.firstExactMatchColumn > -1 Then\n If LCase$(p.originalArray(ipRow, p.firstExactMatchColumn)) <> LCase$(p.firstExactMatchValue) Then Exit Function\n End If\n If p.secondExactMatchColumn > -1 Then\n If LCase$(p.originalArray(ipRow, p.secondExactMatchColumn)) <> LCase$(p.secondExactMatchValue) Then Exit Function\n End If\n If p.thirdExactMatchColumn > -1 Then\n If LCase$(p.originalArray(ipRow, p.thirdExactMatchColumn)) <> LCase$(p.thirdExactMatchValue) Then Exit Function\n End If\n ' End Exact Match check\n\n ' Start Negative Match check\n If p.firstColumnToExclude > -1 Then\n If LCase$(p.originalArray(ipRow, p.firstColumnToExclude)) = LCase$(p.firstValueToExclude) Then Exit Function\n End If\n If p.secondColumnToExclude > -1 Then\n If LCase$(p.originalArray(ipRow, p.secondColumnToExclude)) = LCase$(p.secondValueToExclude) Then Exit Function\n End If\n If p.thirdColumnToExclude > -1 Then\n If LCase$(p.originalArray(ipRow, p.thirdColumnToExclude)) = LCase$(p.thirdValueToExclude) Then Exit Function\n End If\n ' End Negative Match check\n\n ' Start isBetween check\n If p.firstColumnIsBetween > -1 Then\n If p.originalArray(ipRow, p.firstColumnIsBetween) < p.firstLowValue Or p.originalArray(ipRow, p.firstColumnIsBetween) > p.firstHighValue Then Exit Function\n End If\n If p.secondColumnIsBetween > -1 Then\n If p.originalArray(ipRow, p.secondColumnIsBetween) < p.secondLowValue Or p.originalArray(ipRow, p.secondColumnIsBetween) > p.secondHighValue Then Exit Function\n End If\n If p.thirdColumnIsBetween > -1 Then\n If p.originalArray(ipRow, p.thirdColumnIsBetween) < p.thirdLowValue Or p.originalArray(ipRow, p.thirdColumnIsBetween) < p.thirdHighValue Then Exit Function\n End If\n ' End isBetween check\n RowValidates = True\n\nEnd Function\n</code></pre>\n\n<p>Unfortunately I don't have you spreadsheet so I can't test the code for correctness but I can say that it compiles without error and has no relevant RubberDuck code inspection warnings.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T11:10:24.370",
"Id": "238155",
"ParentId": "238095",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T08:54:26.667",
"Id": "238095",
"Score": "5",
"Tags": [
"array",
"vba",
"excel"
],
"Title": "Filter a two dimension array"
}
|
238095
|
<p>I'm new to Python, but have experience in a variety of other languages. I've learnt that a code review early on would make sure I don't start with bad habits. Which are more difficult to get out the longer you keep them.</p>
<p>This is a Discord bot for one of my hobby projects.</p>
<pre><code>import os
import random
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
token = os.getenv('DISCORD_TOKEN')
bot = commands.Bot(command_prefix='!')
@bot.command(name='ability', aliases=['a', 'ab'], help='Roll an ability check. Parameters: ability [no. of heroic dice].')
async def ability(ctx, ability:int, heroic:int=0):
if ability < -5 or ability > 5:
await ctx.send('Invalid ability value "{}". Must be between -5 and +5'.format(ability))
return
if heroic < 0 or heroic > 5:
await ctx.send('Invalid heroic dice amount "{}". Must be between 0 and 5 (3 + 2 ritual dice)'.format(heroic))
return
dice = 2 + abs(ability) + heroic
keep_dice = 2 + heroic
if (ability < 0):
keep = 'lowest'
else:
keep = 'highest'
roll = []
for x in range(0, dice):
roll.append(roll_die())
result = sorted(roll)
if keep == 'highest':
result.reverse()
outcome = result[:keep_dice]
# check for critical success (a pair) or failure (all 1s)
last = -1
critical = False
fail = True
for d in outcome:
if d != 1:
fail = False
if d == last and d != 1:
critical = True
last = d
if critical:
# critical success - add the next highest/lowest die as well
if keep_dice == dice:
# roll an additional die
outcome.append(roll_die())
outcome.sort()
else:
outcome = result[:keep_dice+1]
elif fail:
outcome = []
for x in range(0, keep_dice):
outcome.append(0)
# now sum up all our dice for the total
sum = 0
for d in outcome:
sum += d
embed = discord.Embed(title='**Dragon Eye** Ability Test for {}'.format(ctx.author.name),
description='Rolling {}d10, keep {} {}'.format(dice, keep, keep_dice),
color=0x22a7f0)
embed.add_field(name='Roll', value=format(roll), inline=False)
embed.add_field(name='Outcome', value=format(outcome), inline=True)
embed.add_field(name='Total', value=format(sum), inline=True)
if critical:
embed.add_field(name='Additional Info', value='**Critical Success**', inline=True)
elif fail:
embed.add_field(name='Additional Info', value='**Critical Fail**', inline=True)
await ctx.send(embed=embed)
def roll_die(sides=10):
die = random.randint(1, sides)
return die
bot.run(token)
</code></pre>
|
[] |
[
{
"body": "<h1>List Comprehension</h1>\n\n<p>Instead of</p>\n\n<blockquote>\n<pre><code>roll = []\nfor x in range(0, dice):\n roll.append(roll_die())\n</code></pre>\n</blockquote>\n\n<p>do this</p>\n\n<pre><code>roll = [roll_die() for _ in range(0, dice)]\n</code></pre>\n\n<p>The result is the same, it requires less code, and more pythonic. This also utilizes the <code>_</code>. The underscore is meant to show that the variable in the loop isn't used. This applies to other places in your code as well.</p>\n\n<h1>Ternary Operator</h1>\n\n<p>Instead of</p>\n\n<blockquote>\n<pre><code>if (ability < 0):\n keep = 'lowest'\nelse:\n keep = 'highest'\n</code></pre>\n</blockquote>\n\n<p>do this</p>\n\n<pre><code>keep = 'lowest' if ability < 0 else 'highest'\n</code></pre>\n\n<p>Using a ternary operator can keep you from writing more code, and looks a lot nicer. In this case, it converts four lines into one, which is a big plus.</p>\n\n<h1>Direct Returns</h1>\n\n<p>You don't have to assign a value inside a function before returning it. In this case, you don't need a <code>dice</code> variable inside <code>roll_die()</code>. You can simply return the call to <code>random.randint</code>. Take a look:</p>\n\n<pre><code>def roll_die(sides=10):\n return random.randint(1, sides)\n</code></pre>\n\n<h1>Using <code>sum</code></h1>\n\n<p>Instead of</p>\n\n<blockquote>\n<pre><code>sum = 0\nfor d in outcome:\n sum += d\n</code></pre>\n</blockquote>\n\n<p>use pythons built-in <a href=\"https://docs.python.org/3/library/functions.html#sum\" rel=\"nofollow noreferrer\"><code>sum</code></a> function</p>\n\n<pre><code>dice_sum = sum(outcome)\n</code></pre>\n\n<p>The <code>sum</code> functions returns the sum of all the numbers in an iterable. So, you can pass the list used in the loop to that function. It does the same thing you do, but it's already written.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T17:29:51.213",
"Id": "467018",
"Score": "0",
"body": "Thanks, all of these are great comments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T02:21:50.140",
"Id": "467054",
"Score": "0",
"body": "Isn't `d for d in outcome` the same as `outcome`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T04:17:41.147",
"Id": "467056",
"Score": "0",
"body": "@BlueRaja-DannyPflughoeft That's an excellent point. I missed that while I was reviewing. The answer has been edited."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T16:36:59.543",
"Id": "238119",
"ParentId": "238105",
"Score": "7"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/users/153917\">@Linny</a> already told you about list comprehensions. His suggestion would currently lead to the following code:</p>\n\n<pre><code>roll = [roll_die() for _ in range(0, dice)]\n\nresult = sorted(roll)\nif keep == 'highest':\n result.reverse()\n</code></pre>\n\n<p>Looking at the <a href=\"https://docs.python.org/3/library/functions.html#sorted\" rel=\"nofollow noreferrer\">documentation of <code>sorted(...)</code></a>, reveals that is also accepts an argument called <code>reversed</code>. Using that extra parameter allows the code piece above to be rewritten as</p>\n\n<pre><code>result = sorted(roll, reverse=(keep == 'highest'))\n</code></pre>\n\n<hr>\n\n<p>Another neat list-trick is that you can use <code>outcome = [0, ] * keep_dice</code> to generate a list of a given size with the same elements at all spots. However, <a href=\"https://stackoverflow.com/a/33513257\">be warned of the caveats</a>.</p>\n\n<hr>\n\n<p>Depending on which Python versions the code should run on, maybe also have a look at the new <a href=\"https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498\" rel=\"nofollow noreferrer\">f-string formatting</a>. Using them allows code like</p>\n\n<blockquote>\n<pre><code>embed = discord.Embed(title='**Dragon Eye** Ability Test for {}'.format(ctx.author.name),\n description='Rolling {}d10, keep {} {}'.format(dice, keep, keep_dice),\n color=0x22a7f0)\n</code></pre>\n</blockquote>\n\n<p>to be rewritten as</p>\n\n<pre><code>embed = discord.Embed(title=f'**Dragon Eye** Ability Test for {ctx.author.name}',\n description=f'Rolling {dice}d10, keep {keep} {keep_dice}',\n color=0x22a7f0)\n</code></pre>\n\n<p>f-strings are very powerful and also allow more complex expressions to be used:</p>\n\n<pre><code>embed.add_field(\n name='Additional Info',\n value=f'**Critical {\"Success\" if critical else \"Fail\"}**',\n inline=True\n)\n</code></pre>\n\n<hr>\n\n<p>The string flags <code>'highest'/'lowest'</code> could be replaced with an <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">Enum</a>. IDEs with autocompletion can help with them and therefore it's easier to avoid typos. However, this will slightly increase the effort needed to print them nicely for the user. In this special case a simple bool variable would also work, since you only have two possible values. The enum as well as the bool version could then use a ternary expression for printing if you want to follow this route.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T17:34:17.043",
"Id": "467019",
"Score": "0",
"body": "Thank you. Those are good hints as well. I saw the f-strings, but didn't understand what they are for. Now I do. :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T17:00:13.357",
"Id": "238121",
"ParentId": "238105",
"Score": "6"
}
},
{
"body": "<h1>Compact Comparisons</h1>\n\n<p>Instead of</p>\n\n<blockquote>\n<pre><code>if ability < -5 or ability > 5:\n</code></pre>\n</blockquote>\n\n<p>try</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if not -5 <= ability <= 5:\n</code></pre>\n\n<p>I prefer these kinds of comparisons when defining acceptable bounds of inputs because you get a firm definition of the upper and lower bound without having to jump around to see where the variable is relative to the number and where the sign is pointing.</p>\n\n<h1>Cool Counter</h1>\n\n<blockquote>\n<pre><code>last = -1\ncritical = False\nfail = True\nfor d in outcome:\n if d != 1:\n fail = False\n if d == last and d != 1:\n critical = True\n last = d\n</code></pre>\n</blockquote>\n\n<p>There's a lot of code here, and it's not particularly readable. In the built in collections module, there's a class called <a href=\"https://docs.python.org/3.1/library/collections.html\" rel=\"nofollow noreferrer\">Counter</a>, you can use it to replace this code like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\n# ... \n\ncounts = Counter(outcome)\n# check for critical success (a pair) or failure (all 1s)\nfail = counts[1] == keep_dice\ncritical = not fail and any([ count >= 2 for _, count in counts.items() ])\n</code></pre>\n\n<p>If you use this <code>Counter</code> cleverly, you can avoid having to keep making sure that <code>outcomes</code> is sorted and reversed properly.</p>\n\n<h1>Cromulent Class</h1>\n\n<p>I'm not so overzealous as to apply OOP where it isn't needed, but the fact that you forgot to reverse <code>outcome</code> here makes me wonder if there's a legitimate need for a class that wraps your dice rolls.</p>\n\n<blockquote>\n<pre><code> if critical:\n # critical success - add the next highest/lowest die as well\n if keep_dice == dice:\n # roll an additional die\n outcome.append(roll_die())\n outcome.sort()\n</code></pre>\n</blockquote>\n\n<pre class=\"lang-py prettyprint-override\"><code>from random import randint\nfrom collections import Counter\n\ndef roll_die(sides=10):\n return randint(1, sides)\n\nclass DiceRoll:\n \"\"\"Keeps track of which numbers have been rolled and which will be kept\"\"\"\n\n def __init__(self, total: int):\n self.dice = [ roll_die() for i in range(total) ]\n self.keep(0)\n\n \"\"\"Change the number of dice that are being kept in this roll\n\n count: how many dice to keep\n highs: whether or not to keep the highest dice.\"\"\"\n def keep(self, count: int, highs: bool = True):\n # roll any extra die if necessary\n self.dice += [ roll_die() for i in range(count - len(self.dice)) ]\n self.kept = Counter(sorted(self.dice, reverse = highs)[:count])\n\n \"\"\"Returns a Boolean indicating if all rolls kept herein are of the same digit.\n\n The digit can be supplied as the parameter, otherwise True is returned if\n the kept rolls consist of only one digit regardless of what that digit is.\n\n If no dice have been rolled or kept, False is returned.\n \"\"\"\n def keeps_only(self, d: int = None):\n least_one = [ k for k, count in self.kept.items() if count != 0 ]\n return len(least_one) == 1 and (least_one[0] is d or d is None)\n\n \"\"\"Returns a Boolean indicating if at least two rolls of the same digit are kept herein.\n\n The digit can be supplied as the parameter, otherwise the Boolean returned indicates if\n *any* digit is repeated at least once.\n \"\"\"\n def keeps_pair(self, d: int = None):\n return any(count >= 2 and (n is d or d is None) for n, count in self.kept.items())\n\n \"\"\"Returns the number of dice that aren't being discarded in this DiceRoll\"\"\"\n def kept_count(self):\n return len(self.kept_list())\n\n \"\"\"Returns a list of all of the dice as currently kept in the DiceRoll\"\"\"\n def kept_list(self):\n return list(self.kept.elements())\n\n \"\"\"Sets the results of all of the rolls (kept or not) to the provided digit.\"\"\"\n def set_all(self, digit: int):\n self.dice = [digit] * len(self.dice)\n self.keep(self.kept_count())\n\n# input\nability, heroic = [ int(input(a + ': ')) for a in ['ability', 'heroic'] ]\nif not -5 <= ability <= 5:\n print(f'Invalid ability value \"{ability}\". Must be between -5 and +5')\nif not 0 <= heroic <= 5:\n print(f'Invalid heroic dice amount \"{heroic}\". Must be between 0 and 5 (3 + 2 ritual dice)')\n\n# basic roll config\ntotal = 2 + abs(ability) + heroic\nkeep_count = 2 + heroic\nkeep_highs = ability >= 0\n\n# make the roll\nroll = DiceRoll(total)\nroll.keep(keep_count, keep_highs)\n\n# info now for printing later\nraw = roll.dice.copy();\ninfo = ''\n\n# special effects\nif roll.keeps_only(1):\n roll.set_all(0)\n info = \"Failure\"\nelif roll.keeps_pair():\n roll.keep(keep_count + 1, keep_highs)\n info = \"Success\"\n\nprint(f\"\"\"\nRolling {total}d10, keep {'highest' if keep_highs else 'lowest'} {keep_count}\nRoll: {format(raw)}\nOutcome: {format(roll.kept_list())}\nTotal: {sum(roll.kept_list())}\n{f'Additional Info: **Critical {info}**' if info else ''}\n\"\"\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T22:56:24.457",
"Id": "238142",
"ParentId": "238105",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "238119",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T11:41:39.830",
"Id": "238105",
"Score": "11",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Interactive Discord bot for tabletop RPG"
}
|
238105
|
<p>I am trying to make the following function as fast as possible on large matrices. The matrices can have dimensions in the range of 10K-100K. The matrix values are always between 0 and 1. The function resembles matrix multiplication, but with log operations in the inner loop. These log operations appear to be a bottleneck.</p>
<p>I tried various ways of using Numba and Cython. I also tried writing as much as I could with Numpy. I also experimented with doing fewer memory lookups, but this did not seem to give much advantage. The fastest version is below. High precision is greatly preferred, but if there is a way to increase speed at its expense, that would also be appreciated. Thank you for your feedback.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import numba
from numba import njit, prange
@numba.jit(nopython=True, fastmath=True, parallel=True)
def f(A, B):
len_A = A.shape[0]
len_B = B.shape[0]
num_factors = B.shape[1]
C = np.zeros((len_A, len_B))
for i in prange(len_A):
for j in prange(len_B):
for a in prange(num_factors):
A_elem = A[i,a]
B_elem = B[j,a]
AB_elem = (A_elem + B_elem)/2
C[i,j] += A_elem * np.log(A_elem/AB_elem) + \
B_elem * np.log(B_elem/AB_elem) + \
(1-A_elem) * np.log((1-A_elem)/(1-AB_elem)) + \
(1-B_elem) * np.log((1-B_elem)/(1-AB_elem))
C = (np.maximum(C, 0)/2*num_factors)**0.5
return C
#A = np.random.rand(10000, 10000)
#B = np.random.rand(10000, 10000)
#f(A, B)
</code></pre>
|
[] |
[
{
"body": "<p>I think you can rearrange your equation from</p>\n\n<p><span class=\"math-container\">\\$\nAB_{ija} = \\frac{1}{2}(A_{ia} + B_{ja})\n\\$</span></p>\n\n<p><span class=\"math-container\">\\$\n\\begin{align}\nC_{ij} = \\sum_a & A_{ia}\\cdot \\log\\left(\\frac{A_{ia}}{AB_{ija}}\\right) + B_{ja}\\cdot \\log\\left(\\frac{B_{ja}}{AB_{ija}}\\right) + \\\\\n&+ (1-A_{ia})\\cdot \\log\\left(\\frac{1-A_{ia}}{1-AB_{ija}}\\right) + (1-B_{ja})\\cdot \\log\\left(\\frac{1-B_{ja}}{1-AB_{ija}}\\right)\n\\end{align}\n\\$</span></p>\n\n<p>to</p>\n\n<p><span class=\"math-container\">\\$\n\\begin{align}\nC_{ij} = \\sum_a & A_{ia} \\cdot \\log A_{ia} + B_{ja}\\cdot \\log B_{ja} - 2AB_{ija}\\cdot \\log AB_{ija}\\\\\n&+ (1-A_{ia}) \\cdot \\log (1-A_{ia}) + (1-B_{ja})\\cdot \\log (1-B_{ja}) - 2(1-AB_{ija})\\cdot \\log (1-AB_{ija})\\\\\n= \\sum_a & A_{ia}\\cdot \\log A_{ia} + \\sum_a B_{ja}\\cdot \\log B_{ja} - 2\\sum_a AB_{ija}\\cdot \\log AB_{ija} + \\dots\n\\end{align}\n\\$</span></p>\n\n<p>This will at least save you some divisions, which can be a bit slower. But the crucial part is to see that you can compute the sums separately. The sums with only <span class=\"math-container\">\\$A\\$</span> or <span class=\"math-container\">\\$B\\$</span> are a lot less computation, which you would otherwise repeat, and only the combined terms are (computationally) hard.</p>\n\n<p>It also means that there is probably a <code>numpy</code> way to eliminate at least some of your <code>for</code> loops, which might give you a bit of a speedup, although <code>numba</code> will negate some of that (by already having sped up the <code>for</code> loops). The hard part is then to use the <code>numpy</code> broadcasting correctly to achieve this, which is left as an exercise for now :).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T14:36:44.177",
"Id": "238114",
"ParentId": "238107",
"Score": "2"
}
},
{
"body": "<p>You can simplify this by rearranging the function as follows (writing <code>z=(a+b)/2</code>):</p>\n\n<pre><code>a log(a/z) + b log(b/z) + (1-a) log( (1-a)/(1-z) ) + (1-b) log( (1-b)/(1-z) )\n\n= a log(a) + b log(b) + (1-a) log(1-a) + (1-b) log(1-b) - 2z log(z) - 2(1-z)log(1-z)\n</code></pre>\n\n<p>The first 4 terms can be evaluated outside the main loop, so that you only need to evaluate <code>log(z)</code> and <code>log(1-z)</code> within the inner loop. This should give close to a factor 2 speed up.</p>\n\n<p>Since the remaining function to evaluate in the inner loop, <code>z log(z) + (1-z)log(1-z)</code> is a function of a single variable, you could possible replace this with a look-up table .... but I don't know how much you would gain from that. </p>\n\n<p>Alternatively, use </p>\n\n<pre><code>-log(0.5) - 2*(z-0.5)**2 > -z log(z) - (1-z)log(1-z) > -2z * log(0.5)\n</code></pre>\n\n<p>to first get upper and lower bounds for each <code>C[i,j]</code> and then focus attention on those values for which the upper bound is greater than the maximum of the lower bounds.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T19:01:58.200",
"Id": "239677",
"ParentId": "238107",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T12:16:27.123",
"Id": "238107",
"Score": "6",
"Tags": [
"python",
"performance",
"matrix",
"cython",
"numba"
],
"Title": "Fast execution of function which resembles matrix multiplication"
}
|
238107
|
<p>I'm working with a ASP.NET Core (v2.2) Web Api project and implemented some APIs. However, I'm facing performance issues, hence trying to optimizing the code. Here is the login API code.</p>
<pre><code>[ValidateModel]
[AllowAnonymous]
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody]UserLoginDto loginDto)
{
var model = loginDto.ToModel();
model.Password = ApiSecurityHelper.Decrypt(model.Password, securitySecret);
var user = await _userService.GetUser(model);
if (user == null)
{
return BadRequest(T("Account.InvalidLogin"));
}
var ldapUserInfo = await CheckLdapUserByEmail(model.Email);
if (ldapUserInfo.IsLdapUser)
{
model.LdapUserName = ldapUserInfo.LdapUserName;
model.LdapDomainName = ldapUserInfo.LdapDomainName;
await _userService.LdapUserLogin(model, user);
model.IsLdapUser = user.IsLdapLogin.Equals(LdapCodes.LOGIN_SUCCESS);
}
if (user.EmailConfirmed == null || user.EmailConfirmed == false)
{
if (string.IsNullOrEmpty(user.PasswordHash))
{
return BadRequest(T("Account.VerifyUser"));
}
return BadRequest(T("Constants.KindlyActivateYourAccountToLogin"));
}
if (!user.IsLdapLogin.Equals(LdapCodes.LOGIN_SUCCESS))
{
if (user.IsLdapLogin.Equals(LdapCodes.ERROR_INVALID_CREDENTIALS) || user.IsLdapLogin.Equals(LdapCodes.ERROR_PASSWORD_EXPIRED_1) || user.IsLdapLogin.Equals(LdapCodes.ERROR_PASSWORD_EXPIRED_2))
{
await _activityLogService.AddActivity<object>(null, user.UserId, user.FullName,
ActionType.InvalidCredentials, ModuleType.Account, null, null, null);
return BadRequest(T("Account.InvalidLogin"));
}
if (user.IsLdapLogin.Equals(LdapCodes.NOT_USER))
{
return BadRequest(T("Account.UserNotExist"));
}
}
var userDto = user.ToDto();
//generate access token and refresh token and save refresh token to the db
userDto.Token = ApiTokenHelper.GenerateAccessToken(user, _tokenSecret, _tokenExpiryMinutes);
userDto.RefreshToken = ApiTokenHelper.GenerateRefreshToken();
await _userService.SaveApiRefreshToken(userDto.UserId, userDto.RefreshToken);
//add user activity in CRM
await CreateUpdateCrmUser(user, user.CountryId);
return Success(userDto);
}
</code></pre>
<p>We have requirement that user within the organization should able to login using their system password, for the rest, they should able to login using the password they have set.</p>
<p><code>T</code> is the base controller method, it is fetching resource string from the cache. </p>
<p>Is there a better, cleaner way to handle this?</p>
<p><strong>EDIT:</strong> Added requested coded</p>
<pre><code>protected IActionResult BadRequest(string errorMessage)
{
return Error(HttpStatusCode.BadRequest, errorMessage);
}
protected IActionResult Error(HttpStatusCode statusCode, string errorMessage = "")
{
var errorsRootObject = new ErrorsRootObject()
{
Error = errorMessage
};
var errorsJson = _jsonFieldsSerializer.Serialize(errorsRootObject, null);
return new ErrorActionResult(errorsJson, statusCode);
}
</code></pre>
<hr>
<pre><code>public class ErrorActionResult : IActionResult
{
private readonly string _jsonString;
private readonly HttpStatusCode _statusCode;
public ErrorActionResult(string jsonString, HttpStatusCode statusCode)
{
_jsonString = jsonString;
_statusCode = statusCode;
}
public Task ExecuteResultAsync(ActionContext context)
{
var response = context.HttpContext.Response;
response.StatusCode = (int)_statusCode;
response.ContentType = Constants.applicationslashjson;
using (TextWriter writer = new HttpResponseStreamWriter(response.Body, Encoding.UTF8))
{
writer.Write(_jsonString);
}
return Task.CompletedTask;
}
}
</code></pre>
<hr>
<pre><code>[JsonObject(Title = "UserLoginDto")]
public class UserLoginDto
{
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("password")]
public string Password { get; set; }
}
public class LoginViewModel
{
public string Email { get; set; }
[DataType(DataType.Password)]
public string Password { get; set; }
public bool RememberMe { get; set; }
public string PhoneNumber { get; set; }
public string Otp { get; set; }
public string ReturnUrl { get; set; }
//Add Lat-Long parameters & UserAgent
public decimal UserLatitude { get; set; }
public decimal UserLongitude { get; set; }
public string UserAgent { get; set; }
public string UserTimeZone { get; set; }
public string Token { get; set; }
public bool TwoFactorEnabled { get; set; }
public string MobileNumberBlockSpanMessage { get; set; }
public string ErrorMessage { get; set; }
public LdapCodes IsLdapLogin { get; set; }
public bool IsLdapUser { get; set; }
public string LdapDomainName { get; set; }
public string LdapUserName { get; set; }
[HiddenInput]
public string ExternalAppName { get; set; }
[HiddenInput]
public string ExternalAppToken { get; set; }
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T14:18:58.430",
"Id": "466981",
"Score": "2",
"body": "Welcome to code review, it would be better if the whole class was included but we need to definitely see what `BadRequest()` and `model` are."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T17:23:56.137",
"Id": "467088",
"Score": "0",
"body": "Thanks @pacmaninbw, the whole controller contain a lot of code though, will try to add required information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-02T06:46:00.650",
"Id": "467198",
"Score": "1",
"body": "@pacmaninbw Added required information"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-03T14:06:30.870",
"Id": "467336",
"Score": "0",
"body": "If you have a performance issues, we have to know what `_userService.GetUser(model)`, `CheckLdapUserByEmail(model.Email)` and `_userService.LdapUserLogin(model, user)` do. Maybe put some logging into your code to narrow longest running method."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T13:06:40.730",
"Id": "238109",
"Score": "1",
"Tags": [
"c#",
".net",
"asp.net-core",
"active-directory"
],
"Title": "Handle login method with external users and LDAP users"
}
|
238109
|
<p>I want to create an object, that represents a progress output.</p>
<p>In a GUI this would be a progress bar, in a console application it may be a text output, that can only be written, but not changed anymore (e.g. the progress bar cannot rewind). </p>
<p>Other possible implementations could include sending a e-mail every 10% of progress and in the best case the API should be open for any other idea how to communicate progress as well.</p>
<p>When I start using the API in programs, it will be hard to change it later on, so it should be well-thought. I hope to get helpful feedback here and hints which use cases the current API may not cover.</p>
<hr>
<p>My current idea for the API is this one:</p>
<pre><code>class Progress{
public:
// Called by the function that reports progress
virtual void setMaxProgress(int value);
virtual void setCanStop(bool can_stop);
virtual void start(std::string description);
virtual void progress(int value);
virtual void incProgress(int steps = 1);
virtual void info(std::string message);
virtual bool shouldStop();
virtual void end();
virtual bool wasStopped();
private:
// Called by the progress implementation
virtual bool canStop();
virtual int currentProgress();
virtual int maxProgress();
};
</code></pre>
<p>The functions in detail:</p>
<ul>
<li>The program sets the maximum progress, e.g. for processing 50 items: <code>setMaxProgress(50)</code></li>
<li>The program sets that the process can be interrupted (e.g. by rolling back a transaction or returning a partial result): <code>setCanStop(true)</code>.</li>
<li>The program starts progress: <code>start("I am calculating foo")</code>.</li>
<li>The program reports that <code>11</code> items in total were processed: <code>progress(11)</code></li>
<li>The program reports that it processed 1 item: <code>incProgress()</code>.</li>
<li>After each item the program asks if the user requested the operation to be interrupted (e.g. using a cancel button) with: <code>shouldStop()</code>.</li>
<li>The program displays some status message with <code>info("Second step ...")</code>.</li>
<li>The program reports that the task is finished (the progress implementation should hide the progress bar): <code>end()</code>.</li>
<li>The progress implementation asks how many steps are needed with: <code>maxProgress()</code>.</li>
<li>The progress implementation asks how many steps are already finished with: <code>currentProgress()</code>.</li>
<li>The progress implementation asks if it should show a cancel button (may not be implemented): <code>canStop()</code>.</li>
<li>The program queries if the user clicked cancel to determine if the algorithm finished or was interrupted with: <code>wasStopped()</code>.</li>
</ul>
<p>An implementation with a progress bar (GUI or TUI) may set the maximum value to 50 and display a cancel button when <code>canStop()</code> is true.</p>
<pre><code>[==== ] 40% [cancel]
</code></pre>
<p>A text mode implementation may calculate the percentage and display a simple progress bar, ignoring <code>canStop()</code></p>
<pre><code>0 =============== 100
|||||
</code></pre>
<hr>
<p>I currently use two implementations that look almost like this one:</p>
<ul>
<li>One counts the progress steps and every time the percentage is increased by a certain amount (depending on the console width), it outputs a dot. When some info message is printed, it outputs the current progress after it again.</li>
<li>The other one updates the global Maya progress bar. On each progress update it sends a script command to Maya to ask if cancel was pressed and sends the updated progress information. When cancel was pressed, an internal variable is set that makes <code>shouldStop</code> return true. The <code>info</code> method uses the Maya status bar to display a message.</li>
</ul>
<p><em>(I don't really use the info method, but it was in the code base that contained the first implementation</em></p>
<hr>
<p>Example implementation:</p>
<pre><code>class SimpleProgress {
public:
SimpleProgress(int progress_bar_length = 50, int max_progress = 100): progress_bar_length(progress_bar_length), max_progress(max_progress) {};
virtual void start(std::string describtion) {
std::cerr << "Starting: " << describtion << std::endl;
_description = describtion;
};
virtual void end() {
std::cerr << "Finished: " << _description << std::endl;
};
virtual void setMaxProgress(int value) {
max_progress = value;
};
virtual void progress(int progress) {
assert(max_progress >= 0);
assert(progress <= max_progress);
for(int i = 0; i < (progress - current_progress) / max_progress * progress_bar_length; i++) {
std::cerr << "=";
}
current_progress = progress;
};
virtual void incProgress(int steps = 1) {
if(max_progress >= 0) {
assert(current_progress <= max_progress);
progress(current_progress + steps);
} else {
// Progress without a known maximum value.
std::cerr << "." << std::endl;
}
};
virtual int maxProgress() override {
return max_progress;
};
virtual void info(std::string message) {
std::cerr << message << std::endl;
for(int i = 0; i < current_progress / max_progress * progress_bar_length; i++) {
std::cerr << "=";
}
};
virtual void setCanStop(bool can_stop) {
};
virtual bool canStop() {
return false;
};
virtual bool shouldStop() {
return false;
}
private:
int current_progress = 0;
int max_progress = -1;
int progress_bar_length;
std::string _description;
};
</code></pre>
<p><em>(Note that this is only a prototype as I am currently rewriting the class from a more complex project)</em></p>
<p>For a non-interactive implementation, you could for example want to stop when a certain runtime is exceeded, implementing the methods like this:</p>
<pre><code> virtual void setCanStop(bool can_stop) {
_can_stop = can_stop;
};
virtual bool canStop() {
return _can_stop;
};
virtual bool shouldStop() {
if(_can_stop && runtime >= max_runtime) {
return true;
} else {
return false;
}
}
</code></pre>
<hr>
<p>Example usage:</p>
<pre><code>void doSomething(Progress *progress = nullptr) {
DummyProgress dummyProgress;
if(progress == nullptr) {
progress = &dummyProgress;
}
progress->setMaxProgress(50);
progress->canStop(true);
progress->start("Calculating");
for(int i=0; i < 50; i++) {
progress->progress(i);
//
// Calculate something for step i
//
if(progress->shouldStop()) {
progress->end();
break;
}
}
if(progress->wasStopped()) {
std::cerr << "Not all items were processed." << std::endl;
} else {
progress->end();
}
}
</code></pre>
<hr>
<p>I would like to get feedback about what is possibly missing in my API, what could be improved and what may be a bad idea?</p>
<hr>
<p>Feedback on suggestions:</p>
<ul>
<li>Replace <code>setMaxProgress</code> and other setters with parameters for <code>start()</code>. This will help to avoid code that did not set theses properties.</li>
<li>Making getters <code>const</code></li>
<li>I cannot purely rely on callbacks for the cancel button, as I need to support one implementation that requires an active query if cancel was clicked, i.e., running <code>progressBar -query -isCancelled</code> in Maya (<a href="https://download.autodesk.com/us/maya/2011help/CommandsPython/progressBar.html" rel="nofollow noreferrer">docs</a>).</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T13:20:17.287",
"Id": "466974",
"Score": "2",
"body": "The code is not complete and just with the class definition you are only get improvements on the class that could be wrong because you didn't share the code on the post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T13:53:00.983",
"Id": "466976",
"Score": "1",
"body": "Consider adding at least one implementation and one usage of this interface to help reviewers generate more useful answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T14:56:26.857",
"Id": "466993",
"Score": "0",
"body": "@camp0 I am mostly interested in feedback for designing the interface, i.e., what functions are useful and what functions I will want to remove later because of bad design, when my other projects already depend on them. I want to have the good design right from the start so I do not need to change a lot of projects later on to use a changed API."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T14:59:09.847",
"Id": "466995",
"Score": "0",
"body": "@L.F. I added some code that outputs a text based progress bar and a suggestion how the `shouldStop` methods could be implemented for it. Adding the existing MEL code would be too much code for the example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T21:32:56.733",
"Id": "467045",
"Score": "1",
"body": "I don't think this question is a good fit for CodeReview.SE. It's not really a review of code that has already been fully implemented and instead asks \"Is this a good design?\" **before most of the code has actually been written**. And while there undoubtedly is value to posing that question, I feel like it might be better suited to another site of the stack exchange network (possibly Programmers.SE?)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T19:29:25.680",
"Id": "467094",
"Score": "0",
"body": "@hoffmale I have read quite a few questions about code, that got a lot of answers about design decisions, so I thought here are probably many people who think a lot about software architecture and how to design APIs and how to prevent anti-patterns and so on. The difference to some other questions is, that I do not want people to be careful not to suggest too large changes. Nobody needs to say \"I would do it totally different, but you can't change that much now\", when I ask before making things permanent things."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T00:53:12.093",
"Id": "467112",
"Score": "1",
"body": "Again, have you had a look at [softwareengineering.se] (previously programmers.SE)? One of the focal points of that site is \"requirements, software architecture and design\", so your question would seem a lot more on topic there."
}
] |
[
{
"body": "<p>I encourage the use of interfaces, but this is not an interface. In an interface all the methods are public, and your code has private methods (which I'm not sure can actually compile given that they're <code>private</code>). The ideas of interfaces is that you only define the communication between objects, and don't define anything about the implementation details. What you have here is intended to be an abstract base class (assuming you change every private method to protected).</p>\n\n<p>In most progress-bar interfaces I saw there weren't that many methods. Usually what you use is something like <code>start(...)</code>, <code>setProgress(double ...)</code> and <code>stop()</code>, and pass whatever arguments you need in the method call. It's simpler to pass all the arguments that are needed in one call instead of knowing that you actually have to call <code>setSomething</code> and <code>setSomethingElse</code> before calling <code>start()</code>. </p>\n\n<p>Also keep in mind that one challenge of progress-bars are that they're usually a singleton (whether or not they follow the design pattern) so you need to think about how to handle many different objects accessing the same progress-bar. When you hold state, you're gonna have a lot of carry-on state from previous call and have unexpected behavior unless of course you complicate your progress-bar calls a little more by relying on clients to use some <code>clear</code> method.</p>\n\n<p>I would look at your class from a <a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow noreferrer\">YAGNI</a> perspective. I don't think you should have one interface for progress-bars and for sending emails whenever a progress of something reaches some point. I don't think it's gonna be the progress-bar responsibility in most cases. In most cases you have some object performing some operation and updating the progress in the progress bar (completion% and message if needed), so that class would be the one sending emails. It would be much easier if you can subscribe to some event on the progress-bar to handle any progress changes. Events are a great tool when you want to be able to respond to something without adding responsibility to classes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T14:32:21.463",
"Id": "466986",
"Score": "0",
"body": "Sorry about the \"interface\" I thought more about the concept than the language feature. I reduced my existing code a lot to keep the question as open as possible and added the public/private while writing the question to make more clear what I intend to do. I do not need inheritance and may implement it using templates, but before fixing anything I need to know a good set of methods."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T14:36:28.237",
"Id": "466987",
"Score": "0",
"body": "My current projects needs to update a singleton progress bar from a blocking algorithm. I have one implementation that scripts a GUI progress bar with cancel button (disabled when the algorithm does not support it) and one that outputs one dot per percent on a console. Now I want to design a class that can be passed either as base class pointer or using templates to any future algorithm in which I need it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T15:02:56.240",
"Id": "466996",
"Score": "0",
"body": "Unless I'm missing something, all the points remain. Use a simple interface with few simple methods. You don't need templates, and your domain objects don't need to know if they're updating the progress of some console window or some GUI application. It doesn't matter. You can have an option to enable a \"cancel\" button and to enable/disable it during the progress-bar run, but you don't want the progress-bar itself to be concerned with the reasons for enabling/disabling the button"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T15:21:09.320",
"Id": "466999",
"Score": "0",
"body": "I do not want the algorithm to know about the progress bar. I want it only to know about a progress object, that has a method to set parameters (max progress, can the operation be stopped, a short description of the operation), a method to set (or increase) progress and a method to test if the user wants to stop the current operation. I'll add some example usage to my question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T15:25:19.123",
"Id": "467000",
"Score": "0",
"body": "I know that's what you want. It's a single interaction, why do you need `setThis` `setThat` `setThatOtherThing` when you can simply `start(this, that, thatOtherThing)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T15:32:08.297",
"Id": "467003",
"Score": "1",
"body": "Merging them into start is a good suggestion. Btw. should I add suggestions to the question when I like them or should they remain in answers / comments on this site?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T15:37:15.207",
"Id": "467004",
"Score": "0",
"body": "I think it's better if you leave the question as is, in case someone disagrees with me and presents a better argument."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T18:13:00.583",
"Id": "467027",
"Score": "1",
"body": "@allo Once you receive an answer to your question, you should not make any substantial edits to it as this can invalidate the answer. See [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers)"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T13:56:10.353",
"Id": "238112",
"ParentId": "238111",
"Score": "3"
}
},
{
"body": "<p>Methods should be <code>const</code> where possible (<code>currentProgress</code>, <code>maxProgress</code>, various \"stop\" related functions - but see below).</p>\n\n<p>This class should have a constructor. In particular, besides having a default constructor, having one that can take the initial state (like max progress and/or an initial message) would streamline its use without having to call multiple <code>set</code> type functions.</p>\n\n<p>Since your class is intended to be derived from, a <code>virtual</code> destructor, even if empty or defaulted, is necessary to avoid problems when destroying progress bars via a pointer to the base class.</p>\n\n<p>Asking a progress bar if the current calculation or task should stop seems counter intuitive to me. Not all users of progress will need this capability, and it gets away from the Single Responsibility Principle. The progress bar should just handle progress. The calculation or task can handle the stopping. In some cases (like a GUI progress bar with a \"stop\" button) the progress class may need to keep track if a stop is requested. This can be handled by the derived class, in cooperation with the task that is using the Progress object. Should the stop be pushed to the task? Should the task query the progress to see if the stop button was hit? What about multiple threads processing the task?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T19:38:41.190",
"Id": "467095",
"Score": "0",
"body": "The getters should of course be const. I probably do not want to use the constructor like the `start` function, as the object is a singleton representing the progress display."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T19:51:09.673",
"Id": "467097",
"Score": "0",
"body": "One of the implementations I use is scripting the Maya progress bar by running `MEL` commands from C++. The Maya API is not using callbacks for clicks on the cancel button, but you need to query if cancel was clicked. So my implementation for Maya calls the MEL command `progressBar -query -isCanceled` in my `shouldStop()` function. See the [progressBar docs](https://download.autodesk.com/us/maya/2011help/CommandsPython/progressBar.html) for details on this implementation. This is probably not the best design in the Maya API, but I need to be able to deal with it in my progress bar wrapper."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T18:11:23.783",
"Id": "238125",
"ParentId": "238111",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T13:11:56.163",
"Id": "238111",
"Score": "4",
"Tags": [
"c++",
"api"
],
"Title": "API for a progress display function"
}
|
238111
|
<p>I am very new to Rust. I have written a <a href="https://en.wikipedia.org/wiki/Conjugate_gradient_method" rel="nofollow noreferrer">conjugate gradient algorithm</a> function for <code>CsMatrix</code> structure from <a href="https://www.nalgebra.org/" rel="nofollow noreferrer">nalgebra</a></p>
<pre class="lang-rust prettyprint-override"><code>fn conjugate_gradient(m: &CsMatrix<f64>, rhs: &DVector<f64>, tol: f64, max_iter: Option<u32>) -> DVector<f64> {
let n_iters = max_iter.unwrap_or(1000);
println!("Iters: {}", n_iters);
let mut x: CsVector<f64, Dynamic> = rhs.clone().into();
let mut r: CsVector<f64, Dynamic> = rhs.clone().into();
r = r.add(&(m.mul(&x).mul(-1.0_f64)));
let mut p: CsVector<f64, Dynamic> = r.clone();
let mut r2 = r.values_mut().fold(0.0_f64, |acc, x| acc + (*x)*(*x));
for _ in 0..n_iters {
let m_p: DVector<f64> = m.mul(&p).into();
let p_full: DVector<f64> = p.clone().into();
let a = r2/(p_full.dot(&m_p));
x = x.add(&(p.clone().mul(a)));
r = r.add(&(m.mul(&p).mul(-a)));
let r2_new = r.values_mut().fold(0.0_f64, |acc, x| acc + (*x)*(*x));
println!("Residual {}", r2_new);
if r2_new < tol {
return x.into();
}
let b = r2_new/r2;
p = r.add(&(p.mul(b)));
r2 = r2_new;
}
println!("Maximum number of iteration reached.");
x.into()
}
</code></pre>
<p>Vector-vector (dot) product seems to be missing in the library (transpose didn't help).</p>
<p>I struggle with the concept of ownership, so any comment on bad usage of cloning, references, mutability, etc. would be helpful.
Also, if anyone with experience with <em>nalgebra</em> could suggest a better approach to using sparse matrices that would be very nice.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T17:29:18.603",
"Id": "467017",
"Score": "0",
"body": "yes, it works fine to the best of my knowledge. I just don't know if the `clone` calls are necessary/idiomatic."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T15:11:12.047",
"Id": "238115",
"Score": "3",
"Tags": [
"rust"
],
"Title": "Conjugate gradient method for a sparse matrix"
}
|
238115
|
<pre><code> function get_sql_string(dbConn,query_string,col_delim,row_delim) {
var result = dbConn.executeCachedQuery( query_string );
var result_string = '';
var column_count = result.getMetaData().getColumnCount();
if ( col_delim ){
col_delim = col_delim;
}
else {
col_delim = ',';
}
if ( row_delim ){
row_delim = row_delim;
}
else {
row_delim = '\n';
}
if(result.size() > 0){
while (result.next()) {
i = 1;
var line = '';
while (i <= column_count) {
line = line + result.getString(i) + col_delim;
i++;
}
result_string = result_string + line.slice(0, -1) + row_delim;
}
result_string = result_string.slice(0, -1);
result.close();
if (result_string.toString() != 'null' || result_string != null) {
return result_string.trim();
}
else {
return '';
}
}
else {
dbConn.close();
return '';
}
dbConn.close();
}
</code></pre>
<p>Executes a SQL select query and creates a string from the results </p>
<ul>
<li><p><code>@param0 {String} dbConn</code> - connection string for database</p></li>
<li><p><code>@param1 {String} query_string</code> - query to execute</p></li>
<li><p><code>@param2 {String} col_delim</code> - column delimiter separates each value in a row, default value is a commma</p></li>
<li><p><code>@param3 {String} row_delim</code> - row delimiter separates earch row in the resultset, default value is a newline character</p></li>
<li><p><code>@return {String}</code> returns the resultset as a string with column and row delimiters</p></li>
</ul>
<p>Above is a function in that converts a SQL resultset to a string. I want to learn how to make this code more succint for maintainability. Can someone help? Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T17:21:03.713",
"Id": "467015",
"Score": "2",
"body": "Can you elaborate about _\"more efficient\"_ please? In which particular ways of efficiency? Performance, maintainability, etc.?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T17:24:08.747",
"Id": "467016",
"Score": "0",
"body": "I want someone to take alook at this code and ask \"Why did he do it that way? Here's a simple, succint way to do it.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T17:48:01.173",
"Id": "467024",
"Score": "3",
"body": "_\"Why did he do it that way?\"_ These things should be usually explained a priori by the author (in comments, or concepts)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T18:26:34.813",
"Id": "467028",
"Score": "0",
"body": "I am the author. Is there a succint way to re-write this code for maintainability?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T18:30:20.840",
"Id": "467029",
"Score": "3",
"body": "Add such concerns for review to your question please, not in comments."
}
] |
[
{
"body": "<p>You write this is a </p>\n\n<blockquote>\n <p>Javascript function to convert SQL resultset to a string</p>\n</blockquote>\n\n<p>however that is not true. It's a function that </p>\n\n<ol>\n<li>executes an SQL query</li>\n<li>converts its result set to a string</li>\n<li>(sometimes) closes its DB connection</li>\n</ol>\n\n<p>Generally its bad idea to have a function to do more than one thing. Especially the closing of a DB connection that (I presume) is passed in open is very out of place and unexpected to the user of this function, more so because it only happens when the result set of the query is empty. (The last <code>dbConn.close()</code> is never executed).</p>\n\n<p>Conversely the result set is only closed if it isn't empty. I don't know which DB library you are using, so it may be ok, but I doubt it.</p>\n\n<p>Generally you should be using <code>try ... finally</code> blocks to make sure you are closing your resources.</p>\n\n<hr>\n\n<p>Next you have pointless assignments such as <code>col_delim = col_delim;</code> when handling default argument values. All current JavaScript implementations support <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters\" rel=\"nofollow noreferrer\">default \nparameters</a>:</p>\n\n<pre><code> function get_sql_string(dbConn, query_string, col_delim = \",\", row_delim = \"\\n\") {\n</code></pre>\n\n<p>Also look into using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a>/<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let\" rel=\"nofollow noreferrer\"><code>let</code></a> instead of <code>var</code>.</p>\n\n<hr>\n\n<p>Another potential bug is the use of <code>.slice(0, -1)</code>. Besides being inefficient, it assumes that the delimiters are exactly one character long, which may not be the case. At the very least you should be using <code>.slice(0, -col_delim.length)</code>, better would be not to add this final delimiter in the first place. This could be done by collecting the results/lines in arrays and using <code>.join(col_delim)</code>.</p>\n\n<p>String concatenation (especially in a loop) is anyway very inefficient and using <code>join</code> would help here, too.</p>\n\n<hr>\n\n<p>Other than that: Code formatting is very inconsistent. For example:</p>\n\n<ul>\n<li><code>if(</code> vs <code>if (</code> </li>\n<li><code>if (...){</code> <code>if (...) {</code></li>\n</ul>\n\n<p>etc. Choose one style and stay with it (preferably the latter version). Consider using an editor/IDE that can format the code for you.</p>\n\n<hr>\n\n<p>Example reimplentation (untested):</p>\n\n<pre><code>function executeQueryAndFormatResult(dbConn, queryString, colDelim = \",\", rowDelim = \"\\n\") {\n try {\n const result = dbConn.executeCachedQuery(queryString);\n return formatResult(result, colDelim, rowDelim);\n } finally {\n if (result) {\n result.close();\n }\n }\n}\n\nfunction formatSqlResult(result, colDelim = \",\", rowDelim = \"\\n\") {\n const columnCount = result.getMetaData().getColumnCount();\n const lines = [];\n while (result.next()) {\n const row = [];\n row.length = columnCount; // Allows JS engine to reserve the needed number of entries ahead of time\n for (let i = 1; i <= columnCount; i++) {\n row[i-1] = result.getString(i);\n }\n lines.push(row.join(colDelim));\n }\n return lines.join(rowDelim);\n}\n</code></pre>\n\n<p>EDIT: Do the columns actually start with index 1? It seems unusual, but I've adjusted my code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-02T14:39:50.927",
"Id": "467243",
"Score": "0",
"body": "Thank you! When I was testing my code, if I started the index at 0 it returned column names in the resultset."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-02T15:18:35.273",
"Id": "467251",
"Score": "0",
"body": "@dsaini Yes, that makes sense. I didn't think of that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-02T09:31:06.990",
"Id": "238226",
"ParentId": "238124",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "238226",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T17:14:49.613",
"Id": "238124",
"Score": "1",
"Tags": [
"javascript",
"beginner",
"sql"
],
"Title": "Javascript function to convert SQL resultset to a string"
}
|
238124
|
<p>I'm just wondering Is there any ways I could simplify the following code without making it too difficult:</p>
<p>Actually I want to extract specific year data from content node based on lastNumberOfYears variable.</p>
<p><strong>Example</strong>: Content array has 2019,2018,2017,2016 years data and lastNumberOfYears value is 2 then output should have only 2019, 2018 data. other scenario is if content array is like 2020, 2014, 2013 then output should have 2020, 2014 data (if lastNumberOfYears value is 2)</p>
<p><strong>My solution</strong></p>
<p><strong>Step 1</strong> : Define predefined data</p>
<pre><code>const content = [{
"document": "/content/path/document1.pdf",
"date": "2020-02-20"
}, {
"document": "/content/path/file.docx",
"date": "2019-02-20"
}, {
"document": "/content/abc/document2.docx",
"date": "2018-06-20"
}, {
"document": "/document/order/order.pdf",
"date": "2020-06-20"
}, {
"document": "/content/order/update.pdf",
"date": "2018-03-21"
}, {
"document": "/content/author/author.pdf",
"date": "2017-03-21"
}, {
"document": "/content/path/dummy.pdf",
"date": "2016-02-15"
}, {
"document": "/content/dummy/dummy.docx",
"date": "2015-12-15"
}];
let lastNumberOfYears = 2;
let selectedYearArray = [];
</code></pre>
<p><strong>Step 2</strong>: Convert content data into year base data</p>
<pre><code>const result = content.reduce((current, value) => {
const dateYear = new Date(value.date).getFullYear();
current[dateYear] = current[dateYear] || [];
current[dateYear].push(value);
return current;
}, {});
/*
output is like
{
"2015":[{...}],"2016":[{}],..."2020":[{}, {}]
}
*/
</code></pre>
<p><strong>Step 3</strong>: Put specific year data in same order for result array</p>
<pre><code>Object.values(result).forEach(value => value.reverse());
</code></pre>
<p><strong>Step 4</strong>: Create Year array from object key</p>
<pre><code>const yearsArray = Object.keys(result).sort((first, second) => (first > second ? -1 : 1));
</code></pre>
<p><strong>Step 5</strong>: Create last number of year array using lastNumberOfYears variable
<strong>Step 6</strong>: Extract Step 5 data from result array define in step 3
<strong>Step 7</strong>: Remove year key and join all array value of Step 6 outcome</p>
<pre><code>if (yearsArray.length !== 0 && lastNumberOfYears <= yearsArray.length) {
for (let i = 0; i < lastNumberOfYears; i++) {
selectedYearArray.push(yearsArray[i]);
}
/*
Step 5: console.log(selectedYearArray);
*/
const filteredResult = Object.keys(result)
.filter(key => selectedYearArray.includes(key))
.reduce((obj, key) => {
obj[key] = result[key];
return obj;
}, {});
/*
Step 6: console.log(filteredResult);
*/
contentObj = [].concat.apply([],Object.values(filteredResult));
/*
Step 7:
*/
console.log(contentObj.reverse());
}
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>[{
"document": "/content/path/document1.pdf",
"date": "2020-02-20"
}, {
"document": "/document/order/order.pdf",
"date": "2020-06-20"
}, {
"document": "/content/path/file.docx",
"date": "2019-02-20"
}]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T19:15:17.247",
"Id": "467031",
"Score": "0",
"body": "This is working code but time complexity is bit high so want to know how to improve time complexity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T19:19:24.753",
"Id": "467032",
"Score": "0",
"body": "What is your criteria for improvement? Just execution time for a given set of data? My first thought would be use a `Map` object with year as the index and retain that Map so you can easily look up any items by year from then on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T19:27:42.910",
"Id": "467033",
"Score": "0",
"body": "Actually I want to do it in single step like single filter function involve not too much steps like here total 6-7 steps involve."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T19:31:26.810",
"Id": "467035",
"Score": "1",
"body": "I can't really tell what your criteria is for evaluating what is \"better\"? You mention reducing steps? You mention time complexity? You mention simplifying? I'd say you need to state an objective criteria and focus the post on that specific criteria."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T19:32:43.873",
"Id": "467036",
"Score": "0",
"body": "my criteria is time complexity and performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-02T11:08:51.343",
"Id": "467219",
"Score": "0",
"body": "Welcome to Code Review! We need to know *what the code is intended to achieve*. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436), rather than your concerns about the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-03T19:30:13.167",
"Id": "467379",
"Score": "0",
"body": "@jfriend00 A post doesn't need to have *one* specific criteria for improvement."
}
] |
[
{
"body": "<p>Here's a scheme that appears to be about 7 times faster that yours when run in node.js:</p>\n\n<pre><code>function getData2(content, lastNumberOfYears) {\n // organize data by year into a Map object\n const map = new Map()\n for (let item of content) {\n const year = new Date(item.date).getFullYear();\n let yearData = map.get(year);\n if (yearData) {\n yearData.push(item);\n } else {\n map.set(year, [item]);\n }\n }\n\n /* map object data looks like this:\n Map {\n 2020 => [\n { document: '/content/path/document1.pdf', date: '2020-02-20' },\n { document: '/document/order/order.pdf', date: '2020-06-20' }\n ],\n 2019 => [ { document: '/content/path/file.docx', date: '2019-02-20' } ],\n 2018 => [\n { document: '/content/abc/document2.docx', date: '2018-06-20' },\n { document: '/content/order/update.pdf', date: '2018-03-21' }\n ],\n 2017 => [ { document: '/content/author/author.pdf', date: '2017-03-21' } ],\n 2016 => [ { document: '/content/path/dummy.pdf', date: '2016-02-15' } ],\n 2015 => [ { document: '/content/dummy/dummy.docx', date: '2015-12-15' } ]\n }\n */\n\n // get lastNumberOfYears by getting all the years, sorting them \n // and getting most recent ones\n let sortedYears = Array.from(map.keys()).sort();\n if (sortedYears.length > lastNumberOfYears) {\n sortedYears = sortedYears.slice(-lastNumberOfYears);\n }\n let result = [];\n for (let year of sortedYears) {\n result.push(map.get(year));\n }\n return result.flat();\n\n}\n\nfunction time(fn) {\n const start = process.hrtime.bigint();\n let result = fn();\n const end = process.hrtime.bigint();\n console.log(result);\n console.log(`Benchmark took ${end - start} nanoseconds`);\n}\n</code></pre>\n\n<p>It uses the following steps:</p>\n\n<ol>\n<li>Parse years and put each year's into a Map object with the year as the key and the value as an array of values for that year</li>\n<li>Get the years from the Map object, sort them and get the desired <code>lastNumberOfYears</code></li>\n<li>Collect the results from the Map object for each of the chosen years and flatten them into a single array</li>\n</ol>\n\n<hr>\n\n<p>If you want to run both yours and mine in node.js, here's the entire program I used to compare:</p>\n\n<pre><code>const inputData = [{\n \"document\": \"/content/path/document1.pdf\",\n \"date\": \"2020-02-20\"\n }, {\n \"document\": \"/content/path/file.docx\",\n \"date\": \"2019-02-20\"\n }, {\n \"document\": \"/content/abc/document2.docx\",\n \"date\": \"2018-06-20\"\n }, {\n \"document\": \"/document/order/order.pdf\",\n \"date\": \"2020-06-20\"\n }, {\n \"document\": \"/content/order/update.pdf\",\n \"date\": \"2018-03-21\"\n }, {\n \"document\": \"/content/author/author.pdf\",\n \"date\": \"2017-03-21\"\n }, {\n \"document\": \"/content/path/dummy.pdf\",\n \"date\": \"2016-02-15\"\n }, {\n \"document\": \"/content/dummy/dummy.docx\",\n \"date\": \"2015-12-15\"\n}];\n\nfunction getData1(content, lastNumberOfYears) {\n\n let selectedYearArray = [];\n\n const result = content.reduce((current, value) => {\n const dateYear = new Date(value.date).getFullYear();\n current[dateYear] = current[dateYear] || [];\n current[dateYear].push(value);\n return current;\n }, {});\n\n /*\n output is like\n {\n \"2015\":[{...}],\"2016\":[{}],...\"2020\":[{}, {}]\n }\n */\n\n Object.values(result).forEach(value => value.reverse());\n\n const yearsArray = Object.keys(result).sort((first, second) => (first > second ? -1 : 1));\n\n if (yearsArray.length !== 0 && lastNumberOfYears <= yearsArray.length) {\n for (let i = 0; i < lastNumberOfYears; i++) {\n selectedYearArray.push(yearsArray[i]);\n }\n\n /*\n Step 5: console.log(selectedYearArray);\n */\n\n const filteredResult = Object.keys(result)\n .filter(key => selectedYearArray.includes(key))\n .reduce((obj, key) => {\n obj[key] = result[key];\n return obj;\n }, {});\n\n /*\n Step 6: console.log(filteredResult);\n */\n\n contentObj = [].concat.apply([],Object.values(filteredResult));\n\n /*\n Step 7:\n */\n return contentObj.reverse();\n }\n}\n\nfunction getData2(content, lastNumberOfYears) {\n // organize data by year into a Map object\n const map = new Map()\n for (let item of content) {\n const year = new Date(item.date).getFullYear();\n let yearData = map.get(year);\n if (yearData) {\n yearData.push(item);\n } else {\n map.set(year, [item]);\n }\n }\n\n // get lastNumberOfYears by getting all the years, sorting them \n // and getting most recent ones\n let sortedYears = Array.from(map.keys()).sort();\n if (sortedYears.length > lastNumberOfYears) {\n sortedYears = sortedYears.slice(-lastNumberOfYears);\n }\n let result = [];\n for (let year of sortedYears) {\n result.push(map.get(year));\n }\n return result.flat();\n\n}\n\nfunction time(fn) {\n const start = process.hrtime.bigint();\n let result = fn();\n const end = process.hrtime.bigint();\n console.log(result);\n console.log(`Benchmark took ${end - start} nanoseconds`);\n}\n\ntime(() => getData1(inputData, 2));\n\ntime(() => getData2(inputData, 2));\n</code></pre>\n\n<p>And, the output on my desktop computer was this:</p>\n\n<pre><code>[\n { document: '/content/path/document1.pdf', date: '2020-02-20' },\n { document: '/document/order/order.pdf', date: '2020-06-20' },\n { document: '/content/path/file.docx', date: '2019-02-20' }\n]\nBenchmark took 602501 nanoseconds\n[\n { document: '/content/path/file.docx', date: '2019-02-20' },\n { document: '/content/path/document1.pdf', date: '2020-02-20' },\n { document: '/document/order/order.pdf', date: '2020-06-20' }\n]\nBenchmark took 89100 nanoseconds\n</code></pre>\n\n<p>Note a slightly different sort order of the results. I didn't see in your description if a specific sort order of results was required or not.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T20:13:51.363",
"Id": "467040",
"Score": "0",
"body": "Thanks man, Yes its too fast."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T20:32:04.403",
"Id": "467042",
"Score": "0",
"body": "Map and sortedYears.slice(-lastNumberOfYears); is killer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T20:08:38.960",
"Id": "238134",
"ParentId": "238127",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "238134",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T19:05:00.953",
"Id": "238127",
"Score": "0",
"Tags": [
"javascript",
"array",
"ecmascript-6"
],
"Title": "How to simplify this ES6 Array code"
}
|
238127
|
<p>I need to generate random text for tests. I do that using alphanumeric characters and some special characters as well.</p>
<p>For some special cases, I cannot generate the random text with tags.
I have the concept of a <code>tag</code> as text surrounded in curly braces (e.g. <code>{name}</code>).</p>
<p>I have written a simple code to clean up the tags (e.g. removing one of the curly braces) and I'd like some feedback if looks ok for Scala.</p>
<pre><code>val allCharacters = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890!@#%*()_+-=[]{x}|?.;:`"
def removeTags(text: String): String = {
// A tag is any text between {}, like `{name}`
def containsTag(text: String): Boolean = {
val noTagsRegex: Pattern = Pattern.compile("^((?!(\\{.*\\})).)*$")
!noTagsRegex.matcher(text).matches()
}
var newText = text
if (containsTag(newText)) {
val randomPosition = Random.nextInt(allCharacters.length - 1)
newText = text.replace("}", allCharacters(randomPosition).toString)
}
newText
}
</code></pre>
<p>Below an idea of results running this method:</p>
<ol>
<li><p>Text without tags</p>
<ul>
<li>input: "dlfkhfks sldfjhsldf qiweo 93450934 %&%&%&^%"</li>
<li>output: "dlfkhfks sldfjhsldf qiweo 93450934 %&%&%&^%" (exactly the same)</li>
</ul></li>
<li><p>Text with 1 tag</p>
<ul>
<li>input: "dlfkhfks s{ldf}jhsldf qiweo 93450934 %&%&%&^%"</li>
<li>output: "dlfkhfks s4ldf}jhsldf qiweo 93450934 %&%&%&^%" (the <code>{</code> was replaced)</li>
</ul></li>
<li><p>Text with more than 1 tag</p>
<ul>
<li>input: "dlfkhfks s{ldf}jhsldf {{@}} qiweo 93450934 %&%&%&^%"</li>
<li>output: "dlfkhfks s4ldf}jhsldf 44@}} qiweo 93450934 %&%&%&^%"</li>
</ul></li>
</ol>
<p>There is room for improvements, like not doing <code>replace</code> to all occurrences by the same character, but this is something for another moment.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T20:58:10.047",
"Id": "467044",
"Score": "0",
"body": "can you look at your question one more again and maybe add some more info like input texts or another? I see some problems in what you write in question and what in your code: regular expression do not find curly braces for simple example like `sometext {name} sometext` (look at: https://regex101.com/r/2PR2kC/1) and in next you replace `\"}\"` for random symbol from `allCharacters` where you also has curly braces."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T18:02:24.833",
"Id": "467176",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T18:03:07.093",
"Id": "467177",
"Score": "0",
"body": "@Gudsaf No. A new question should be posted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T20:46:58.280",
"Id": "467189",
"Score": "0",
"body": "@Mast: Thank you for clarifying that. Won’t happen again."
}
] |
[
{
"body": "<h2>Beautify your regex</h2>\n<p>Say <strong>No</strong> to <code>Pattern.compile</code> and instead of</p>\n<blockquote>\n<pre><code> Pattern.compile("^((?!(\\\\{.*\\\\})).)*$")\n</code></pre>\n</blockquote>\n<p>use scalish way:</p>\n<pre><code> "^((?!(\\\\{.*\\\\})).)*$".r\n</code></pre>\n<p>Say <strong>No</strong> to <code>\\\\</code> in regex and instead of</p>\n<blockquote>\n<pre><code>"^((?!(\\\\{.*\\\\})).)*$"\n</code></pre>\n</blockquote>\n<p>use <code>"""</code> way:</p>\n<pre><code>"""^((?!(\\{.*\\})).)*$"""\n</code></pre>\n<h2>Return values without <code>val</code>/<code>var</code></h2>\n<p>You can simply write your <code>containsTag</code> without <code>val</code> and result of last line will return from function - it will return your's matches:</p>\n<pre><code>def containsTag(text: String): Boolean = {\n ! """^((?!(\\{.*\\})).)*$""".r.matches(text)\n}\n</code></pre>\n<h2>Choose your destiny</h2>\n<p>Sometimes it is good to use <code>if</code>/<code>else</code> but more readable <code>match</code>/<code>case</code>:</p>\n<pre><code>containsTag(text) match {\n case true =>\n val randomPosition = Random.nextInt(allCharacters.length - 1)\n text.replace("}", allCharacters(randomPosition).toString)\n case _ =>\n text\n}\n</code></pre>\n<h2>Feel the power</h2>\n<p>Collect it all together:</p>\n<pre><code> val allCharacters = "qwertyuiopasdfghjklzxcvbnmQWERTY" +\n "UIOPASDFGHJKLZXCVBNM1234567890!@#%*()_+-=[]{x}|?.;:`"\n\n def removeTags(text: String): String = {\n\n def containsTag(text: String): Boolean = {\n ! """^((?!(\\{.*\\})).)*$""".r.matches(text)\n }\n\n containsTag(text) match {\n case true =>\n val randomPosition = Random.nextInt(allCharacters.length - 1)\n text.replace("}", allCharacters(randomPosition).toString)\n case _ =>\n text\n }\n }\n\n val res = removeTags("my friendly {name} is $userNickname$")\n</code></pre>\n<h2>For random chars</h2>\n<p>According to <a href=\"https://stackoverflow.com/a/21261910/4367350\">answer</a> in <a href=\"https://stackoverflow.com/questions/21261737/replacing-characters-in-a-string-in-scala\">Replacing characters in a String in Scala</a> you can use construction without while loop but with <code>map</code> + <code>lambda</code> like in code below:</p>\n<pre><code> val allCharacters = "+=-?"\n\n def removeTags(text: String): String = {\n\n def containsTag(text: String): Boolean = {\n ! """^((?!(\\{.*\\})).)*$""".r.matches(text)\n true\n }\n\n containsTag(text) match {\n case true =>\n text.map(\n (c) => c match {\n case '{' =>\n val randomPosition = Random.nextInt(allCharacters.length - 1)\n allCharacters(randomPosition)\n case c => c // for another char which is not == {\n }\n )\n case _ =>\n text\n }\n }\n</code></pre>\n<p>Then it will be good to <strong>divide functionality</strong> and create new <code>Char => Char</code> transformer function from anonymous <code>(c) => c match {..}</code> which we lay in <code>text.map(...)</code>:</p>\n<pre><code>//...\ndef replaceRandom(c: Char): Char = {\n c match {\n case '{' =>\n val randomPosition = Random.nextInt(allCharacters.length - 1)\n allCharacters(randomPosition)\n case c => c\n }\n}\n\ncontainsTag(text) match {\n case true => text.map((c) => {replaceRandom(c)})\n case _ => text\n}\n//...\n</code></pre>\n<p><strong>Simplify</strong> code in two parts.</p>\n<p>Part 1: simplify <code>match/case</code> in <code>replaceRandom(c: Char): Char</code> :</p>\n<pre><code>def replaceRandom(c: Char): Char = {\n c match {\n case '{' =>\n val randomPosition = Random.nextInt(allCharacters.length - 1)\n allCharacters(randomPosition)\n case c => c\n }\n}\n\n// remove unneeded "{" and "}"\ndef replaceRandom2(c: Char): Char = c match {\n case '{' =>\n val randomPosition = Random.nextInt(allCharacters.length - 1)\n allCharacters(randomPosition) \n case c => c\n}\n</code></pre>\n<p>Then part 2: simplify <code>map((c) => {replaceRandom(c)})</code>:</p>\n<pre><code>containsTag(text) match {\n case true => text.map((c) => {replaceRandom(c)})\n case _ => text\n}\n\n//remove unneeded "{" and "}"\ncontainsTag(text) match {\n case true => text.map((c) => replaceRandom(c))\n case _ => text\n}\n\n//remove unneeded "(c)" to wildcard "_"\ncontainsTag(text) match {\n case true => text.map(replaceRandom(_))\n case _ => text\n}\n\n//remove unneeded wildcard "_"\ncontainsTag(text) match {\n case true => text.map(replaceRandom)\n case _ => text\n}\n</code></pre>\n<h2>Feel the power again</h2>\n<p>So for your task i will chose that variant: all functions are divided, logic placed is simple if/else and now good readable (as you see now it good readable also with if/else as i wrote to you above). After, when logic will grow you can use instead if/else match/case.</p>\n<pre><code> def removeTags(text: String): String = {\n\n def containsTag(text: String): Boolean = {\n ! """^((?!(\\{.*\\})).)*$""".r.matches(text)\n true\n }\n\n def replaceRandom(c: Char): Char = c match {\n case '{' =>\n val randomPosition = Random.nextInt(allCharacters.length - 1)\n allCharacters(randomPosition)\n case c => c\n }\n\n if (containsTag(text))\n text.map(replaceRandom)\n else text\n\n }\n\n val allCharacters = "+=-?"\n val e = "my fr{{{iend{{{ly {{name} is $userNickname$"\n println(removeTags(e))\n</code></pre>\n<hr />\n<p>P.S. or place to think</p>\n<ol>\n<li>Maybe your regex not working? Check it at: <a href=\"https://regex101.com/r/2PR2kC/1\" rel=\"nofollow noreferrer\">Regex101</a></li>\n<li>Why you need to replace <code>}</code> symbol with another random from <code>allCharacters </code> which can be also <code>}</code>?</li>\n<li>The bad, the good and the <code>!</code>: maybe try to rewrite your <code>!noTagsRegex</code> to <code>noTagsRegex</code>? It can be more readable for another people.</li>\n</ol>\n<blockquote>\n<p>Also i want to see additions to my review too, that code is too verbose, so welcome!</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T13:28:50.637",
"Id": "467077",
"Score": "0",
"body": "@Gussaf: Thanks a lot. This is a valuable feedback for me. I’m wondering if I replace the match by a while loop, it can try to replace the curly braces using the allCharacters variable until something that doesn’t match a tag."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T14:30:50.557",
"Id": "467083",
"Score": "0",
"body": "@Tom: why you need to replace `match/case` to `while loop`? I think that it is necessary to describe the task. You want to create loop which will replace curly braces over number of texts like \"take text1 and replace braces\" and then \"take text2 and replace braces\" and then \"take text3...\" and so on?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T06:36:16.893",
"Id": "467118",
"Score": "1",
"body": "@Gussaf: I've added more information in the question. Sorry if it wasn't clear before. The `while loop` would be useful if by picking a random character from `allCharacters` results in `{` again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T12:25:30.763",
"Id": "467145",
"Score": "1",
"body": "@Tom ok, update answer with that information - it really help to solve problem)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T22:13:03.033",
"Id": "238140",
"ParentId": "238131",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "238140",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T19:16:12.857",
"Id": "238131",
"Score": "4",
"Tags": [
"strings",
"scala"
],
"Title": "Clean up tags from a text"
}
|
238131
|
<p>I recently wrote a python code for <a href="https://www.geeksforgeeks.org/matrix-exponentiation/" rel="nofollow noreferrer">matrix exponentiation</a>.</p>
<p>Here's the code:</p>
<pre class="lang-py prettyprint-override"><code>from typing import List
Matrix = List[List[int]]
MOD = 10 ** 9 + 7
def identity(n: int) -> Matrix:
matrix = [[0] * n for _ in range(n)]
for i in range(n):
matrix[i][i] = 1
return matrix
def multiply(mat1: Matrix, mat2: Matrix, copy: Matrix) -> None:
r1, r2 = len(mat1), len(mat2)
c1, c2 = len(mat1[0]), len(mat2[0])
result = [[0] * c2 for _ in range(r1)]
for i in range(r1):
for j in range(c2):
for k in range(r2):
result[i][j] = (result[i][j] + mat1[i][k] * mat2[k][j]) % MOD
for i in range(r1):
for j in range(c2):
copy[i][j] = result[i][j]
def power(mat: Matrix, n: int) -> Matrix:
res = identity(len(mat))
while n:
if n & 1:
multiply(res, mat, res)
multiply(mat, mat, mat)
n >>= 1
return res
def fib(n: int) -> int:
if n == 0:
return 0
magic = [[1, 1],
[1, 0]]
mat = power(magic, n - 1)
return mat[0][0]
if __name__ == '__main__':
print(fib(10 ** 18))
</code></pre>
<p>I would mainly like to improve this code performance wise, but any comments on style is also much appreciated.</p>
<p>Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T15:29:05.150",
"Id": "467159",
"Score": "0",
"body": "Nothing wrong with your code, but this isn't actually the matrix exponential, it's a matrix power. https://en.wikipedia.org/wiki/Matrix_exponential"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T15:44:36.163",
"Id": "467163",
"Score": "0",
"body": "@Bijan Matrix _exponentiation_ is completely different from Matrix _exponential_. Matrix exponentiation is a popular topic in Competitive Programming."
}
] |
[
{
"body": "<p>Using the numpy module for numerical computations is often better as the code is generally simpler and much faster. Here is a version adapted to use numpy:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from typing import List\nimport numpy as np\nMatrix = np.matrix\n\nMOD = 10 ** 9 + 7\n\n\ndef power(mat: Matrix, n: int) -> Matrix:\n res = np.identity(len(mat), dtype=np.int64)\n\n while n:\n if n & 1:\n np.matmul(res, mat, out=res)\n res %= MOD\n\n np.matmul(mat, mat, out=mat)\n mat %= MOD # Required for numpy if you want correct results\n n >>= 1\n\n return res\n\n\ndef fib(n: int) -> int:\n if n == 0:\n return 0\n\n magic = np.matrix([[1, 1], [1, 0]], dtype=np.int64)\n mat = power(magic, n - 1)\n return mat[0,0]\n\n\nif __name__ == '__main__':\n print(fib(10 ** 18))\n</code></pre>\n\n<p>As you can see, using numpy reduce significantly the size of the code since it provide primitive for creating and computing matrices (eg. matrix multiplication).\nNumpy is also faster since it uses fast native code to perform the computations. However, here, your matrices are too small so that numpy can provide any speed-up.\nAlso note that numpy as a downside: it does not support large integers as python does. So, the code above works well as long as you do not increase too much the value of <code>MOD</code>. You can use <code>dtype=object</code> to force numpy to support large integers but it will be slower (especially on bigger matrices).</p>\n\n<p>Besides using numpy, you can also specialize your code to compute 2x2 matrices much faster in this specific case. Here is the result:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from typing import List\nMatrix = List[List[int]]\n\nMOD = 10 ** 9 + 7\n\n\ndef identity_2x2() -> Matrix:\n return [1, 0, 0, 1]\n\n\ndef multiply_2x2(mat1: Matrix, mat2: Matrix, copy: Matrix) -> None:\n a00, a01, a10, a11 = mat1\n b00, b01, b10, b11 = mat2\n\n copy[0] = (a00 * b00 + a01 * b10) % MOD\n copy[1] = (a00 * b01 + a01 * b11) % MOD\n copy[2] = (a10 * b00 + a11 * b10) % MOD\n copy[3] = (a10 * b01 + a11 * b11) % MOD\n\n\ndef power_2x2(mat: Matrix, n: int) -> Matrix:\n res = identity_2x2()\n\n while n:\n if n & 1:\n multiply_2x2(res, mat, res)\n\n multiply_2x2(mat, mat, mat)\n\n n >>= 1\n\n return res\n\n\ndef fib(n: int) -> int:\n if n == 0:\n return 0\n\n magic = [1, 1, 1, 0]\n mat = power_2x2(magic, n - 1)\n return mat[0]\n\n\nif __name__ == '__main__':\n print(fib(10 ** 18))\n</code></pre>\n\n<p>This is faster because the default interpreter (CPython) executes loops very slowly, so it is better to avoid them as much as possible. It is also faster because no additional list is created. </p>\n\n<p>Please note that if you want your code to run faster, you could use the <a href=\"https://www.pypy.org/\" rel=\"nofollow noreferrer\">PyPy</a> interpreter.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T14:50:49.217",
"Id": "467157",
"Score": "0",
"body": "Great answer! But why does the first code output `0`? Also, I'm using this as a template for matrix exponentiation problems in general, so the code has to be flexible!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T15:23:00.480",
"Id": "467158",
"Score": "0",
"body": "It does not return `0` on my machine, neither on an [online python IDE](https://repl.it/languages/python3). Maybe you are running on a 32 bits system where np.int64 are not supported? Try to test with smaller inputs to see if this is due to an integer overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T15:39:58.630",
"Id": "467161",
"Score": "0",
"body": "Yes, you're right. I have a 32-bit system and the code does work for smaller values. Is there any way I can make it work on a 32-bit system? Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T18:14:17.317",
"Id": "467179",
"Score": "0",
"body": "I just discover that can use `dtype=object` as a fallback solution to solve this but note that it could be much slower (although probably not more that if it was done in pure python)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T18:21:29.543",
"Id": "467181",
"Score": "0",
"body": "It shows `TypeError: Object arrays are not currently supported` when I run it. Full error: https://hastebin.com/inuxureyoz.txt"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T18:28:18.260",
"Id": "467183",
"Score": "0",
"body": "Wow, that quite surprising. Which version of python do you have?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T18:29:47.827",
"Id": "467184",
"Score": "0",
"body": "The version I have is 3.6"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T18:29:59.200",
"Id": "467185",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/105055/discussion-between-srivaths-and-jerome-richard)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-01T11:30:11.783",
"Id": "238191",
"ParentId": "238132",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T19:38:35.730",
"Id": "238132",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"matrix"
],
"Title": "Matrix Exponentiation in Python"
}
|
238132
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.