body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I'm having some issues understanding why PDO is 6X slower executing a query than the depreciated MySQL query function. Here's my code:</p> <pre><code>$conn = new PDO('mysql:host=localhost;dbname=work', 'root', 'Montreal'); protected function query_s($table, $col = '*', $where_col , $where, $return_col) { $q = $conn-&gt;query("SELECT $col FROM $table WHERE $where_col='".$where."' LIMIT 1"); $f = $q-&gt;fetch(); $result = $f[$return_col]; return $result; } </code></pre> <p>Which retrieves 1 piece of information for a specific column. </p> <p>The old code:</p> <pre><code>protected function query_s($table, $col = '*', $where_col , $where, $return_col) { $SQL = mysql_query("SELECT $col FROM ".$table." WHERE $where_col='$where' LIMIT 1") or die(mysql_error()); $data = mysql_fetch_array($SQL); $this-&gt;query_rows = mysql_num_rows($SQL); return $data[$return_col]; } </code></pre> <p>As soon as I run the <code>PDO</code> version in a while loop through a database search (user tries to find something), it takes almost 6 seconds to retrieve 50 rows... Normally, it would take around 0.02 seconds with the <code>MySQL</code> function</p> <p>I'm fairly new with PDO and I'm trying to write new code with it. I'm missing something here.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-24T19:26:09.550", "Id": "41192", "Score": "0", "body": "Take a look at the Database class here: http://codereview.stackexchange.com/questions/26507/generic-method-for-database-calls" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T13:15:53.350", "Id": "41339", "Score": "0", "body": "Please post your calling code for each test." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T19:22:26.657", "Id": "41412", "Score": "0", "body": "What I'm noticing is that I have to create a completely separate class to call my every query. I also noticed that making the connection within a class' method is A LOT slower than making the connection within the `__construct()` function... I'm quite confused." } ]
[ { "body": "<p>Change your connection string from host=localhost to host=127.0.0.1, for some reason PDO is slow at resolving the host name, just when using PDO always use the IP address of the server.</p>\n\n<p>Also why are you fetching one row at a time when you need 50?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T20:07:09.967", "Id": "26818", "ParentId": "26581", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-24T18:01:20.003", "Id": "26581", "Score": "2", "Tags": [ "php", "mysql", "pdo" ], "Title": "MySQL vs PDO execution time" }
26581
<p>I have the <code>List</code> method that takes sorting parameter to sort results. The sorting parameter value is the same as the column name.</p> <pre><code>public ActionResult List(string sorting = "Name", string sortingMethod = "ASC") { var productList = productRepository.Get(); if(!String.IsNullOrEmpty(Sorting){ if(String.IsNullOrEmpty(SortingMethod) ||SortingMethod == "ASC"){ switch(sorting){ case "Name" : productList = productList.OrderBy(x =&gt; x.Name); break; case "Price" : productList = productList.OrderBy(x =&gt; x.Price); break; case "Category" : productList = productList.OrderBy(x =&gt; x.Price); break; //... } }else{ switch(sorting){ case "Name" : productList = productList.OrderByDescending(x =&gt; x.Name); break; case "Price" : productList = productList.OrderByDescending(x =&gt; x.Price); break; case "Category" : productList = productList.OrderByDescending(x =&gt; x.Price); break; //... } } } return View(productList.ToList()); } </code></pre> <p>But I believe there is a better way to make code shorter.</p> <pre><code>public ActionResult List(string sorting = "Name", string sortingMethod = "ASC") { var productList = productRepository.Get(); if(!String.IsNullOrEmpty(Sorting){ if(String.IsNullOrEmpty(SortingMethod) ||SortingMethod == "ASC"){ productList = productList.OrderBy(); // &lt;== ??? }else{ productList = productList.OrderByDescending(); // &lt;== ??? } } return View(productList.ToList()); } </code></pre>
[]
[ { "body": "<p>What about seperating your sorting from your criteria? I'm like you, I'm sure there is another way so am interested to see other opinions. I'm not exactly sure if this would scale for multiple orderBys either but I think it might (NOTE: this code is untested and some types are not defined)</p>\n\n<p>Something along the lines of:</p>\n\n<pre><code>public ActionResult List(string sorting = \"Name\", string sortingMethod = \"ASC\")\n{\n var sortDirection = GetSortDirection(sortingMethod);\n var criteria = GetSortCriteria(sorting);\n\n var products = GetProductsOrderBy(criteria, sortDirection);\n\n return View(products.ToList());\n}\n\n// I'm not actually sure of the return type here. Will attempt to test when I\n// get in front of my development pc\nFunc&lt;Product, object&gt; GetSortCriteria(string sortOn) \n{\n switch(sortOn) \n {\n case \"Price\":\n case \"Category\":\n return x =&gt; x.Price;\n default:\n return x.Name;\n }\n}\n\nIEnumerable&lt;ProductList&gt; GetProductsOrderBy(Action sortOn, SortDirection sortDirection)\n{\n var productList = productRepository.Get();\n\n return sortDirection == SortDirection.Ascending ?\n productList.OrderBy(sortOn) :\n productList.OrderByDescending(sortOn);\n}\n\nSortDirection GetSortDirection(string sortBy) \n{\n return sortBy == \"ASC\" ? SortDirection.Ascending : SortDirection.Descending;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T18:26:45.147", "Id": "41410", "Score": "0", "body": "I just tried the code, but it's not working. Error message say : The type arguments for method 'System.Linq.Queryable.OrderBy<TSource,TKey>(System.Linq.IQueryable<TSource>, System.Linq.Expressions.Expression<System.Func<TSource,TKey>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. C:\\Users\\mark\\documents\\visual studio 2012\\..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T21:13:50.857", "Id": "41415", "Score": "0", "body": "@Expertwannabe I thought that might be the case but wasn't 100 when typing. I'll have another think and try another option." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-24T19:55:14.280", "Id": "26586", "ParentId": "26584", "Score": "1" } } ]
{ "AcceptedAnswerId": "26586", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-24T19:03:41.460", "Id": "26584", "Score": "1", "Tags": [ "c#", "asp.net", "sorting" ], "Title": "Lamba sorting for results" }
26584
<p>I implemented sleepsort in Go. I am new to channels, and I'd like to get some advice on them, especially on how to close channels after N messages have been sent on them. Currently I use a counter and an if statement (see the second for loop in <code>Sleepsort</code>), but maybe this can be done in a nicer way?</p> <pre><code>package main import ( "fmt" "time" ) func sleep(n int, channel chan&lt;- int) { time.Sleep(time.Duration(n) * time.Second) channel &lt;- n } func Sleepsort(xs []int) []int { channel := make(chan int, len(xs)) for _, x := range xs { go sleep(x, channel) } result := make([]int, len(xs)) i := 0 for x := range channel { result[i] = x i++ if i == len(xs) { close(channel) } } return result } func main() { xs := []int{2, 5, 2, 1, 4, 3, 5} fmt.Printf("%v\n", Sleepsort(xs)) } </code></pre> <p>Other advice is also very appreciated.</p>
[]
[ { "body": "<p>I'm self-answering since I found a nicer way to do this.</p>\n\n<p>In this case, you can loop from 0 to N and receive from the channel manually, rather than using <code>range</code>.</p>\n\n<pre><code>for i := 0; i &lt; len(xs); i++ {\n result[i] = &lt;-channel\n}\nclose(channel)\n</code></pre>\n\n<p><code>close(channel)</code> is not strictly needed here since the channel would already be closed by the garbage collector.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-10T08:13:36.730", "Id": "51970", "Score": "2", "body": "Or even, `for i := range result { result[i] = <-channel }`: http://play.golang.org/p/KeSVFxJcYF" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-24T21:28:52.667", "Id": "26588", "ParentId": "26587", "Score": "4" } } ]
{ "AcceptedAnswerId": "26588", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-24T21:10:08.660", "Id": "26587", "Score": "4", "Tags": [ "go", "concurrency" ], "Title": "Sleepsort in Go" }
26587
<p>I got this class in C# which works fine. But I was wondering if there was a more elegant solution to what I am trying to do. It looks rather clumsy and inefficient for a Logging functionality.</p> <p>The code should be fairly self-explanatory.</p> <pre><code>public static class Log { public static string EngineName { get; set; } private static List&lt;String&gt; logdata = new List&lt;string&gt;(); static void LogMessage(string msg) { Console.WriteLine("[{0}][LOG]: {1}", EngineName, msg); StringBuilder sb = new StringBuilder(); sb.Append("[").Append(EngineName).Append("][LOG]: ").Append(msg); logdata.Add(sb.ToString()); } public static void EngineMessage(string msg) { Console.WriteLine("[{0}][ENGINE]: {1}", EngineName, msg); StringBuilder sb = new StringBuilder(); sb.Append("[").Append(EngineName).Append("][Engine]: ").Append(msg); logdata.Add(sb.ToString()); } public static void ExceptionMessage(Exception e) { Console.WriteLine("[{0}][EXCEPTION]: {1}", EngineName, e.Message); StringBuilder sb = new StringBuilder(); sb.Append("[").Append(EngineName).Append("][EXCEPTION]: ").Append(e.Message); logdata.Add(sb.ToString()); } public static void CustomMessage(string title, string msg) { title.ToUpper(); Console.WriteLine("[{0}][{1}]: {2}", EngineName, title, msg); StringBuilder sb = new StringBuilder(); sb.Append("[").Append(EngineName).Append("][").Append(title).Append("]: ").Append(msg); logdata.Add(sb.ToString()); } public static void ClearLogData() { logdata.Clear(); } public static void PrintLog() { Console.WriteLine("===== LOG DATA =====\n"); Console.WriteLine(new DateTime().ToString()+"\n"); foreach(string s in logdata) { Console.WriteLine(s + "\n"); } } public static void SaveLog(string path) { throw new NotSupportedException(); } } </code></pre> <p><strong>EDIT</strong></p> <p>Based on feedback from the accepted answer here is my revised code:</p> <pre><code>public static class Log { public static string EngineName { get; set; } private static List&lt;String&gt; logdata = new List&lt;string&gt;(); public static void LogMessage(string msg, ELogflag flag, string title = "") { StringBuilder sb = new StringBuilder(); sb.Append("[" + EngineName + "]"); switch (flag) { case ELogflag.LOG: sb.Append("[LOG]"); break; case ELogflag.ENGINE: sb.Append("[ENGINE]"); break; case ELogflag.CRITICAL: sb.Append("[CRITICAL]"); break; case ELogflag.CUSTOM: title = title.ToUpper(); sb.Append("[" + title + "]"); break; default: sb.Append("[UNKNOWN]"); break; } sb.Append(msg); Console.WriteLine(sb.ToString()); logdata.Add(sb.ToString()); } public static void ClearLogData() { logdata.Clear(); } public static void PrintLog() { Console.WriteLine("===== LOG DATA =====\n"); Console.WriteLine(new DateTime().ToString() + "\n"); foreach (string s in logdata) { Console.WriteLine(s + "\n"); } } public static void SaveLog(string path) { throw new NotSupportedException(); } } </code></pre> <p>And my new Enum:</p> <pre><code>enum ELogflag { LOG, ENGINE, CRITICAL, CUSTOM } </code></pre>
[]
[ { "body": "<p>C# is not my main language, so I apologize for any mistakes that may exist in the following code.</p>\n\n<hr>\n\n<p>There is quite a bit of duplication in this class. It seems like <code>LogMessage()</code>, <code>EngineMessage()</code> and <code>ExceptionMessage()</code> could all delegate to <code>CustomMessage()</code>. For example:</p>\n\n<pre><code>public static void LogMessage(string msg)\n{\n CustomMessage(\"LOG\", msg);\n}\n\n// etc ...\n</code></pre>\n\n<hr>\n\n<p>It also looks like the same string is being built twice in each function. It would be better to create the string once. Maybe something like this instead:</p>\n\n<pre><code>string logMsg = String.Format(\"[{0}][{1}]: {2}\", EngineName, title, msg);\nConsole.WriteLine(logMsg);\nlogdata.Add(logMsg);\n</code></pre>\n\n<hr>\n\n<pre><code>title.ToUpper();\n</code></pre>\n\n<p>Does this work? I would not expect this to modify the string in place, but rather return a new string. You probably need to do this:</p>\n\n<pre><code>title = title.ToUpper();\n</code></pre>\n\n<hr>\n\n<p>With the above changes:</p>\n\n<pre><code>public static void LogMessage(string msg)\n{\n CustomMessage(\"LOG\", msg);\n}\n\npublic static void EngineMessage(string msg)\n{\n CustomMessage(\"ENGINE\", msg);\n}\n\npublic static void ExceptionMessage(Exception e)\n{\n CustomMessage(\"EXCEPTION\", msg);\n}\n\npublic static void CustomMessage(string title, string msg)\n{\n string logMsg = String.Format(\"[{0}][{1}]: {2}\", EngineName, title.ToUpper(), msg);\n Console.WriteLine(logMsg);\n logdata.Add(logMsg);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T00:09:45.617", "Id": "41211", "Score": "0", "body": "Just wanted some standard methods to call. If nothing fits the standard calls, do a Custom message for the log. Maybe I could make an Enum with flags. ENGINE, LOG, EXCEPTION, CUSTOM, and then just check for that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T00:25:44.137", "Id": "41212", "Score": "0", "body": "You can keep those standard methods and still eliminate much of the duplication by delegating to `CustomMessage()`. I've updated my answer to hopefully make that clearer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-24T23:44:21.743", "Id": "26593", "ParentId": "26590", "Score": "1" } }, { "body": "<p>Have you considered using <a href=\"http://nuget.org/packages/log4net\" rel=\"nofollow\">log4net</a>? If not I would recommend this as a simple and well tested logging framework:</p>\n\n<p>Other considerations to the implementation might include:</p>\n\n<ol>\n<li>Threadsafety. I don't think (?) this code is threadsafe. You could call LogMessage at the same time as PrintLog is being called causing contention in the logData list. You might want to take a look at <a href=\"http://msdn.microsoft.com/en-us/library/dd997305.aspx\" rel=\"nofollow\">thread safe lists</a> if available.</li>\n</ol>\n\n<p>My simple re-work of the methods to try and make your LogMessage method a bit more focused:</p>\n\n<pre><code>public static class Log\n{\n public static string EngineName { get; set; } \n private static readonly List&lt;String&gt; logdata = new List&lt;string&gt;();\n\n public static void LogMessage(string msg, ELogflag flag, string title = \"\")\n {\n StringBuilder sb = new StringBuilder();\n sb.Append(Format(EngineName));\n sb.Append(Format(LogType(flag, title)));\n sb.Append(msg);\n\n string errorMessage = sb.ToString();\n\n WriteLine(errorMessage);\n logdata.Add(errorMessage);\n }\n\n public static void ClearLogData()\n {\n logdata.Clear();\n }\n\n public static void PrintLog()\n {\n WriteLine(\"===== LOG DATA =====\");\n WriteLine(new DateTime().ToString());\n foreach (string s in logdata)\n {\n WriteLine(s);\n }\n }\n\n // Single method reponsible for doing the actual write. If you later\n // decide to write to a file for example this is the only method that needs changing\n private static void WriteLine(string msg)\n {\n Console.WriteLine(msg + \"\\n\");\n }\n\n private static void WriteLine(StringBuilder msg)\n {\n WriteLine(msg.ToString());\n }\n\n // We don't need to use a switch here. Just get the name from the enum\n private static string LogType(ELogflag flag, string customMsg = \"\")\n {\n string message = flag == ELogflag.CUSTOM ? customMsg : flag.ToString();\n return message.ToUpper();\n }\n\n // Single method for determining the format of your headers\n private static string Format(string message)\n {\n return string.Format(\"[{0}]\", message);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T09:56:20.543", "Id": "41226", "Score": "0", "body": "You are right that it isn't thread-safe which is something I have to check on if I started to thread my application. I will have a look at the Log Framework though. Could be interesting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T19:42:41.350", "Id": "41243", "Score": "0", "body": "@Vipar I believe it can be installed via a Nuget package as well which should make it a bit easier to get started" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T20:09:19.313", "Id": "41245", "Score": "0", "body": "How delightful. I'll look into it :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T08:11:13.630", "Id": "26599", "ParentId": "26590", "Score": "1" } } ]
{ "AcceptedAnswerId": "26593", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-24T22:55:25.390", "Id": "26590", "Score": "4", "Tags": [ "c#", "logging" ], "Title": "More Elegant Solution to Logging Class" }
26590
<p>I am writing a game like Pong. Therefore I am using an entity system approach, so I use a Component-based design.</p> <p>The hardest part until now was to write the collision system. As I just began with the component based design I am sometimes very unsure how to do something with this approach. With a "normal" OOP approach I would just have a ball class which has special collision, and a paddle class which interacts with the ball etc.</p> <p>But here it is different as I am not able to tell which object I am looking at because I just have a collection of components. So I can only know what the object could do and what data it holds.</p> <p>My code is in Blitzmax, which is not used that often.</p> <p>Here is the code of the system:</p> <pre><code>Rem bbdoc: Collision system to handly collisions between entities. End Rem Type TCollision_System Extends TSystem rem bbdoc: If objects collide, one of them is moved back by this distance. endrem Const MOVE_AWAY_DISTANCE:Int = 2 rem bbdoc: Constructor for collision system. Here are just all initial things done. endrem Function Create:TSystem(entity_Manager:TEntityManager) Local system:TCollision_System = New TCollision_System system.entity_Manager = entity_Manager system.required_Components = New TList system._init_Required_Components() Return system End Function Rem bbdoc: Required component types are registered in the list to get compatible entities. endrem Method _init_Required_Components() Self.required_Components.AddLast(TComponent_Type.COLLISION_COMPONENT) Self.required_Components.AddLast(TComponent_Type.POSITION_COMPONENT) Self.required_Components.AddLast(TComponent_Type.RENDER_COMPONENT) End Method Rem bbdoc: Here the actual collision is done. Every possible kind of collision is handled here. endrem Method update() 'Get all compatible entities to check them for collision. Local entities_Collision:TList = Self.entity_Manager.get_All_Entities_With_Components_With_Type(Self.required_Components) For Local entity_One:TEntity = EachIn entities_Collision Local render_Components_One:TList = Self.entity_Manager.get_Components_With_Type_Of_Entity(TComponent_Type.RENDER_COMPONENT, entity_One) Local position_Components_One:TList = Self.entity_Manager.get_Components_With_Type_Of_Entity(TComponent_Type.POSITION_COMPONENT, entity_One) Local collision_Components_One:TList = Self.entity_Manager.get_Components_With_Type_Of_Entity(TComponent_Type.COLLISION_COMPONENT, entity_One) 'We assume that only one component is used for collision, so we do not iterate through the lists of components. Local render_One:TRender_Component = TRender_Component(render_Components_One.First()) Local position_One:TPosition_Component = TPosition_Component(position_Components_One.First()) Local collision_One:TCollision_Component = TCollision_Component(collision_Components_One.First()) For Local entity_Two:TEntity = EachIn entities_Collision 'Do nothing if the both objects are the same - An object cannot collide with itself. If(entity_One = entity_Two) Then Continue EndIf Local render_Components_Two:TList = Self.entity_Manager.get_Components_With_Type_Of_Entity(TComponent_Type.RENDER_COMPONENT, entity_Two) Local position_Components_Two:TList = Self.entity_Manager.get_Components_With_Type_Of_Entity(TComponent_Type.POSITION_COMPONENT, entity_Two) Local collision_Components_Two:TList = Self.entity_Manager.get_Components_With_Type_Of_Entity(TComponent_Type.COLLISION_COMPONENT, entity_Two) 'As above, only one component is needed, not the complete list. Local render_Two:TRender_Component = TRender_Component(render_Components_Two.First()) Local position_Two:TPosition_Component = TPosition_Component(position_Components_Two.First()) Local collision_Two:TCollision_Component = TCollision_Component(collision_Components_Two.First()) 'If both objects are static, then do nothing, because actually there is no collision, as they never moved. If(collision_One.get_Is_Static() And collision_Two.get_Is_Static()) Then Continue EndIf If(ImagesCollide(render_One.get_Image(), position_One.get_X(), position_One.get_Y(), 0, render_Two.get_Image(), position_Two.get_X(), position_Two.get_Y(), 0)) Then 'As long as the images collide, we have to move the objects. While(ImagesCollide(render_One.get_Image(), position_One.get_X(), position_One.get_Y(), 0, render_Two.get_Image(), position_Two.get_X(), position_Two.get_Y(), 0)) 'Calculate the outer positions of the first object (this is just where the image ends). Local max_Point_One:TVector2 = TVector2.Create(position_One.get_X() + render_One.get_Frame_Width() / 2.0, position_One.get_Y() + render_One.get_Frame_Height() / 2.0) Local min_Point_One:TVector2 = TVector2.Create(position_One.get_X() - render_One.get_Frame_Width() / 2.0, position_One.get_Y() - render_One.get_Frame_Height() / 2.0) 'Calculate the outer positions of the second object (where the iamge ends). Local max_Point_Two:TVector2 = TVector2.Create(position_Two.get_X() + render_Two.get_Frame_Width() / 2.0, position_Two.get_Y() + render_Two.get_Frame_Height() / 2.0) Local min_Point_Two:TVector2 = TVector2.Create(position_Two.get_X() - render_Two.get_Frame_Width() / 2.0, position_Two.get_Y() - render_Two.get_Frame_Height() / 2.0) 'First: Check if the objects overlap on the y-axis. If((position_One.get_Y() &lt;= max_Point_Two.get_Y() And position_One.get_Y() &gt;= min_Point_Two.get_Y()) Or (position_Two.get_Y() &lt;= max_Point_One.get_Y() And position_Two.get_Y() &gt;= min_Point_One.get_Y())) Then 'They also have to overlap on the x-axis. If(max_Point_Two.get_X() &gt; min_Point_One.get_X() And min_Point_Two.get_X() &lt; max_Point_One.get_X()) Then 'Decide which object has to be pushed in which direction. If(min_Point_Two.get_X() &lt; min_Point_One.get_X()) Then If(Not(collision_Two.get_Is_Static_X())) Then position_Two.add_X(-MOVE_AWAY_DISTANCE) Else If(Not(collision_One.get_Is_Static_X())) Then position_One.add_X(MOVE_AWAY_DISTANCE) EndIf EndIf Else If(Not(collision_Two.get_Is_Static_X())) Then position_Two.add_X(MOVE_AWAY_DISTANCE) Else If(Not(collision_One.get_Is_Static_X())) Then position_One.add_X(-MOVE_AWAY_DISTANCE) EndIf EndIf EndIf EndIf EndIf 'First: Check if the objects overlap on the x-axis. If((position_One.get_X() &lt;= max_Point_Two.get_X() And position_One.get_X() &gt;= max_Point_Two.get_X()) Or (position_Two.get_X() &lt;= max_Point_One.get_X() And position_Two.get_X() &gt;= min_Point_One.get_X())) Then 'They also have to overlap on the y-axis. If(max_Point_Two.get_Y() &gt; min_Point_One.get_Y() And min_Point_Two.get_Y() &lt; max_Point_One.get_Y()) Then 'Decide which object has to be pushed in which direction. If(min_Point_Two.get_Y() &lt; min_Point_One.get_Y()) Then If(Not(collision_Two.get_Is_Static_Y())) Then position_Two.add_Y(-MOVE_AWAY_DISTANCE) Else If(Not(collision_One.get_Is_Static_Y())) Then position_One.add_Y(MOVE_AWAY_DISTANCE) EndIf EndIf Else If(Not(collision_Two.get_Is_Static_Y())) Then position_Two.add_Y(MOVE_AWAY_DISTANCE) Else If(Not(collision_One.get_Is_Static_Y())) Then position_One.add_Y(MOVE_AWAY_DISTANCE) EndIf EndIf EndIf EndIf EndIf Wend 'Now handle the collision of each object alone. This is used for physic things. If(Not(collision_One.get_Is_Static())) Then Self._handle_Collision_Single(entity_One, position_One, render_One, position_Two, render_Two) EndIf If(Not(collision_Two.get_Is_Static())) Then Self._handle_Collision_Single(entity_Two, position_Two, render_Two, position_One, render_One) EndIf EndIf Next Next End Method Rem bbdoc: Here everything which should be only done once per collision is done with a single object. endrem Method _handle_Collision_Single(entity_Active:TEntity, position_Component:TPosition_Component, render_Component:TRender_Component, position_Passive:TPosition_Component, render_Passive:TRender_Component) 'Actually it should not happen. But better check for NULL reference. If(Self.entity_Manager.get_Components_With_Type_Of_Entity(TComponent_Type.movement_Component, entity_Active) &lt;&gt; Null) Then Local movement_Components_List:TList = Self.entity_Manager.get_Components_With_Type_Of_Entity(TComponent_Type.MOVEMENT_COMPONENT, entity_Active) 'Here as well: We use only one movement component. Local movement_Component:TMovement_Component = TMovement_Component(movement_Components_List.First()) 'If the entity has a physics component, then calculate everything. Otherwise just set velocity to zero. If(Self.entity_Manager.get_Components_With_Type_Of_Entity(TComponent_Type.physics_Component, entity_Active) &lt;&gt; Null) Then 'Get the borders of the second object (only x-axis) Local x_Pos_Max_Two:Float = position_Passive.get_X() + render_Passive.get_Frame_Width() / 2.0 Local x_Pos_Min_Two:Float = position_Passive.get_X() - render_Passive.get_Frame_Width() / 2.0 'Get the borders of the actual object (only x-axis) Local x_Pos_Max_One:Float = position_Component.get_X() + render_Component.get_Frame_Width() / 2.0 Local x_Pos_Min_One:Float = position_Component.get_X() - render_Component.get_Frame_Width() / 2.0 Local is_normal_Horizontally:Byte 'Check if the objects collide on the x-axis or the y-axis. If(x_Pos_Min_One &lt;= x_Pos_Max_Two And x_Pos_Max_One &gt;= x_Pos_Min_Two) Then is_normal_Horizontally = True Else is_normal_Horizontally = False EndIf 'Get the normal vector of the second object (the passive object) to calculate reflection. Local normal_Vector:TVector2 = Self.get_Normal(position_Passive, render_Passive, is_normal_Horizontally) 'Store the velocity as a vector to handle it more easily. Local velocity:TVector2 = TVector2.Create(movement_Component.get_X_Velocity(), movement_Component.get_Y_Velocity()) 'Here the reflected vector is calculated. 'Let r be the reflected vector. 'Then it is: r = v - 2 * n * (n*v), where n is the normal vector of the passive object and v is the velocity vector. Local scalar:Float = normal_Vector.scalar_Multiplication(velocity) * 2 Local second_Part:TVector2 = normal_Vector.scale_New(scalar) second_Part.scale(-1.0) Local new_Velocity:TVector2 = velocity.add_New(second_Part) Rem \v |n /r \ | / \ | / _____\|/_____ endrem 'Set the new velocity vector. movement_Component.set_X_Velocity(new_Velocity.get_X()) movement_Component.set_Y_Velocity(new_Velocity.get_Y()) Else movement_Component.set_X_Velocity(0) movement_Component.set_Y_Velocity(0) EndIf EndIf End Method Rem bbdoc: Calculates the normal vector of a line which is given by the passive object. endrem Method get_Normal:TVector2(position:TPosition_Component, render:TRender_Component, horizontally:Byte) Local start_Point:TVector2 Local end_Point:TVector2 'If vertically is true, then the line is horizontally, otherwise the line is vertically. If(horizontally) Then start_Point = TVector2.Create(position.get_X(), position.get_Y()) end_Point = TVector2.Create(position.get_X() + render.get_Frame_Width() / 2.0, position.get_Y()) Else start_Point = TVector2.Create(position.get_X(), position.get_Y()) end_Point = TVector2.Create(position.get_X(), position.get_Y() + render.get_Frame_Height() / 2.0) EndIf 'Calculate the normal by using two given points on the line. Return TVector2.make_Normal(start_Point, end_Point) End Method Rem bbdoc: This method does nothing in this system. endrem Method draw() End Method End Type </code></pre> <p>This is the vector class which is used in the system, just if someone needs to look up some methods:</p> <pre><code>Rem bbdoc: 2D Vector representation. endrem Type TVector2 Field x:Float Field y:Float Rem bbdoc: Constructor. Creates vector which has the given components. endrem Function Create:TVector2(x:Float, y:Float) Local vec:TVector2 = New TVector2 vec.x = x vec.y = y Return vec End Function '#region Getter/Setter Method get_X:Float() Return Self.x End Method Method get_Y:Float() Return Self.y End Method Method set_X(new_X:Float) Self.x = new_X End Method Method set_Y(new_Y:Float) Self.y = new_Y End Method Method get_Length:Float() Local x_Quad:Float = Self.x * Self.x Local y_Quad:Float = Self.y * Self.y Return Sqr(x_Quad + y_Quad) End Method '#endregion Method add_X(value:Float) Self.x = Self.x + value End Method Method add_Y(value:Float) Self.y = Self.y + value End Method Method add(to_Add:TVector2) Self.x = Self.x + to_add.get_X() Self.y = Self.y + to_add.get_Y() End Method Method scale(factor:Float) Self.x = Self.x * factor Self.y = Self.y * factor End Method Method scale_X(factor:Float) Self.x = Self.x * factor End Method Method scale_Y(factor:Float) Self.y = Self.y * factor End Method Method normalize() Local length:Float = Self.get_Length() Self.x = Self.x * (1.0 / length) Self.y = Self.y * (1.0 / length) End Method Method normalize_New:TVector2() Local length:Float = Self.get_Length() Local new_Vec:TVector2 = TVector2.Create(Self.x * (1.0 / length), Self.y * (1.0 / length)) Return new_Vec End Method Method scalar_Multiplication:Float(other_Vector:TVector2) Return(Self.x * other_Vector.get_X() + Self.y * other_Vector.get_Y()) End Method Method scale_New:TVector2(factor:Float) Local new_Vec:TVector2 = TVector2.Create(Self.x * factor, Self.y * factor) Return new_Vec End Method Method add_New:TVector2(to_Add:TVector2) Local new_Vec:TVector2 = TVector2.Create(Self.x + to_Add.get_X(), Self.y + to_Add.get_Y()) Return new_Vec End Method Function make_Normal:TVector2(start_Position:TVector2, goal_Position:TVector2) Local directional_Vector:TVector2 = TVector2.Create(goal_Position.get_X() - start_Position.get_X(), goal_Position.get_Y() - start_Position.get_Y()) Local normal_Vector:TVector2 = TVector2.Create(directional_Vector.get_Y(), -directional_Vector.get_X()) normal_Vector.normalize() Return normal_Vector End Function End Type </code></pre> <p>I tried to not tell in the comments what is done, but why it is done. This is pretty hard to do.</p> <p>My actual question is now: What do you think about the code? How would you improve it? What is not so good about the code (e.g. performance, readability, maybe possible errors etc.)?</p> <p>As far as I tried it, the code works for each possible case (ball hits boundaries, ball hits paddle from the side, ball hits paddle from up or down).</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-24T23:00:10.563", "Id": "26591", "Score": "4", "Tags": [ "performance", "collision", "graphics", "entity-component-system", "basic-lang" ], "Title": "Collision system in Pong-like game" }
26591
<p>I am trying to calculate work progress in percentage. I have multiple batches, and each batch contains a set of tasks and each task also contains a set of sub tasks. Below code is the best I could do. Is there any more efficient way to do this?</p> <p>I just edited the code using the Math static method to do help with rounding and getting the next up value.</p> <pre><code> double numOfBatches = 3; double weightOfEachBatch = (1*100)/numOfBatches; double numOfTasksInEachBatch = 1; double weightOfEachTask = (1*weightOfEachBatch)/numOfTasksInEachBatch; double numOfSubTasksInEachTask = 2; double weightOfEachSubTask = (1*weightOfEachTask)/numOfSubTasksInEachTask; System.out.println("Weight of each batch: " + weightOfEachBatch + "%"); System.out.println("Weight of each task: " + weightOfEachTask + "%"); System.out.println("Weight of each sub task: " + weightOfEachSubTask + "%"); double fromBatchWeight = 0; for(int i = 1; i &lt;= numOfBatches; i++) { double toBatchWeight = weightOfEachBatch * i; System.out.println( "Batch " + i + " from " + Math.floor(fromBatchWeight) + "% to " + Math.floor(toBatchWeight) + "%"); double fromTaskWeight = fromBatchWeight; for(int j = 1; j &lt;= numOfTasksInEachBatch; j++) { double toTaskWeight = (weightOfEachTask * j) + fromBatchWeight; System.out.println( "\tTask " + j + " from " + Math.floor(fromTaskWeight) + "% to " + Math.floor(toTaskWeight) + "%"); double fromSubTaskWeight = fromTaskWeight; for(int k = 1; k &lt;= numOfSubTasksInEachTask; k++) { double toSubTaskWeight = (weightOfEachSubTask * k) + fromTaskWeight; System.out.println( "\t\tSub Task " + k + " from " + Math.floor(fromSubTaskWeight) + "% to " + Math.floor(toSubTaskWeight) + "%"); fromSubTaskWeight = Math.nextUp(toSubTaskWeight); } fromTaskWeight = Math.nextUp(toTaskWeight); } fromBatchWeight = Math.nextUp(toBatchWeight); } </code></pre> <p>The output looks like this</p> <pre class="lang-none prettyprint-override"><code>Weight of each batch: 33.333333333333336% Weight of each task: 33.333333333333336% Weight of each sub task: 16.666666666666668% Batch 1 from 0.0% to 33.0% Task 1 from 0.0% to 33.0% Sub Task 1 from 0.0% to 16.0% Sub Task 2 from 16.0% to 33.0% Batch 2 from 33.0% to 66.0% Task 1 from 33.0% to 66.0% Sub Task 1 from 33.0% to 50.0% Sub Task 2 from 50.0% to 66.0% Batch 3 from 66.0% to 100.0% Task 1 from 66.0% to 100.0% Sub Task 1 from 66.0% to 83.0% Sub Task 2 from 83.0% to 100.0% </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T12:03:28.533", "Id": "41269", "Score": "2", "body": "What if different batches have a different number of tasks? What if different tasks have a different number of subtasks? Or is that not an issue for what you're looking for?" } ]
[ { "body": "<ol>\n<li><pre><code>System.out.println(\"\\t\\tSub Task \" + k + \" from \" + Math.floor(fromSubTaskWeight) + \"% to \"\n + Math.floor(toSubTaskWeight) + \"%\");\n</code></pre>\n\n<p>I'd use <code>System.out.format</code> here, it's easier to read than string concatenation:</p>\n\n<pre><code>System.out.format(\"\\t\\tSub Task %d from %f%% to %f%%%n\", \n k, Math.floor(fromSubTaskWeight), Math.floor(toSubTaskWeight));\n</code></pre>\n\n<p>With that you can easily format floating numbers.</p>\n\n<pre><code>Weight of each task: 33,333333%\nWeight of each sub task: 16,666667%\n</code></pre>\n\n<p>Could be a readable</p>\n\n<pre><code>Weight of each task: 33,33%\nWeight of each sub task: 16,67%\n</code></pre>\n\n<p>With</p>\n\n<pre><code>System.out.format(\"Weight of each task: %.2f%%%n\", weightOfEachTask);\nSystem.out.format(\"Weight of each sub task: %.2f%%%n\", weightOfEachSubTask);\n</code></pre></li>\n<li><p>Having three nested for loops is hard to read. I'd try to extract out a <code>printSubtaskWeights</code> and a <code>printTaskWeights</code> method.</p></li>\n<li><p>I've seen earlier the <code>numOfSubTasksInEachTask</code> style variables but I've found <code>subTasksInEachTaskNumber</code> more easier to work with. Maybe because if more than one variable starts with <code>numOf</code> it's hard to differentiate them.</p></li>\n<li><p><code>i</code>, <code>j</code>, <code>k</code> variables could be more descriptive and could express their purpose. For example, \n<code>batchNumber</code>, <code>taskNumber</code> and <code>subtaskNumber</code>.</p></li>\n<li><p>Batches, tasks and subtasks looks very similar. I'd try to create a common abstraction for them and use that three times instead of duplication.</p>\n\n<pre><code>public class Item {\n\n private int subItemCount;\n private double weight;\n\n public Item(final int subItemCount, double weight) {\n super();\n this.subItemCount = subItemCount;\n this.weight = weight;\n }\n\n public int getSubItemCount() {\n return subItemCount;\n }\n\n public double getOneSubItemWeight() {\n final double subItemWeight = (1 * weight) / subItemCount;\n return subItemWeight;\n }\n\n public String getWeightInfo() {\n return String.format(\"Weight of each %s: %.2f%%\", \n name, getOneSubItemWeight());\n }\n}\n</code></pre>\n\n<p>(I'd call it <code>Task</code> but it hasn't already been used.)</p>\n\n<p>I started refactoring the code but I guess I won't finish it. The beginning of the code looked like this:</p>\n\n<pre><code>final Item batches = new Item(3, 100);\nfinal Item tasks = new Item(1, batches.getOneSubItemWeight());\nfinal Item subtasks = new Item(2, tasks.getOneSubItemWeight());\n</code></pre>\n\n<p><code>100</code> is the batches' weight, tasks and subtasks inherit the weight of their parents.</p>\n\n<p>Note that the duplicated <code>Weight of each</code> print statement was also moved to the <code>Item</code> class.</p>\n\n<p>I'd also try to move a loop into the <code>Item</code> class and call subitem printing from that method. I'd reduce the number of loops to one. Something like this: </p>\n\n<pre><code>public class Item {\n\n private final Item subitems;\n ...\n\n public void print(double fromWeight) {\n for (int item = 1; item &lt;= itemCount; item++) {\n\n double toWeight = getItemWeight() * item;\n System.out.format(\"%s %d from %f%% to %f%%%n\", \n name, item, Math.floor(fromBatchWeight),\n Math.floor(toBatchWeight));\n\n if (subitems != null) {\n subitems.print(fromWeight);\n }\n fromWeight = Math.nextUp(toWeight);\n }\n}\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-23T12:33:26.083", "Id": "42586", "ParentId": "26592", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-24T23:43:19.263", "Id": "26592", "Score": "4", "Tags": [ "java", "performance" ], "Title": "Calculate work progress in percentage of batches that contain tasks and task contain sub tasks" }
26592
<p>I've been developing a simple console application in C++ using the <a href="http://www.grinninglizard.com/tinyxml2/">TinyXML2</a> library, and I honestly can't help but feel what I'm doing is not very robust. Maybe that's just the nature of parsing XML (this is my first foray into the topic, so I've no idea.)</p> <p>The following code works to the best of my knowledge, but it feels like there has to be a better way than manually navigating to each element, checking for null pointers, then grabbing the information. Is there a more elegant way to handle this? I have to be missing something within the documentation, because I feel like I'm writing a lot of redundant code here.</p> <pre><code>#include &lt;iostream&gt; #include "tinyxml2.h" int main() { tinyxml2::XMLDocument document; if (document.LoadFile("games.xml") == tinyxml2::XML_SUCCESS) { std::cout &lt;&lt; "'games.xml' successfully loaded." &lt;&lt; std::endl; tinyxml2::XMLElement *root = document.RootElement(); std::cout &lt;&lt; root-&gt;Value() &lt;&lt; std::endl; tinyxml2::XMLElement *child; for (child = root-&gt;FirstChildElement(); child != nullptr; child = child-&gt;NextSiblingElement()) { std::cout &lt;&lt; "\t" &lt;&lt; child-&gt;Value() &lt;&lt; std::endl; if (child-&gt;FirstChildElement("name") == nullptr) { std::cerr &lt;&lt; "Error: null pointer." &lt;&lt; std::endl; return 1; } if (child-&gt;FirstChildElement("system") == nullptr) { std::cerr &lt;&lt; "Error: null pointer." &lt;&lt; std::endl; return 1; } if (child-&gt;FirstChildElement("status") == nullptr) { std::cerr &lt;&lt; "Error: null pointer." &lt;&lt; std::endl; return 1; } const char* game_name = child-&gt;FirstChildElement("name")-&gt;GetText(); const char* game_system = child-&gt;FirstChildElement("system")-&gt;GetText(); const char* game_status = child-&gt;FirstChildElement("status")-&gt;GetText(); if (game_name == nullptr || game_system == nullptr || game_status == nullptr) { std::cout &lt;&lt; "Error: null pointer." &lt;&lt; std::endl; return 1; } std::cout &lt;&lt; "\t\t" &lt;&lt; game_name &lt;&lt; std::endl; std::cout &lt;&lt; "\t\t" &lt;&lt; game_system &lt;&lt; std::endl; std::cout &lt;&lt; "\t\t" &lt;&lt; game_status &lt;&lt; std::endl; } } else { std::cerr &lt;&lt; "Unable to load 'games.xml'. Error code: " &lt;&lt; document.ErrorID() &lt;&lt; std::endl; return 1; } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T14:11:43.537", "Id": "41237", "Score": "2", "body": "I'm not familiar with TinyXML2, but have you considered [pugixml](http://pugixml.org/)?\nFrom its tutorial it doesn't seem to use a lot of pointers (and thus seems significantly lighter on the whole null-pointer-checks aspect you mention): http://pugixml.googlecode.com/svn/tags/latest/docs/quickstart.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T07:40:05.700", "Id": "41569", "Score": "0", "body": "Had a look at pugixml and it seems vastly easier to use (and it seems to have better documentation!) Was able to recreate my project rather quickly without the hassle of checking against null pointers. Thanks a bunch for the suggestion!" } ]
[ { "body": "<p>In your code I do agree there more redundancy than I like to see. I would suggest writing some helper functions, and perhaps leveraging exceptions instead of return codes (I won't show that here).</p>\n\n<pre><code>const char* FirstChildElementText(tinyxml2::XMLElement *parent, const char *child_name)\n{\n auto child = parent-&gt;FirstChildElement(child_name);\n return (child != nullptr) ? child-&gt;GetText() : nullptr;\n}\n: : :\nfor (child = root-&gt;FirstChildElement(); child != nullptr; child = child-&gt;NextSiblingElement()) {\n auto game_name = FirstChildElementText(child, \"name\");\n auto game_system = FirstChildElementText(child, \"system\");\n auto game_status = FirstChildElementText(child, \"status\");\n\n if (game_name == nullptr || ...)\n : : :\n}\n</code></pre>\n\n<p>This helps a bit. Always be on the lookout for a good refactoring. Even if you already found a better XML library for your needs.</p>\n\n<p>(I have things I dislike about both DOM and SAX style XML parsing, either being too lenient or too much work. Really, all in all, I suspect that directly working with XML is approaching things from the wrong level. But I don't have a great solution, so I'll get off my soap box.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T05:30:52.773", "Id": "35507", "ParentId": "26598", "Score": "3" } }, { "body": "<p>You could use <code>\"\\n\"</code> instead of <code>std::endl</code> to help a bit with performance. The latter also flushes the buffer, which you probably don't need here (even then, you could just use <code>\"\\n\"</code> and <code>std::flush</code>). More info about the differences <a href=\"https://stackoverflow.com/questions/213907/c-stdendl-vs-n\">here</a>.</p>\n\n<p>You could also make the return error values more readable with <a href=\"http://en.cppreference.com/w/cpp/utility/program/EXIT_status\" rel=\"nofollow noreferrer\"><code>EXIT_FAILURE</code></a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T06:30:42.177", "Id": "47543", "ParentId": "26598", "Score": "2" } }, { "body": "<p>I write <a href=\"http://en.wikipedia.org/wiki/XML_Schema_(W3C)\" rel=\"nofollow noreferrer\">an XSD file</a> to define the structure of the XML: for example, to specify that the XML contains an element named <code>name</code> which contains text.</p>\n\n<p>Before I parse the XML at run-time, I invoke one validation function, to verify that the XML has the structure defined by the XSD.</p>\n\n<p>I then use simplified parsing statements which assume (because I just already tested/validated it against the XSD) that the XML has the required/specified format: for example, I would read <code>child-&gt;FirstChildElement(\"name\")-&gt;GetText();</code> without checking for null pointers.</p>\n\n<hr>\n\n<p>However, maybe the TinyXML-2 library you're using doesn't support validation using XSD files (i.e. doesn't implement a 'validate' method).</p>\n\n<p>The <a href=\"https://github.com/leethomason/tinyxml2\" rel=\"nofollow noreferrer\">library's README</a> includes code like the following:</p>\n\n<pre><code>// Navigate to the title, using the convenience function,\n// with a dangerous lack of error checking.\nconst char* title = doc.FirstChildElement( \"PLAY\" )-&gt;FirstChildElement( \"TITLE\" )-&gt;GetText();\n</code></pre>\n\n<p>I don't know what \"dangerous\" is meant to mean in that context. I wonder whether it would be enough to wrap that code in an <a href=\"https://stackoverflow.com/a/1823749/49942\">O/S-specific exception handler</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T06:49:14.303", "Id": "47545", "ParentId": "26598", "Score": "2" } } ]
{ "AcceptedAnswerId": "35507", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T07:34:23.190", "Id": "26598", "Score": "7", "Tags": [ "c++", "c++11", "parsing", "xml", "console" ], "Title": "Rigidness and verbose nature of XML parsing" }
26598
<p>This is a simple but complete console application where I experiment with genetic algorithm to try to figure out the best way to construct a battle mech that would win in a simple turn-based combat. </p> <p>I welcome your criticism and pointers about what I could improve in the code above: architecture-wise, technique-wise, presentation-wise, and whatever else catches your interest. To provide at least a sample code as per the local rules, this is the method to make two mechs meet in combat:</p> <pre><code>// Match::match() // ============== // A static method that can be used to execute a match between the two provided mechs. // Return value: 0 = draw, 1 = mech #1 wins, 2 = mech #2 wins. int Match::match (Mech&amp; m1, Mech&amp; m2) { m1.resetCombatValues(); m2.resetCombatValues(); int turn = 0; static const int turnLimit = 25; // Each turn: while (turn &lt; turnLimit) { m1.actCombatTurn (m2); m2.actCombatTurn (m1); bool mech1Alive = m1.isAlive(); bool mech2Alive = m2.isAlive(); if (!mech1Alive &amp;&amp; !mech2Alive) return 0; if (!mech1Alive) return 2; if (!mech2Alive) return 1; turn++; } // Turn limit reached. return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T13:36:29.473", "Id": "41232", "Score": "0", "body": "Instead of coded return values, I'd consider using an enumeration for clarity: http://en.cppreference.com/w/cpp/language/enum\n\n// A good rule of thumb is that if you have to document a special meaning of (implicit) enumerators, like \"0 = draw, 1 = mech #1 wins, 2 = mech #2 wins\", then it's probably better to use an explicit enumeration." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T13:52:39.740", "Id": "41234", "Score": "0", "body": "I would also suggest making this a namespace non-member function instead of a static member function: http://stackoverflow.com/a/1435105/859774" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T13:56:43.880", "Id": "41235", "Score": "0", "body": "Further, unless you're supporting negative turns count `turnLimit` or want `turn` to go backward (would that even make sense in your context? BTW, `turn++` looks awkward, change it to `++turn`), I would use `size_t` instead of `int` for `turn` and `turnLimit`: http://en.cppreference.com/w/cpp/types/size_t" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T13:59:59.050", "Id": "41236", "Score": "0", "body": "I think I also wouldn't use `mech1Alive` or `mech2Alive` but rather their opposites (e.g., `mech1Dead` or `mech2Dead`) -- note that you're always negating them in your `if` statements, so it would improve code clarity to do so straight away." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T15:56:48.207", "Id": "41239", "Score": "0", "body": "You do realize that the rules are there for a reason, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T17:03:58.623", "Id": "41240", "Score": "0", "body": "@Matt Thanks a lot! Good points, I especially like the one with the explicit enumeration to clear up what is the return value, that does make it all easier to read. I edited the online version." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T18:14:01.173", "Id": "41242", "Score": "0", "body": "@MartinZiegler Sure! I've just looked at the online version, BTW. Your next step should be to remove _all_ uses of `new` and _all_ of the resource-owning raw pointers: preferably change them to (stack-allocated) automatic variables, then _only_ for the ones for which you can't do that (if any, don't just assume that, but _carefully_ verify that free-store/heap dynamic allocation is _absolutely_ required!) use `std::unique_ptr`, and finally, as a last resort, use `std::shared_ptr`." } ]
[ { "body": "<p>Here's a summary of my comments in the answer format:</p>\n\n<ul>\n<li><p>Instead of coded return values, I'd consider using an enumeration for clarity: <a href=\"http://en.cppreference.com/w/cpp/language/enum\" rel=\"nofollow noreferrer\">http://en.cppreference.com/w/cpp/language/enum</a><br>\n// A good rule of thumb is that if you have to document a special meaning of (implicit) enumerators, like \"<code>0 = draw, 1 = mech #1 wins, 2 = mech #2 wins</code>\", then it's probably better to use an explicit enumeration.</p></li>\n<li><p>I would also suggest using a namespace non-member function instead of a static member function whenever possible: <a href=\"https://stackoverflow.com/a/1435105/859774\">https://stackoverflow.com/a/1435105/859774</a></p></li>\n<li><p>Further, unless you're supporting negative turns count <code>turnLimit</code> or want turn to go backward (would that even make sense in your context? BTW, <code>turn++</code> looks awkward, change it to <code>++turn</code>), I would use <code>size_t</code> instead of <code>int</code> for <code>turn</code> and <code>turnLimit</code>: <a href=\"http://en.cppreference.com/w/cpp/types/size_t\" rel=\"nofollow noreferrer\">http://en.cppreference.com/w/cpp/types/size_t</a><br>\n// NOTE: in fact, the cases where <code>int</code> is the right type to choose are <em>significantly</em> rarer than most beginning developers seem to assume -- as a good rule of thumb, whenever you think you should use an <code>int</code>, you should always stop and think whether it's actually a good idea -- e.g., are you <em>sure</em> you really want negative values?</p></li>\n<li><p>I also wouldn't use <code>mech1Alive</code> or <code>mech2Alive</code> but rather their opposites (e.g., <code>mech1Dead</code> or <code>mech2Dead</code>) -- note that you're always negating them in your <code>if</code> statements, so it would improve code clarity to do so straight away, at the outset. </p></li>\n<li><p>I've just looked at the online version, BTW. Your next step should be to remove <em>all</em> uses of <code>new</code> (and, consequently, <em>all</em> manual invocations of <code>delete</code>) and <em>all</em> of the resource-owning raw pointers: preferably change them to (stack-allocated) automatic variables (using references, preferably to <code>const</code>, when avoiding copies is necessary), then <em>only</em> for the ones for which you can't possibly do that (if there are any, don't just assume this, but <em>carefully</em> verify that free-store/heap dynamic allocation is in fact <em>absolutely</em> required!) use <code>std::unique_ptr</code>, and finally, as a last resort, use <code>std::shared_ptr</code> (and, as a last resort after this last resort ;], in the <em>extremely rare</em> case you have need to break a cycle, consider <code>std::weak_ptr</code>).<br>\nSee: <a href=\"https://codereview.stackexchange.com/a/25721/24670\">https://codereview.stackexchange.com/a/25721/24670</a></p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T14:11:08.577", "Id": "41275", "Score": "0", "body": "Thanks a lot – I've reworked the structure so that I do not allocate 'on my own' almost anywhere now. I still allocate new Mechs dynamically and only store the pointer within the population vector, because it is quite a heavy structure to move around, and I do move it around quite a lot. I store those as `unique_ptr`'s in the Population that created them, so AFAIU that should be OK." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T18:22:04.233", "Id": "26610", "ParentId": "26600", "Score": "7" } } ]
{ "AcceptedAnswerId": "26610", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T10:42:25.253", "Id": "26600", "Score": "5", "Tags": [ "c++" ], "Title": "'Genetic algorithm' implementation for constructing a battle mech" }
26600
<p>I have three tables for a blog system.</p> <p>The blog</p> <pre><code>CREATE TABLE IF NOT EXISTS lm_blog( blog_id INT UNSIGNED NOT NULL AUTO_INCREMENT, title VARCHAR(80) NOT NULL UNIQUE, action VARCHAR(80) NOT NULL UNIQUE INDEX, url VARCHAR(80) NOT NULL UNIQUE, summary VARCHAR (255) NOT NULL, article TEXT NOT NULL, created DATE NOT NULL, updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, publish TINYINT UNSIGNED DEFAULT 0, PRIMARY KEY(blog_id)); </code></pre> <p>The tags</p> <pre><code>CREATE TABLE IF NOT EXISTS lm_blog_tags( tag_id INT UNSIGNED NOT NULL AUTO_INCREMENT, tag VARCHAR(32) NOT NULL UNIQUE INDEX, description TEXT, PRIMARY KEY(tag_id) ); </code></pre> <p>And the relationships</p> <pre><code>CREATE TABLE IF NOT EXISTS lm_blog_tag_relationships( blog_id INT UNSIGNED NOT NULL, tag_id INT UNSIGNED NOT NULL, PRIMARY KEY(blog_id, tag_id), FOREIGN KEY (blog_id) REFERENCES lm_blog(blog_id), FOREIGN KEY (tag_id) REFERENCES lm_blog_tags(tag_id) ); </code></pre> <p>I want to search for blogs by a tag name and have all the tags for that blog. I am currently using <code>GROUP_CONCAT</code> to group the tags and filter it with a <code>HAVING LIKE</code> clause.</p> <p>I.E to search for aticles with a PHP tag</p> <pre><code>SELECT T2.blog_id, T2.title, T2.url, T2.summary, T2.article, GROUP_CONCAT(T3.tag SEPARATOR ':') AS tags FROM lm_blog_tag_relationships AS T1 INNER JOIN lm_blog AS T2 ON T1.blog_id = T2.blog_id INNER JOIN lm_blog_tags AS T3 ON T1.tag_id = T3.tag_id GROUP BY T2.blog_id HAVING tags LIKE '%:PHP:%' OR tags LIKE '%:PHP' OR tags LIKE 'PHP:%' ORDER BY T2.blog_id DESC </code></pre> <p>I'm assuming there is a better way to get the same results.</p>
[]
[ { "body": "<p>Using a like with a leading wild card will likely be very slow as no indexes can be used. As such they should be avoided, which should be easy to do when the string you are checking it a concatenation of values from a table.</p>\n\n<p>I would suggest you do another join from the blog table to the blog tag relationship table, and from that another join to the blog tag table but specifying that the tag is <strong>php</strong> . This should mean any blog with a php tag will be brought back (complete with all its tags concatenated together) while any blog without that tag will be ignored.</p>\n\n<p>Not tested, but something like the following</p>\n\n<pre><code>SELECT T2.blog_id, T2.title, T2.url, T2.summary, T2.article, GROUP_CONCAT(T3.tag SEPARATOR ':') AS tags\nFROM lm_blog_tag_relationships AS T1\nINNER JOIN lm_blog AS T2 ON T1.blog_id = T2.blog_id\nINNER JOIN lm_blog_tags AS T3 ON T1.tag_id = T3.tag_id\nINNER JOIN lm_blog_tag_relationships T4 ON T2.blog_id = T4.blog_id\nINNER JOIN lm_blog_tags AS T5 ON T4.tag_id = T5.tag_id AND T5.tag SEPARATOR = 'PHP'\nGROUP BY T2.blog_id\nORDER BY T2.blog_id DESC\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T12:37:17.307", "Id": "26796", "ParentId": "26601", "Score": "1" } }, { "body": "<p>Since lm_blog_tags.tag is <code>UNIQUE</code>, I don't quite see why you need tag_id. If you get rid of it, you can use lm_blog_tags.tag directly in lm_blog_tag_relationships.</p>\n\n<p>Untested and assuming the table are redesigned according to the above paragraph:</p>\n\n<pre><code>SELECT T2.blog_id, T2.title, T2.url, T2.summary, T2.article, GROUP_CONCAT(T4.tag SEPARATOR ':')\nFROM lm_blog AS T2\nINNER JOIN lm_blog_tag_relationships as T4 on T2.blog_id = T4.blog_id\nWHERE T2.blog_id IN (SELECT blog_id FROM lm_blog_tag_relationships WHERE tag == 'xxxxx')\nGROUP BY T2.blog_id\nORDER BY T2.blog_id DESC\n</code></pre>\n\n<p>You could also use a sub-query and <code>IN</code> even if you do not redesign the tables.</p>\n\n<p>I did not quite get your line:</p>\n\n<pre><code>HAVING tags LIKE '%:PHP:%' OR tags LIKE '%:PHP' OR tags LIKE 'PHP:%'\n</code></pre>\n\n<p>I guess <code>tags</code> is <code>lm_blog_tags.tag</code>. And I would expect each such tag to be just one word, not concatenated words with a <code>:</code> separator as you output. I assume you have the join table because there is only one word per <code>lm_blog_tags.tag</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T20:03:31.847", "Id": "48321", "Score": "0", "body": "concat will add the `:` betwwen tags so if php was the first tag it would look like `php:` and if it was the last it would be `:php`. My terrible like clause was to find those and if they are in the mddle `:php:`\n\nI recall reading that joining on numeric ids is faster than a unique string. Is it true or should I drop the numeric ids?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T21:20:37.203", "Id": "48325", "Score": "0", "body": "I don't know about the performance issue... I had not thought about that. But it adds a lot of complexity, so you should weigh that carefully." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T13:52:04.940", "Id": "30367", "ParentId": "26601", "Score": "1" } }, { "body": "<p>SQL databases are supposed to be good at joins and indexed searches, not so much unindexed string pattern matching. Therefore, I would replace your <code>HAVING tags LIKE …</code> clause with a <code>WHERE EXISTS</code> subselect.</p>\n\n<p>I also renamed your table aliases to make more sense.</p>\n\n<pre><code>SELECT b.blog_id, b.title, b.url, b.summary, b.article,\n GROUP_CONCAT(t.tag SEPARATOR ':') AS tags\n FROM\n lm_blog AS b\n INNER JOIN lm_blog_tag_relationships AS bt\n ON bt.blog_id = b.blog_id\n INNER JOIN lm_blog_tags AS t\n ON t.tag_id = bt.tag_id\n WHERE EXISTS (\n SELECT filter_t.tag_id\n FROM\n lm_blog_tags AS filter_bt\n INNER JOIN lm_tags AS filter_t\n ON filter_t.tag_id = filter_bt.tag_id\n WHERE\n filter_bt.blog_id = b.blog_id AND\n filter_t.tag = 'PHP'\n )\n GROUP BY b.blog_id\n ORDER BY b.blog_id DESC\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T19:59:01.453", "Id": "48320", "Score": "0", "body": "I thought sub selects are also inefficient and should be used only when absolutely needed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T20:06:14.797", "Id": "48322", "Score": "0", "body": "The only way to tell which approach runs faster in practice on MySQL is to try it with real data. However, unless you have a demonstrated performance problem, you are probably better off saying what you mean in SQL rather than using string-matching hacks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T01:51:18.903", "Id": "48337", "Score": "0", "body": "My string hack is terrible which is why I posted the question :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T18:29:42.263", "Id": "30387", "ParentId": "26601", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T11:33:57.897", "Id": "26601", "Score": "2", "Tags": [ "sql", "mysql" ], "Title": "Blog & Blog Tags SQL Statements" }
26601
<p>I have this version of John Conway's Game Of Life in Java:</p> <p><code>Frame</code> class:</p> <pre><code>import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JSeparator; import javax.swing.JToolBar; public class Frame extends JFrame { private Board board; private BoardInterface boardInterface; private JMenuBar menuBar; private JMenu fileMenu, runMenu; private JMenuItem newMenuItem, clearMenuItem, randMenuItem, exitMenuItem, runMenuItem, pauseMenuItem; private JToolBar toolBar; private JButton run, pause; private Image runToolbar, pauseToolbar; public Frame(Board board) { this.board = board; boardInterface = new BoardInterface(board); setTitle("The Game of Life"); setSize(board.getWidth() * board.getMultiplier() + 5, board.getHeight() * board.getMultiplier() + 101); setResizable(false); setVisible(true); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); add(boardInterface); setMenuBar(); setToolbar(); } public void setMenuBar() { menuBar = new JMenuBar(); add(menuBar, BorderLayout.NORTH); fileMenu = new JMenu("File"); menuBar.add(fileMenu); newMenuItem = new JMenuItem("New"); fileMenu.add(newMenuItem); newMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new Frame(new Board()); } }); fileMenu.add(new JSeparator()); clearMenuItem = new JMenuItem("Clear Board"); fileMenu.add(clearMenuItem); clearMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { board.setBoard(board.clearBoard()); } }); randMenuItem = new JMenuItem("Random Board"); fileMenu.add(randMenuItem); randMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { board.setBoard(board.randomBoard()); } }); fileMenu.add(new JSeparator()); exitMenuItem = new JMenuItem("Exit"); fileMenu.add(exitMenuItem); exitMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); runMenu = new JMenu("Run"); menuBar.add(runMenu); runMenuItem = new JMenuItem("Run"); runMenu.add(runMenuItem); runMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { boardInterface.setIsActive(true); } }); pauseMenuItem = new JMenuItem("Pause"); runMenu.add(pauseMenuItem); pauseMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { boardInterface.setIsActive(false); } }); } public void setToolbar() { toolBar = new JToolBar(); toolBar.setLayout(new FlowLayout(FlowLayout.CENTER)); toolBar.setFloatable(false); add(toolBar, BorderLayout.SOUTH); runToolbar = new ImageIcon("src/playToolbar.png").getImage().getScaledInstance(25, 25, Image.SCALE_SMOOTH); run = new JButton(new ImageIcon(runToolbar)); toolBar.add(run); run.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { boardInterface.setIsActive(true); } }); pauseToolbar = new ImageIcon("src/pauseToolbar.png").getImage().getScaledInstance(25, 25, Image.SCALE_SMOOTH); pause = new JButton(new ImageIcon(pauseToolbar)); toolBar.add(pause); pause.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { boardInterface.setIsActive(false); } }); } public static void main(String[] args) { Frame frameInterface = new Frame(new Board()); } } </code></pre> <p><code>BoardInterface</code> class:</p> <pre><code>import java.awt.Color; import java.awt.Graphics; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JPanel; import javax.swing.Timer; public class BoardInterface extends JPanel implements ActionListener { Timer animation = new Timer(500, this); private Board board; private boolean isActive; public BoardInterface(final Board board) { this.board = board; setBackground(Color.BLACK); addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (!isActive) { board.getBoard()[e.getY() / board.getMultiplier()][e.getX() / board.getMultiplier()] = !board.getBoard()[e.getY() / board.getMultiplier()][e.getX() / board.getMultiplier()]; } else { Toolkit.getDefaultToolkit().beep(); } } }); } public void setIsActive(boolean toSet) { isActive = toSet; } @Override public void paintComponent(Graphics g) { super.paintComponent(g); for (int i = 0; i &lt; board.getHeight(); i++) { for (int j = 0; j &lt; board.getWidth(); j++) { g.setColor(board.getBoard()[i][j] ? Color.GREEN : Color.GRAY); g.fillRect(j * board.getMultiplier(), i * board.getMultiplier(), board.getMultiplier() - 1, board.getMultiplier() - 1); } } if (isActive) { animation.restart(); } else { animation.stop(); repaint(); } } public void actionPerformed(ActionEvent e) { if (e.getSource().equals(animation)) { board.nextGeneration(); repaint(); } } } </code></pre> <p><code>Board</code> class:</p> <pre><code>import java.util.Random; public class Board { private boolean[][] board; private int height, width, multiplier = 10; public Board() { this(new boolean[60][60]); } public Board(final boolean[][] board) { this.board = board; height = board.length; width = board[0].length; } public int getHeight() { return height; } public void setHeight(int n) { height = n; } public int getWidth() { return width; } public void setWidth(int n) { width = n; } public int getMultiplier() { return multiplier; } public void setMultiplier(int n) { multiplier = n; } public boolean[][] getBoard() { return board; } public void setBoard(boolean[][] n) { for (int i = 0; i &lt; height; i++) { for (int j = 0; j &lt; width; j++) { board[i][j] = n[i][j]; } } } public boolean[][] randomBoard() { Random rand = new Random(); boolean[][] randBoard = new boolean[height][width]; for (int i = 0; i &lt; height; i++) { for (int j = 0; j &lt; width; j++) { randBoard[i][j] = rand.nextBoolean(); } } return randBoard; } public boolean[][] clearBoard() { boolean[][] emptyBoard = new boolean[height][width]; for (int i = 0; i &lt; height; i++) { for (int j = 0; j &lt; width; j++) { emptyBoard[i][j] = false; } } return emptyBoard; } public int max(int i, int j) { return i &gt; j ? i : j; } public int countSurrounding(int a, int b) { int count = 0; int[][] surrounding = {{a - 1, b - 1}, {a - 1, b }, {a - 1, b + 1}, {a , b - 1}, {a , b + 1}, {a + 1, b - 1}, {a + 1, b }, {a + 1, b + 1}}; for (int[] i: surrounding) { try { if (board[i[0]][i[1]]) { count++; } } catch (ArrayIndexOutOfBoundsException e) {} } return count; } public void nextGeneration() { boolean[][] nextBoard = new boolean[height][width]; for (int i = 0; i &lt; height; i++) { for (int j = 0; j &lt; width; j++) { nextBoard[i][j] = board[i][j]; } } for (int i = 0; i &lt; height; i++) { for (int j = 0; j &lt; width; j++) { if (board[i][j] &amp;&amp; !(countSurrounding(i, j) == 2 || countSurrounding(i, j) == 3)) { nextBoard[i][j] = false; } else if (!board[i][j] &amp;&amp; countSurrounding(i, j) == 3) { nextBoard[i][j] = true; } } } board = nextBoard; } } </code></pre> <p>And I came here to ask the standard question: can anyone provide an honest code review? Thanks.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T07:47:22.710", "Id": "41266", "Score": "1", "body": "That's a good start. To bump up performance a bit, rather than creating a new board for every time you create the next generation, you should instead create two boards. One will represent the current generation and the other to represent the next. Use the current board to generate the next generation. Once the next generation is calculated, swap it with the old \"current\" generation and repeat the process. Since the calculations of the states of the cells are completely independent of each other, there's plenty of opportunity to parallelize the process." } ]
[ { "body": "<p>I am not a Java pro, so not everything I say now must be correct, but here is my review:</p>\n\n<p>First of all: \nYou did a good job when it comes to encapsulating. Nearly all of your methods are just a few lines, so every method really only does what it is supposed to do.\nFurthermore, your code is a good example that code, if it is well written, needs no comments to explain WHAT is done. Because you should see from the code itself what is done.</p>\n\n<p>So here come the negative things:</p>\n\n<ul>\n<li>Also code does not necessarily need comments which tell WHAT is done, it needs (in my opinion) comments which tell WHY something is done. So I miss some comments in your code, for example just a short explanation how the classes work together, or, for example because this is not clear to me, why the height and width of the board is not set in the constructor.</li>\n<li><p>You should not use \"magic numbers\". That means do not hardcode sizes or positions or something similar. For example in the Board constructor you make an array with size [60][60]. That is fine. But if you want to change the size later, then you have too look where you wrote the size. Better would be if you wrote the values as a constant in the class. So you can easily find and change it, and, as additional extra, use it everywhere in the class. Maybe you come to a point where you need this. The same advice is for the part where you create you JFrame.</p>\n\n<p>setSize(board.getWidth() * board.getMultiplier() + 5, board.getHeight() * board.getMultiplier() + 101);\nYou should write these numbers as constants. If you change the size of your frame, then you will have to change this numbers as well. So you can easier find them as constants. Or even better, if this is possible: Calculate the size of your frame dynamically.</p></li>\n<li><p>In your board class, you have getter and setter for the board's height and width. But why is the setter for the width and height public? You use the values of height and width in every update step. So what would happen if they were changed somewhere out of the class? My advise, when it comes to array sizes, is: Do not use setter for this values. When the array is already created, then nothing may change the borders. Only change the borders when the array is changed as well.</p></li>\n<li><p>In the method setBoard you assume that the array which you get has the same size (or bigger) than the array you are holding in your object. You should make a quick check if the passed array has the same size (or is bigger, what would be okay but would make no sense). Otherwise your program will crash when the passed array is smaller. It is also not very clear what this method should do. Should the passed array be the new array? Then you should adjust the size of your intern array. Or should just the values passed like you do it now? Then you have to check the size of the array.</p></li>\n<li><p>You often use very short, inexpressively variable or parameter names. This is okay in a nested for loop (although I would prefer iX and iY instead of i and j, but that is just a habit). But it is not okay for parameters. For example you use \"n\" as parameter in \"setMultiplier\" and you use \"n\" as parameter in \"setBoard\". They differ in type and in what they are supposed to be used for. You parameter names should describe what they are for. This does not need to be a long name, just something like \"new_Board_Array\" or \"multiplier_Value\". Imagine you have a method with more than one parameter and you use your naming convention: public int foo(int n, bool[][] m, float k).\nThen it would be messy inside your method.</p></li>\n</ul>\n\n<p>This is all what I noticed.\nJust out of curiosity: Do you want to add more functionality to your game of life program? For example when I wrote a game of life program I added some functionality like saving the curent field or going backward in the game to see older fields. You can also implement some functionality like speeding up the game or having custom field sizes instead of fixed 60*60.</p>\n\n<p>Hope this helps you a bit.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T14:13:37.077", "Id": "26606", "ParentId": "26602", "Score": "1" } }, { "body": "<p>It is pretty good. I agree with the comments of @MOrgenstern.</p>\n\n<p>There is one big problem however: you are frequently trying to fetch elements outsize the arrays range in <code>countSurrounding()</code>, and you catch the exceptions. You should never use exceptions to deal with standard conditions since they kill performance. You could fix that in many ways. One way which would add efficiency would be to precompute the neighbors of each cell at creation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T07:38:41.117", "Id": "41265", "Score": "0", "body": "What I would see in typical implementations would be \"border\" cells adding extra rows/columns on the edges that do not contribute to the simulation. That way you can safely ignore those cells and spending time checking conditions or handling exceptions when creating the next generation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T12:20:32.227", "Id": "41271", "Score": "0", "body": "That's possible too, but I don't like it so much since you'll have to add non-standard code elsewhere to ignore the extra rows. For example when generating the new active cells and when printing the board and maybe in many other places. I suspect it will end up being more complex than just dealing correctly with the neighbor counting." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T22:55:06.323", "Id": "26615", "ParentId": "26602", "Score": "0" } }, { "body": "<h2>Frame</h2>\n\n<p><strong>Important Issues</strong></p>\n\n<ul>\n<li>Exit just disposes. This is fine for extra spawned frames, but the last one should really exit, or you risk the JVM just hanging around.</li>\n<li>UI creation should happen on the Event Dispatch Thread (EDT), in the <code>main</code> method, use <code>SwingUtilities.invokeLAter()</code> to surround the creation of the first <code>Frame</code>.</li>\n<li>Have only <code>BoardInterface</code> know about the <code>Board</code> class, this way the <code>Frame</code> only directly depends on <code>BoardInterface</code> (this involves creating some delegate methods on <code>BoardInterface</code>).</li>\n</ul>\n\n<p><strong>Minor Issues</strong></p>\n\n<ul>\n<li>All widget fields can be converted to local variables.</li>\n<li>The remaining fields can be made final. </li>\n<li>I would use <code>Action</code>s instead of <code>ActionListener</code>s for the buttons and menu items. This way buttons and menu items that do the same thing can share the same action, and you can enable/disable an action according to context (e.g. disable run action when already running)</li>\n<li>Get rid of String literals and magic numbers (replace by explaining constants).</li>\n</ul>\n\n<h2>BoardInterface</h2>\n\n<p><strong>Minor Issues</strong></p>\n\n<ul>\n<li>Timer visibility modifier : set to private.</li>\n<li>Rename to BoardPanel (Interface causes confusion with the language construct)</li>\n<li>Use an (anonymous) inner class for the ActionListener\n<ul>\n<li>this avoids exposing an extra public method, that is useless to\nnormal clients</li>\n<li>this makes the if clause that checks the source superfluous</li>\n</ul></li>\n<li>do not increase visibility of the overridden method <code>paintComponent()</code>, keep it protected.</li>\n</ul>\n\n<h2>Board</h2>\n\n<p><strong>Imortant Issues</strong></p>\n\n<ul>\n<li>Do not catch ArrayIndexOutOfBoundsException, check indices before accessing them.</li>\n<li>Multiplier belongs on BoardInterface. Move it there.</li>\n<li>Hide the internal array representation.\n<ul>\n<li>all you really need is methods to toggle, and query cells.</li>\n</ul></li>\n</ul>\n\n<p><strong>Minor Issues</strong></p>\n\n<ul>\n<li>Replace manual array copy with <code>System.arrayCopy()</code></li>\n<li>Remove unused methods</li>\n<li>make <code>countSurrounding()</code> private</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-17T08:24:11.797", "Id": "151586", "Score": "0", "body": "I think it's correct to dispose the frames. If the application is hanging around after frame disposal, there's a bug, and using `System.exit()` or `WindowConstants.EXIT_ON_CLOSE` is just a cover-up for that bug. Agreeing with everything else, so got my +1, especially for `Action` instead of `ActionListener`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-17T12:01:55.473", "Id": "151614", "Score": "0", "body": "@ChristianHujer Note that I'm saying disposing is fine. Just that after closing the last frame the application does not end. There's no code in place to actually exit." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T11:24:39.850", "Id": "26623", "ParentId": "26602", "Score": "3" } } ]
{ "AcceptedAnswerId": "26623", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T13:39:10.760", "Id": "26602", "Score": "2", "Tags": [ "java", "swing", "game-of-life", "awt" ], "Title": "Game Of Life 3 in Java" }
26602
<p>I have been playing with event driven javascript lately, and have wondered if it's a good/bad thing for objects listening for their own events as a way of abstracting and simplifying internal logic.</p> <p>Consider the following:</p> <pre><code>function MyModule(options) { this.options = options; this.data = {}; this.setListeners(); //... } MyModule.prototype = new EventEmitter; MyModule.prototype.constructor = MyModule; MyModule.prototype.updateBasket = function() { var self = this, url = this.options.url; $.ajax(url) .done(function(data) { self.emit('basketupdate:success', data); }) .fail(function(jqxhr, textStatus, err) { self.emit('basketupdate:error', err); }) .complete(function() { self.emit('basketupdate:complete'); }); }; MyModule.prototype.setListeners = function() { var self = this; this.on('basketupdate:success', function(data) { // ... do something on success self.data = data; }); this.on('basketupdate:success', function(data) { // ... do something else on success console.dir(data); }); this.on('basketupdate:error', function() { // ... do something to handle the error }); }; var module = new MyModule({ url: '/path/to/request' }); module.updateBasket(); </code></pre> <p>A simple module with an ajax request. I could quite easily put all the logic in the corresponding callback, or even map callbacks to internal methods. However I'm quite liking this approach to simplifying the code.</p> <p>Are there downsides or potential problems to structuring the code in the way that I haven't considered. Or would this be seen as an anti-pattern with events only intended to be listened to from elsewhere?</p>
[]
[ { "body": "<p>You could do this, but it's not really useful.</p>\n\n<p>This code is just easier to read:</p>\n\n<pre><code>MyModule.prototype.updateBasket = function() {\n var self = this,\n url = this.options.url;\n\n $.ajax(url)\n .done(this.done)\n .fail(this.fail)\n .complete(this.complete);\n};\n\nMyModule.prototype.done = function(data) {\n // Do something when done\n};\n\nMyModule.prototype.fail = function(data) {\n // Do something when request failed\n};\n\nMyModule.prototype.complete = function(data) {\n // Do something no matter what\n};\n</code></pre>\n\n<p>And you could give more meaningful names to your methods.</p>\n\n<p>Event emitters are useful when you're playing with different objects that you don't want to link together.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T14:04:10.897", "Id": "26604", "ParentId": "26603", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T13:58:56.497", "Id": "26603", "Score": "3", "Tags": [ "javascript" ], "Title": "Javascript objects listening to their own events" }
26603
<p>I want to separate the code inside my <code>Add button click event</code> from the code in order to make my code looks more arranged. this is my code before these changes (i am using BackgroundWorker in order to avoid my GUI to freeze because every file that I am choosing need to open process and check if this is file OK before add this file into my Listbox):</p> <pre><code>private void btnAddfiles_Click(object sender, EventArgs e) { System.IO.Stream stream; if (openFileDialog1.ShowDialog() == DialogResult.OK) { fileSelected(); if (openFileDialog1.FileNames.Length &gt; 0) lastPath = Path.GetDirectoryName(openFileDialog1.FileNames[0]); ListboxFile lbf = new ListboxFile(); lbf.OnFileAddEvent += lbf_OnFileAddEvent; BackgroundWorker backgroundWorker = new BackgroundWorker(); backgroundWorker.WorkerReportsProgress = true; backgroundWorker.DoWork += (s3, e3) =&gt; { foreach (String file in openFileDialog1.FileNames) { try { if ((stream = openFileDialog1.OpenFile()) != null) { int numberOfFiles = openFileDialog1.SafeFileNames.Length; using (stream) { lbf.checkFile(file); lastPath = Path.GetDirectoryName(openFileDialog1.FileNames[0]); } } } catch (Exception ex) { MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); } } }; backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler( (s3, e3) =&gt; { //update my gui }); backgroundWorker.RunWorkerAsync(); } } </code></pre> <p>and this is after the changes:</p> <pre><code>private void btnAddfiles_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { fileSelected(); } } private void fileSelected() { if (openFileDialog1.FileNames.Length &gt; 0) lastPath = Path.GetDirectoryName(openFileDialog1.FileNames[0]); ListboxFile lbf = new ListboxFile(); lbf.OnFileAddEvent += lbf_OnFileAddEvent; BackgroundWorker backgroundWorker = new BackgroundWorker(); backgroundWorker.WorkerReportsProgress = true; backgroundWorker.DoWork += (s3, e3) =&gt; { foreach (String file in openFileDialog1.FileNames) { System.IO.Stream stream; try { if ((stream = openFileDialog1.OpenFile()) != null) { int numberOfFiles = openFileDialog1.SafeFileNames.Length; using (stream) { lbf.checkFile(file); lastPath = Path.GetDirectoryName(openFileDialog1.FileNames[0]); } } } catch (Exception ex) { MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); } } }; backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler( (s3, e3) =&gt; { //update my gui }); backgroundWorker.RunWorkerAsync(); } </code></pre> <p>So, what I did is necessary ? Maybe something else was better ?</p> <pre><code>public class ListboxFile { public delegate void OnFileAdd(string file); public event OnFileAdd OnFileAddEvent; private static List&lt;string&gt; _files; public ListboxFile() { _files = new List&lt;string&gt;(); } private void add(string file) { _files.Add(file); OnFileAddEvent(file); } public void remove(string file) { if (_files.Contains(file)) { _files.Remove(file); } } public void clear() { _files.Clear(); } public void checkFile(string file) { if ((new Editcap()).isLibpcapFormat(file)) { add(file); } } public List&lt;string&gt; list { get { return _files; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T21:07:50.817", "Id": "41254", "Score": "0", "body": "show us `Editcap.isLibpcapFormat`. Also looks like you might want to make it static." } ]
[ { "body": "<p>well in part it helps, but you need to keep taking it a bit further. Think of it as a building blocks. Button_Click is the top most level and should be readable like a book. have the method state its intent. maybe this might have been a better idea</p>\n\n<pre><code>private void btnaddfiles_click(object sender, EventArgs e)\n{\n GetFolderToAddFilesFrom();\n}\n</code></pre>\n\n<p>Now when someone comes in and wants to know exactly what the button does they don't have to read the source code and figure out what it does. The method states very clearly what it is supposed to do. The further you go down the list the more details you add.</p>\n\n<p>so what should the next level look like? Maybe something like this.</p>\n\n<pre><code> private void GetFolderToAddFilesFrom()\n {\n if (openFileDialog1.ShowDialog() == DialogResult.OK)\n {\n CheckFilesInFolder();\n }\n if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)\n {\n CheckFilesInFolder();\n }\n }\n</code></pre>\n\n<p>as you see I have 2 dialogs now. One was yours, the other is simply a folder browser. Judging by the code you provided I would say the FolderBrowser is the actual control you want and not the other. Either way you only need one. But they do the same thing. Once you've selected a Folder you then go to check the files in the folder. <code>fileSelected()</code> tells us the state your openFileDialog is in, not what the method does. We want all our methods to tell us what they do. Hence, <code>CheckFilesInFolder()</code> Lets gander at that method now. Notice how each level gets more and more detailed, but we still aren't doing any nitty gritty work. It's just easy to read right now.</p>\n\n<pre><code> private void CheckFilesInFolder()\n {\n if (openFileDialog1.FileNames.Length &gt; 0)\n {\n lastPath = Path.GetDirectoryName(openFileDialog1.FileNames[0]);\n }\n lastPath = folderBrowserDialog1.SelectedPath;\n\n ListboxFile lbf = new ListboxFile();\n lbf.OnFileAddEvent += lbf_OnFileAddEvent;\n\n StartBackgroundFileChecker();\n }\n</code></pre>\n\n<p>I still have both options in use for the folder selector. I believe the second one is the one you are after. Plus it is only 1 line long. The previous call told us we are going to be checking the Files in the Folder. Although we don't do that we are getting ready to do that. So maybe we could have chose another name such as PrepareToCheckFilesInFolder() but the last line does start the checker, therefore it isn't the worst name in the world.\nAnd you can guess what the last method looks like i'm sure.</p>\n\n<p>To answer your question then it is not <em>necessary</em> to move it out because obviously it still works either way. But you have to ask yourself if you'll know what that method does a month from now. Will you have to re-read your code and figure out what it does or will you be able to read the method name and know EXACTLY what it does. The second is the preferred way. Now you can reuse the code elsewhere if you need. If someone else comes in and reads your code they won't be temped to repeat the code you have, they'll just use your code. This is preferred.</p>\n\n<p>Last little tip is that you don't use your stream. Even if you did end up using your stream you are using <code>using</code> incorrectly.</p>\n\n<p>consider something like this</p>\n\n<pre><code> foreach (string file in Directory.GetFiles(lastPath))\n {\n try\n {\n using (var stream = new System.IO.FileStream(file, FileMode.Open, FileAccess.Read))\n {\n lbf.checkFile(file);\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show(\"Error\");\n }\n }\n</code></pre>\n\n<p>but since you don't use stream it would appear that this works just as well</p>\n\n<pre><code> foreach (string file in Directory.GetFiles(lastPath))\n {\n try\n {\n //stream was not used, and is not included here.\n lbf.checkFile(file);\n }\n catch (Exception ex)\n {\n MessageBox.Show(\"Error: Could not read file from disk. Original error: \" + ex.Message);\n }\n }\n</code></pre>\n\n<p>You may notice that i took out the check for more than 0 files in the directory. Foreach does that for me because if the list is empty it just skips the foreach statement. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T20:12:34.517", "Id": "41247", "Score": "0", "body": "First thanks for your help ! i still need to jump into this code and understand what you're doing but you absolutely right that i have another method that open Folder and recursively add all the files from this folder, BTW that about using Threading in this code to prevent my GUI to freeze ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T20:31:49.067", "Id": "41252", "Score": "0", "body": "@user2214609 it freezing could be something else. Generally speaking you'd want to move the Background worker closer to the work that causes it to \"slowdown\" Maybe you can show us the class ListBoxFile?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T20:44:40.687", "Id": "41253", "Score": "0", "body": "see my update.." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T19:35:51.447", "Id": "26613", "ParentId": "26607", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T17:08:29.003", "Id": "26607", "Score": "0", "Tags": [ "c#", "winforms" ], "Title": "Is it necessary to move OpenFileDialog code for opening the files and put it into a separate method?" }
26607
<p>I'll keep this short. I've never actually done professional C++. I don't really know any of the 'best practices'. I'd like to get some review on a simple class that I've made.</p> <p>My Vector2d.h file:</p> <pre><code>#ifndef VECTOR2D_H #define VECTOR2D_H #include &lt;cfloat&gt; #include &lt;climits&gt; /*The Vector2d class is an object consisting of simply an x and y value. Certain operators are overloaded to make it easier for vector math to be performed.*/ class Vector2d { public: /*The x and y values are public to give easier access for outside funtions. Accessors and mutators are not really necessary*/ float x; float y; //Constructor assigns the inputs to x and y. Vector2d(); Vector2d(float, float); /*The following operators simply return Vector2ds that have operations performed on the relative (x, y) values*/ Vector2d operator+(const Vector2d&amp;) const; Vector2d operator-(const Vector2d&amp;) const; Vector2d operator*(const Vector2d&amp;) const; Vector2d operator/(const Vector2d&amp;) const; //Check if the Vectors have the same values. bool operator==(const Vector2d&amp;) const; /*Check which Vectors are closer or further from the origin.*/ bool operator&gt;(const Vector2d&amp;) const; bool operator&lt;(const Vector2d&amp;) const; bool operator&gt;=(const Vector2d&amp;) const; bool operator&lt;=(const Vector2d&amp;) const; //Negate both the x and y values. Vector2d operator-() const; //Apply scalar operations. Vector2d operator*(const float&amp;) const; Vector2d operator/(const float&amp;) const; //Product functions static float DotProduct(const Vector2d&amp;, const Vector2d&amp;); static float CrossProduct(const Vector2d&amp;, const Vector2d&amp;); //Returns the length of the vector from the origin. static float Magnitude(const Vector2d&amp;); //Return the unit vector of the input static Vector2d Normal(const Vector2d&amp;); //Return a vector perpendicular to the left. static Vector2d Perpendicular(const Vector2d&amp;); //Return true if two line segments intersect. static bool Intersect(const Vector2d&amp;, const Vector2d&amp;, const Vector2d&amp;, const Vector2d&amp;); //Return the point where two lines intersect. static Vector2d GetIntersect(const Vector2d&amp;, const Vector2d&amp;, const Vector2d&amp;, const Vector2d&amp;); }; #endif </code></pre> <p>And for my Vector2d.cpp file:</p> <pre><code>#include "Vector2d.h" #include &lt;cmath&gt; Vector2d::Vector2d() { x = 0.0; y = 0.0; } Vector2d::Vector2d(float sourceX, float sourceY) { x = sourceX; y = sourceY; } Vector2d Vector2d::operator+(const Vector2d &amp;v) const { return Vector2d(x+v.x, y+v.y); } Vector2d Vector2d::operator-(const Vector2d &amp;v) const { return Vector2d(x-v.x, y-v.y); } Vector2d Vector2d::operator*(const Vector2d &amp;v) const { return Vector2d(x*v.x, y*v.y); } Vector2d Vector2d::operator/(const Vector2d &amp;v) const { return Vector2d(x/v.x, y/v.y); } bool Vector2d::operator==(const Vector2d &amp;v) const { return ((x == v.x) &amp;&amp; (y == v.y)); } bool Vector2d::operator&gt;(const Vector2d &amp;v) const { return (x*x + y*y) &gt; (v.x*v.x + v.y*v.y); } bool Vector2d::operator&lt;(const Vector2d &amp;v) const { return (x*x + y*y) &lt; (v.x*v.x + v.y*v.y); } bool Vector2d::operator&gt;=(const Vector2d &amp;v) const { return (x*x + y*y) &gt; (v.x*v.x + v.y*v.y) || (x*x + y*y) == (v.x*v.x + v.y*v.y); } bool Vector2d::operator&lt;=(const Vector2d &amp;v) const { return (x*x + y*y) &lt; (v.x*v.x + v.y*v.y) || (x*x + y*y) == (v.x*v.x + v.y*v.y); } Vector2d Vector2d::operator-() const { return Vector2d(-x, -y); } Vector2d Vector2d::operator*(const float&amp; scalar) const { return Vector2d(x*scalar, y*scalar); } Vector2d Vector2d::operator/(const float&amp; scalar) const { return Vector2d(x/scalar, y/scalar); } float Vector2d::DotProduct(const Vector2d &amp;a, const Vector2d &amp;b) { return ((a.x * b.x) + (a.y * b.y)); } float Vector2d::CrossProduct(const Vector2d &amp;a, const Vector2d &amp;b) { return ((a.x * b.y) - (a.y * b.x)); } float Vector2d::Magnitude(const Vector2d &amp;v) { return sqrt((v.x * v.x) + (v.y * v.y)); } Vector2d Vector2d::Normal(const Vector2d &amp;v) { float magnitude = Magnitude(v); return Vector2d(v.x / magnitude, v.y / magnitude); } Vector2d Vector2d::Perpendicular(const Vector2d &amp;v) { return Vector2d(v.y, -v.x); } bool Vector2d::Intersect(const Vector2d &amp;aa, const Vector2d &amp;ab, const Vector2d &amp;ba, const Vector2d &amp;bb) { Vector2d p = aa; Vector2d r = ab - aa; Vector2d q = ba; Vector2d s = bb - ba; float t = CrossProduct((q - p), s) / CrossProduct(r, s); float u = CrossProduct((q - p), r) / CrossProduct(r, s); return (0.0 &lt;= t &amp;&amp; t &lt;= 1.0) &amp;&amp; (0.0 &lt;= u &amp;&amp; u &lt;= 1.0); } Vector2d Vector2d::GetIntersect(const Vector2d &amp;aa, const Vector2d &amp;ab, const Vector2d &amp;ba, const Vector2d &amp;bb) { float pX = (aa.x*ab.y - aa.y*ab.x)*(ba.x - bb.x) - (ba.x*bb.y - ba.y*bb.x)*(aa.x - ab.x); float pY = (aa.x*ab.y - aa.y*ab.x)*(ba.y - bb.y) - (ba.x*bb.y - ba.y*bb.x)*(aa.y - ab.y); float denominator = (aa.x - ab.x)*(ba.y - bb.y) - (aa.y - ab.y)*(ba.x - bb.x); return Vector2d(pX / denominator, pY / denominator); } </code></pre> <p>Thanks in advance!</p>
[]
[ { "body": "<h2>Disclaimer</h2>\n\n<p>I will mostly not critique what your class is doing, but mainly suggest how to make your interface as natural as possible (<strong>do as the ints do</strong>) by <a href=\"https://stackoverflow.com/questions/4421706/operator-overloading\">operator overloading best practices</a> in terms of return type and const-correctness. I will mostly stick to C++98/03 and only sparingly suggest C++11 features. You could read the revamped <a href=\"http://herbsutter.com/2013/05/20/gotw-4-class-mechanics/\" rel=\"nofollow noreferrer\">GotW series for more information on the C++11 issues</a> (such as uniform initialization and move semantics).</p>\n\n<h2>Class definition</h2>\n\n<pre><code>#ifndef VECTOR2D_H\n#define VECTOR2D_H\n\n#include &lt;cfloat&gt;\n#include &lt;climits&gt;\n\n/*The Vector2d class is an object consisting of simply an x and\n y value. Certain operators are overloaded to make it easier\n for vector math to be performed.*/\n</code></pre>\n\n<p>First, I would change <code>Vector2d</code> into a class template taking a single template parameter <code>T</code> that you can define later to be <code>float</code> or <code>double</code>.</p>\n\n<pre><code>template&lt;class T&gt;\nclass Vector2d {\npublic:\n /*The x and y values are public to give easier access for\n outside funtions. Accessors and mutators are not really\n necessary*/\n T x;\n T y;\n</code></pre>\n\n<p>Second, always initialize class members in the <a href=\"https://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-list\">constructor member-initaliation-list</a>:</p>\n\n<pre><code> //Constructor assigns the inputs to x and y.\n Vector2d(): x(T(0)), y(T(0)) {}\n Vector2d(const&amp; T vx, const&amp; T vy): x(vx), x(vy) {}\n</code></pre>\n\n<p>Third, I would change your arithmetic operators to compound assignment operators that are non-const and return by reference</p>\n\n<pre><code> /*The following operators simply return Vector2ds that\n have operations performed on the relative (x, y) values*/\n Vector2d&amp; operator+=(const Vector2d&amp; v) { x += v.x; y += v.y; return *this; }\n Vector2d&amp; operator-=(const Vector2d&amp; v) { x -= v.x; y -= v.y; return *this; }\n Vector2d&amp; operator*=(const Vector2d&amp; v) { x *= v.x; y *= v.y; return *this; }\n Vector2d&amp; operator/=(const Vector2d&amp; v) { x /= v.x; y /= v.y; return *this; }\n</code></pre>\n\n<p>Fourth, I would the equality operator as a friend function that is symmetric in its arguments, and add the missing <code>operator!=</code>. Furthermore, I'd define <code>operator==</code> in terms of the C++11 <code>std::tuple</code> using the <code>std::tie</code> helper and the other operator in terms of this one</p>\n\n<pre><code> //Check if the Vectors have the same values (uses pairwise comparison of `std::tuple` on the x,y values of L and R.\n friend bool operator==(const Vector2d&amp; L, const Vector2d&amp; R) { return std::tie(L.x, L.y) == std::tie(R.x, R.y); }\n friend bool operator!=(const Vector2d&amp; L, const Vector2d&amp; R) { return !(L == R); }\n</code></pre>\n\n<p>Fifth, if you insist on having comparison operators <code>&lt;</code>, then I would not compare norms. Why? One reason is that you already define a norm function (Magnitude) later on, and you could simply compare vector norms directly. Furthermore, it is not a natural mathematical ordering. I would personally prefer (but it's a matter of taste!) use the natural ordering defined by <code>std::tuple</code> that does lexicograpical comparison on the x and then the y values:</p>\n\n<pre><code> //Check if the Vectors have the same values (uses pairwise comparison of `std::tuple` on the x,y values of L and R.\n friend bool operator&lt; (const Vector2d&amp; L, const Vector2d&amp; R) { return std::tie(L.x, L.y) &lt; std::tie(R.x, R.y); }\n friend bool operator&gt;=(const Vector2d&amp; L, const Vector2d&amp; R) { return !(L &lt; R); }\n friend bool operator&gt; (const Vector2d&amp; L, const Vector2d&amp; R) { return R &lt; L ; }\n friend bool operator&lt;=(const Vector2d&amp; L, const Vector2d&amp; R) { return !(R &lt; L); }\n</code></pre>\n\n<p>Sixth, the unary minus operator is fine as it is</p>\n\n<pre><code> //Negate both the x and y values.\n Vector2d operator-() const { return Vector2d(-x, -y); }\n</code></pre>\n\n<p>Seventh, the scalar compound assignment should be non-const and return-by-reference</p>\n\n<pre><code> //Apply scalar operations.\n Vector2d&amp; operator*=(const&amp; T s) { x *= s; y *= s; return *this; }\n Vector2d&amp; operator/=(const&amp; T s) { x /= s; y /= s; return *this; }\n};\n</code></pre>\n\n<p>Note that I define all class member functions inside the class definition. This is mainly done for brevity and to avoid repetitive coding. You can also split up the declaration and definition, but since I suggest to make a class template, those member function definitions also need to be in a header file. If you decide to keep it a regular class, then you can put the member definitions in a source file (you could still follow the other suggestions).</p>\n\n<h2>Rest of the class interface</h2>\n\n<p>First, you could define your original arithmetic members as non-member function templates that are symmetric in their arguments and are one-liners forwarding to the corresponding member compound assignments</p>\n\n<pre><code>template&lt;class T&gt; Vector2d&lt;T&gt; operator+(const Vector2d&lt;T&gt;&amp; L, const Vector2d&lt;T&gt;&amp; R) { return Vector2d&lt;T&gt;(L) += R; }\ntemplate&lt;class T&gt; Vector2d&lt;T&gt; operator-(const Vector2d&lt;T&gt;&amp; L, const Vector2d&lt;T&gt;&amp; R) { return Vector2d&lt;T&gt;(L) -= R; }\ntemplate&lt;class T&gt; Vector2d&lt;T&gt; operator*(const Vector2d&lt;T&gt;&amp; L, const Vector2d&lt;T&gt;&amp; R) { return Vector2d&lt;T&gt;(L) *= R; }\ntemplate&lt;class T&gt; Vector2d&lt;T&gt; operator/(const Vector2d&lt;T&gt;&amp; L, const Vector2d&lt;T&gt;&amp; R) { return Vector2d&lt;T&gt;(L) /= R; }\n</code></pre>\n\n<p>Second, you also define your original 2 scalar member functions as 4 scalar non-member function templates so that you can both left- and right-multiply (your version only allowed right-multiplication by a scalar). Again these are one-liners forward to the corresponding member compound assignments</p>\n\n<pre><code>template&lt;class T&gt; Vector2d&lt;T&gt; operator*(const T&amp; s, const Vector2d&lt;T&gt;&amp; v) { return Vector2d&lt;T&gt;(v) *= s; }\ntemplate&lt;class T&gt; Vector2d&lt;T&gt; operator*(const Vector2d&lt;T&gt;&amp; v, const T&amp; s) { return Vector2d&lt;T&gt;(v) *= s; }\ntemplate&lt;class T&gt; Vector2d&lt;T&gt; operator/(const T&amp; s, const Vector2d&lt;T&gt;&amp; v) { return Vector2d&lt;T&gt;(v) /= s; }\ntemplate&lt;class T&gt; Vector2d&lt;T&gt; operator/(const Vector2d&lt;T&gt;&amp; v, const T&amp; s) { return Vector2d&lt;T&gt;(v) /= s; }\n\n#endif\n</code></pre>\n\n<p>Note that these non-member function should also be defined right inside the header where you have your class definitions. Why? this way users of <code>Vector2d&lt;T&gt;</code> only need to include the header that contains <a href=\"http://www.gotw.ca/publications/mill02.htm\" rel=\"nofollow noreferrer\">the entire class interface</a>.</p>\n\n<h2>Utility functions</h2>\n\n<p>First, the remain <code>static</code> member functions from your original class definition should be defined as non-member function templates because they can be implemented entirely in terms of the public member functions and the other non-member functions.</p>\n\n<pre><code>//Product functions\ntemplate&lt;class T&gt; T DotProduct(const Vector2d&lt;T&gt;&amp;, const Vector2d&lt;T&gt;&amp;);\ntemplate&lt;class T&gt; T CrossProduct(const Vector2d&lt;T&gt;&amp;, const Vector2d&lt;T&gt;&amp;);\n</code></pre>\n\n<p>Second, rename <code>Magnitude</code> to the acutal algorithm used to compute it (because there are <a href=\"http://en.wikipedia.org/wiki/Norm_%28mathematics%29\" rel=\"nofollow noreferrer\">many other norms used in geometry</a>)</p>\n\n<pre><code>//Returns the length of the vector from the origin.\ntemplate&lt;class T&gt; T EuclideanNorm(const Vector2d&lt;T&gt;&amp;);\n</code></pre>\n\n<p>The rest of the utility functions look fine at first glance:</p>\n\n<pre><code>//Return the unit vector of the input\ntemplate&lt;class T&gt; Vector2d&lt;T&gt; Normal(const Vector2d&lt;T&gt;&amp;);\n\n//Return a vector perpendicular to the left.\ntemplate&lt;class T&gt; Vector2d&lt;T&gt; Perpendicular(const Vector2d&lt;T&gt;&amp;);\n\n//Return true if two line segments intersect.\ntemplate&lt;class T&gt; bool Intersect(const Vector2d&lt;T&gt;&amp;, const Vector2d&lt;T&gt;&amp;, const Vector2d&lt;T&gt;&amp;, const Vector2d&lt;T&gt;&amp;);\n\n//Return the point where two lines intersect.\ntemplate&lt;class T&gt; Vector2d&lt;T&gt; GetIntersect(const Vector2d&lt;T&gt;&amp;, const Vector2d&lt;T&gt;&amp;, const Vector2d&lt;T&gt;&amp;, const Vector2d&lt;T&gt;&amp;);\n</code></pre>\n\n<p>I have not much to say on the implementation of these utility functions, except that you can see that they are all using the extended class interface (both member and non-member functions). Again you can decide for yourself if you want to make them function templates or not, but in any case I would put them in a seperate header (or header + source file for non-templates) so that only users that are actually interested in such geometry functionality can include it.</p>\n\n<h2>Notes for further reading</h2>\n\n<p>The <a href=\"http://www.boost.org/doc/libs/1_53_0/libs/utility/operators.htm\" rel=\"nofollow noreferrer\">Boost.Operators library</a> can automate most of the work for you (notice that there is a lot of repetition and similarity for the various arithmetic and relational operators? As always, familiarize yourself with Boost!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-09T01:33:08.860", "Id": "42198", "Score": "0", "body": "Thanks, this is really helpful!\nWhat's the reason for changing all the arithmetic operators to compound assignments?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-09T06:18:52.120", "Id": "42204", "Score": "2", "body": "@TylerSlabinski In order to \"do as the ints do\", you generally want to provide both `OP` and `OP=` for `OP` equal to `+ - * /`. But `OP=` needs to return a reference and therefore is a member function. The `OP` version can then be written as a non-member. See also [this column](http://www.drdobbs.com/cpp/how-non-member-functions-improve-encapsu/184401197) by Scott Meyers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-09T16:46:13.813", "Id": "42219", "Score": "0", "body": "Final questions: Why should the comparison `==` and `!=` operators be `friend` operators? Couldn't I make them non-member operators like `+-*/` with the same affect? And what benefit do I get from using `std::tie` compared to just `L.x == R.x && L.y == R.y`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-09T16:48:33.827", "Id": "42221", "Score": "1", "body": "@TylerSlabinski `==` need access to `x` and `y`, so they need to be either members or friend non-members. I prefer them to be friend non-members because that way they are symmetric in their left/right arguments. It's also how Boost.Operators does it. The `std::tie` thing is overkill for 2D vectors, but comes in handy if you every want to go to 3D or higher. Especially for `<`, the `std::tie` is generally the easiest way to do lexicographical ordering, for `==` there is not so much benefit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-09T16:53:46.723", "Id": "42222", "Score": "0", "body": "But `x` and `y` are both public, so couldn't they access them as non-members?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-09T17:13:19.903", "Id": "42223", "Score": "0", "body": "@TylerSlabinski I missed that! Yes, you could then make all the relational operators non-members." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-27T23:46:05.253", "Id": "200402", "Score": "0", "body": "On modifying comparison operators in the original code, you have changed the implementation! The author wanted to be able to compare points based on their distance from the center, not member-wise comparison." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-28T06:20:57.747", "Id": "200435", "Score": "0", "body": "@rezeli i explicitly mention that, and also point out that norms can already be compared directly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-14T13:35:27.033", "Id": "228831", "Score": "0", "body": "@TemplateRex Although I have read your comments and the Article by Scorr Meyers, I am still unable to understand how changing arithmetic operators to compound assignments improves the code. How does it replace them? Aren't the use cases completely different?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-14T20:40:52.253", "Id": "228900", "Score": "0", "body": "@exilit in general, if you have `op=` and `op+`, then you also want to have `op+=` so that `a = a + b;` can be shortened to `a += b;`. This gives a complete arithmetic interface. But once you have such compound assignments, the easiest way is to express `op+` in terms of `op+=` (see section \"Rest of the class Interface\"). Furthermore, it makes `op+` symmetric in left/right argument." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-14T21:07:28.667", "Id": "228901", "Score": "1", "body": "Oh sorry, my fault. After reading it multiple times I somehow overlooked that the basic Arithmetik operands are deined as non-members." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-06T18:50:46.840", "Id": "27112", "ParentId": "26608", "Score": "12" } } ]
{ "AcceptedAnswerId": "27112", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T17:34:20.963", "Id": "26608", "Score": "8", "Tags": [ "c++", "classes", "interface", "operator-overloading" ], "Title": "Review of 2d Vector class" }
26608
<p>In my Rails 4 app i used to have every view contain a content_for :nav tag which included all of the links for the nav bar in my layout. This was getting annoying because if i wanted to add a button i would have to go through every view and add that link. I decide to make a partial view in layouts/_nav.haml which contains:</p> <pre><code>= link_to 'Home', root_path, :class =&gt; "btn #{active_page(root_path)}" = link_to 'Sign in', sign_in_path, :class =&gt; "btn #{active_page(sign_in_path)}" = link_to 'Account', account_path, :class =&gt; "btn #{active_page(account_path)}" </code></pre> <p>and then in my application_helper.rb i added:</p> <pre><code>def active_page(path) 'active' if current_page?(path) end </code></pre> <p>I know this isn't the best approach, is there any way to DRY up this solution or make it better. Im using bootstrap and i tried the simple-navigation gem but it wasn't that useful in my situation.</p>
[]
[ { "body": "<p>You could create another helper to create your navigation links:</p>\n\n<pre><code>def navigation_link_to(text, path)\n link_to text, path, class: \"btn #{active_page(path)}\"\nend \n</code></pre>\n\n<p>Then in your view:</p>\n\n<pre><code>= navigation_link_to 'Home', root_path\n= navigation_link_to 'Sign in', sign_in_path\n= navigation_link_to 'Account', account_path\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T20:04:05.470", "Id": "41244", "Score": "0", "body": "+1 this is the bottom-up approach to DRY, let's hope someone to contribute the top-down approach :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T20:12:16.937", "Id": "41246", "Score": "0", "body": "What do you mean with \"top-down DRY\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T20:22:16.467", "Id": "41248", "Score": "0", "body": "A top-down DRYing here would use a `each` loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T20:24:01.227", "Id": "41249", "Score": "0", "body": "Ah yeah, I didn't wanna do that since I think this is more clear to read in the view code, than defining an array of objects. Perhaps unless you have a very large amount of links." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T20:26:29.190", "Id": "41250", "Score": "0", "body": "Exactly, when there are few elements that's the more readable. And when elements grow you can always combine both, a method abstraction + a loop of the data." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T22:11:09.970", "Id": "41257", "Score": "0", "body": "Thank you this helps a lot, im going to use this for now but i will try to make a top-down approach and i will post it later." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T17:41:04.207", "Id": "41758", "Score": "0", "body": "My only addition is that 'navigation' is a long word. Consider `nav_link_to`." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T19:46:59.080", "Id": "26614", "ParentId": "26612", "Score": "7" } } ]
{ "AcceptedAnswerId": "26614", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-25T19:04:18.097", "Id": "26612", "Score": "3", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "DRY up Rails Navigation Code" }
26612
<p>I'm reading on design patterns for a software engineering class. I am doing small implementations of some I find the most interesting / applicable to better understand them.</p> <p>I'd like a code review on my design, more particularly on the degree of coupling between my Observer and Publisher classes. I feel that the <code>add_observer()</code> function may be coupled too strongly with the <code>Observer</code> object and that there may be a way to do this with looser coupling.</p> <p><strong>Observer.h</strong></p> <pre><code>#ifndef OBSERVER_H_INCLUDED #define OBSERVER_H_INCLUDED #include &lt;string&gt; class Publisher; class Observer { public: virtual void eventOnProperty(Publisher* source, std::string event_name, std::string value) = 0; }; #endif </code></pre> <p><strong>Publisher.h</strong></p> <pre><code>#ifndef PUBLISHER_H_INCLUDED #define PUBLISHER_H_INCLUDED #include "Observer.h" #include &lt;list&gt; #include &lt;string&gt; class Publisher { public: void notify_observers(std::string, std::string); void add_observer(Observer*); protected: std::list&lt;Observer*&gt; my_observers; }; #endif </code></pre> <p><strong>Publisher.cpp</strong></p> <pre><code>#include "Publisher.h" #include "Observer.h" #include &lt;string&gt; #include &lt;list&gt; void Publisher::notify_observers(std::string event_name, std::string value) { std::list&lt;Observer*&gt;::iterator it; for(it = my_observers.begin(); it != my_observers.end(); it++) { (*it)-&gt;eventOnProperty(this, event_name, value); } } void Publisher::add_observer(Observer* obs) { my_observers.push_back(obs); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T04:28:05.030", "Id": "41262", "Score": "0", "body": "Don't have time to go into a lot of detail at the moment, but both your classes should have `virtual` destructors. Also, ownership semantics are somewhat unclear here." } ]
[ { "body": "<p>Don't pass by pointer. There is no ownership associated with it (and it can be NULL and thus you need to test for that).</p>\n\n<pre><code>class Publisher {\n\n // Is the publisher taking ownership of the observer?\n void add_observer(Observer*);\n</code></pre>\n\n<p>Is your class taking ownership?</p>\n\n<p>If the answer is yes (you take ownership and thus control lifespan). Then you should pass the object using a smart pointer that allows transfer of ownership.</p>\n\n<pre><code> void add_observer(std::unique_ptr&lt;Observer&gt; obs);\n</code></pre>\n\n<p>If the answer is sort of. We are taking shared ownership (ie there might be other objects that are also using it). Then you pass using a smart pointer indicating shared ownership.</p>\n\n<pre><code> void add_observer(std::shared_ptr&lt;Observer&gt; obs);\n</code></pre>\n\n<p>If the answer is <strong>NO</strong> then you pass a reference (as a reference can not be NULL) and also indicates that you don't have onership. </p>\n\n<pre><code> void add_observer(Observer&amp; obs);\n</code></pre>\n\n<p>If you do take ownership you need to do some work in the destructor of your publisher to make sure that you correctly relinquish ownership when the publisher dies.</p>\n\n<p>If you don't have an ownership claim. This also means that the lifespan of the object may not live as longer as the publisher so you also need a way for the object to remove itself if it dies first and for the publisher to notify the observer that it has dies so it does not de-register itself from a dead object.</p>\n\n<pre><code> void del_observer(Observer&amp; obs);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T18:31:42.093", "Id": "26677", "ParentId": "26617", "Score": "3" } } ]
{ "AcceptedAnswerId": "26677", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T02:58:46.213", "Id": "26617", "Score": "3", "Tags": [ "c++", "design-patterns" ], "Title": "Very simple implementation of observer pattern in C++" }
26617
<p>I know this dining philosophers problem has been researched a lot and there are resources everywhere. But I wrote simple code to solve this problem with C and then turned to the Internet to see if it's correct. I wrote this with mutexes only and almost all implementations on the Internet use a semaphore. Now I'm not sure about my code.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;pthread.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; #define NO_OF_PHILOSOPHERS 5 pthread_t philosophers[NO_OF_PHILOSOPHERS]; pthread_mutex_t mutex_forks = PTHREAD_MUTEX_INITIALIZER;; int forks[NO_OF_PHILOSOPHERS]; void init() { int i; for(i=0; i&lt;NO_OF_PHILOSOPHERS; i++) forks[i] = 0; } void philosopher(int i) { int right = i; int left = (i - 1 == -1) ? NO_OF_PHILOSOPHERS - 1 : (i - 1); int locked; while(1) { locked = 0; while(!locked) { pthread_mutex_lock(&amp;mutex_forks); if(forks[right] || forks[left]) { pthread_mutex_unlock(&amp;mutex_forks); // give up the forks unless you can take both at once. printf("Philosopher %d cannot take forks. Giving up and thinking.\n",i); usleep(random() % 1000); // think. continue; } forks[right] = 1; // take forks. forks[left] = 1; pthread_mutex_unlock(&amp;mutex_forks); locked = 1; } printf("Philosopher %d took both forks. Now eating :)\n",i); usleep(random() % 500); printf("Philosopher %d done with eating. Giving up forks.\n",i); pthread_mutex_lock(&amp;mutex_forks); // give up forks. forks[right] = 0; forks[left] = 0; pthread_mutex_unlock(&amp;mutex_forks); usleep(random() % 1000); } } int main() { init(); int i; for(i=0; i&lt;NO_OF_PHILOSOPHERS; i++) pthread_create( &amp;philosophers[i], NULL, philosopher, (void*)i); for(i=0; i&lt;NO_OF_PHILOSOPHERS; i++) pthread_join(philosophers[i],NULL); return 0; } </code></pre> <p>Now for me, the code looks like it's working fine, but people on the Internet seem to make a lot of fuss than this to write the solution for Dining Philosophers.</p> <p>As such, I thought of asking these questions:</p> <ol> <li>Can there be a deadlock in the code?</li> <li>Can there be a starvation of a philosopher?</li> <li>Have I missed the whole point of the Dining Philosophers Problem?</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-28T08:45:11.077", "Id": "79535", "Score": "0", "body": "casting an int `(int i;)` to a void pointer (`(void*)i` ) is undefined behaviour. Either pass `(void *) &i` or simply `&i`" } ]
[ { "body": "<p>In the problem as I have seen it, the philosophers only take one fork at a time and can hang on to it (but they only eat when they have 2 forks). You have simplified it by having them take both or none.</p>\n\n<p>There shouldn't be any deadlocks as the philosopher only has 0 or 2 forks, but there is still potential for starvation if the 2 neighbouring philosophers start eating again before the philosopher has finished thinking. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-26T15:17:09.727", "Id": "45748", "Score": "0", "body": "Agreed. It's supposed to be a simplification of a complicated program that has a number of different exclusive resources, each of which may be acquired separately, but of which some threads require overlapping subsets." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T23:13:38.967", "Id": "26647", "ParentId": "26618", "Score": "3" } }, { "body": "<p>You should also be careful of the thread-start pattern. If you start them in a loop and they immediately reach for a fork before the other philosophers are initialized the sequencing trivializes the problem. That said, it is as much a thought experiment as an actual implementation challenge, intended to force you to think about how to deterministically break the behavior for all the philosophers without them having different code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T13:05:47.677", "Id": "26667", "ParentId": "26618", "Score": "1" } }, { "body": "<blockquote>\n <p>Or have I missed the whole point of dining philosophers problem?</p>\n</blockquote>\n\n<p>Yes, sort of. The solution with a single global lock protecting all manipulation with forks is trivial and overly restrictive: essentially, the whole table is locked just to check if there are two free forks nearby. As the result, no two philosophers can even try to take or return forks at the same time, even if they do not share forks. Enforcing such a restriction to real people eating at a round table would be unrealistic, especially if the number of philosophers is not as small as 5 :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-30T16:08:43.390", "Id": "45761", "ParentId": "26618", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T05:06:17.420", "Id": "26618", "Score": "8", "Tags": [ "c", "concurrency", "locking", "pthreads", "dining-philosophers" ], "Title": "Dining philosophers problem with mutexes" }
26618
<p>Please assume I've exhaustively tried to come up with a set-based solution to my T-SQL problem, and that I need to use a cursor. The following is the typical<sup>1</sup> boilerplate for a T-SQL cursor:</p> <pre class="lang-sql prettyprint-override"><code>DECLARE @myId AS INT; DECLARE myCursor CURSOR FAST_FORWARD FOR SELECT id FROM MyTable; OPEN myCursor; FETCH NEXT FROM myCursor INTO @myId; -- COPY... WHILE @@FETCH_STATUS = 0 BEGIN PRINT 'Doing the cursor work!'; FETCH NEXT FROM myCursor INTO @myId; -- ...PASTE! :'( END; CLOSE myCursor; DEALLOCATE myCursor; </code></pre> <p>On Stack Overflow it's already been <a href="https://stackoverflow.com/q/12261566/419956">asked how to avoid the duplication</a>. Please suppose this is quite important (e.g. it's somehow unavoidable to <code>FETCH</code> many columns into variables). While trying to come up with a solution to DRY the two <code>FETCH</code> statements into one, I ended up with boilerplate similar to <a href="https://stackoverflow.com/a/12261991/419956">the OP's answer to the mentioned question</a>:</p> <pre class="lang-sql prettyprint-override"><code>DECLARE @myId AS INT; DECLARE myCursor CURSOR FAST_FORWARD FOR SELECT id FROM MyTable; OPEN myCursor; WHILE 1=1 -- Not very pretty, but required to keep the FETCH statement DRY. BEGIN FETCH NEXT FROM myCursor INTO @myId; IF @@FETCH_STATUS &lt;&gt; 0 BREAK; PRINT 'Doing the cursor work!'; END; CLOSE myCursor; DEALLOCATE myCursor; </code></pre> <p>Now, my code review question comes down to: is there any elegant way to DRY out duplicate <code>FETCH</code> statements from the "default" boilerplate (1st snippet)? If my second snippet is the easiest way, then I'd love to know if there is any way to get rid of the nasty <code>WHILE 1=1</code> statement? Or is it a necessary sacrifice?</p> <p>*Bonus (subjective) question:</p> <p>Although the <code>WHILE 1=1</code> bit from the second boilerplate isn't very pretty, I think I prefer it a lot over duplicating the <code>FETCH</code> statement. Any insights as to why the first boilerplate is much more prominent / widespread? Am I missing a major advantage of the first snippet?</p> <hr> <p><sup>1</sup> Taken / adapted from the 70-461 exam training kit.</p>
[]
[ { "body": "<p>The infinite loop idiom in languages that have boolean literals is <code>while ( true )</code> but it seems the boolean type and its literals (e.g., <code>TRUE</code>/<code>FALSE</code>) have gone the way of the <code>DO ... WHILE</code> as far as T-SQL is concerned. This means you're stuck with true-evaluating expressions of which <code>1=1</code> is the simplest.</p>\n\n<p>In your case I'd replace the start of the loop with <code>WHILE (1=1) -- Loop until BREAK.</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T11:19:46.033", "Id": "26663", "ParentId": "26620", "Score": "4" } } ]
{ "AcceptedAnswerId": "26663", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T08:42:45.270", "Id": "26620", "Score": "3", "Tags": [ "sql", "sql-server", "cursor" ], "Title": "DRY cursors: preventing T-SQL's FETCH statement from being repeated" }
26620
<p>I'm looking for the best and fastest way to do a determinant, for determinants until 15x15.</p> <pre><code>int Determinant(const vector&lt;vector&lt;int&gt; &gt; &amp;a,int n) { int i,j,j1,j2; int det = 0; vector&lt;vector&lt;int&gt; &gt; m(n, vector&lt;int&gt;(n)); if (n == 1) { /* Shouldn't get used */ det = a[0][0]; } else if (n == 2) { det = a[0][0] * a[1][1] - a[1][0] * a[0][1]; } else { det = 0; for (j1=0;j1&lt;n;j1++) { for (i=1;i&lt;n;i++) { j2 = 0; for (j=0;j&lt;n;j++) { if (j == j1) continue; m[i-1][j2] = a[i][j]; j2++; } } det += pot(-1,1+j1+1) * a[0][j1] * Determinant(m,n-1); } } det = abs(det)%2; return det; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-13T21:21:53.490", "Id": "42554", "Score": "0", "body": "Could you indicate whether my answer was helpful, or if not, how it could be improved?" } ]
[ { "body": "<p>Unless this is a homework assignment, you should probably not be writing your own linear algebra routines, but rely on libraries instead. Not only is it very hard to write <strong>correct and efficient</strong> general-purpose algorithms, for numerical algorithms there is an added requirement of <strong>numerical stability</strong>. For those reasons it is best to use established libraries such as <a href=\"http://eigen.tuxfamily.org/index.php?title=Main_Page\" rel=\"nofollow\">Eigen</a>. </p>\n\n<p>A determinant can be done using <a href=\"http://eigen.tuxfamily.org/dox/TutorialLinearAlgebra.html#TutorialLinAlgInverse\" rel=\"nofollow\">the example in the documentation</a></p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;Eigen/Dense&gt;\nusing namespace std;\nusing namespace Eigen;\nint main()\n{\n Matrix3f A;\n A &lt;&lt; 1, 2, 1,\n 2, 1, 0,\n -1, 1, 2;\n cout &lt;&lt; \"Here is the matrix A:\\n\" &lt;&lt; A &lt;&lt; endl;\n cout &lt;&lt; \"The determinant of A is \" &lt;&lt; A.determinant() &lt;&lt; endl;\n}\n</code></pre>\n\n<p>Output</p>\n\n<pre><code>Here is the matrix A:\n1 2 1\n2 1 0\n-1 1 2\nThe determinant of A is -3\n</code></pre>\n\n<p>Granted, for binary matrices the numerical stability argument that holds for floating point matrices is not really relevant, but the correctness and efficiency arguments remain important enough to warrant library use over hand-written implementations. </p>\n\n<p><strong>UPDATE</strong>: I just noticed that you got the same suggestion to start exploring Eigen in your other CodeReview question. I really encourage you to do so because it lets you focus on your application rather than on low-level implementation details that have been solved by others already. Unless of course, learning such details is what you are interested in.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-14T07:15:18.350", "Id": "42589", "Score": "0", "body": "Ok, the point is that has be able to be compiled in any computer without the need of installing something new" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-14T07:42:51.597", "Id": "42592", "Score": "0", "body": "@Trouner I understand your hesitance for reliance on 3rd party code. OTOH, reinventing the wheel has its own costs. Regarding portability: Eigen is available on Windows, Linux and Mac, and it is open source. Other than that, I don't think this forum is the best place to get good matrix-algorithm feedback." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-06T12:38:24.163", "Id": "27082", "ParentId": "26625", "Score": "2" } } ]
{ "AcceptedAnswerId": "27082", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T13:27:34.827", "Id": "26625", "Score": "2", "Tags": [ "c++", "performance", "algorithm", "matrix" ], "Title": "Determinant of a binary matrix" }
26625
<p>I have made a mini image gallery which consists of one large div which has a background image of one of the galleries images. Underneath that are five thumbnail images, that when clicked, change the background image of the large div above. </p> <p>All code works as expected but it looks like it could be improved. How can I rewrite it in a shorter, cleaner looking way?</p> <pre><code>$("#thumb2").on('click', function(){ $(".main-image").css('background-image', 'url(img/lrg-img/use/dscn2717.png)'); }); $("#thumb1").on('click', function(){ $(".main-image").css('background-image', 'url(img/lrg-img/use/dscn2714.png)'); }); $("#thumb3").on('click', function(){ $(".main-image").css('background-image', 'url(img/lrg-img/use/dscn2720.jpg)'); }); $("#thumb4").on('click', function(){ $(".main-image").css('background-image', 'url(img/lrg-img/use/dscn2733.jpg)'); }); $("#thumb5").on('click', function(){ $(".main-image").css('background-image', 'url(img/lrg-img/use/dscn2735.jpg)'); }); </code></pre>
[]
[ { "body": "<p>You're using <code>$(\".main-image\")</code> a lot. It would be better to make a variable for that.\nAll the id's start with \"thumb\", so it might be better to use one click event handler on a selector that looks like this: <code>$(\"[id^='thumb']\")</code>. You can then, in the body of the click handler, get the id by using <code>$(this).attr('id')</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T14:03:55.170", "Id": "26628", "ParentId": "26626", "Score": "4" } }, { "body": "<p>Yes. There is a lot of optimization potential in this code.</p>\n\n<ol>\n<li><p>You should define a class for your thumbnails (e.g. \"thumbnail\").\nIt would make querying a lot easier: </p>\n\n<pre><code>$(\".thumbnail\")\n</code></pre>\n\n<p>and you got all of them. Besides you could use the id for numbering, which makes it a lot more intuitive to get the right thumbnail</p>\n\n<pre><code>$(\".thumbnail[id='1']\")\n</code></pre>\n\n<p>gets the thumbnail with the id of \"1\".</p></li>\n<li><p>You could use a dispatching function, which you invonke \"onClick\":</p>\n\n<pre><code>var thumbnails={\"1\":\"img/lrg-img/use/dscn2717.png\" ... } // same for the other ids \nfunction getImageUrlByThumbnailId(id){ return thumbnails[id]; }\n</code></pre>\n\n<p>This makes it possible to write code once and update dynamincally (if wanted).\nSo you could write the code once, to update a thumbnail and invoke this \"onClick\".</p></li>\n<li><p>Perhaps you should cache the <code>$(\".main-image\")</code> selection.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T14:47:44.490", "Id": "26629", "ParentId": "26626", "Score": "2" } }, { "body": "<p>If you were to add, say, a data attribute (called something like data-full-image) to the thumbnails, and give each one a class of .thumbnail, then you could replace all of it with something like:</p>\n\n<pre><code>$(\".thumbnail\").click(function() {\n var imageName = $(this).data(\"full-image\");\n $(\".main-image\").css('background-image', 'url(img/lrg-img/use/'+ imageName +'.png)');\n});\n</code></pre>\n\n<p>Also note than click(function) is shorthand for on(\"click\", function).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-21T09:10:23.893", "Id": "27621", "ParentId": "26626", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T13:45:44.197", "Id": "26626", "Score": "1", "Tags": [ "javascript", "jquery", "image" ], "Title": "Mini image gallery" }
26626
<p>I'm solving Project Euler problems and uploading <a href="https://github.com/nicoekkart/python/tree/master/Project%20Euler" rel="nofollow">my solutions</a> to GitHub. Some of my solutions are just based on math and are thanks to that very fast, but #14 is way too slow, and I have no idea how to optimize it.</p> <pre><code>""" Longest Collatz sequence ------------------------ The following iterative sequence is defined for the set of positive integers: n n/2 (n is even) n 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 40 20 10 5 16 8 4 2 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? NOTE: Once the chain starts the terms are allowed to go above one million. Approach: A function `collatz` which returns the number of terms in the chain, given it's starting position. It goes trough the sequence, but It also remembers previous ones using a global dictionary. Get the maximum one. """ collatz_counts = {} def collatz(n): count = 1 start = n while n!=1: if n in collatz_counts: count += collatz_counts[n] break if n%2==0: n/=2 else: n = 3*n+1 count += 1 collatz_counts[start] = count return count answer = max(((collatz(i),i) for i in range(1,1000000))) print("The starting position generating the longest sequence is {0}".format(answer[1])) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T14:53:58.650", "Id": "41278", "Score": "0", "body": "Is it that slow? It takes 3.6s on my computer. One optimization is to use a list for indices less than eg. tn million, and use a dictionary otherwise. Initialize that list before using it. It shave 0.4 seconds (3.7->3.3). Try implementing this in C++ to see how much comes from Python." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T15:05:50.360", "Id": "41279", "Score": "0", "body": "It's a little bit longer on my computer, but I'm trying to optimize as much as possible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T15:40:17.647", "Id": "41281", "Score": "2", "body": "Note: Project Euler is about algorithms, not micro-optimizations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T15:44:14.740", "Id": "41282", "Score": "0", "body": "I know. I have the answer, but this is just for myself, to learn more about python. Is there anything that I can do better?" } ]
[ { "body": "<p>I can not say something about optimizing the python code.\nBut wouldn't it be much faster if you cache partial chains of numbers?\nFrom my understanding of the problem it should not be impossible that sometimes collatz series overlap, so that you know that from element X in the series, the number of steps down to 1 are already precalculated.\nI have something like a dictionary in mind elementx->length of chain down to 1.\nSo that, after you calculated an initial value, you make a lookup for each step, if there is a length already known; and if not cache the result at the end of the calculation.</p>\n\n<p>Perhaps this is some kind of speedup to the algorithm.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T17:11:39.330", "Id": "41284", "Score": "0", "body": "I am doing that, using the `collatz_counts` dictionary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T18:26:35.520", "Id": "41285", "Score": "0", "body": "Oh sorry. I overlooked that on the first read ;)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T17:06:23.800", "Id": "26633", "ParentId": "26627", "Score": "0" } }, { "body": "<p>You have a bug. Try calling <code>collatz(2)</code> a few times and you'll see the result increment by one each time.</p>\n\n<p>The source of trouble is initializing <code>count</code> to 1. It means you always add at least 1 to the memoized value. Note however that initializing <code>count</code> to 0 instead would give incorrect results when the loop terminates by the <code>n != 1</code> condition.</p>\n\n<p>You can avoid this bug and simplify your code at the same time: if you initialize <code>collatz_counts</code> to <code>{1: 1}</code> you can loop <code>while n not in collatz_counts:</code> and eliminate the <code>if ... break</code>.</p>\n\n<p><hr>\nNote also that an odd number is always followed by an even number in the sequence, so you can take two steps with <code>n = (n * 3 + 1) // 2</code></p>\n\n<hr>\n\n<p>I suppose you are on Python 3 because you are using <code>print()</code>. Note that <code>n/=2</code> is float division. <code>n</code> becomes a float which slows down subsequent calculations. Use <code>n //= 2</code> instead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T07:28:31.320", "Id": "26654", "ParentId": "26627", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T13:46:42.543", "Id": "26627", "Score": "2", "Tags": [ "python", "optimization", "programming-challenge" ], "Title": "Increasing speed of Project Euler #14 - Longest Collatz Sequence" }
26627
<p>Code reviews and suggestions to improve coding style are welcome.</p> <pre><code>using ExpressionEvaluatorLibrary; namespace ExpressionEvaluator { class Program { static void Main(string[] args) { ConsoleKeyInfo cki = new ConsoleKeyInfo(); Console.WriteLine(" Mathematical Expression Evaluation"); Console.WriteLine("Maximum length : 250 characters"); Console.WriteLine("Allowed Operators : +, -, *, /"); do { string strUserInput = ""; if (args.Length == 0) { Console.Write("\n\nEnter an Expression: "); strUserInput = Console.ReadLine(); } else { // TO be able to run from command prompt. strUserInput = args[0]; } IExpressionModel expressionModel = new ExpressionModel(); string strValidate = expressionModel.ExpressionValidate(strUserInput); if (strValidate == "Valid") { try { string strPostFixExpression = expressionModel.ConvertToPostfix(strUserInput); // Console.WriteLine(strPostFixExpression); string strResult = expressionModel.EvaluateExpression(strPostFixExpression); Console.WriteLine("\n The result is: " + strResult); } catch (Exception e) { Console.WriteLine(e); } } else { Console.WriteLine(strValidate); } Console.WriteLine("\nPress any key to continue; press the 'Esc' key to quit."); cki = Console.ReadKey(false); } while (cki.Key != ConsoleKey.Escape); } } } namespace ExpressionEvaluatorLibrary { public interface IExpressionModel { string ExpressionValidate(string strUserEntry); string ConvertToPostfix(string strValidExpression); string EvaluateExpression(string strPostFixExpression); } } namespace ExpressionEvaluatorLibrary { public class ExpressionModel : IExpressionModel { public string ExpressionValidate(string strUserEntry) { strUserEntry = strUserEntry.Trim(); if (string.IsNullOrEmpty(strUserEntry)) return "There was no entry."; if (strUserEntry.Length &gt; 250) //250 seemed better than 254 return "More than 250 characters entered."; string[] fixes = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; bool boolStartsWith = fixes.Any(prefix =&gt; strUserEntry.StartsWith(prefix)); if (!boolStartsWith) return "The expression needs to start with a number."; bool boolEndsWith = fixes.Any(postfix =&gt; strUserEntry.EndsWith(postfix)); if (!boolEndsWith) return "The expression needs to end with a number."; if (!Regex.IsMatch(strUserEntry, "^[-0-9+*/ ]+$")) return "There were characters other than Numbers, +, -, * and /."; if (!Regex.IsMatch(strUserEntry, "[-+*/]")) return "Not a mathematical expression"; string[] strOperator = Regex.Split(strUserEntry, @"\d+"); for (int i = 1; i &lt; strOperator.Length - 1; i++) //the first and last elements of the array are empty { if (strOperator[i].Trim().Length &gt; 1) return "Expression cannot have operators together '" + strOperator[i] + "'."; } return "Valid"; } public string ConvertToPostfix(string strValidExpression) { StringBuilder sbPostFix = new StringBuilder(); Stack&lt;Char&gt; stkTemp = new Stack&lt;char&gt;(); for (int i = 0; i &lt; strValidExpression.Length; i++) { char chExp = strValidExpression[i]; if (chExp == '+' || chExp == '-' || chExp == '*' || chExp == '/') { sbPostFix.Append(" "); if (stkTemp.Count &lt;= 0) stkTemp.Push(chExp); else if (stkTemp.Peek() == '*' || stkTemp.Peek() == '/') { sbPostFix.Append(stkTemp.Pop()).Append(" "); i--; } else if (chExp == '+' || chExp == '-') { sbPostFix.Append(stkTemp.Pop()).Append(" "); stkTemp.Push(chExp); } else { stkTemp.Push(chExp); } } else { sbPostFix.Append(chExp); } } for (int j = 0; j &lt;= stkTemp.Count; j++) { sbPostFix.Append(" ").Append(stkTemp.Pop()); } string strPostFix = sbPostFix.ToString(); strPostFix = Regex.Replace(strPostFix, @"[ ]{2,}", @" "); return strPostFix; } public string EvaluateExpression(string strPostFixExpression) { Stack&lt;string&gt; stkTemp = new Stack&lt;string&gt;(); string strOpr = ""; string strNumLeft = ""; string strNumRight = ""; List&lt;String&gt; lstPostFix = strPostFixExpression.Split(' ').ToList(); for (int i = 0; i &lt; lstPostFix.Count; i++) { stkTemp.Push(lstPostFix[i]); if (stkTemp.Count &gt;= 3) { Func&lt;string, bool&gt; myFunc = (c =&gt; c == "+" || c == "-" || c == "*" || c == "/"); bool isOperator = myFunc(stkTemp.Peek()); if (isOperator) { strOpr = stkTemp.Pop(); strNumRight = stkTemp.Pop(); strNumLeft = stkTemp.Pop(); double dblNumLeft, dblNumRight; bool isNumLeft = double.TryParse(strNumLeft, out dblNumLeft); bool isNumRight = double.TryParse(strNumRight, out dblNumRight); if (isNumLeft &amp;&amp; isNumRight) { double dblTempResult; switch (strOpr) { case ("+"): dblTempResult = dblNumLeft + dblNumRight; stkTemp.Push(dblTempResult.ToString()); break; case ("-"): dblTempResult = dblNumLeft - dblNumRight; stkTemp.Push(dblTempResult.ToString()); break; case ("*"): dblTempResult = dblNumLeft * dblNumRight; stkTemp.Push(dblTempResult.ToString()); break; case ("/"): dblTempResult = dblNumLeft / dblNumRight; stkTemp.Push(dblTempResult.ToString()); break; } } } } } return stkTemp.Pop(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-05T18:23:26.697", "Id": "43992", "Score": "0", "body": "Generally, if I were to write such thing, I'd look into [Polish notation](http://en.wikipedia.org/wiki/Polish_notation) which would make it easier to parse the expression and then build the [expression trees](http://msdn.microsoft.com/en-us/library/bb397951.aspx) for operators." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T14:02:39.417", "Id": "44102", "Score": "0", "body": "@PatrykĆwiek thank you for the suggestion. I'll take a look at how I could use them." } ]
[ { "body": "<ol>\n<li><p>If I'm not mistaken your acceptable input expressions are in infix notation and look like this:</p>\n\n<pre><code>number [+-*/] number [+-*/] number ....\n</code></pre>\n\n<p>In that case you can greatly simplify you validation check with a single regular expression:</p>\n\n<pre><code>^\\d+(\\s*[+-*/]\\s*\\d+)+$\n</code></pre>\n\n<p>It checks for strings starting with a number composed out of 1 or more digits followed by 1 or more groups of <code>[+-*/] number</code>. The <code>\\s*</code> allows any number of white spaces between operators and numbers.</p></li>\n<li><p>When you validate you should not return a <code>string</code> representing the validation result. Two alternative options:</p>\n\n<ol>\n<li><p>Return a <code>ValidationResult</code> object like this:</p>\n\n<pre><code>class ValidationResult\n{\n bool readonly IsValid;\n string readonly FailureReason;\n\n private ValidationResult() { }\n\n public static ValidationResult Valid()\n {\n return new ValidationResult { IsValid = true; }\n }\n\n public static ValidationResult Invalid(string reason)\n {\n return new ValidationResult { IsValid = false; FailureReason = reason; }\n }\n}\n</code></pre>\n\n<p>Use: <code>return ValidationResult.Invalid(\"some error\")</code></p></li>\n<li><p>Throw a <code>ValidationException</code> with the message as the failure reason and catch it when calling the validation method and log/display the message to the user.</p></li>\n</ol></li>\n<li><p>You are doing a lot of parsing and re-parsing by passing everything around as strings. This is not really a good way of doing it and also very inefficient as you are constantly throwing away information and having to reconstruct it via parsing it out of the string.</p>\n\n<p>Here is how I would split it up:</p>\n\n<ul>\n<li>Write a tokenizer which splits the input string into tokens (numbers and operators) and provides the next token to the parser</li>\n<li>The parser should build the expression tree. The operators should be the nodes and the leaves are the numbers. This way you can traverse it anyway you like infix, postfix, prefix and you retain the information about the parsed input. </li>\n<li>Evaluating just means to traverse the tree and evaluate the nodes and the operands.</li>\n</ul>\n\n<p>Some skeleton code:</p>\n\n<p>The nodes of the tree:</p>\n\n<pre><code>interface INode\n{\n double Evaluate();\n}\n\nabstract class Operator : INode\n{\n protected readonly INode Left;\n protected readonly INode Right;\n\n protected Operator(INode left, INode right)\n {\n Left = left;\n Right = right;\n }\n\n public abstract double Evaluate();\n\n public static Operator FromString(string op, INode left, INode right)\n {\n switch (op)\n {\n case \"+\": return new Add(left, right);\n case \"-\": return new Sub(left, right);\n case \"*\": return new Mul(left, right);\n case \"/\": return new Div(left, right);\n default: throw new ArgumentException(\"Invalid operator\", \"op\");\n }\n }\n}\n\nclass Add : Operator\n{\n public Add(INode left, INode right) : base(left, right) {}\n\n public override double Evaluate()\n {\n return Left.Evaluate() + Right.Evaluate();\n }\n}\n\n// ...\n// similar classes for Sub, Mul And Div \n// ...\n\nclass Constant : INode\n{\n private readonly double _Number;\n\n public Constant(double number)\n {\n _Number = number;\n }\n\n public double Evaluate() \n { \n return _Number;\n }\n}\n</code></pre>\n\n<p>Parsing (will only deal with valid input):</p>\n\n<pre><code>public IEnumerable&lt;string&gt; Tokenize(string input)\n{\n // assuming only spaces or tabs are allowed in the expression\n return string.Split(new [] { ' ', '\\t' }, StringSplitOptions.RemoveEmptyEntries);\n}\n\npublic INode ParseTokens(IEnumerable&lt;string&gt; tokens)\n{ \n INode left = new Constant(Double.Parse(tokens.First()));\n\n tokens = tokens.Skip(1);\n\n // last token of expression is always a number\n if (!tokens.Any()) return left;\n\n var op = tokens.First();\n\n // recursive descending\n INode right = ParseTokens(tokens.Skip(1));\n\n return Operator.FromString(op, left, right);\n}\n</code></pre>\n\n<p>Actually evaluating the input becomes:</p>\n\n<pre><code>double EvaluateInput(string input)\n{\n var tokens = Tokenize(input);\n var root ParseToken(tokens);\n return root.Evaluate();\n}\n</code></pre>\n\n<p>Ideally you actually create a <code>Tokenizer</code> class which gets instantiated with the input string and where you can call <code>Next()</code> on which will return the next token. The tokenizer should be passed to the parse method. I just used simple <code>IEnumerable</code> because it was quicker to show the basic concept.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-29T20:36:32.967", "Id": "159981", "Score": "0", "body": "this approach doesn't include operator priority and won't work with more then one operation." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-30T10:45:39.203", "Id": "36405", "ParentId": "26631", "Score": "3" } } ]
{ "AcceptedAnswerId": "36405", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T15:38:06.057", "Id": "26631", "Score": "3", "Tags": [ "c#", "regex", "console" ], "Title": "Mathematical expression evaluator." }
26631
<p>This is a continuation from here:<br/> <a href="https://stackoverflow.com/questions/16761207/java-theory-classes-design-for-currency-futures-and-metals-analysis">https://stackoverflow.com/questions/16761207/java-theory-classes-design-for-currency-futures-and-metals-analysis</a> <br/></p> <p>I have created 2 classes for now.<br/> 1) Historical Data <br/> 2) Futures. <br/></p> <p>Here is the Code: It does the following: Takes in a file, checks if it is a file, dynamically creates an array based on the size of the file then it prints it out as a string. As you can see this is procedural still. It works but I am not using OOP principals</p> <pre><code>import java.awt.List; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.StringTokenizer; /* * This will allow me to uploadFutures historical csv data into an arraylist * I then want to perform analysis on it */ public class Futures extends HistoricalData{ // absolute path of my file File esFuturesData = new File("C:/Users/Administrator/Desktop/Stock Project/Tick Data Source Files/TextFiles/Completed/test.txt"); // need to declare an list to loop through it public ArrayList&lt;E&gt; myList = new ArrayList&lt;E&gt;(); // need a method to see if the file can be read. public boolean isaFile() { return esFuturesData.isFile(); } // need a method to get the size of the file .. public int sizeofFile() throws IOException{ // variable z for size of file int z = 0; if(isaFile()){ // read in the file esFuturesData and store it in object reader BufferedReader reader = null; try{ reader = new BufferedReader(new FileReader(esFuturesData)); // need to find out how many rows are in the file while(reader.readLine() != null) { //when there is new line increment z by 1 z +=1; } } catch (IOException ex) { System.err.println(); } finally{ if(reader != null){ reader.close(); } } } else{ System.out.println("This is not a file"); } return z; } // need to create a dynamic String array based on the size of the file public void createArray(){ // reset the rows of the file to 0. int rowCount =0; // create a testData array based on the number of rows method and that is of 4 columns myList = new ArrayList[sizeofFile()][5]; // we need to read in the file.. // catch any errors.. BufferedReader reader = null; try{ reader = new BufferedReader(new FileReader(esFuturesData)); // we need to create a line of type String to store what we are putting through it.. String line = null; // need to keep reading until there is nothing left. while((line=reader.readLine()) != null){ // we need to put the line into the array testData StringTokenizer p = new StringTokenizer(line,","); // while there is something to read while(p.hasMoreTokens()){ // loop through the first column and add a 1 for (int columnCount = 0; columnCount&lt;1;columnCount++){ // need to convert to string representation of an int myList[rowCount][columnCount] = "0"; } // loop through the columns for (int columnCount = 1; columnCount&lt;5;columnCount++){ myList [rowCount][columnCount] = p.nextToken(); //System.out.printf("%s", testData [x][y]); } // end of for loop rowCount++; } // end of while loop } // end of other while loop } // end of try braces catch(Exception e){ System.err.println(); } // end of catch } // end of create array braces // method that prints the file as a String public void printArrayAsString(){ // Some Housekeeping System.out.printf(" ID"); System.out.printf(" Date"); System.out.printf(" Time "); System.out.printf(" Price"); System.out.printf(" Volume"); System.out.println(); // need a loop to go through each row number for(int rowCount = 0; rowCount &lt; myList.length; rowCount++ ){ // print out each row number // System.out.printf("%s", x); // print out a space System.out.printf(" "); { for(int columnCount = 0; columnCount &lt; 5; columnCount++ ){ System.out.printf("%s", myList [rowCount][columnCount]); System.out.printf(" "); } System.out.println(); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T10:56:30.463", "Id": "41320", "Score": "0", "body": "@Bobby as per your very useful comments I have updated my code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T11:08:09.030", "Id": "41324", "Score": "0", "body": "@Bobby as per your very useful comments I have updated my code. I tried using the ArrayList option but running into problems. I want to add a new unique key to each unique row before I parse it. Then I want to upload my esFuturesData object to the ArrayList after I parse it. my thinking may be wrong on this. what is the best format to have the data in the ArrayList as I will want to do analysis on the date, time, price and volume at a later stage. The data format is as following for the futures data: date (ddmmyy),time,price,volume example: 021211,154611,00901.75,2" } ]
[ { "body": "<p>First, your indentation, brace-style and white-space usage is all mixed/messed up, fix that (hit \"Format Code\" in your favorite IDE if available).</p>\n\n<hr>\n\n<pre><code>// reads in a esfutures file and stores it as esfuturesdataobject \n</code></pre>\n\n<p><a href=\"http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html\" rel=\"nofollow\">Java documentation</a> normally looks like this:</p>\n\n<pre><code>/**\n * This is an important variable\n */\nprivate String awesomeness = null;\n</code></pre>\n\n<p>That allows IDEs and other systems to pick up on them and f.e. display them directly to you.</p>\n\n<hr>\n\n<pre><code>File esfuturesdata = new File(\"C://Users//Administrator//Desktop//Stock Project//Tick Data Source Files//TextFiles//Completed//test.txt\");\n</code></pre>\n\n<ul>\n<li><a href=\"http://www.oracle.com/technetwork/java/codeconv-138413.html\" rel=\"nofollow\">Variable names in Java should be lowerCamelCase</a>.</li>\n<li>You've got a hardcoded path here, is that really what you want?</li>\n<li><p>Windows uses backslashes <code>\\</code> which need to be escaped, slashes <code>/</code> don't need to be escaped, so it's one <em>or</em> the other:</p>\n\n<pre><code>C:\\\\Users\\\\Administrator\\\\..\nC:/Users/Administrator/...\n</code></pre></li>\n<li><p>Consider adding a visibility modificator (<code>private</code>, <code>public</code>) for clarity.</p></li>\n</ul>\n\n<hr>\n\n<pre><code>// need to declare an tesdata Array for looping through my data\nString [][] testData;\n</code></pre>\n\n<p>Consider if a <code>List&lt;T&gt;</code> might be more interesting in this case.</p>\n\n<hr>\n\n<pre><code>BufferedReader reader = new BufferedReader(new FileReader(futuresdata));\n</code></pre>\n\n<p>Readers and similar should be closed after usage. On possible design to do this is this:</p>\n\n<pre><code>BufferedReader reader = null;\ntry {\n reader = new BufferedReader(new FileReader(file));\n // Usage goes here.\n} catch (IOException ex) {\n // Exception handling goes here.\n} finally {\n if(reader != null) {\n reader.close();\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code>catch (Exception e)\n</code></pre>\n\n<p>Do not catch generic Exceptions, catch only those which are necessary and handle them gracefully. Also consider if you may want those thrown, because at the moment the application will happily continue on if the file could not be read for <em>any</em> reason.</p>\n\n<pre><code>System.out.println(\"e\");\n</code></pre>\n\n<p>What is that supposed to be?! Not to mention that errors should to stderr, which is <code>System.err.println()</code>.</p>\n\n<hr>\n\n<pre><code>// reset the rows of the file to 0.\nint x =0;\n</code></pre>\n\n<p>If that variable holds the number of rows, then please also give it a meaningful name, like <code>rows</code> row <code>rowCount</code>.</p>\n\n<hr>\n\n<pre><code>}// end of futures class brackets\n</code></pre>\n\n<p>If your code is well structured and correctly intended, such comments are unnecessary.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T07:53:20.533", "Id": "26655", "ParentId": "26637", "Score": "3" } }, { "body": "<p>I'm not sure I understand the current class design. What does <code>HistoricalData</code> look like?</p>\n\n<p>Think about the different things you are working with, what they represent, and what you want to do with them. Then model them as classes.</p>\n\n<p>For example, I see something that represents a line in the CSV file. I can see it has things like ID, Date, Price, etc. Currently, these appear to be just strings in an array. Consider creating a class to represent this, with properties of the appropriate data type (for example, <code>java.util.Date</code> for the date &amp; time). Maybe something like <code>HistoricalDataElement</code>(?). Maybe you can come up with a better name. What would you call the data in a single row in the CSV file?</p>\n\n<p>It may also make sense to create a separate class to represent a collection of <code>HistoricalDataElement</code>s. This could be a good place to put some functions that operate on the set of data as a whole. You'll have to decide if this makes sense for your scenario. Maybe you will have multiple classes to do different kinds of analysis.</p>\n\n<p>You should also consider separating the parsing into it's own class.</p>\n\n<p>Here is a very rough outline of what I am thinking:</p>\n\n<pre><code>public class HistoricalDataElement {\n private String id;\n private Date dateTime;\n private BigDecimal price;\n private long volume;\n // getters/setters\n}\n\npublic class HistoricalData {\n private List&lt;HistoricalDataElement&gt; historicalDataElements;\n public long doSomeAnalysis() {...}\n public long doSomeOtherAnalysis() {...}\n // etc\n}\n\npublic class HistoricalDataParser {\n public HistoricalData parse(File file) {...}\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T13:36:49.027", "Id": "41341", "Score": "0", "body": "@ Joe thanks. let me work on what you have given me along with other comments from this thread and previous thread. Im very new to this so am not sure what the best way is but i like the idea of having seperate variables for each of the data elements in my file. I am going to spend more time on working on my classes design and specifying what each is meant to do and will be open to suggestions on each." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T13:06:00.220", "Id": "26668", "ParentId": "26637", "Score": "1" } } ]
{ "AcceptedAnswerId": "26655", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T20:24:31.700", "Id": "26637", "Score": "1", "Tags": [ "java", "object-oriented" ], "Title": "Java Theory: Classes Design for Currency, Futures and Metals Analysis 1" }
26637
<p>Is this code good for checking if the variable <code>texto</code> is empty or not? How would it be done with try and catch?</p> <pre><code>public class RedProfesionalException extends Exception { public RedProfesionalException(String message) { super(message); } } public class Comentari extends Object { private String autor, texto; public Comentari(String autor, String texto) throws RedProfesionalException{ this.autor = autor; this.texto = texto; if (texto==null || texto.equals("")) throw new RedProfesionalException("You have written nothing"); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T20:49:16.823", "Id": "41290", "Score": "2", "body": "There is nothing wrong with your current code..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T07:33:09.010", "Id": "41310", "Score": "2", "body": "Please consider converting your names/variables to English before posting it here. In this case it does not matter much, but if the examples get more complicated it's a necessity." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T10:41:55.160", "Id": "41319", "Score": "0", "body": "Does the `Comentari` class has an ID field not shown here? Does it have setters/getters (especially setters) for `autor` and `texto` also not shown here?" } ]
[ { "body": "<p>The current way of throwing your exception is absolutely fine from what I can see, I'm not quite sure what your question is supposed to be as since you want to throw an exception, you do not actually want to use try/catch. That part is left for the client code.</p>\n\n<p>Point is, the code you have right now is just fine :)</p>\n\n<p><em><strong>EDIT</em></strong></p>\n\n<p>Perhaps you mean that you have to write code which makes use of the class to test if an exception has been thrown? In that case it would look something like:</p>\n\n<pre><code>try\n{\n String autor = \"SomeAuthor\";\n String texto = null;\n\n Comentari newComentari = new Comentari(autor, texto);\n}\ncatch (RedProfesionalException ex)\n{\n // React to caught exception here...\n}\n</code></pre>\n\n<p>Perhaps this is what you want?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T20:58:00.827", "Id": "41291", "Score": "0", "body": "I am asked to do it with try and catch, do you know how?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T21:08:23.373", "Id": "41292", "Score": "0", "body": "I have edited the answer above with additional information. Is this what you are trying to accomplish?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T21:23:58.017", "Id": "41293", "Score": "0", "body": "The javadoc says me that RedProfesionalExceptions throws when the text is empty, with the following text: \"you must write something!\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T07:52:47.257", "Id": "41312", "Score": "0", "body": "Which is correct :-) I'm sorry but I'm having a hard time understanding exactly what you want to do besides what has already been shown. Perhaps another person knows what it is you are trying to achieve :-)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T20:55:12.857", "Id": "26639", "ParentId": "26638", "Score": "1" } }, { "body": "<p>I disagree. This code should be improved.</p>\n\n<pre><code>try\n{\n String autor = \"SomeAuthor\";\n String texto = null;\n\n Comentari newComentari = new Comentari(autor, texto);\n}\ncatch {RedProfesionalException ex)\n{\n // React to catched exception here...\n}\n</code></pre>\n\n<p>That is not how object orientation works.\nIt is a bad habit to throw exceptions in a constructor:</p>\n\n<pre><code>public class Comentari extends Object {\n private String autor, texto;\n\n public Comentari(String autor, String texto) throws RedProfesionalException{\n this.autor = autor;\n this.texto = texto;\n if (texto==null || texto.equals(\"\"))\n throw new RedProfesionalException(\"You have written nothing\");\n\n }\n\n}\n</code></pre>\n\n<p>One reason to choose OOP is the advantage of creating an object in a predefined state. What you wanted is: you wanted to create a valid Comentari object. What you did is: in case the state of your object would be invalid, your object would be created and just break in to pieces because of your exception.\nIt would be much cleaner to wrap this into a factory function like:</p>\n\n<pre><code>public Comentari createComentariWithAuthorAndText(String autor, String texto){\n if (texto==null || texto.equals(\"\"))\n throw new RedProfesionalException(\"You have written nothing\");\n return new Comentari(author, texto);\n}\n</code></pre>\n\n<p>So there is nerver an inconsistent object created and no objects were harmed ;)\nAnother solution would be to allow the creation of an empty commentary, but check later, if comentari.getTexto() is empty and handle that fact later.</p>\n\n<p>So the try/catch looks like:</p>\n\n<pre><code>try\n {\n String autor = \"SomeAuthor\";\n String texto = null;\n\n Comentari newComentari = createComentariWithAuthorAndText(autor, texto);\n }\n catch {RedProfesionalException ex)\n {\n // React to catched exception here...\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T09:06:33.633", "Id": "41315", "Score": "0", "body": "Oh I agree completely, good point. I didn't take it any further because the question seemed to be more about a misconception or misunderstanding of what to do with the actual try/catch once an exception is thrown. But +1 for taking the design further. Definitely the best answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T10:24:06.107", "Id": "41316", "Score": "0", "body": ">*So there is nerver an inconsistent object created ...*\n\nIf you have a public constructor, as is the case here, all bets are off." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T11:32:37.093", "Id": "41326", "Score": "0", "body": "It should be more a metaphor: the object is killed in statu nascendi so to say. Nevertheless I think, throwing exceptions in constructors is not a nice behaviour." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T08:12:19.180", "Id": "26658", "ParentId": "26638", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T20:46:32.623", "Id": "26638", "Score": "-1", "Tags": [ "java", "validation", "constructor", "exception" ], "Title": "Checking whether a comment contains text" }
26638
<p>There are a few common jQuery call I find my self calling when creating my app. I need some help and maybe a better way to do all this or rewrite it.</p> <h3>1) Singleton Selector</h3> <p>If I want to select only one class I would do it like this:</p> <pre><code>$(&quot;#tempo&quot;).on(&quot;click&quot;, &quot;.entity&quot;, function(e){ $(&quot;.selected&quot;).removeClass(&quot;selected&quot;); $(this).addClass('selected'); // .... </code></pre> <hr /> <h3>2) Resource Selector</h3> <p>I have a div with all the resource elements (divs,ul) with formated code added class and even children). This is the code I write a lot to select it, clone it and append it.</p> <pre><code>// $R = $('div.resources'); - Create only once. $R.find(&quot;.folder&quot;).clone() .addClass(id++) .appendTo(&quot;#folders&quot;); </code></pre> <hr /> <h3>3) Prevent Double Actions</h3> <p>I have quite a lot of ajax request to the server once a button gets clicked and have to disable the button from being double clicked each time.</p> <pre><code>$(&quot;button#new_game&quot;).on(&quot;click&quot;,function(e){ if( $(this).hasClass(&quot;clicked&quot;) == false ){ var $pre = $(this); $pre.addClass(&quot;clicked&quot;); createAjaxCall(function(result){ $pre.removeClass(&quot;clicked&quot;); } } }); </code></pre> <p>Adding the clicked class can allow me to customize the button a bit I should mention, So I can't really use <code>.data()</code></p> <p>These are the three main jQuery repetitive/non optimized problems I run into.</p>
[]
[ { "body": "<p>I'd say you're on the right track with all your code. The trick is probably to abstract some of the oft-repeated code into functions/plugins.</p>\n\n<p>For the \"singleton selector\", wrapping your code in a plugin would seem the way to go. But note that your current code might need tweaking. You have this line:</p>\n\n<pre><code> $(\".selected\").removeClass(\"selected\")\n</code></pre>\n\n<p>which will remove the <code>selected</code> class from elements <em>anywhere</em> on the page. In your example, you'd probably want only to remove the class from <code>.entity</code> elements within the <code>#tempo</code> element.</p>\n\n<p>Here's a (very quick) sketch of a plugin, that should do what you want (and keep it limited to the container element):</p>\n\n<pre><code>$.fn.singleSelection = function(classSelector, handler) {\n return this.each(function() {\n var container = $(this);\n container.on(\"click\", classSelector, function (event) {\n container.find(classSelector + \".selected\").removeClass(\"selected\");\n $(this).addClass(\"selected\");\n if( typeof handler === \"function\" ) {\n handler.call(this, event);\n }\n });\n });\n};\n</code></pre>\n\n<p>Your code can then be shortened to</p>\n\n<pre><code>$(\"#tempo\").singleSelection(\".entity\"); // you can add a click handler too\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/bpZtM/2/\" rel=\"nofollow\">Here's a demo</a>.</p>\n\n<p>But... jQueryUI <a href=\"http://jqueryui.com/button/#radio\" rel=\"nofollow\">already has this functionality</a>, so if you feel like using that, go right ahead. It's certainly been tested better than what you see above :)<br>\nHowever, for such a simple thing, jQueryUI seems like overkill. But there are probably other, leaner plugins you can find, which'll do what you need - this is just an example.</p>\n\n<hr>\n\n<p>For your second point, I'd probably wrap the code in an <code>addFolder</code> function somewhere. But it's a little hard to be more specific without knowing more about the context.</p>\n\n<hr>\n\n<p>For your third point, you could again make a simple jQuery plugin that'd only forward events to your click handler if the element doesn't have the \"clicked\" class. There are also various \"debounce\" plugins out there to throttle clicks, but most simply impose a time limit rather than explicitly wait for an ajax operation to finish.</p>\n\n<p>In any event, here's another (very quick) sketch of a jQuery plugin</p>\n\n<pre><code>$.fn.clickOnce = function(handler) {\n return this.each(function() {\n var element = $(this);\n element.on(\"click\", function (event) {\n if( !element.hasClass(\"clicked\") ) {\n element.addClass(\"clicked\");\n if( typeof handler === \"function\" ) {\n handler.call(this, event);\n }\n }\n });\n });\n};\n</code></pre>\n\n<p>In your code you could then do:</p>\n\n<pre><code>$(\"button#new_game\").clickOnce(function (event) {\n // this will only be called if the button wasn't already clicked\n var button = $(this);\n createAjaxCall(function (result) {\n // it's your responsibility to remove the \"clicked\" class\n button.removeClass(\"clicked\");\n }); \n});\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/77GZJ/\" rel=\"nofollow\">Here's a demo</a></p>\n\n<p>Again, there are no doubt ready-made plugins that do this and do it better.</p>\n\n<p>By the way, I personally find it easier to pass jQuery's XHR objects around, as they act as <a href=\"http://api.jquery.com/category/deferred-object/\" rel=\"nofollow\">deferred objects/promises</a>. I.e.:</p>\n\n<pre><code>var xhr = $.ajax(...); // create an XHR obj from any of jQuery's ajax functions\n\nxhr.done(function (data) {\n // success handler\n});\n\nxhr.fail(function (err) {\n // failure handler\n});\n\nxhr.always(function () {\n // complete handler\n});\n</code></pre>\n\n<p>So if your <code>createAjaxCall()</code> function returns an xhr object, you can attach a handler to the <code>always</code> \"event\", and use that to clear the <code>clicked</code> class. That seems more robust (and readable) to me.</p>\n\n<p>p.s. You could use a <code>data-*</code> <em>attribute</em> (set with <code>.attr()</code> instead of <code>.data()</code>), and still have custom styling with CSS like</p>\n\n<pre><code>button[data-clicked='true'] { // CSS attribute selectors are neat!\n ...\n}\n</code></pre>\n\n<p>but browser support is limited compared to using simple classes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T23:27:40.027", "Id": "41301", "Score": "0", "body": "Wow, really great write up, about the second problem i stored all my html <div id=\"resource> .. all divs </div> and then clone a selected example, find() seems to work but is it optimized." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T22:48:57.867", "Id": "26646", "ParentId": "26640", "Score": "2" } }, { "body": "<p>Besides what Flambino wrote I have a small remark to (3):\nWhy are you storing unnecessary information in the DOM?\nI would prefer a solution, where you use a simple variable to keep track of whether the button performs an action or not. So you wouldn't have to update the DOM twice for nada.\nThe DOM is a bad place for storing the state of your application.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T11:55:10.520", "Id": "41330", "Score": "1", "body": "I'm not sure if you read my whole question but I need the dom change as the class has styling associated with it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T12:11:19.900", "Id": "41332", "Score": "1", "body": "Oh, ok ;) I overlooked that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T08:28:38.977", "Id": "26659", "ParentId": "26640", "Score": "0" } } ]
{ "AcceptedAnswerId": "26646", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T21:00:05.190", "Id": "26640", "Score": "3", "Tags": [ "javascript", "jquery", "html", "html5", "jquery-ui" ], "Title": "Replacing simple jQuery methods for better use" }
26640
<p>I am breaking my head with how to get rid of semantic duplication(Code that is syntactically the same but does different things).</p> <p>I can't find anywhere a post or something that mentions a bit how to refactor this kind of duplication. All I found was this:<br> <a href="https://blogs.agilefaqs.com/2011/07/21/duplicate-code-and-ceremony-in-java/" rel="nofollow noreferrer">Duplicate Code and Ceremony in Java</a> but it does not go into detail on how to refactor it. </p> <p>This is the code that is causing me problem:</p> <pre><code>public class TeamValidator { public boolean isThereALeader(List&lt;Member&gt; team) { Iterator&lt;Member&gt; iterator = team.iterator(); while(iterator.hasNext()) { Member member = iterator.next(); String role = member.getRole(); if(role.equals("Leader")) return true; } return false; } public boolean areThereAtLeast2NewJoiners(List&lt;Member&gt; team) { int amountOfNewJoiners = 0; for(Member member:team) { if(amountOfNewJoiners == 2) return true; DateTime aMonthAgo = DateTime.now().minusMonths(1); if(member.startingDate().isAfter(aMonthAgo)) { amountOfNewJoiners++; } } return false; } } </code></pre> <p>In these two methods there is semantic duplication, because both <em>iterate</em> a list and also check some condition/s. Any idea how could I make this semantic duplication disappear?<br> I would really appreciate some tip or suggestion on how to refactor this.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T22:04:03.063", "Id": "41297", "Score": "0", "body": "BTW, I think the second method is wrong. If the second new joiner is the last item in the collection, the method will incorrectly return `false`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-25T05:11:52.443", "Id": "43252", "Score": "0", "body": "Strictly speaking, `candidate.getRole().equals(\"Leader\");` should be `candidate.isRole(\"Leader\")`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-26T09:47:26.953", "Id": "458957", "Score": "0", "body": "(Check what happens when `amountOfNewJoiners` gets incremented when `member` is the last item in `team`.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-27T17:04:00.213", "Id": "459081", "Score": "0", "body": "A very nice example of why first class functions are good :) `.filter()` is all that would be needed here." } ]
[ { "body": "<p>Well for a start, choose a style: Use the enhanced for loop, or use explicit iterators. Don't use one in one place and another in another. Other than that, I'm not seeing enough similar in the loops to justify spending any time on it as opposed to, say, actually getting something else done. :-)</p>\n\n<p>But if you really, really want to, you can create an interface that evaluates loop conditions, implement concrete classes for the two situations, and use them. I don't think it buys you much.</p>\n\n<p>(The below also fixes the false negative if you have exactly two members and they're both new joiners.)</p>\n\n<p>Definition:</p>\n\n<pre><code>abstract class LoopEvaluator&lt;T&gt; {\n public boolean eval(List&lt;T&gt; list) {\n for (T element : list) {\n if (this.evalElement(element)) {\n return true;\n }\n }\n return false;\n }\n abstract boolean evalElement(T element);\n}\n\nclass LookForLeaders&lt;T extends Member&gt; extends LoopEvaluator&lt;T&gt; {\n @override\n public bool evalElement(T element) {\n return element.getRole().equals(\"Leader\");\n }\n}\n\nclass LookForTwoNewJoiners extends LoopEvaluator&lt;T&gt; {\n private int newJoiners;\n\n @override\n public boolean eval(List&lt;T&gt; list) {\n\n this.newJoiners = 0;\n\n return super.eval(list);\n }\n\n @override\n public boolean evalElement(T element) {\n DateTime aMonthAgo = DateTime.now().minusMonths(1);\n if(member.startingDate().isAfter(aMonthAgo)) {\n this.newJoiners++;\n }\n return newJoiners == 2;\n }\n}\n</code></pre>\n\n<p>Use:</p>\n\n<pre><code>public class TeamValidator { \n\n @override\n public boolean isThereALeader(List&lt;Member&gt; team) { \n return new LookForLeader().eval(team);\n } \n\n @override\n public boolean areThereAtLeast2NewJoiners(List&lt;Member&gt; team) { \n return new LookForTwoNewJoiners().eval(team);\n }\n}\n</code></pre>\n\n<p>It's late and I haven't double-checked the syntax, but you get the idea...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T21:42:24.523", "Id": "41294", "Score": "0", "body": "Thanks for the answer. I will give it a try. By the way, I moved the question to this forum, maybe is more apropiate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T04:27:47.730", "Id": "41304", "Score": "0", "body": "The false negative occurs whenever the second new joiner is the last member. Best to check conditions like that at the point where you increment the counter." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T21:19:03.810", "Id": "26644", "ParentId": "26642", "Score": "4" } }, { "body": "<p>This is a case where lambdas and a library of higher-order functions are very useful. For example in C#, both of your methods are pretty much one-liners:</p>\n\n<pre><code>public bool IsThereALeader(List&lt;Member&gt; team)\n{\n return team.Any(member =&gt; member.Role == \"Leader\");\n}\n\npublic bool AreThereAtLeast2NewJoiners(List&lt;Member&gt; team)\n{\n DateTime aMonthAgo = DateTime.Now.AddMonths(-1);\n return team.Count(member =&gt; member.StartingDate &gt; aMonthAgo) &gt;= 2;\n}\n</code></pre>\n\n<p>(The second method will iterate the whole collection even if it finds two new joiners early on, but that's not likely to matter.)</p>\n\n<p>In Java, you can emulate lambdas using anonymous classes, but the syntax is <em>much</em> more verbose (and I don't know if there is a library that provides the required helper functions).</p>\n\n<p>There are also some libraries listed at <a href=\"https://stackoverflow.com/q/1217228/41071\">the Stack Overflow question <em>What is the Java equivalent for LINQ?</em></a> that you could use for this purpose.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T04:30:34.383", "Id": "41305", "Score": "0", "body": "Yes, I'm very much looking forward to the appearance of real closures in Java 8!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-15T13:51:26.680", "Id": "197540", "Score": "0", "body": "@svick for large collections, performance considerations could be significant. I'd recommend `team.Where(member => member.StartingData > aMonthAgo).Take(2).Count() == 2` instead. It would stop iterating over the collection after finding first two new joiners, which is perfectly sufficient." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-15T14:29:58.297", "Id": "197560", "Score": "0", "body": "@KonradMorawski Yeah, if you know performance is important, that would be an improvement." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T22:19:33.947", "Id": "26645", "ParentId": "26642", "Score": "1" } }, { "body": "<p><code>both Iterate a list and also check some condition/s</code> and then return true if the condition is met for any element in the collection, otherwise they return false.</p>\n\n<p>It's exactly what you describe, lets write the code:</p>\n\n<p>We have a list or collection to make it more generic. <code>List&lt;T&gt;</code>.</p>\n\n<p>Then we have some conditions checked against T elements.\nYou can define an interface for a condition.</p>\n\n<pre><code>interface Condition&lt;T&gt; {\n boolean check (t t);\n}\n</code></pre>\n\n<p>You can create a new condition for whatever you want to check.</p>\n\n<p>Now all you need is a method that iterates a collection of Ts and checks them all against a condition. Put that in a utility class and you're done></p>\n\n<pre><code>static boolean checkAgainstCondition(Collection&lt;T&gt; collection, Condition&lt;T&gt; condition) {\n for (T t: collection) {\n if (condition.check(t) {\n return true;\n }\n }\n return false;\n }\n</code></pre>\n\n<p>Similarly you can have utility methods like:</p>\n\n<pre><code>static int countMatches(Collection&lt;T&gt; collection, Condition&lt;T&gt; condition) {\n //count how many elements meet the condition.\n</code></pre>\n\n<p>or</p>\n\n<pre><code>static boolean moreMatchesThan(Collection&lt;T&gt; collection, Condition&lt;T&gt; condition, count) {\n //return true if there are more than count elements in the collection that meet the condition.\n</code></pre>\n\n<p>You can do the same trick also in similar cases for example when you want to select an element from the collection that matches the condition, or if you want to remove from the collection elements that match to a condition etc. It's just the condition interface + utility class.</p>\n\n<p>You can see the idea implemented in this utility <a href=\"http://code.google.com/p/bo2/source/browse/#svn/trunk/Bo2Utils\" rel=\"nofollow\">project</a>. <a href=\"http://code.google.com/p/bo2/source/browse/trunk/Bo2Utils/main/gr/interamerican/bo2/utils/conditions/Condition.java\" rel=\"nofollow\">Condition interface</a>, <a href=\"http://code.google.com/p/bo2/source/browse/trunk/Bo2Utils/main/gr/interamerican/bo2/utils/CollectionUtils.java\" rel=\"nofollow\">utility class 1</a> and <a href=\"http://code.google.com/p/bo2/source/browse/trunk/Bo2Utils/main/gr/interamerican/bo2/utils/SelectionUtils.java\" rel=\"nofollow\">utility class 2</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T01:01:47.937", "Id": "26649", "ParentId": "26642", "Score": "1" } }, { "body": "<p>Key here is to identify that both functions check whether there are at least <em>n</em> members that match a certain condition.</p>\n\n<p>So we introduce a Matcher interface :</p>\n\n<pre><code>public interface Matcher&lt;T&gt; {\n\n boolean matches(T candidate);\n\n}\n</code></pre>\n\n<p>Which we then use to make a method <code>hasAtLeastNMatches()</code>. And both methods can be implemented by calling that.</p>\n\n<pre><code>public class TeamValidator {\n\n public boolean isThereALeader(List&lt;Member&gt; team) {\n return hasAtLeastNMatches(team, Is.Leader, 1);\n }\n\n public boolean areThereAtLeast2NewJoiners(List&lt;Member&gt; team) {\n final DateTime aMonthAgo = DateTime.now().minusMonths(1);\n return hasAtLeastNMatches(team, Is.NewJoiner, 1);\n }\n\n private boolean hasAtLeastNMatches(Iterable&lt;Member&gt; members, Matcher&lt;Member&gt; condition, int minimumNumberOfMatches) {\n int count = 0;\n for (Member member : members) {\n if (condition.matches(member) &amp;&amp; ++count &gt;= minimumNumberOfMatches) {\n return true;\n }\n }\n return false;\n }\n\n private static enum Is implements Matcher&lt;Member&gt; {\n Leader {\n @Override\n public boolean matches(Member candidate) {\n return candidate.getRole().equals(\"Leader\");\n }\n },\n\n NewJoiner {\n @Override\n public boolean matches(Member candidate) {\n return candidate.startingDate().isAfter(DateTime.now().minusMonths(1));\n }\n }\n }\n\n}\n</code></pre>\n\n<p>Method <code>hasAtLeastNMatches()</code> can obviously also be reused ouside this class. In fact this kind of reuse is so common that several open source code projects offer these kinds methods and interfaces: e.g. <a href=\"http://commons.apache.org/proper/commons-collections/\">Apache commons collections</a> and <a href=\"https://code.google.com/p/guava-libraries/wiki/FunctionalExplained\">Guava</a> . In fact what I called Matcher they both call <code>Predicate</code>. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-15T13:40:29.237", "Id": "197538", "Score": "0", "body": "a nitpick: `private static enum` - now this is a redundancy, enum is already static by itself, just like an interface" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T05:23:53.270", "Id": "26652", "ParentId": "26642", "Score": "5" } }, { "body": "<p>You can use the functional style for this task. This will help splitting the logic and general loop, so it simplifies the reading the code.</p>\n\n<p>I've wrote this in sublime, so there may be some errors in code, but the main idea is clear from this example:</p>\n\n<pre><code>public class TeamValidator {\n\n public static interface Function &lt;R, T&gt; {\n R apply(T val);\n } \n\n public boolean generalIteration(Function&lt;Boolean, Member&gt; func, List&lt;Member&gt; list) {\n Boolean result = false;\n for (Member member : list) {\n result = func.apply(member);\n if (result) break;\n }\n return result;\n }\n\n public boolean isThereALeader(List&lt;Member&gt; team) {\n return generalIteration(new Function&lt;Boolean, Member&gt;() {\n @Override\n public Boolean apply(Member member) {\n return \"Leader\".equals(member.getRole());\n }\n }, team);\n }\n\n public boolean areThereAtLeast2NewJoiners(List&lt;Member&gt; team) {\n final int[] amountOfNewJoiners = {0};\n return generalIteration(new Function&lt;Boolean, Member&gt;() {\n @Override\n public Boolean apply(Member member) {\n DateTime aMonthAgo = DateTime.now().minusMonths(1);\n if (member.startingDate().isAfter(aMonthAgo)) {\n int val = amountOfNewJoiners[0];\n amountOfNewJoiners[0] = ++val;\n }\n return (amountOfNewJoiners[0] == 2);\n }\n }, team);\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T04:30:39.483", "Id": "26734", "ParentId": "26642", "Score": "0" } }, { "body": "<p>I would use <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/FluentIterable.html\" rel=\"nofollow\"><code>FluentIterable</code></a> from <a href=\"https://code.google.com/p/guava-libraries/\" rel=\"nofollow\">Google's Guava</a> libraries to do away with a lot of boiler-plate, consider the following:</p>\n\n<pre><code>public class TeamValidator { \n\n public boolean isThereALeader(List&lt;Member&gt; team) { \n return FluentIterable.from(team).anyMatch(new Predicate&lt;Member&gt;() {\n @Override\n public boolean apply(Member member) {\n return member.getRole().equals(\"Leader\");\n }\n });\n } \n\n public boolean areThereAtLeast2NewJoiners(List&lt;Member&gt; team) { \n final DateTime aMonthAgo = DateTime.now().minusMonths(1);\n return FluentIterable.from(team).filter(new Predicate&lt;Member&gt;() {\n @Override\n public boolean apply(Member member) {\n return member.startingDate().isAfter(aMonthAgo);\n }\n }).size() &gt;= 2; \n }\n}\n</code></pre>\n\n<p>This can further be improved by extracting the <code>Predicate</code>s as classes, e.g.:</p>\n\n<pre><code>...\npublic boolean isThereALeader(List&lt;Member&gt; team) { \n return FluentIterable.from(team).anyMatch(new TeamLeaderExistsPredicate());\n}\n...\n</code></pre>\n\n<p>This allows the logic contained in the <code>Predicate</code> to be reused, if needs be, and is easier on the eye.</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>Java 8 equivalent:</p>\n\n<pre><code>boolean leaderExists = team.stream().anyMatch(m -&gt; \"Leader\".equals(m.getRole()));\n\nLocalDateTime aMonthAgo = LocalDateTime.now().minusMonths(1);\nboolean atLeastTwoNewJoinersExist = team.stream()\n .filter(m -&gt; m.startingDate().isAfter(aMonthAgo))\n .count() &gt;= 2;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T08:49:40.837", "Id": "26741", "ParentId": "26642", "Score": "3" } }, { "body": "<p>If code is syntactically the same, it is the same code... I think you are over-thinking this. The two code examples above are different enough to warrant their existence.</p>\n\n<p>Now, if you wanted to eliminate two methods that did the exact same thing, but lived in two places, that is simple. Just delete the one with less usage, then replace all calls to the old method with the new one. This is incredibly simple if they share the same method signature, slightly more involved if they do not.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-24T19:24:09.710", "Id": "27742", "ParentId": "26642", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-05-26T21:13:57.423", "Id": "26642", "Score": "9", "Tags": [ "java" ], "Title": "Computing predicates of multiple items avoiding duplication of iteration code" }
26642
<p>I made my first Brainfuck program today, which prints the numbers 0-255 and the corresponding character.</p> <p>I was wondering if I could improve my program, as I'm repeating myself a lot (e.g. 3 x copy &amp; paste "comparer" function):</p> <pre><code>max == 255 LF == 10 space == 32 '0' == 48 '9' == 57 ':' == 58 Memory: counter ':' space LF char max&amp;1 cmp1 0 0 num1 '9'&amp;1 cmp2 0 0 num2 '9'&amp;1 cmp3 0 0 num3 '9'&amp;1 cmp4 0 0 +++++ +++ [ &gt; +++++ ++ &gt; ++++ &gt; + &gt; ++++ [ &gt; +++++ +++ &lt; - ] &gt;&gt;&gt;&gt; &gt; +++++ + &gt; +++++ ++ &gt;&gt;&gt; &gt; +++++ + &gt; +++++ ++ &gt;&gt;&gt; &gt; +++++ + &gt; +++++ ++ &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; - ] &gt; ++ &gt;&gt; ++ &gt;&gt; &gt;&gt;&gt;&gt;&gt; ++ &gt;&gt;&gt;&gt;&gt; ++ &gt;&gt;&gt;&gt;&gt; ++ &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; Memory: 0 58 32 10 0 256 0 0 0 48 57 0 0 0 48 57 0 0 0 48 57 0 0 0 &gt;&gt;&gt;&gt;&gt; &gt; + [ - &gt;&gt;&gt; . &gt;&gt;&gt;&gt;&gt; . &gt;&gt;&gt;&gt;&gt; . &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt; . &gt; . &gt;&gt; . &lt; . Number increasing logic &gt;&gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt;&gt; &gt; + Comparer: num1 num2 out 0 0 [ - &gt;- &gt;&gt;&gt;+ &lt;&lt;&lt;&lt; ] &gt;&gt;+ set equal flag &lt; if num1 != num2 [ &gt;- clear equal flag ] &gt; if num1 == num2 [ &gt; ] &gt; go to last and put numbers back [ &lt;&lt;&lt;+ &lt;+ &gt;&gt;&gt;&gt;- ] &lt;&lt;&lt;&lt; reset pointer &gt;&gt; [ &lt;&lt; ----- ----- &lt;&lt;&lt;&lt;&lt; + &gt;&gt;&gt;&gt;&gt; &gt;&gt; - ] &lt;&lt; &lt;&lt;&lt;&lt;&lt; Comparer: num1 num2 out 0 0 [ - &gt;- &gt;&gt;&gt;+ &lt;&lt;&lt;&lt; ] &gt;&gt;+ set equal flag &lt; if num1 != num2 [ &gt;- clear equal flag ] &gt; if num1 == num2 [ &gt; ] &gt; go to last and put numbers back [ &lt;&lt;&lt;+ &lt;+ &gt;&gt;&gt;&gt;- ] &lt;&lt;&lt;&lt; reset pointer &gt;&gt; [ &lt;&lt; ----- ----- &lt;&lt;&lt;&lt;&lt; + &gt;&gt;&gt;&gt;&gt; &gt;&gt; - ] &lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; + Comparer: num1 num2 out 0 0 [ - &gt;- &gt;&gt;&gt;+ &lt;&lt;&lt;&lt; ] &gt;&gt;+ set equal flag &lt; if num1 != num2 [ &gt;- clear equal flag ] &gt; if num1 == num2 [ &gt; ] &gt; go to last and put numbers back [ &lt;&lt;&lt;+ &lt;+ &gt;&gt;&gt;&gt;- ] &lt;&lt;&lt;&lt; reset pointer &gt;&gt; Inverter: in/out 0 0 [ &gt; + &lt; - ] + &gt; [ &lt; - &gt; - ] &lt; ] </code></pre>
[]
[ { "body": "<p>I think this would be a more efficient way of doing it (at least for the printable ASCII characters):</p>\n\n<pre><code>++++[-&gt;++++++++&lt;] Use cell 0 for loop and cell 1 for ASCII codes\n++++[-&gt;&gt;++++++++&lt;&lt;]&gt;&gt;&gt; Use cell 2 for the space\n+++&gt;++&gt; Use cells 3 and 4 for the number equivalent\n++++++++&lt;&lt;&lt;&lt;&lt; Use cell 5 for incrementing the number equivalent\n++++++++++++++++++++++++++++++++++++++++\n++++++++++++++++++++++++++++++++++++++++ Get 95 for the loop\n+++++++++++++++\n[&gt;.+&gt;.&gt;.&gt;.+&gt;-[----------&lt;&lt;-&gt;&gt;&gt;]&lt;++++++++++&lt;&lt;+ Output ASCII &amp; space &amp; equivalent ASCII code\n&lt;&lt;&lt;] Go back to cell 0\n</code></pre>\n\n<p>Tell me how this works for you. I don't exactly see why you need that comparing function. Also, note that I do use cell 6, but only to escape loops (as it has a value of 0).</p>\n\n<p><strong>The fixed code</strong></p>\n\n<p>Here is some different code with the same original formatting as the one in your question:</p>\n\n<pre><code>++++++++[&gt;+++++++&gt;++++&gt;+&gt;++++[&gt;++++++++&lt;-]&gt;&gt;&gt;&gt;&gt;++++++&gt;+++++++&gt;&gt;&gt;&gt;++++++&gt;+++++++&gt;&gt;&gt;&gt;++++++&gt;+++++++&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;-]&gt;++&gt;&gt;++&gt;&gt;&gt;&gt;&gt;&gt;&gt;++&gt;&gt;&gt;&gt;&gt;++&gt;&gt;&gt;&gt;&gt;++&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&gt;&gt;&gt;&gt;&gt;&gt;+[-&gt;&gt;&gt;.&gt;&gt;&gt;&gt;&gt;.&gt;&gt;&gt;&gt;&gt;.&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;.&gt;.&gt;&gt;.&lt;.&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;+[-&gt;-&gt;&gt;&gt;+&lt;&lt;&lt;&lt;]&gt;&gt;+&lt;[&gt;-]&gt;[&gt;]&gt;[&lt;&lt;&lt;+&lt;+&gt;&gt;&gt;&gt;-]&lt;&lt;&lt;&lt;&gt;&gt;[&lt;&lt;----------&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;-]&lt;&lt;&lt;&lt;&lt;&lt;&lt;[-&gt;-&gt;&gt;&gt;+&lt;&lt;&lt;&lt;]&gt;&gt;+&lt;[&gt;-]&gt;[&gt;]&gt;[&lt;&lt;&lt;+&lt;+&gt;&gt;&gt;&gt;-]&lt;&lt;&lt;&lt;&gt;&gt;[&lt;&lt;----------&lt;&lt;&lt;&lt;&lt;+&gt;&gt;&gt;&gt;&gt;&gt;&gt;-]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;+[-&gt;-&gt;&gt;&gt;+&lt;&lt;&lt;&lt;]&gt;&gt;+&lt;[&gt;-]&gt;[&gt;]&gt;[&lt;&lt;&lt;+&lt;+&gt;&gt;&gt;&gt;-]&lt;&lt;&lt;&lt;&gt;&gt;[&gt;+&lt;-]+&gt;[&lt;-&gt;-]&lt;]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-15T00:25:21.387", "Id": "65726", "Score": "0", "body": "There are some good ideas here, but this doesn't actually work. For example, for the space character, you print ASCII bytes 0x03 (`ETX`) and 0x02 (`STX`) instead of 0x33 (`3`) and 0x32 (`2`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-15T11:02:23.437", "Id": "65756", "Score": "0", "body": "The good idea in this code is to keep a counter to increment the units digit 10 times instead of comparing it against a max value; comparison would take many more operations. However, it is far from being on par with the original. It crashes when the pointer goes to cell -1 (because in line 8, inside the inner brackets, `<<` and `>>>` are mismatched). I looks like a botched \"if (x != 0)\". Since BF only offers \"while\", to achieve \"if\" you have to copy `x` to two temp cells, one of which will be zeroed when executing the body, the other of which is needed to restore `x` to its original value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-15T11:51:12.037", "Id": "65766", "Score": "0", "body": "Yeah, sorry about the space... didn't realize that happened." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T20:49:47.630", "Id": "65995", "Score": "5", "body": "The fixed code you introduced in [Rev 3](http://codereview.stackexchange.com/revisions/39251/3) works. However, this is Code Review, not Programming Puzzles & Code Golf. Please explain your answer: how it works, and how it improves on the code in the original question in the aspects that the OP asked about." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-17T10:56:51.673", "Id": "198016", "Score": "4", "body": "The first code block here only results in gibberish, it prints ` ! \" # $ % & ' `. The cells your are using **don't add up and doesn't make sense.** Why use 95 for the loop? And what is the purpose of that loop? Why does cell 1 also contain value 32, same as cell 2? In addition, the \"fixed code\" that you show **is nothing but a minimized version of the code in the original question, with all comments stripped**. This answer provides no real value at all in my opinion." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-14T23:33:04.423", "Id": "39251", "ParentId": "26648", "Score": "10" } }, { "body": "<p>Congratulations. This was pretty readable code, by brainfuck standards. I was able to follow it.</p>\n\n<p>By initializing your <code>max</code> cell to 256, you've made your code portable to work on non-wrapping brainfuck interpreters as well. If you just wanted it to work on a wrapping brainfuck interpreter (i.e., one that works modulo 256), you could have left the cell set to 0. I considered changing the program to just loop 256 times instead of comparing the character against the maximum value, but it turns out that 255 times is much easier than looping 256 times when the machine operates modulo 256. You already have a comparison routine, so it's easy to just use it again. (Though preferably not by copying and pasting the code — more on that below.)</p>\n\n<p>While there may be <a href=\"https://stackoverflow.com/a/13946554/1157100\">simpler ways</a> to print a number as a decimal string, you asked to optimize for readability, so I have opted to stay close to your original strategy.</p>\n\n<p>The key to readability, I think, is to add strategic comments. In brainfuck, any characters other than the eight commands (<code>&gt;&lt;+-.,[]</code>) are ignored. You can also add comments of the form <code>[-][Any comment text goes here]</code>, with two caveats:</p>\n\n<ol>\n<li>The pointer must be pointing to a cell containing 0 or a cell that you want to be zeroed.</li>\n<li>Any character can appear inside, as long as square brackets occur in pairs.</li>\n</ol>\n\n<p>The main goals of your comments should be to clarify:</p>\n\n<ol>\n<li><p>What the intention of each chunk of code is.</p>\n\n<p>It is not so important, in my opinion, to be able to follow every single micro-operation as long as you can understand the big picture.</p></li>\n<li><p>What the memory layout is, and why it is laid out that way.</p>\n\n<p>I've given \"variable names\" to all important cells. There is also a long explanatory comment in the code below about what I call \"frames\", or groups of consecutive cells.</p></li>\n<li><p>Which cell is the current one at any point in the program.</p>\n\n<p>It's a relatively minor bug if a cell contains the wrong value. However, if the pointer is not where it is supposed to be, the program blows up in a spectacular way. Therefore, I have developed the notation to mark the current pointer location in parentheses at strategic points throughout the code.</p></li>\n</ol>\n\n<hr>\n\n<p>You raise a valid concern about repeating the comparison routine three times in your code. The way to handle that in brainfuck is to let the routine crawl along the cells, frame by frame, like a construction crew working on a section of highway. Just put the appropriate signposts to let it know where to stop crawling.</p>\n\n<hr>\n\n<pre><code>[-][\n # See MEMORY_LAYOUT below for explanation of SETUP.\n]\nSETUP\n +++++ +++ [ -\n &gt; +++++ ++ (Colon)\n &gt; ++++ (Space)\n &gt; + (Newline)\n\n &gt;&gt;&gt;&gt;&gt;&gt;\n ++++ [ -\n &gt; +++++ +++ (Loop_limit)\n &lt;\n ]\n\n &gt;&gt;&gt;&gt;&gt; &gt;\n &gt; +++++ ++ (C_limit)\n &gt; +++++ + (c_ascii)\n &gt;&gt;&gt;&gt;\n &gt; +++++ ++ (X_limit)\n &gt; +++++ + (x_ascii)\n &gt;&gt;&gt;&gt;\n &gt; +++++ ++ (I_limit)\n &gt; +++++ + (i_ascii)\n\n &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;\n ]\n &gt; ++ (Colon)\n &gt;&gt; ++ &gt; (all_done)\n &gt;&gt; + &gt;&gt;&gt;&gt; (Loop_limit)\n &gt;&gt; + &gt;&gt;&gt;&gt; ++ (C_limit)\n &gt;&gt; + &gt;&gt;&gt;&gt; ++ (X_limit)\n &gt;&gt; + &gt;&gt;&gt;&gt; ++ (I_limit)\n\n &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;\nEND_SETUP\n\nMEMORY_LAYOUT\n[-][\n # Using Roman abbreviations i, x, and c for units, tens, and hundreds,\n # respectively. Braces { } indicate a frame: a repeated consecutive group\n # of cells. Cells named with Uppercase are constants. At all times,\n # parentheses indicate the current cell; neighboring cells may be noted\n # as well in the code.\n\n # The main loop starts working from the last frame. It compares the last\n # two cells in the frame, and performs a carry if applicable. It then\n # proceeds to the preceding frame and repeats. The first \"frame\" is\n # special, as noted by the first cell being 0. The comparison routine\n # will not be performed on it. However, when ascii reaches Loop_limit,\n # all_done will be incremented to 1, since it is located at the offset\n # within the frame where carrying would increment a value.\n\n { (0) Colon=\":\"=58 Space=\" \"=32 Newline=\"\\n\"=10 not_all_done=0 all_done=0 }\n { Compare_frame_0=1 0 0 0 Loop_limit=256 ascii=\"\\0\"=0 }\n { Compare_frame_1=1 0 0 0 C_limit=\":\"=58 c_ascii=\"0\"=48 }\n { Compare_frame_2=1 0 0 0 X_limit=\":\" x_ascii=\"0\" }\n { Compare_frame_3=1 0 0 0 I_limit=\":\" i_ascii=\"0\" }\n]\nEND_MEMORY_LAYOUT\n\n&gt;&gt;&gt;&gt;\n+\nWHILE (not_all_done) [ -\n # Print one line of output\n &gt;&gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt;&gt; &gt;&gt;&gt; . (c_ascii)\n &gt;&gt;&gt;&gt;&gt; &gt; . (x_ascii)\n &gt;&gt;&gt;&gt;&gt; &gt; . (i_ascii)\n &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt; . (Colon)\n &gt; . (Space)\n &gt;&gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt; . (ascii)\n INCR (ascii)\n +\n &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt; . (Newline)\n\n &gt;&gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt;&gt; &gt;\n INCR (i_ascii)\n +\n\n &lt;&lt;&lt;&lt;&lt;\n REPEAT (Compare_frame_?) [\n &gt;&gt;&gt;&gt;&gt;\n IFEQ eq_flag=0 ascii_save=0 ?_limit (?_ascii)\n [ -\n &lt; - &lt; + &gt;&gt;\n ] ascii_save=ascii; diff=limit=limit MINUS ascii; ascii=0\n\n &lt;&lt;&lt; + (eq_flag=1)\n &gt;&gt; [\n &lt;&lt; - &gt;&gt; [ - &gt; + &lt; ]\n ] ifneq { eq_flag=0 ; ascii=diff }; (diff=0)\n # Restore diff\n &gt; [ - &lt; + &gt; ]\n # Restore limit and ascii\n &lt;&lt; (ascii_save) [ - &gt; + &gt; + &lt;&lt; ]\n &lt; (eq_flag) [\n THEN\n [-][\n # Perform carrying. If ascii == Loop_limit, then\n # \"carrying\" will set the all_done flag.\n ]\n &lt;&lt;&lt; +\n &gt;&gt;&gt;&gt;&gt; &gt; ----- -----\n &lt;&lt;&lt;\n ]\n END_IFEQ (eq_flag=0) ascii_save=0 ?_limit ?_ascii\n\n &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;\n (Compare_frame_next)\n ]\n\n &gt;&gt;&gt;&gt;&gt;\n BOOL_NEGATE_AND_CLEAR not_all_done=0 (all_done)\n &lt; +\n &gt; [ - &lt; - &gt; ]\n &lt; (not_all_done)\n END_BOOL_NEGATE_AND_CLEAR\n]\n</code></pre>\n\n<p>It is possible to reduce the frame size by one. However, you would probably have to reuse the same cell for <code>not_all_done</code> and <code>all_done</code>, which would hurt readability.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-15T19:54:10.687", "Id": "65837", "Score": "15", "body": "I am astonished that there exits experts in this language. Or that the concept of \"readability\" means something in it. It's amazing what the Human mind can do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T08:12:07.887", "Id": "65877", "Score": "0", "body": "@WayneConrad: Not really, I think. Once you realize that you only move a pointer through one big allocated block of memory (in C terms: `++pointer; --pointer; ++*pointer; --*pointer`) it is quite easy to understand. Or if you like the analogy more, imagine Brainfuck as a language for a tape." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T15:36:15.370", "Id": "65921", "Score": "3", "body": "@WayneConrad Probably the longest program written without a generator is found here - http://www.49-6-dev.net/ftotwen.htm" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-17T11:17:49.413", "Id": "198019", "Score": "0", "body": "You say that it was asked to optimize for readability, but what I can see it was asked to optimize to avoid repetition in the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-17T15:37:20.950", "Id": "198070", "Score": "0", "body": "@SimonForsberg Readability was mentioned in the deleted comments (though not by the OP)." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-14T23:34:27.893", "Id": "39252", "ParentId": "26648", "Score": "40" } }, { "body": "<h3>Analysis</h3>\n\n<p>I analyzed your code with my <a href=\"https://github.com/Zomis/Brainduck\" rel=\"nofollow noreferrer\">Brainduck</a> and I found a couple of improvements. First up, let's see what Brainduck says. I will not post the full output here, just the parts that I found the most interesting.</p>\n\n<p>First of all, at runtime your program performs approximately 1.47 MILLION commands. This is quite much.</p>\n\n<h3>While loop - 49 to 58</h3>\n\n<p>My analysis showed interesting patterns in the number of times that your while loops are being performed. I found that some of your while loops have a clear sequence of:</p>\n\n<pre><code>[49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, (repeat 49 - 58 a couple of times...), 49, 50, 51, 52, 53, 54]\n</code></pre>\n\n<p>This means that the first time it is started it is performed 49 times, then 50, then 51, and so on up until 58, then it goes down to 49 times again, then 50, then 51, etc... this while-loop is your comparison of <code>if (a == b)</code>.</p>\n\n<p>What you are doing is comparing <code>if (a == b)</code>, this is however a very long operation in Brainfuck, as you need to move the memory back and forth, it has a runtime complexity of \\$O(n)\\$ where \\$n\\$ is the value of <code>a</code>.</p>\n\n<h3>Modulo 10</h3>\n\n<p>There is also this interesting while loop:</p>\n\n<pre><code>[1, 1, 1, 1, 1, 1, 1, 1, 1, 0, (1 x 9 times), 0, (1 x 9 times), 0, (1 x 9 times), 0, (1 x 6 times)]\n</code></pre>\n\n<p>This is you deciding whether or not to increase the next number in the tape, for example when the last digit changes from <code>9</code> to <code>0</code> it is time to increase the second to last digit from <code>x</code> to <code>x + 1</code>.</p>\n\n<p>It is much more effective in Brainfuck to <strong>count down to zero</strong> rather than <em>count up to \\$x\\$</em>.</p>\n\n<p>Instead of counting from 49 to 58 and comparing <code>x</code> to 58 all the time, <strong>initialize a memory cell nearby to 10 and count down to zero</strong>, when it has reached zero, it is time to reset it to 10 and increase the next number (going from <code>09</code> to <code>10</code>).</p>\n\n<p>The same principle can be applied to your ending condition, you initialize the value 256, and then you compare with 256 all the time. Instead initialize 256 and decrease it by 1 until it reaches zero, then it is time to end your loop.</p>\n\n<h3>Other small changes</h3>\n\n<p>Your code contains some sequences of <code>&gt;&gt;&lt;&lt;</code> that leads to no change, which leads to it being possible to simplify. I would recommend that you simplify these and instead improve the comments about where the current tape position is located.</p>\n\n<h3>Resulting code</h3>\n\n<pre><code>max == 255\nLF == 10\nspace == 32\n'0' == 48\n'9' == 57\n':' == 58\nMemory: counter\n ':' space LF\n char max&amp;1 cmp1 0 0\n num1 '9'&amp;1 cmp2 0 0\n num2 '9'&amp;1 cmp3 0 0\n num3 '9'&amp;1 cmp4 0 0\n\n+++++ +++\n[\n &gt; +++++ ++\n &gt; ++++\n &gt; +\n\n &gt;\n ++++\n [\n &gt; +++++ +++\n &lt; -\n ]\n\n &gt;&gt;&gt;&gt;\n &gt; +++++ +\n &gt; +\n &gt;&gt;&gt;\n &gt; +++++ +\n &gt; +\n &gt;&gt;&gt;\n &gt; +++++ +\n &gt; +\n\n &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; -\n]\n&gt; ++\n&gt;&gt; ++\n&gt;&gt;\n&gt;&gt;&gt;&gt;&gt; ++\n&gt;&gt;&gt;&gt;&gt; ++\n&gt;&gt;&gt;&gt;&gt; ++\n\n&lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt;\n\nMemory: 0\n 58 32 10\n 0 (Current Ascii) 256 (Countdown) 0 0 0\n 48 10 0 0 0\n 48 10 0 0 0\n 48 10 0 0 0\npositioned at 256 countdown\n[\n -&gt;\n\n &gt;&gt;&gt; .\n &gt;&gt;&gt;&gt;&gt; .\n &gt;&gt;&gt;&gt;&gt; .\n &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;\n .\n &gt; .\n &gt;&gt; .+\n &lt; .\n\n Number increasing logic\n &gt;&gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt;&gt; &gt;\n +\n &gt;-\n &gt;+ set equal flag\n &lt; if num1 != 0\n [\n &gt;- clear equal flag\n ]\n &gt; if num1 == 0\n [\n Reset this counter to 10 and decrease digit to 0 again\n &lt;+++++ +++++\n &lt;----- -----\n Increase the next number by one\n &lt;&lt;&lt;&lt;&lt; +\n &gt; -\n Reset the equal flag\n &gt;&gt;&gt;&gt; &gt;&gt; - &gt;\n ]\n &lt;&lt;[&lt;] positioned at the digit\n\n &lt;&lt;&lt;&lt; goto next\n\n &gt;&gt;+ set equal flag\n &lt; if num1 != 0\n [\n &gt;- clear equal flag\n ]\n &gt; if num1 == 0\n [\n Reset this counter to 10 and decrease digit to 0 again\n &lt;+++++ +++++\n &lt;----- -----\n Increase the next number by one\n &lt;&lt;&lt;&lt;&lt; +\n &gt; -\n Reset the equal flag\n &gt;&gt;&gt;&gt; &gt;&gt; - &gt;\n ]\n &lt;&lt;[&lt;] positioned at the digit\n\n &lt;&lt;&lt;&lt;&lt; &lt;&lt;&lt;\n]\n</code></pre>\n\n<p>The only changes here are that I never do <code>if (a == b)</code> comparison and instead always decrease some value down to 0 instead. This applies to both your <code>if (x == 58)</code> checks and your <code>if (x == 256)</code> check.</p>\n\n<h3>For 8-bit Brainfuck interpreters</h3>\n\n<p><a href=\"https://codereview.stackexchange.com/a/39252/31562\">200_success mentioned</a> that your code supported 8-bit Brainfuck interpreters as well, thanks to your <code>if (x == 256)</code> check. As I removed that check here, the above code doesn't work for 8-bit wrapping BF interpreters. However, that can be solved by instead of having one 256 value, you have 2 of value 128.</p>\n\n<p>Replace in the memory initialization:</p>\n\n<pre><code>++++\n[\n &gt; +++++ +++\n &lt; -\n]\n</code></pre>\n\n<p>with</p>\n\n<pre><code>++++\n[\n &gt; ++++\n &gt; ++++\n &lt;&lt; -\n]\n</code></pre>\n\n<p>This will initialize 2 cells with value 128 instead of one cell with value 256. Luckily, the cell after the 256 value was unused by my code, so this is an easy change.</p>\n\n<p>Loop check:</p>\n\n<p>Replace the start of the 256 loop:</p>\n\n<pre><code>[\n -&gt;\n</code></pre>\n\n<p>with</p>\n\n<pre><code>[[\n -&gt;\n</code></pre>\n\n<p>and replace the <code>]</code> on the last line with <code>]&gt;[-&lt;+&gt;]&lt;]</code>.</p>\n\n<p>This will, once the innermost loop has been finished, check for a value on the next cell and if there is a non-zero value there it will move it to the cell before and then it will use that value for the loop and continue decreasing until it hits zero. This will make your loop be performed <code>x + y</code> times, where in this case both x and y is 128, making it a total of 256. Of course these values could be adjusted to be <code>255 + 1</code> so that the moving of <code>y</code> to the position of <code>x</code> is performed faster.</p>\n\n<h3>Resulting performance</h3>\n\n<p>Analysis says that this code, with the support for 8-bit interpreters applied, only performs 30 934 operations at runtime, which is about 2% of your 1.47 million. So <strong>this program will be 50 times faster</strong> than your original.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-17T10:52:17.630", "Id": "107859", "ParentId": "26648", "Score": "15" } }, { "body": "<p>This seems pretty complicated. The first thing i noticed in your code is many \"&lt;&lt;&lt;&lt;>>\" commands which could be shortened to \"&lt;&lt;\".</p>\n\n<p>I just thought about this and made an ASCII viewer by myself. It is only runnable on wrapping 8-bit interpreters but it is much easier to understand.</p>\n\n<pre><code>Tape: [\":\"(58)] [\" \"(32)] [lf(10)] [count(0)] [temp] [0] [numPrint]\n\n++++++++[-&gt;+++++++&gt;++++&gt;+&lt;&lt;&lt;] set values 0 56 32 8\n&gt;++&gt;&gt;++ set values 0 58 32 10\n&gt;+[ do 255 times (starting at 1)\n [-&gt;+&gt;&gt;+&lt;&lt;&lt;] copy count to temp and numPrint\n &gt;[-&lt;+&gt;] move it back to count\n\n &gt;&gt;&gt;+[[-]&lt;[-&gt;+&lt;[-&gt;+&lt;[-&gt;+&lt;[-&gt;+&lt;[-&gt;+&lt;[-&gt;+&lt;[-&gt;+&lt;[-&gt;+&lt;[-&gt;+&lt;[-&gt;[-]&gt;&gt;+&gt;+&lt;&lt;&lt;]]]]]]]]]&lt;]&gt;&gt;[&gt;]++++++[-&lt;++++++++&gt;]&gt;&gt;]&lt;&lt;&lt;[.[-]&lt;&lt;&lt;]\n use number printing routine from Brainfuck Wiki\n\n &lt;&lt;&lt;&lt;.&gt;. print \": \"\n &gt;&gt;. print symbol\n &lt;. print lf\n &gt;+ increment symbol\n]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-04T09:26:01.647", "Id": "381327", "Score": "0", "body": "If you replace the number printing routine by this, it will also print leading zeroes: >>>>>>>>>>>>-<<<<<<<<<+[[-]<[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->[-]>>+>+<<<]]]]]]]]]<]>>[>]++++++[-<++++++++>]>>+]<<<[.[-]<<<]" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-07-03T09:58:05.850", "Id": "197709", "ParentId": "26648", "Score": "2" } } ]
{ "AcceptedAnswerId": "39252", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T23:27:25.057", "Id": "26648", "Score": "47", "Tags": [ "brainfuck" ], "Title": "ASCII table in Brainfuck" }
26648
<p>I'm making a comparing section, which I've just started typing, trying to get something working. It's working now, but as you can see its pretty messy. I feel this could be done in one or two less queries, or I should break it apart into smaller methods.</p> <pre><code>foreach (XMLObject source in Sources) { var matchedElement = destList.FirstOrDefault(s.ElementName == source.ElementName); // checks to see if it exists in one list but not the other if (matchedElement == null) // element is in one list and not the other { var alter = lstAlteration.FirstOrDefault( a =&gt; a.ElementName == source.ElementName &amp;&amp; a.ChangeInfo.ChangeFrom == source.ElementName); // check to see if the the element is a Removal (Changed From would not be blank) if (alter == null) // Removal has not been triggered { alter = new Alteration { ElementName = source.ElementName, ChangeInfo = new ChangeDetail( {ChangeTo = source.ElementName} }; } else { alter.ChangeInfo.ChangeTo = source.ElementName; } lstAlteration.Add(alter); } } </code></pre>
[]
[ { "body": "<p>I'd like to suggest the following:</p>\n\n<pre><code> foreach (XMLObject source in Sources)\n {\n if (destList.Exists(s.ElementName == source.ElementName))\n continue;\n // perform a lightweight check\n if (lstAlteration.Exists(a =&gt; a.ElementName == source.ElementName \n &amp;&amp; a.ChangeInfo.ChangeFrom == source.ElementName)) \n {\n lstAlteration.Where(a =&gt; a.ElementName == source.ElementName\n &amp;&amp; a.ChangeInfo.ChangeFrom == source.ElementName).First()\n .ChangeInfo.ChangeTo = source.ElementName;\n }\n else\n {\n lstAlteration.Add(new Alteration\n {\n ElementName = source.ElementName,\n ChangeInfo = new ChangeDetail( {ChangeTo = source.ElementName}\n });\n }\n }\n</code></pre>\n\n<ol>\n<li>Reduce nesting</li>\n<li>Perform lightweight checks instead of instance materializing.</li>\n<li>Compact code, ommiting extra variable</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T04:56:23.207", "Id": "26651", "ParentId": "26650", "Score": "2" } }, { "body": "<pre><code>foreach (var source in Sources.Where(x =&gt; !destList.Exists(s =&gt; s.ElementName == x.ElementName))\n{\n var alter = lstAlteration.FirstOrDefault(a =&gt; a.ElementName == source.ElementName\n &amp;&amp; a.ChangeInfo.ChangeFrom == source.ElementName);\n\n if (alter == null) {\n alter = new Alteration\n {\n ElementName = source.ElementName,\n ChangeInfo = new ChangeDetail()\n };\n\n lstAlteration.Add(alter);\n }\n\n alter.ChangeInfo.ChangeTo = source.ElementName;\n}\n</code></pre>\n\n<ul>\n<li>Sorter</li>\n<li>Only one .ChangeInfo.ChangeTo = source.ElementName; execution</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T07:36:15.463", "Id": "41311", "Score": "1", "body": "Shouldn't where clause be \"**not** exists in destList\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-04T15:09:38.357", "Id": "41822", "Score": "0", "body": "I like that the \"not exists\" is filtered at the get-go, fundamentally simplifying the proceeding logic; allowing the loop to be focused on what its supposed to be doing." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T05:44:48.880", "Id": "26653", "ParentId": "26650", "Score": "3" } }, { "body": "<p>Just a small note as I think <a href=\"https://codereview.stackexchange.com/users/14749/peter-kiss\">Peters</a> answer is pretty clean and tidy.</p>\n\n<p>You may want to consider a consistant naming convention. For the same list type you use a prefix of <strong>lst</strong> (lstAlterations) and a suffix of <strong>List</strong> (destList). I'm not a huge fan of this convention (others might beg to differ) so instead I would probably look at naming the lists something like just <em>alterations</em> and <em>destinations</em>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T11:07:08.900", "Id": "41322", "Score": "0", "body": "you are absolutely right!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T08:07:44.153", "Id": "26657", "ParentId": "26650", "Score": "3" } } ]
{ "AcceptedAnswerId": "26653", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T02:52:19.530", "Id": "26650", "Score": "1", "Tags": [ "c#" ], "Title": "Comparison application" }
26650
<p>I have never been entirely comfortable using <code>malloc()</code> and <code>free()</code> directly. For one thing, 99% of the time that I would like to call <code>malloc</code>, I would prefer it to take two arguments like <code>calloc</code> and do the multiplication itself, instead of taking one argument. Beyond that, I've often wished that <code>free</code> could magically zero out the pointer it is passed (which, of course, is impossible for it to do, since its pointer argument is pass-by-value).</p> <p>So I've put together a very small library of wrapper functions to address these and minor other issues I have with <code>malloc</code> / <code>calloc</code> / <code>realloc</code> / <code>free</code> / <code>memset</code> / <code>memcpy</code>. The functions in this little library are:</p> <ul> <li><strong><code>mem_alloc</code></strong> — Allocate a block of memory, given an item count and item size. This is simply a <code>malloc</code> wrapper.</li> <li><strong><code>mem_alloc_clear</code></strong> — Allocate and clear a block of memory, given an item count and item size. This is simply a <code>calloc</code> wrapper.</li> <li><strong><code>mem_clear</code></strong> — Clear a block of memory, given a pointer, item count, and item size. This is a <code>memset</code> / <code>bzero</code> wrapper.</li> <li><strong><code>mem_copy</code></strong> — Copy a block of memory, given a source and destination pointer, item count, and item size. This is a <code>memcpy</code> wrapper.</li> <li><strong><code>mem_realloc</code></strong> — Reallocate a block of memory, given a pointer, item count, and item size. This is simply a <code>realloc</code> wrapper.</li> <li><strong><code>mem_alloc_copy</code></strong> — Allocate a block of memory and copy memory into it, given a source pointer, item count, and item size.</li> <li><strong><code>mem_alloc_clone</code></strong> — Allocate a block of memory and copy memory into it, given only a source pointer. The size of the block is automagically determined by calling <code>mem_size</code>.</li> <li><strong><code>mem_dealloc</code></strong> — Deallocate a block of memory, given a pointer, and set that pointer to null. This is a <code>free</code> wrapper, implemented as a hidden function and a visible macro.</li> <li><strong><code>mem_size</code></strong> — Return the size of a previously allocated block of memory. This is simply a <code>malloc_size</code> wrapper.</li> </ul> <p>Note that none of these take a <code>size_t</code> of bytes directly. Instead, they compute the size by multiplying a count of items times the size of an item (like <code>calloc</code> does). This is much more convenient for me and saves me a whole bunch of parenthesization in client code.</p> <p>And now here is the source code...</p> <h2>Header file</h2> <pre><code>extern size_t mem_size (void *memory); extern void *mem_alloc (size_t item_count, size_t item_size); extern void *mem_alloc_clear (size_t item_count, size_t item_size); extern void mem_clear (void *memory, size_t item_count, size_t item_size); extern void *mem_realloc (void *memory, size_t item_count, size_t item_size); extern void *mem_alloc_copy (void *memory, size_t item_count, size_t item_size); extern void *mem_alloc_clone (void *memory); extern void mem_copy (void *memory_dest, void *memory_src, size_t item_count, size_t item_size); extern void mem_dealloc_ (void **memory); // (Do not call directly) #define mem_dealloc(p) mem_dealloc_((void **)(void *)(p)) </code></pre> <p>Notes:</p> <ol> <li><p>The actual deallocation routine, named <code>mem_dealloc_</code>, should not be called directly, as it is wrapped by a macro named <code>mem_dealloc</code>, which allows the caller to write <code>mem_dealloc(&amp;pointer)</code> without the compiler warning about incompatible pointer types and without having to explicitly write <code>mem_dealloc((void **)&amp;pointer)</code>.</p></li> <li><p>The reason for writing <code>(void **)(void *)(p)</code> instead of <code>(void **)(p)</code> in the <code>mem_dealloc</code> macro is because the latter causes compile-time errors with ARC (Automatic Reference Counting) in cases of memory pointing to Objective-C objects, whereas the former has no such issue.</p></li> </ol> <h1>Implementation file</h1> <h2>Return allocation size</h2> <p><strong><code>mem_size</code></strong> returns the size in bytes of a previously-allocated memory block. It relies on the built-in function <code>malloc_size</code>.</p> <pre><code>size_t mem_size(void *memory) { if (memory != NULL) return malloc_size(memory); else return 0; } </code></pre> <h2>Allocate memory</h2> <p><strong><code>mem_alloc</code></strong> allocates a new block of memory, given an item count and item size. Upon failure, like <code>malloc</code>, it returns <code>NULL</code>.</p> <pre><code>void *mem_alloc(size_t item_count, size_t item_size) { void *memory = malloc(item_count * item_size); return memory; } </code></pre> <h2>Allocate and clear memory</h2> <p><strong><code>mem_alloc_clear</code></strong> allocates and clears a new block of memory (technically, it allocates a block of cleared memory), given an item count and item size. Upon failure, like <code>calloc</code>, it returns <code>NULL</code>.</p> <pre><code>void *mem_alloc_clear(size_t item_count, size_t item_size) { void *memory = calloc(item_count, item_size); return memory; } </code></pre> <h2>Clear memory</h2> <p><strong><code>mem_clear</code></strong> clears all bytes in a block of memory to zero, given a block pointer, an item count, and item size.</p> <pre><code>void mem_clear(void *memory, size_t item_count, size_t item_size) { assert(memory != NULL); memset(memory, 0, item_count * item_size); } </code></pre> <h2>Copy memory</h2> <p><strong><code>mem_copy</code></strong> copies a block of memory, given a source and destination pointer (in traditional C reverse order), an item count, and item size.</p> <pre><code>void mem_copy(void *memory_dest, void *memory_src, size_t item_count, size_t item_size) { assert(memory_dest != NULL); assert(memory_src != NULL); memcpy(memory_dest, memory_src, item_count * item_size); } </code></pre> <h2>Reallocate memory</h2> <p><strong><code>mem_realloc</code></strong> reallocates a block of memory, given a pointer to the existing block and a new item count and item size. Upon failure, like <code>realloc</code>, it returns <code>NULL</code>.</p> <pre><code>void *mem_realloc(void *memory, size_t item_count, size_t item_size) { memory = realloc(memory, item_count * item_size); return memory; } </code></pre> <h2>Allocate and copy memory</h2> <p><strong><code>mem_alloc_copy</code></strong> allocates a new block of memory and copies the contents of an existing area of memory, given a pointer to the existing area, an item count, and item size. Upon failure, it returns <code>NULL</code>.</p> <pre><code>void *mem_alloc_copy(void *memory, size_t item_count, size_t item_size) { assert(memory != NULL); void *new_memory = mem_alloc(item_count, item_size); if (new_memory != NULL) mem_copy(new_memory, memory, item_count, item_size); return new_memory; } </code></pre> <h2>Allocate cloned memory</h2> <p><strong><code>mem_alloc_clone</code></strong> allocates a new block of memory, cloning an existing block of memory into it. To determine the size of the block, it relies upon the <code>mem_size</code> function. Upon failure, it returns <code>NULL</code>.</p> <pre><code>void *mem_alloc_clone(void *memory) { assert(memory != NULL); return mem_alloc_copy(memory, mem_size(memory), 1); } </code></pre> <h2>Deallocate memory</h2> <p><strong><code>mem_dealloc_</code></strong> deallocates a block of memory, given a pointer to it. This routine should not be called directly, but only via the <code>mem_dealloc</code> macro, which is defined in the header file.</p> <p><strong><code>mem_dealloc</code></strong> deallocates a block of memory, given a <em>pointer to a pointer</em> to it, and then sets the pointer to <code>NULL</code>.</p> <p>The calling convention here is to write <code>mem_dealloc(&amp;pointer)</code>.</p> <pre><code>void mem_dealloc_(void **memory) { assert(memory != NULL); if (*memory) { free(*memory); *memory = NULL; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T01:22:26.900", "Id": "41499", "Score": "1", "body": "Is there any particular reason you've chosen not to also wrap `memmove()`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T01:25:26.687", "Id": "41500", "Score": "0", "body": "Huh... no, actually, it didn't occur to me to add a wrapper for `memmove()`. I've never really needed it in 25 years of C programming, except maybe once long ago when shifting some strings around the hard way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-20T20:01:12.357", "Id": "43036", "Score": "1", "body": "You might want to mark your pointers as `restrict` in mem_copy." } ]
[ { "body": "<p>Your code looks good, but your library doesn't seem to do much. The thing that bothers you (from my understanding), is that you can't call <code>malloc</code> like <code>calloc</code> and that the pointer given to <code>free</code> doesn't get set to <code>NULL</code>.</p>\n\n<p>IMHO, that doesn't need a whole library which basically only wraps functions. The following two macros would achive the same, but without the overhead:</p>\n\n<pre><code>#define mymalloc(item_count, item_size) malloc((item_count) * (item_size))\n#define myfree(ptr) do { \\\n free(ptr); \\\n (ptr) = NULL; \\\n} while(0)\n</code></pre>\n\n<p>Why the whole library if the two macros above could do the same?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T19:15:19.857", "Id": "41352", "Score": "0", "body": "Thanks. Originally, I had a bunch of code involving pointer arithmetic that implemented the `malloc_size` functionality manually using a metadata struct tucked away at the head of every allocation block, so the wrappers were actually necessary then, as I need to track the sizes of allocated blocks in a cache class at a higher level and the best place to track the size is in the block itself. But then I discovered `malloc_size` and took all that out because it was unneeded." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T19:20:02.270", "Id": "41353", "Score": "0", "body": "Regarding library vs. macros — as it stands now, 7 of these 9 routines are basically direct wrappers for standard library functions. The other 2 wrap a combination of standard library functions. I like having them in a unified namespace `mem_xxxxx`. Not listed here are also some (more complex) wrappers for doing memory-mapping of files conveniently. These functions here, as you point out, could all be macros instead of functions, yeah...although I'd probably go with inline functions rather than macro definitions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T19:20:48.650", "Id": "41354", "Score": "0", "body": "p.s. I like your `do { xxx; yyy; } while (0)` trick. Nice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T15:45:36.773", "Id": "41402", "Score": "2", "body": "Note that the semi-colon after while(0) should be deleted" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T09:01:05.243", "Id": "26660", "ParentId": "26656", "Score": "4" } }, { "body": "<p>I agree with <a href=\"https://codereview.stackexchange.com/a/26660/23307\">this answer</a> that what you have written is not necessary. All the\nsame, I have a few comments on the code, the main one being that\n<code>malloc_size()</code> is a non-standard function. Your Mac has it and perhaps the\nBSDs too, but Linux and Windows don't. This limits the usefulness of the\nlibrary still further.</p>\n\n<p>Some minor coding issues are the lack of braces, eg on conditionals,\nand unnecessary variables, as in:</p>\n\n<pre><code> void *memory = malloc(item_count * item_size);\n return memory;\n\nwhich could be just\n\n return malloc(item_count * item_size);\n</code></pre>\n\n<p>Also you don't use <code>const</code> where you could (for unchanged pointer parameters,\ne.g. <code>memory_src</code> in <code>mem_copy</code>).</p>\n\n<p>In <code>mem_alloc_clone</code> the call to <code>mem_alloc_copy</code> has the <code>memory</code> parameter in\nthe wrong place.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T19:27:10.133", "Id": "41355", "Score": "0", "body": "I had the intermediate variable names in there because I was stepping through with the interactive debugger once to track down a problem that had occurred when I'd accidentally passed a `sizeof(uint64_t *)` instead of `sizeof(uint64_t)`. Also, at one time I had considered throwing an exception on null pointers, so I would have needed the intermediate variable for that. Yeah, they could be pruned out now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T19:30:52.527", "Id": "41357", "Score": "0", "body": "p.s. Thanks for noticing the parameter misplacement. That was actually something I just introduced last night while posting this! (d'Oh) While describing the functions, I'd noticed that my parameter ordering wasn't consistent across all the functions, so I cleaned it up here after pasting in the code. Then I went back and changed the real code. But I goofed here when I made the change in parallel." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T17:52:18.147", "Id": "26676", "ParentId": "26656", "Score": "2" } }, { "body": "<p>I support the idea of this abstraction although I would make all of these methods <code>static inline</code> and drop them in a header file. With the state of optimizers today I think the overhead would be minimal.</p>\n\n<p>I like the abstraction mostly because I deal with code that runs on all sorts of different embedded platforms. Some of which do not have the standard-C heap functions. It makes porting a breeze.</p>\n\n<p>For the API itself I would merge the functionality of mem_alloc_copy() into mem_copy(), thusly:</p>\n\n<pre><code>void * mem_copy(void *memory_dest, void *memory_src, size_t item_count, size_t item_size)\n{\n assert(memory_src != NULL);\n void * const result = (memory_dest != NULL) ? memory_dest : mem_alloc(item_count, item_size);\n if (result != NULL)\n mem_copy(result, memory_src, item_count, item_size);\n return result;\n}\n</code></pre>\n\n<p>And mem_alloc_clone() I would rename to mem_dup() [like strdup()].</p>\n\n<p>Also, your mem_copy() code snippet appears to calling itself using tail recursion, um, like forever. Care needs to be taken with mem_alloc_copy() and mem_copy() as they can cause memory access violations if item_count and item_size together exceed the original allocation size of the source pointer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T02:51:28.963", "Id": "41421", "Score": "0", "body": "Fixed the `mem_copy` typo where it should have said `memcpy` — thanks. Just added that one yesterday and hadn't actually tested it yet (d'Oh!)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T02:54:14.257", "Id": "41422", "Score": "1", "body": "The reason I called it `mem_alloc_clone` is because its primary intended use is for inside a `clone` instance method of a class — e.g., when cloning the backing store for an object." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T12:55:53.147", "Id": "26700", "ParentId": "26656", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T07:58:06.577", "Id": "26656", "Score": "5", "Tags": [ "c", "memory-management" ], "Title": "Are these memory-allocation wrapper functions kosher with all C compilers?" }
26656
<p>I'm trying to join two tables based on one to one mapping without any common column. </p> <p>For example, I have 3 records in the first table and 2 records in the second table.</p> <p>The mapping should be as follows:</p> <p><img src="https://i.stack.imgur.com/3Jrx9.png" alt="enter image description here"></p> <p>As there is no third record in the second table, nulls should be displayed.</p> <p>In order to implement this, I've tried the following code:</p> <pre><code>declare @FirstTable table (StudentId int, SubjectId int) declare @SecondTable table (MarksId int, RankId int, LastRank int) insert into @FirstTable values (1, 1) insert into @FirstTable values (1, 2) insert into @FirstTable values (1, 3) insert into @SecondTable values (1, 4, 10) insert into @SecondTable values (1, 5, 11) ;with XmlTable (RowNumber, StudentId, SubjectId) as ( select row_number() over(order by StudentId) as RowNumber, * from @FirstTable ) ,TechnicalIdsTable (RowNumber, MarksId, RankId, LastRank) as ( select row_number() over(order by MarksId) as RowNumber, * from @SecondTable ) select x.StudentId, x.SubjectId, t.MarksId, t.RankId, t.LastRank from XmlTable x left join TechnicalIdsTable t on x.RowNumber = t.RowNumber </code></pre> <p>Based on the above code, I am able to achieve the output. Let me know whether this is a proper approach or not.</p> <p>Here's a new example:</p> <p><img src="https://i.stack.imgur.com/e6fY8.png" alt="enter image description here"></p> <p>In this case, there are three students enrolled for sports, you can check the order in which they enrolled. But there are only two vacant sports available and the order in which they have to be selected.</p> <p>Now using my query, which will be </p> <pre><code>declare @Students table (StudentId int, StudentName varchar(50), EnrolledOn datetime) declare @Sports table (SportId int, SportName varchar(50)) insert into @Students values (1, 'John', '2013-05-25 10:00:00') insert into @Students values (2, 'Jerry', '2013-05-25 14:30:00') insert into @Students values (3, 'Jane', '2013-05-26 10:30:00') insert into @Sports values (1, 'Golf') insert into @Sports values (2, 'Foot ball') ;with Students (RowNumber, StudentId, StudentName, EnrolledOn) as ( select row_number() over(order by EnrolledOn) as RowNumber, * from @Students ) ,Sports (RowNumber, SportId, SportName) as ( select row_number() over(order by SportId) as RowNumber, * from @Sports ) select s1.StudentId, s1.StudentName, s1.EnrolledOn, s2.SportId, s2.SportName from Students s1 left join Sports s2 on s1.RowNumber = s2.RowNumber </code></pre> <p>I'm getting the expected output. </p> <p>My goal is to assign the 1<sup>st</sup> sport to the student who enrolled in the first and second sport to the second student, and for the third student there will be no sport.</p> <p>Will this be proper now?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T13:02:13.190", "Id": "41336", "Score": "0", "body": "Even if you can get a query to line up the rows in some manner (using a calculated row ID), it may not be stable or survive backup/restore. Why can't you add the PK from one of the tables to the other?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T13:42:08.093", "Id": "41342", "Score": "0", "body": "actually one is a temporary table (with data from UI) and second one is a table variable... I have to combine these two tables on one-to-one mapping and insert these records into a table. so can't have a primary / foreign key" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T15:08:42.813", "Id": "41346", "Score": "0", "body": "In your example above, how can Jane enroll in a sport? Are the student records inserted in the order in which they enroll in the sport from the sports table? Can't you add `StudentId` to the sports table without making it a proper FK." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T06:08:34.743", "Id": "41431", "Score": "0", "body": "In the example, Jane cannot enroll into any sport as there are no vacant sports. Yes the students records are inserted in the order in which they are enrolled. As I mentioned previously, these are not database tables." } ]
[ { "body": "<p>Even if your solution is (almost) correct, the actual problem is in a wrong formulation of the problem.</p>\n\n<p>The main issue in your question is the assumption of a certain order of records within a table. In reality SQL Server <strong>cannot</strong> guarantee original order of records when you do a <code>select</code> statement without <code>order by</code> clause, even <a href=\"http://sqlsoundings.blogspot.com/2007/09/clustered-index-does-not-guarantee.html\" rel=\"nofollow\">if you have a clustered index defined.</a></p>\n\n<p>In order to properly map 2 tables you <strong>must</strong> have a criteria for matching records. You provided a solution that won't generate consistent results. Imagine that you need to add another student/subject (<code>StudentId = 2, SubjectId = 1</code>) and a mark for that. If you add one record to <code>Student/Subject</code> table and one record to <code>Marks</code> table your data will be screwed up since <code>Marks</code> record will be matched against 3rd record (<code>StudentId = 1, SubjectId = 3</code>).</p>\n\n<p>In order to fix the issue you must add a field or fields that allow unique reference of records, that is you must add both StudentId and SubjectId to <code>Marks</code> table. Alternatively you can create a <a href=\"http://en.wikipedia.org/wiki/Surrogate_key\" rel=\"nofollow\">surrogate key</a> in the <code>Student/Subject</code> table and use it as a reference in <code>Marks</code> table.</p>\n\n<p><strong>UPDATE</strong>.\nThe main difference between original question and example in <strong>Edit</strong> section is that records can be ordered by unique key (primary key) in latter case, while in original question <code>order by StudentId</code> didn't guarantee specific order and produced inconsistent results.</p>\n\n<p>Your updated example is using mapping properly, according to (updated) requirements, and will produce consistent results as long as <code>SportId</code> and <code>StudentId</code> are unique in corresponding tables</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T11:44:01.687", "Id": "41328", "Score": "0", "body": "That's a good explanation.. I did not know about this. I think I confused you with the marksid and rankid columns. Please check my edit for more info." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T12:39:35.203", "Id": "41335", "Score": "0", "body": "I case if I want to get uniqueness for my first example, for first table, can I order by \"StudentId, SubjectId\" and for second table, by \"MarksId, RankId\". I guess this should solve the problem for first example. am I correct ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T13:46:01.703", "Id": "41343", "Score": "0", "body": "@Harsha Well, if that's what you want... What happens if `MarksId=1` (whatever it means) gets a new rank with `RankId=1`? In your example it would shift all the other records and will be assigned to the first record in student/subjects table" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T06:13:12.093", "Id": "41432", "Score": "0", "body": "yes.. in that case, the query fails. Its better I modify my tables to add unique columns. Thank you for your answer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T10:26:02.103", "Id": "26662", "ParentId": "26661", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T10:05:42.287", "Id": "26661", "Score": "2", "Tags": [ "sql" ], "Title": "One to one record mapping without any common column between two tables in SQL server" }
26661
<p>This is a "answer" to my own question over at stackoverflow, head over there to see what I am trying to accomplish. <a href="https://stackoverflow.com/questions/16744109/deleting-the-proper-ccsprite-from-an-array-in-a-schedule">https://stackoverflow.com/questions/16744109/deleting-the-proper-ccsprite-from-an-array-in-a-schedule</a> . </p> <p>I ended up doing a rather interesting approach, and I think this might work. </p> <pre><code> -(void)explosionFromPoint:(CGPoint)explosionPoint withSprite:(CCSprite*)sprite; { //int explosionLenght += 1; if (explosionLenght &gt;= 7) //Just for testing purposes, don't have a way to increase it naturally. { explosionLenght = 1; } BOOL topB = YES; BOOL leftB = YES; BOOL bottomB = YES; BOOL rightB = YES; int bombX = (explosionPoint.x + 1); int bombY = (explosionPoint.y + 1); int bombNegX = (explosionPoint.x - 1); int bombNegY = (explosionPoint.y - 1); CGPoint top = ccp(explosionPoint.x, bombY); CGPoint left = ccp(bombNegX, explosionPoint.y); CGPoint bottom = ccp(explosionPoint.x, bombNegY); CGPoint right = ccp(bombX, explosionPoint.y); if (![self isLocationBombable:top]) {topB = NO;} if (![self isLocationBombable:left]) {leftB = NO;} if (![self isLocationBombable:bottom]) {bottomB = NO;} if (![self isLocationBombable:right]) {rightB = NO;} for (int i = 0; i &lt;= explosionLenght; i++) { int bombX = (explosionPoint.x + i); int bombY = (explosionPoint.y + i); int bombNegX = (explosionPoint.x - i); int bombNegY = (explosionPoint.y - i); CGPoint top = ccp(explosionPoint.x, bombY); CGPoint left = ccp(bombNegX, explosionPoint.y); CGPoint bottom = ccp(explosionPoint.x, bombNegY); CGPoint right = ccp(bombX, explosionPoint.y); CCSprite *circleTop = [[CCSprite alloc]initWithFile:@"Circle.png"]; CCSprite *circleLeft = [[CCSprite alloc]initWithFile:@"Circle.png"]; CCSprite *circleBottom = [[CCSprite alloc]initWithFile:@"Circle.png"]; CCSprite *circleRight = [[CCSprite alloc]initWithFile:@"Circle.png"]; if ([self isLocationBombable:top] &amp;&amp; topB == YES) { circleTop.position = [self positionForTileCoord:top]; [self addChild:circleTop]; id fadeTop = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circleTop.position] two:[CCScaleTo actionWithDuration:1 scale:0]]; [circleTop runAction:fadeTop]; } if ([self isLocationBombable:left] &amp;&amp; leftB == YES) { circleLeft.position = [self positionForTileCoord:left]; [self addChild:circleLeft]; id fadeLeft = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circleLeft.position] two:[CCScaleTo actionWithDuration:1 scale:0]]; [circleLeft runAction:fadeLeft]; } if ([self isLocationBombable:bottom] &amp;&amp; bottomB == YES) { circleBottom.position = [self positionForTileCoord:bottom]; [self addChild:circleBottom]; id fadeBottom = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circleBottom.position] two:[CCScaleTo actionWithDuration:1 scale:0]]; [circleBottom runAction:fadeBottom]; } if ([self isLocationBombable:right] &amp;&amp; rightB == YES) { circleRight.position = [self positionForTileCoord:right]; [self addChild:circleRight]; id fadeRight = [CCSequence actionOne:[CCMoveTo actionWithDuration:1 position:circleRight.position] two:[CCScaleTo actionWithDuration:1 scale:0]]; [circleRight runAction:fadeRight]; } } [currentBombs addObject:sprite]; NSLog(@"Explosion done, call checkdamage"); [self schedule:@selector(checkDamageForBomb)]; [self performSelector:@selector(removeSprite:) withObject:sprite afterDelay:3]; } -(void)removeSprite:(CCSprite *)sprite{ if([currentBombs containsObject:sprite]) { NSLog(@"Found sprite in array, TERMINATHOORRR"); [currentBombs removeObject:sprite]; } else { NSLog(@"Didn't find the object in array, didn't delete!"); [self stopCheckDamage]; } } -(void)stopCheckDamage{ [self unschedule:@selector(checkDamageForBomb)]; } -(void)checkDamageForBomb{ for (CCSprite* bomb in currentBombs) { CGPoint bombPos = [self tileCoordForPosition:bomb.position]; for (int i = 0; i &lt;= explosionLenght; i++) { CGPoint playerPos = [self tileCoordForPosition:_cat.position]; int bombX = (bombPos.x + i); int bombY = (bombPos.y + i); int bombNegX = (bombPos.x - i); int bombNegY = (bombPos.y - i); CGPoint centre = bombPos; CGPoint top = ccp(centre.x, bombY); CGPoint left = ccp(bombNegX, centre.y); CGPoint bottom = ccp(centre.x, bombNegY); CGPoint right = ccp(bombX, centre.y); //pastebin.com/biuQBfnv if (CGPointEqualToPoint(top, playerPos) || CGPointEqualToPoint(left, playerPos) || CGPointEqualToPoint(bottom, playerPos) || CGPointEqualToPoint(right, playerPos)) { NSLog(@"Player hit"); [currentBombs removeObject:bomb]; break; } } } } </code></pre> <p>Is this an efficient way to do such a thing? </p>
[]
[ { "body": "<p>I don't know if this is the kind of answer you're looking for, but as this is code review, I'm going to at least review some aspects of your code.</p>\n\n<p>First thing I notice is <code>explosionLenght</code>. It's misspelled. You transposed the last two characters. It should be <code>explosionLength</code>.</p>\n\n<hr>\n\n<p>Additionally, the following bits of code can be combined and refactored. Instead of:</p>\n\n<pre><code>// stuff\n\nBOOL topB = YES;\nBOOL leftB = YES;\nBOOL bottomB = YES;\nBOOL rightB = YES;\n\n// stuff\n\nif (![self isLocationBombable:top])\n{topB = NO;}\nif (![self isLocationBombable:left])\n{leftB = NO;}\nif (![self isLocationBombable:bottom])\n{bottomB = NO;}\nif (![self isLocationBombable:right])\n{rightB = NO;}\n\n// stuff\n</code></pre>\n\n<p>You can instead, just write this:</p>\n\n<pre><code>BOOL topB = [self isLocationBombable:top];\nBOOL leftB = [self isLocationBombable:left];\nBOOL bottomB = [self isLocationBombable:bottom];\nBOOL rightB = [self isLocationBombable:right];\n</code></pre>\n\n<hr>\n\n<p>The following section is problematic to me:</p>\n\n<pre><code>CCSprite *circleTop = [[CCSprite alloc]initWithFile:@\"Circle.png\"];\nCCSprite *circleLeft = [[CCSprite alloc]initWithFile:@\"Circle.png\"];\nCCSprite *circleBottom = [[CCSprite alloc]initWithFile:@\"Circle.png\"];\nCCSprite *circleRight = [[CCSprite alloc]initWithFile:@\"Circle.png\"];\n</code></pre>\n\n<p>Primarily because it's contained within a loop... you're accessing the same file 4 times to initialize a variable, which is already not helpful. And then you do this once per iteration through the loop. I don't know a whole lot about Sprites and don't necessarily understand everything that's going on here, but... I know that you don't need to be doing this.</p>\n\n<p>Grab the data from the file once and outside the loop.</p>\n\n<pre><code>CCSprite *circleTop = [[CCSprite alloc] initWithFile:@\"Circle.png\"];\n</code></pre>\n\n<p>Again, I'm not super familiar with CCSprite. But from here, you can either... use this same variable instead of using 4 variables.</p>\n\n<p>Or if you really want 4 variables, you can do this:</p>\n\n<pre><code>CCSpring *circleLeft = circleTop;\n</code></pre>\n\n<p>(and do that a few more times)</p>\n\n<p>This assigns each variable as a pointer to the same memory location.</p>\n\n<p>But if you truly do need different memory locations, then after you grab from file once, the best method for initializing the others will be doing this:</p>\n\n<pre><code>CCSprite *circleLeft = [circleTop copy];\n</code></pre>\n\n<p>This will copy, bit for bit, the values in the memory location that <code>circleTop</code> points to into a new memory address and make <code>circleLeft</code> a pointer to that location, and it's certainly more efficient then loading from file 4 times.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-23T02:31:59.590", "Id": "42567", "ParentId": "26664", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T11:52:30.377", "Id": "26664", "Score": "1", "Tags": [ "objective-c", "ios" ], "Title": "Is this proper code for removing a CCSprite under certain conditions?" }
26664
<p>Is there a way to write this code block cleaner and more readable?</p> <pre><code> var shareNavigate = function () { scope.sharingActions.shareOnFacebook().done(function () { app.router.navigateToStories(); }); }, sharePublishNavigate = function () { scope.sharingActions.shareOnFacebook().done(function () { scope.model.publish().done(function () { app.router.navigateToStories(); }); }); }, loginSharePublishNavigate = function () { facebookActions.login().done(function () { sharePublishNavigate(); }); }; if (!noViews &amp;&amp; hasEditPermissions) { shareNavigate(); } else if (noViews) { if (hasEditPermissions) { sharePublishNavigate(); } else if (!isLoggeedIn) { loginSharePublishNavigate(); } else { shareNavigate(); } } </code></pre> <p>First I define functions and then in each case I call the relevant function. I am using jQuery deferreds and since I need operation to done, I have many nested methods. Is there any way to beautify this code?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T12:10:07.603", "Id": "41331", "Score": "5", "body": "First thing: use correct indentation!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T12:22:42.020", "Id": "41333", "Score": "0", "body": "Any reason for sharing something, and _then_ publishing it? Seems exactly backwards to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T12:38:23.603", "Id": "41334", "Score": "0", "body": "By the way, you can probably use [`.then`](http://api.jquery.com/deferred.then/) to your advantage, provided you're using jQuery 1.8+: `scope.sharingActions.shareOnFacebook().then(scope.model.publish).then(app.router.navigateToStories);`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T13:12:52.920", "Id": "41337", "Score": "0", "body": "Why do you declare those functions locally instead of in an object of their own?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T04:56:51.150", "Id": "41367", "Score": "0", "body": "Agree @Flambino, and I would put each `.then` on a new line, I know that isn't possible in comments." } ]
[ { "body": "<p>I'd prefer to rewrite this</p>\n\n<pre><code> if (!noViews &amp;&amp; hasEditPermissions) {\n shareNavigate();\n } else if (noViews) {\n if (hasEditPermissions) {\n sharePublishNavigate();\n } else if (!isLoggeedIn) {\n loginSharePublishNavigate();\n } else {\n shareNavigate();\n }\n }\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code> if (hasEditPermissions) {\n if (noViews) {\n sharePublishNavigate();\n } else {\n shareNavigate();\n }\n } else {\n if(loggeedIn) {\n shareNavigate();\n } else {\n loginSharePublishNavigate();\n }\n }\n</code></pre>\n\n<p>The <code>!noViews</code> is redundant and it is usually confusing if you start an if-else expression with a negation. Besides that, try avoiding <code>else if</code> in favor of nested expressions. You should also try to make the boolean expressions functionally independent - if you have checked <code>noViews</code> somewhere, don't check it again.</p>\n\n<p>I am not sure if the truth table for the two blocks are identical. I'll leave that up to you to verify.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T21:58:56.880", "Id": "26679", "ParentId": "26665", "Score": "2" } }, { "body": "<p>Personally, I like comma separated variable definitions, but they ten to get messy when there are assignments or when they become multi-line. A suggestion I found on the net is to only use comma separated declarations <em>if they are not assignments</em>. If they are assignments, <code>var</code> them individually instead. looks cleaner and prevents stray <code>,</code>.</p>\n\n<pre><code>//declarations only\nvar foo, bar, baz;\n\n//assignments:\nvar foo = 1;\nvar bar = 2;\nvar baz = 3;\n</code></pre>\n\n<p>When declaring functions, I'd stick to using \"function declarations\" rather than the \"function expressions\" since:</p>\n\n<ul>\n<li>They contain lesser characters</li>\n<li>They don't look like variables at first sight</li>\n<li>Hoisting advantage (the compiler pulls them up the scope so they look like they are declared on top, regardless of where you place them in the code)</li>\n<li>Avoids the trailing <code>;</code> (you'll know when you use linters)</li>\n<li>They are named which avoids issues with debuggers (better safe then sorry).</li>\n</ul>\n\n<p>The notational difference is the following</p>\n\n<pre><code>//expression - NOT THIS\nvar foo = function(){/*...*/};\n\n//declaration - THIS!\nfunction foo(){/*...*/}\n</code></pre>\n\n<p>As for your nesting functions, they look fine but I suggest you indent properly.</p>\n\n<p>There <em>is</em> a minor overhead in object property access, and you can cache them for shorter access. However, it's a trade-off between readability at times. </p>\n\n<p>You can also assign the function name as callback directly rather than create a function that only calls another function.</p>\n\n<pre><code>var shareOnFacebook = scope.sharingActions.shareOnFacebook;\n\n\nfunction loginSharePublishNavigate() {\n facebookActions.login().done(sharePublishNavigate);\n}\n\nfunction shareNavigate() {\n shareOnFacebook().done(app.router.navigateToStories);\n}\n\nfunction sharePublishNavigate() {\n shareOnFacebook().done(function () {\n scope.model.publish().done(app.router.navigateToStories);\n });\n}\n</code></pre>\n\n<p>For boolean-containing variables, I suggest to be uniform in the name. I usually name them in the <code>true</code> state and prefixed with <code>is</code> or <code>has</code>. So instead of using <code>noViews</code>, I suggest you use <code>hasViews</code>. That way, the conditions will not be garbled in meaning:</p>\n\n<pre><code>//instead of\nif(!noViews &amp;&amp; hasEditPermissions){/*...*/}\n\n//use this\nif(hasViews &amp;&amp; hasEditPermissions){/*...*/}\n</code></pre>\n\n<p>As for the logic, I can't quite figure it out. Here are the possible combinations of the 3 variables used.</p>\n\n<pre><code>view edit login\n0 0 0 = loginSharePublishNavigate\n0 0 1 = shareNavigate\n0 1 0 = sharePublishNavigate\n0 1 1 = sharePublishNavigate\n1 0 0 = ?\n1 0 1 = ?\n1 1 0 = shareNavigate\n1 1 1 = shareNavigate\n</code></pre>\n\n<p>Let's say we factor out <code>loggedIn</code> as our first check and should do <code>loginSharePublishNavigate</code> when not logged in.</p>\n\n<pre><code>view edit login\n/*\n0 0 0 = loginSharePublishNavigate\n0 1 0 = loginSharePublishNavigate\n1 1 0 = loginSharePublishNavigate\n1 0 0 = loginSharePublishNavigate\n*/\n1 0 1 = ? &lt;- what handles this???\n0 1 1 = sharePublishNavigate\n0 0 1 = shareNavigate\n1 1 1 = shareNavigate\n</code></pre>\n\n<p>Still, can't figure it out. If I do some K-map on this, I might get the right combinations, but end up with a more complex condition. Anyways, a generic suggestion is you do filtering rather than nesting:</p>\n\n<pre><code>if(!loggedIn){\n //now in here, it's executing `!loggedIn`\n //not logged in\n}\n//ok, so we are logged in, what next?\nelse if(!hasPermissions){\n //now in here, it's like executing `loggedIn &amp;&amp; !hasPermissions`\n //no permissions\n}\n//ok, we are now logged in and have permissions, what next?\nelse if(!anotherCheck){\n //now in here, it's like executing `loggedIn &amp;&amp; hasPermissions &amp;&amp; !anotherCheck`\n} \n//...and so on...\nelse {\n //now in here, it's like executing `loggedIn &amp;&amp; hasPermissions &amp;&amp; anotherCheck`\n //ok, every check is true by this block\n}\n</code></pre>\n\n<p>We avoided nesting. But this only works in linear conditions. If there are more complex conditions, this won't work. Also, it passes through more checks when all conditions are <code>true</code> which means more overhead. But it's a trade-off for readable code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T22:17:24.757", "Id": "26680", "ParentId": "26665", "Score": "2" } }, { "body": "<p>You would possibly be better off with <code>login</code>, <code>share</code>, <code>publish</code> and <code>navigate</code> as promise-returning worker functions:</p>\n\n<pre><code>var login = function() { return isLoggedIn ? null : facebookActions.login(); }\nvar share = function() { return scope.sharingActions.shareOnFacebook(); };\nvar publish = function() { return scope.model.publish() };\nvar navigate = function() { return app.router.navigateToStories() };\n</code></pre>\n\n<p>Now you can sequence these workers with <code>.then()</code> as follows (or similar) :</p>\n\n<pre><code>var rootPromise = $.Deferred().resolve().promise();\n\nif (noViews) {\n if(hasEditPermissions || !isLoggedIn) {\n rootPromise.then(login).then(share).then(publish).then(navigate);\n }\n else {\n rootPromise.then(share).then(navigate);\n }\n}\nelse if(hasEditPermissions) {\n rootPromise.then(share).then(navigate);\n}\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li><p><code>rootPromise</code> isn't strictly necessary but keeps rest of the code tidier, particularly <code>login()</code>.</p></li>\n<li><p><code>login()</code> returns <code>null</code> if already logged in, allowing the calling logic to be slightly simpler.</p></li>\n<li><p>The whole thing may simplify further depending in part on the relationship between <code>hasEditPermissions</code> and <code>isLoggedIn</code> (See other answers for suggestions).</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T13:11:17.063", "Id": "41451", "Score": "0", "body": "Why did you made: rootPromise.then(login).then(share).then(publish).then(navigate);\ninstead of: login().then(share).then(publish).then(navigate);" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T16:25:16.543", "Id": "41478", "Score": "0", "body": "I was wondering if you might ask. As I said, `rootPromise` isn't strictly necessary and yes, `login()...`. is the other way to proceed but in that case `login()` would need to return a promise under both conditions - `isLoggedIn` and `!isLoggedIn` - otherwise `login().then()` would throw an error. Using a ready-resolved \"rootPromise\" or \"starterPromose\" is quite a common technique when building `.then()` chains." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T10:56:20.753", "Id": "26746", "ParentId": "26665", "Score": "1" } } ]
{ "AcceptedAnswerId": "26680", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T11:53:17.687", "Id": "26665", "Score": "0", "Tags": [ "javascript", "jquery", "facebook" ], "Title": "Support for sharing stories on Facebook" }
26665
<p>I figured something like this:</p> <pre><code>a= [1, 2, 3, 2, 2, 2, 3, 1, 1, 1, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] a.inj­ect({}) { |h, el| h[el]­ = a.cou­nt(el) if h[el]­.nil? ; h }.sor­t_by {|k,v­| v}.re­verse.inje­ct({}) { |h, el| h[el[­0]] = el[1]­ ; h} </code></pre> <p>This outputs:</p> <pre><code>=&gt; {0=&gt;10, 4=&gt;9, 2=&gt;5, 1=&gt;4, 3=&gt;2} </code></pre> <p>But it seems like a clunky solution that does to many passes over the "same" thing.</p> <p>What would be a good way to do this from different viewpoints?</p> <p>I.e:</p> <ol> <li>an "impress your Java friends" (small one-liner not used in production)</li> <li>Performance</li> <li>Easily read </li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T08:14:10.773", "Id": "41435", "Score": "0", "body": "I think you need a longer array for a more representative benchmark. I don't know the big O for all of these, but there might be significant differences with a tougher dataset. What about `a = 1_000.times.map{ rand 9 }` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T08:30:20.653", "Id": "41439", "Score": "0", "body": "Great suggestion, I was thinking that enough iterations would be enough but clearly that was an error in thinking on my part." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T10:58:31.417", "Id": "41443", "Score": "0", "body": "Patrik, if you are worried about performance, you should use `each` and `sort_by!` (without reverse). Of course, that's awful imperative, non-declarative code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T13:22:48.920", "Id": "41453", "Score": "0", "body": "memory consumption might vary, too. chaining group_by and map creates a hash with arrays as values then an array of arrays, while inject directly creates a hash with integers as keys and values." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T17:56:18.087", "Id": "41484", "Score": "0", "body": "Sacrificing some performance for readability seems to ruby way to go (in MRI atleast)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T08:53:50.810", "Id": "41519", "Score": "0", "body": "interesting results. I must admit i was convinced `inject` would be more efficient, but obviously it's not ! I guess using `Array#length` is more efficient than incrementing a counter, due to C implementation. Another lesson learned today." } ]
[ { "body": "<p>Not sure which viewpoint this would be, but this is what I came up with:</p>\n\n<pre><code>Hash[a.group_by {|e| e}.map {|k,v| [k, v.length]}]\n</code></pre>\n\n<p>Update: I'm not thrilled with this, but this one sorts by the occurrence count, descending.</p>\n\n<pre><code>Hash[a.group_by {|e| e}.map {|k,v| [k, v.length]}.sort_by {|a| a[1]}.reverse]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T17:26:40.217", "Id": "41349", "Score": "0", "body": "Hash[a.group_by { |x| x }.map { |k,v| [k, v.length] }.sort.reverse] works, can you make it even cleaner? :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T17:39:02.213", "Id": "41350", "Score": "0", "body": "Am I correct in thinking you want it sorted descending by the occurrence count? The line in your comment doesn't seem to do that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T17:41:36.890", "Id": "41351", "Score": "0", "body": "You are right. Hash[a.group_by { |x| x }.map { |k,v| [k, v.length] }.sort_by { |a,b| b }.reverse] does though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T10:53:10.650", "Id": "41380", "Score": "1", "body": "You can also write: `Hash[xs.group_by { |x| x }.map { |k, vs| [k, vs.length] }.sort_by { |k, length| -length }]`" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T17:07:46.513", "Id": "26674", "ParentId": "26672", "Score": "2" } } ]
{ "AcceptedAnswerId": "26674", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T15:38:17.953", "Id": "26672", "Score": "4", "Tags": [ "ruby" ], "Title": "Creating a sorted hash counting the occurrences of a number in an array" }
26672
<p>I am trying out a small piece of code that would generate HMAC-SHA1. I have been asked to code the HMAC implementation myself using the OpenSSL libs for SHA1 calculation.</p> <p>After 'wiki'ing for the algorithm, here is what I have below. I have used input with RFC 2104 specified test values:</p> <blockquote> <p>key = 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b<br> key_len = 16 bytes<br> data = "Hi There"<br> data_len = 8 bytes digest = 0x9294727a3638bb1c13f48ef8158bfc9d</p> </blockquote> <p>But the output I get is:</p> <pre><code>675b0b3a1b4ddf4e124872da6c2f632bfed957e9* </code></pre> <p>Is this really not the way to implement HMAC? How else can this be done?</p> <pre><code>#include &lt;openssl/evp.h&gt; #include &lt;openssl/bn.h&gt; #include &lt;openssl/sha.h&gt; #include &lt;openssl/err.h&gt; #include &lt;openssl/conf.h&gt; #include &lt;openssl/engine.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; /* for memset() */ #include &lt;unistd.h&gt; #define IPAD 0x36 #define OPAD 0x5C #define SHA1_DIGESTLENGTH 20 #define SHA1_BLOCK_LENGTH 64 #define COUNTER_LENGTH 8 typedef unsigned char uint8_t; typedef unsigned short int uint16_t; typedef unsigned int uint32_t; /** * Key */ #define SECRET { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b , 0x0b , 0x0b , 0x0b , 0x0b , 0x0b , 0x0b , 0x0b , 0x0b} #define COUNTER { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } /* * hmac sha1. */ int main(int argc, char *argv[]){ unsigned char ipad[SHA1_BLOCK_LENGTH]; unsigned char opad[SHA1_BLOCK_LENGTH]; unsigned char algKey[SHA1_BLOCK_LENGTH]; unsigned char msgBuffer[SHA1_BLOCK_LENGTH + COUNTER_LENGTH]; unsigned char valBuffer[SHA1_BLOCK_LENGTH + 20]; unsigned int i; uint8_t ctr[] = "Hi There"; uint8_t hash[20]; uint8_t key[]= SECRET; int len = 16; memset(hash, 0, sizeof(hash)); memset(algKey, 0, sizeof(algKey)); strncpy((char *)algKey, (char *)key, len); memset(ipad, IPAD, sizeof(ipad)); memset(opad, OPAD, sizeof(opad)); for (i = 0; i &lt; SHA1_BLOCK_LENGTH; i++){ ipad[i] ^= algKey[i]; } for (i = 0; i &lt; SHA1_BLOCK_LENGTH; i++){ opad[i] ^= algKey[i]; } memset(msgBuffer, 0, sizeof(msgBuffer)); strncpy((char *)msgBuffer, (char *)ipad, SHA1_BLOCK_LENGTH); strncpy((char *)msgBuffer + SHA1_BLOCK_LENGTH, (char *)ctr, COUNTER_LENGTH); EVP_MD_CTX mdctx, md_ctx; const EVP_MD *md; unsigned char md_value[EVP_MAX_MD_SIZE]; unsigned int md_len; OpenSSL_add_all_digests(); md = EVP_get_digestbyname("sha1"); if(!md) { printf("Unknown message digest\n"); exit(1); } EVP_MD_CTX_init(&amp;mdctx); EVP_DigestInit_ex(&amp;mdctx, md, NULL); EVP_DigestUpdate(&amp;mdctx, msgBuffer,(SHA1_BLOCK_LENGTH + COUNTER_LENGTH) ); EVP_DigestFinal_ex(&amp;mdctx, md_value, &amp;md_len); EVP_MD_CTX_cleanup(&amp;mdctx); printf("Digest is: "); for(i = 0; i &lt; md_len; i++) printf("%02x", md_value[i]); printf("\n"); unsigned char *copy; copy = malloc(md_len); strncpy((char*)copy, (char *)md_value, md_len); memset(valBuffer, 0, sizeof(valBuffer)); strncpy((char *)valBuffer, (char *)opad, SHA1_BLOCK_LENGTH); strncpy((char *)valBuffer + SHA1_BLOCK_LENGTH, (char *)copy, md_len); EVP_MD_CTX_init(&amp;md_ctx); EVP_DigestInit_ex(&amp;md_ctx, md, NULL); EVP_DigestUpdate(&amp;md_ctx, valBuffer, SHA1_BLOCK_LENGTH + 20); printf( "updated Digest..\n"); EVP_DigestFinal_ex(&amp;md_ctx, md_value, &amp;md_len); EVP_MD_CTX_cleanup(&amp;md_ctx); printf("Digest is: "); for(i = 0; i &lt; md_len; i++) printf("%02x", md_value[i]); printf("\n"); return 0; } </code></pre>
[]
[ { "body": "<p>Might I suggest using OpenSSL's built in <a href=\"http://www.openssl.org/docs/crypto/HMAC.html\" rel=\"nofollow noreferrer\"><code>HMAC_*</code></a> methods, instead of re-rolling?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-05-28T05:19:23.950", "Id": "26690", "ParentId": "26673", "Score": "2" } }, { "body": "<ul>\n<li><p>You can make these <code>#define</code>s:</p>\n\n<pre><code>#define SHA1_DIGESTLENGTH 20\n#define SHA1_BLOCK_LENGTH 64\n#define COUNTER_LENGTH 8\n</code></pre>\n\n<p>into a more concise <code>enum</code>:</p>\n\n<pre><code>typedef enum { COUNTER=8, SHA1_DIGEST=20, SHA1_BLOCK=64 } Length;\n</code></pre>\n\n<p>This could also be done with <code>SECRET</code> and <code>COUNTER</code>, but each hex value would need a name.</p>\n\n<p>If you use the <code>enum</code> recommendation, you may need to rename the second <code>COUNTER</code> to avoid possible name-clashing. Perhaps rename it based on what the counter is for.</p></li>\n<li><p>You don't need your own <code>typedef</code>s for these:</p>\n\n<pre><code>typedef unsigned char uint8_t;\ntypedef unsigned short int uint16_t;\ntypedef unsigned int uint32_t;\n</code></pre>\n\n<p>Prefer to use the <code>typedef</code>s already defined in <a href=\"http://en.cppreference.com/w/cpp/types/integer\" rel=\"nofollow\"><code>&lt;stdint.h&gt;</code></a>.</p></li>\n<li><p>For unformatted output with a newline, use <code>puts()</code> instead of <code>printf()</code>:</p>\n\n<pre><code>puts(\"Some text...\");\n</code></pre></li>\n<li><p>I'd recommend splitting this program into separate functions. This will make it easier to tell how the it works and make it easier to maintain. A function should have one purpose, and<code>main()</code> should have minimal implementation (such as acquiring input and calling other functions).</p></li>\n<li><p>There's no need to call <code>exit(1)</code> within <code>main()</code>. Just <code>return 1</code>.</p>\n\n<p>The <code>return 0</code> is also not needed at the end. Reaching this point implies successful termination, so the compiler will do this return for you.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-11T16:47:46.290", "Id": "46942", "ParentId": "26673", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T17:03:48.540", "Id": "26673", "Score": "5", "Tags": [ "c", "reinventing-the-wheel", "cryptography", "openssl" ], "Title": "HMAC-SHA1 implementation" }
26673
<p>This is from an older question of mine that I decided to revisit:</p> <p><a href="https://codereview.stackexchange.com/questions/24399/simple-and-efficient-code-for-finding-factors-and-prime-factorization">Simplifying and optimizing factors and prime factorization generator</a></p> <p>In that question, someone suggested I use an <code>std::map</code> to hold the factors generated from my inputted number. I've also decided to use it with my generated prime factorization, which also works. Based on what I've found online, <code>auto</code> is one way of iterating through an <code>std::map</code>. I've decided to use that since it appears that my compiler supports C++11.</p> <p>Am I using <code>std::map</code> appropriately here, or am I developing some bad habits? I want to develop good habits since I'm interested in using it more in the future.</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstdint&gt; #include &lt;map&gt; #include &lt;cmath&gt; void displayFactors(const std::map&lt;uint64_t, uint64_t&gt; &amp;factors); void displayPrimeFactorization(const std::map&lt;uint64_t, uint64_t&gt; &amp;primeFactorization); void findFactors(uint64_t, std::map&lt;uint64_t, uint64_t&gt; &amp;factors); void findPrimeFactorization(uint64_t positiveInt, std::map&lt;uint64_t, uint64_t&gt; &amp;primeFactorization); int main() { std::map&lt;uint64_t, uint64_t&gt; factors; std::map&lt;uint64_t, uint64_t&gt; primeFactorization; uint64_t positiveInt; std::cout &lt;&lt; "\n\n&gt; Positive Int: "; std::cin &gt;&gt; positiveInt; findFactors(positiveInt, factors); std::cout &lt;&lt; "\n\n * Factors:\n\n"; displayFactors(factors); findPrimeFactorization(positiveInt, primeFactorization); std::cout &lt;&lt; "\n * Prime Factorization:\n\n "; displayPrimeFactorization(primeFactorization); std::cout &lt;&lt; std::endl &lt;&lt; std::endl; std::cin.ignore(); std::cin.get(); } void displayFactors(const std::map&lt;uint64_t, uint64_t&gt; &amp;factors) { for (auto iter = factors.begin(); iter != factors.end(); ++iter) { std::cout &lt;&lt; " " &lt;&lt; iter-&gt;first &lt;&lt; " x " &lt;&lt; iter-&gt;second &lt;&lt; "\n"; } } void displayPrimeFactorization(const std::map&lt;uint64_t, uint64_t&gt; &amp;primeFactorization) { for (auto iter = primeFactorization.begin(); iter != primeFactorization.end(); ++iter) { if (iter != primeFactorization.begin()) std::cout &lt;&lt; " x "; std::cout &lt;&lt; iter-&gt;first; if (iter-&gt;second &gt; 1) std::cout &lt;&lt; '^' &lt;&lt; iter-&gt;second; } } void findFactors(uint64_t positiveInt, std::map&lt;uint64_t, uint64_t&gt; &amp;factors) { uint64_t sqrtInt = static_cast&lt;uint64_t&gt;(sqrt(static_cast&lt;double long&gt;(positiveInt))); for (uint64_t iter = 1; iter &lt;= sqrtInt; ++iter) { if (positiveInt % iter == 0) { uint64_t quotient = positiveInt / iter; factors[iter] = quotient; } } } void findPrimeFactorization(uint64_t positiveInt, std::map&lt;uint64_t, uint64_t&gt; &amp;primeFactorization) { uint64_t divisor = 2; uint64_t power = 0; while (positiveInt != 1) { while (positiveInt % divisor == 0) { positiveInt /= divisor; power++; } if (power &gt; 0) primeFactorization[divisor] = power; power = 0; divisor++; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T11:35:58.327", "Id": "41382", "Score": "0", "body": "Few things for others to cover: either make these functions static or put them in a namespace, for C++ 11 you can consider std::unordered_map, using auto for everything you can, range-based for loops, ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T11:41:53.383", "Id": "41383", "Score": "0", "body": "...also returning factors/primeFactors by value (in combination with move semantics)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T15:12:36.380", "Id": "41399", "Score": "0", "body": "Is that recommended because I'm returning objects by value? I can do that, as well as `auto` (my compiler doesn't seem to support range-based loops)." } ]
[ { "body": "<p>Looks generally ok. You can actually shorten iteration even more if your compiler supports range-based for loops:</p>\n\n<pre><code>for (auto iter = factors.begin(); iter != factors.end(); ++iter)\n{\n std::cout &lt;&lt; \" \" &lt;&lt; iter-&gt;first &lt;&lt; \" x \" &lt;&lt; iter-&gt;second &lt;&lt; \"\\n\";\n}\n</code></pre>\n\n<p>Can be written as:</p>\n\n<pre><code>for(const auto&amp; pair : factors) {\n std::cout &lt;&lt; \" \" &lt;&lt; pair.first &lt;&lt; \" x \" &lt;&lt; pair.second &lt;&lt; \"\\n\";\n}\n</code></pre>\n\n<p>Further, prefer to return by value than pass by non-const reference:</p>\n\n<pre><code>void findFactors(uint64_t positiveInt, std::map&lt;uint64_t, uint64_t&gt; &amp;factors)\n</code></pre>\n\n<p>Should be </p>\n\n<pre><code>std::map&lt;uint64_t, uint64_t&gt; findFactors(uint64_t positiveInt)\n</code></pre>\n\n<p>This will be exactly the same speed in about 98% of situations thanks to (Named) Return Value Optimization.</p>\n\n<p>One final thing to be aware of with <code>map</code>: insertion (or lookup) using <code>[]</code> vs <code>insert</code>. <code>[]</code> performs a lookup; if the value is not found, it is default-constructed and then the copy-assignment operator (<code>operator=</code>) is called to give the object its value. Thus, <code>[]</code> performs a lookup, construction and copy assignment. It also requires a default constructor to be available. <code>insert</code>, on the other hand does not require a default constructor, and will (from memory) call only the copy constructor. It is thus often (slightly) faster (although for plain old data, the difference will be non-existent). The big difference is not requiring a default constructor, which may not exist.</p>\n\n<p>Finally, a really small thing: it should (technically) be <code>std::uint64_t</code>. Importing <code>&lt;cstdint&gt;</code> (as opposed to <code>stdint.h</code>), based on the C++ spec, will guarantee that this (and <code>uint32_t</code>, etc) will live in the <code>std</code> namespace. It may also put them in the global namespace. Most headers seem to put them in both, but to be 100% portable (according to the standard, anyway), it should be prefixed with a <code>std</code> (or brought into scope with a <code>using std::uint64_t</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T04:35:02.387", "Id": "41363", "Score": "0", "body": "Thanks! I'm also doing a variation with std::list/std::pair (also for the first time), and I'll decide which one I prefer after checking the execution speed. Since I don't think it's too different from `std::map` (minus syntax), I won't need to ask a new question about it. Moreover, would std::list/std::pair be more appropriate since I don't need these paired values to be sorted outside of the loop?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T04:41:13.120", "Id": "41364", "Score": "0", "body": "@JamalA If you're just calculating a factor for one number, there likely won't be any speed difference. If you decide to store factorizations for given numbers for later use, however, the speed difference will likely be significant. I'd likely use a `map` anyway (or even an `unordered_map` since you don't care about order). Honestly, the real use cases for `std::list` are fairly limited." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T04:52:35.887", "Id": "41365", "Score": "0", "body": "There's an `std::unordered_map`? Nice. I'll try that instead. I've just finished testing my `std::list/std::pair` code, and the speed difference was a tad worse. I'll try this out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T04:54:36.670", "Id": "41366", "Score": "0", "body": "@JamalA Again, part of C++11, but as far as I know, all recent versions of gcc, visual studio and clang have it. It sits in `<unordered_map>` (there's also, unsurprisingly, an `unordered_set` too)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T05:06:19.180", "Id": "41368", "Score": "0", "body": "Interesting. Well, I've updated everything with `std::unordered_map`, and I got these two execution speeds: 0.03 seconds for the number 1 trillion and 1.13 seconds for the number 1 quadrillion. The former test case was actually faster (less than a second) with `std::map`. Strange." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T11:42:53.943", "Id": "41384", "Score": "1", "body": "Working on sorted data can often be faster due to branch prediction, cache locality, etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T16:47:45.460", "Id": "41406", "Score": "0", "body": "@Yuushi: I was a little hasty with my testing of different maps. After looking at the output with `std::unordered_map`, the list of factors were jumbled-up (not accordingly with my loop). However, the output was just fine with `std::map`. So, the latter is the obvious choice. As for the two methods of insertion, it appears that [] is a tad faster. I'm assuming this is the case because using `std::make_pair` for `std::insert()` involves a little more work. However, I don't know for sure if my loops ever end up overwriting pairs (if it even matters)." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T04:17:52.910", "Id": "26687", "ParentId": "26678", "Score": "3" } }, { "body": "<ul>\n<li><p>The function prototypes can be removed by defining <code>main()</code> below the functions.</p></li>\n<li><p>This type name is a little long:</p>\n\n<pre><code>std::map&lt;uint64_t, uint64_t&gt;\n</code></pre>\n\n<p>and can be \"shortened\" with a <code>typedef</code>:</p>\n\n<pre><code>typedef std::map&lt;uint64_t, uint64_t&gt; IntegerMap;\n</code></pre></li>\n<li><p><code>calculate()</code> can be slow as it's doing two casts. It's especially unnecessary as it's just being done to obtain one number. It can be simplified and made faster by following <a href=\"https://codereview.stackexchange.com/a/36259\">this advice</a>.</p></li>\n<li><p>The name <code>iter</code> is misleading for this loop:</p>\n\n<pre><code>for (uint64_t iter = 1; iter &lt;= sqrtInt; ++iter)\n</code></pre>\n\n<p>It's not actually an iterator, but a loop counter. It could just be given a single-character name, such as <code>i</code>, which is acceptable for such situations only.</p></li>\n<li><p>The <code>if</code> statement in <code>findPrimeFactorization()</code>:</p>\n\n<pre><code>if (power &gt; 0)\n primeFactorization[divisor] = power;\n</code></pre>\n\n<p>should use curly braces to help with maintenance, even though it's a single line. Curly braces are used correctly elsewhere, so they should be used consistently here.</p>\n\n<pre><code>if (power &gt; 0)\n{\n primeFactorization[divisor] = power;\n}\n</code></pre></li>\n<li><p>This is unnecessary, especially with the <code>std::endl</code>s that also flush the buffer. Just remove it.</p>\n\n<pre><code>std::cout &lt;&lt; std::endl &lt;&lt; std::endl;\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-16T00:15:22.703", "Id": "49898", "ParentId": "26678", "Score": "2" } } ]
{ "AcceptedAnswerId": "26687", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-27T20:04:14.993", "Id": "26678", "Score": "4", "Tags": [ "c++", "c++11", "primes", "stl" ], "Title": "First use of std::map in factors and prime factorization program" }
26678
<p>I'm reading Robert C. Martin's "Clean Code" and for the past few days I've been fiddling with its function writing guidelines. At first I thought the idea of functions being two/three lines long to be ludicrous, but I'm slowly getting the hang of it. The problem is, I'm pretty sure I'm overdoing it now.</p> <p>These are the first lines of the module I decided to refactor using the advice from the book.</p> <pre><code>Public Sub ExportAvailabilityData() Dim aplicativo As Excel.Application Set aplicativo = CreateObject("Excel.Application") aplicativo.Visible = True Dim pastaDeTrabalho As Excel.Workbook Set pastaDeTrabalho = aplicativo.Workbooks.Add Do Until pastaDeTrabalho.Sheets.Count = DaysInMonth(Month(Date)) + 1 pastaDeTrabalho.Sheets.Add Loop Dim day As Integer For day = 1 To DaysInMonth(Month(Date)) pastaDeTrabalho.Sheets(day).Name = Format(day, "00") &amp; "." &amp; Format(Month(Date), "00") Next day pastaDeTrabalho.Sheets(DaysInMonth(Month(Date)) + 1).Name = "Summary " &amp; UCase(MonthName(Month(Date))) End Sub Private Function DaysInMonth(ByVal month As Integer) As Integer DaysInMonth = Day(DateSerial(Year(Date), month + 1, 1) - 1) End Function </code></pre> <p>And this is how it looks like today.</p> <pre><code>Public Sub ExportAvailabilityData() Dim aplicativo As Excel.Application Set aplicativo = CreateObject("Excel.Application") aplicativo.Visible = True Dim pastaDeTrabalho As Excel.Workbook Set pastaDeTrabalho = aplicativo.Workbooks.Add CreateSheets pastaDeTrabalho NameSheets pastaDeTrabalho End Sub Private Sub CreateSheets(ByRef pastaDeTrabalho As Excel.Workbook) CreateDailySheets pastaDeTrabalho, Month(Date) CreateSummarySheet pastaDeTrabalho End Sub Private Sub CreateDailySheets(ByRef pastaDeTrabalho As Excel.Workbook, ByVal month As Integer) Do Until pastaDeTrabalho.Sheets.Count = DaysInMonth(month) pastaDeTrabalho.Sheets.Add Loop End Sub Private Sub CreateSummarySheet(ByRef pastaDeTrabalho As Excel.Workbook) pastaDeTrabalho.Sheets.Add End Sub Private Function DaysInMonth(ByVal month As Integer) As Integer DaysInMonth = Day(DateSerial(Year(Date), month + 1, 1) - 1) End Function Private Sub NameSheets(ByRef pastaDeTrabalho As Excel.Workbook) NameDailySheets pastaDeTrabalho, Month(Date) NameSummarySheet pastaDeTrabalho, Month(Date) End Sub Private Sub NameDailySheets(ByRef pastaDeTrabalho As Excel.Workbook, ByVal month As Integer) Dim day As Integer For day = 1 To DaysInMonth(month) pastaDeTrabalho.Sheets(day).Name = AssembleDailySheetName(day, month) Next day End Sub Private Sub NameSummarySheet(ByRef pastaDeTrabalho As Excel.Workbook, ByVal month As Integer) Dim index As Integer index = GetSummarySheetIndex(month) pastaDeTrabalho.Sheets(index).Name = AssembleSummarySheetName(month) End Sub Private Function GetSummarySheetIndex(ByVal month As Integer) As Integer GetSummarySheetIndex = DaysInMonth(month) + 1 End Function Private Function AssembleDailySheetName(ByVal day As Integer, ByVal month As Integer) As String AssembleDailySheetName = Format(day, "00") &amp; "." &amp; Format(month, "00") End Function Private Function AssembleSummarySheetName(ByVal month As Integer) As String AssembleSummarySheetName = "Summary " &amp; UCase(MonthName(month)) End Function </code></pre> <p>When I considered replacing the <code>"."</code> constant inside <code>AssembleDailySheetName()</code> with a call to yet another function (<code>GetDateSeparator()</code> or something similar), I decided to stop and get some feedback.</p>
[]
[ { "body": "<p>I think you have definitely taken it in the right direction. Excellent work!</p>\n\n<p>I don't see any compelling reason to break <code>AssembleDailySheetName()</code> down any further.</p>\n\n<p>My only complaint is that I don't really like the separation of adding and naming the sheets. I see both steps as being part of creating a sheet. I think it would be nice to set the name of the sheet immediately after adding it (in the same function). That will likely eliminate some code as well. I suspect <code>Sheets.Add</code> may return the new sheet. If that's the case, there would be no need to look up the sheet by index to name it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T01:04:49.110", "Id": "41361", "Score": "0", "body": "I'm automating something a colleague of mine used to do manually, so I've ordered the steps exactly like he did. That's why adding and naming are handled separately, I'm kind of stuck in his way of doing the task. To be honest, the idea of keeping addition and naming of sheets close together never crossed my mind. I'll definitely experiment with it, since I have lots of modules that do similar things. Thanks for the feedback." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T00:47:01.203", "Id": "26684", "ParentId": "26682", "Score": "5" } }, { "body": "<p>My problem with breaking down a simple function like this is that it becomes too difficult to read. This is a simple function that creates a sheet for every day of the month. But to understand how it works, I have to trace through all these procedures.</p>\n\n<p>Consider this rewrite:</p>\n\n<pre><code>Public Sub ExportAvailabilityData()\n\n Dim pastaDeTrabalho As Workbook\n Dim dtDay As Date\n\n Const sFMTDAY As String = \"dd.mm\"\n Const sFMTMONTH As String = \"mmmm\"\n Const sSUMMPREFIX As String = \"Summary\"\n\n Set pastaDeTrabalho = Workbooks.Add\n\n For dtDay = DateSerial(Year(Date), month(Date), 1) To DateSerial(Year(Date), month(Date) + 1, 0)\n pastaDeTrabalho.Worksheets.Add.Name = Format(dtDay, sFMTDAY)\n Next dtDay\n\n pastaDeTrabalho.Worksheets.Add.Name = sSUMMPREFIX &amp; Space(1) &amp; UCase(Format(Date, sFMTMONTH))\n\nEnd Sub\n</code></pre>\n\n<p>Outside of declaration lines, this is five lines long. It only takes a few seconds to identify what the three sections do.</p>\n\n<p>The other thing I would change is the name of the procedure. This procedure doesn't export anything. It should be named CreateMonthlyWorkbook() or something like that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T15:44:54.697", "Id": "41401", "Score": "0", "body": "I've omitted the code that does the exporting because I haven't refactored it yet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T15:57:11.617", "Id": "41403", "Score": "0", "body": "Thanks for the VBA tips! I had no idea `DateSerial(year, month, 0)` returned the last day of the previous `month`. And like Joe F suggested and your code demonstrates, adding a sheet and naming it immediately is the right way to go." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T13:23:42.837", "Id": "26704", "ParentId": "26682", "Score": "4" } } ]
{ "AcceptedAnswerId": "26704", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T00:08:50.553", "Id": "26682", "Score": "6", "Tags": [ "vba" ], "Title": "Are these good examples of functions that do one thing only or am I getting a little carried away?" }
26682
<p>I was trying out the <a href="http://beej.us/guide/bgnet/" rel="nofollow">Beej's guide to socket Programming</a> and wrote this. Is there anything that I am obviously doing wrong? Any potential for buffer overflows? Segmentation faults? Any possible errors that I am not checking for?</p> <p>Or anything that I am overdoing?</p> <p>Thanks a lot.</p> <pre><code>/* * sk2.c * * Created on: May 26, 2013 * Author: bharath */ #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/socket.h&gt; #include &lt;netdb.h&gt; #include &lt;string.h&gt; #include &lt;regex.h&gt; #define BUFSIZE 1025 int main(int argC, char *argv[]){ struct addrinfo hints, *results, *p; int status, s,con1, rret; char ipstr[INET6_ADDRSTRLEN]; printf("Bharath's Socket Program\n"); memset(&amp;hints,0,sizeof hints); hints.ai_family=AF_UNSPEC; hints.ai_socktype=SOCK_STREAM; if (argC&lt;2){ fprintf(stderr,"No URI given.\n"); return -1; } regex_t fqdnParser, resourceParser; regmatch_t m; char *fqdn, *resource; if (!regcomp(&amp;fqdnParser,"^[a-zA-Z0-9.]*",0)){ char *buff = argv[1]; if (!regexec(&amp;fqdnParser, argv[1], 1, &amp;m, 0)){ fqdn=(char*)malloc(m.rm_eo-m.rm_so+1); snprintf (fqdn,m.rm_eo-m.rm_so+1,"%.*s \n", m.rm_eo, buff+m.rm_so); *(fqdn+m.rm_eo-m.rm_so)=0; }else{ fprintf(stderr,"Bad URI FQDN.\n"); return -1; } if (!regcomp(&amp;resourceParser,"/.*$",0)){ if (!regexec(&amp;resourceParser, argv[1], 1, &amp;m, 0)){ resource=(char*)malloc(m.rm_eo-m.rm_so+1); snprintf (resource,m.rm_eo-m.rm_so+1,"%.*s \n", m.rm_eo, buff+m.rm_so); *(resource+m.rm_eo-m.rm_so)=0; } else{ resource="/"; } printf("Parsed: [ %s ][ %s ]\n",fqdn,resource); } }else{ fprintf(stderr,"RegEx not compiled.\n"); } regfree(&amp;fqdnParser); regfree(&amp;resourceParser); if ((status=getaddrinfo(fqdn,"http",&amp;hints,&amp;results))!=0){ fprintf(stderr,"Error: %s\n",gai_strerror(status)); return -2; } for(p=results; p!=NULL; p=p-&gt;ai_next){ char *ipver; void *addr; //ipver=malloc(5); if (p-&gt;ai_family==AF_INET){ ipver="IPv4"; struct sockaddr_in *ipv4=(struct sockaddr_in*)p-&gt;ai_addr; addr=&amp;(ipv4-&gt;sin_addr); }else if(p-&gt;ai_family==AF_INET6){ ipver="IPv6"; struct sockaddr_in6 *ipv6=(struct sockaddr_in6*)p-&gt;ai_addr; addr=&amp;(ipv6-&gt;sin6_addr); } inet_ntop(p-&gt;ai_family,addr,ipstr,sizeof ipstr); printf("%s %s\n",ipver, ipstr); if ((s=socket(p-&gt;ai_family,p-&gt;ai_socktype,p-&gt;ai_protocol))!=-1){ if (connect(s,p-&gt;ai_addr,p-&gt;ai_addrlen) == -1){ fprintf(stderr,"Error Connecting."); }else{ char *req; req=(char*)malloc(25+strlen(resource)+strlen(fqdn)); strcpy(req,"GET "); strcat(req,resource); strcat(req," HTTP/1.0\nHost: "); strcat(req,fqdn); strcat(req,"\n\n"); //printf("%d | %s",strlen(resource),req); void *buf; int len,b; long int bc=0; buf=malloc(BUFSIZE); *(char*)(buf+BUFSIZE)=0; len=strlen(req); b=send(s,req,len,0); printf("%d bytes sent\n--------------\n",b); printf("%s\n-----------------\n",req); b=0; do{ if(b&lt;BUFSIZE-1){ *(char*)(buf+b)=0; } printf("%s",(char*)buf); bc+=b; }while ((b=recv(s, buf, BUFSIZE-1, 0))&gt;0); close(s); printf("\n--------------\n%ld bytes received.",bc); free(buf); break; } }else{ fprintf(stderr,"Socket not created: %d\n",s); return -3; } } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T00:47:36.583", "Id": "41420", "Score": "0", "body": "Next code you write think about the poor reader. Code is read much more often than it is written and so you should make the reader's job more pleasant." } ]
[ { "body": "<p>In other C like languages, it is customary to use more whitespace for readability, but maybe C is an exception; I will refrain from editing your example. I like to put spaces around infix operators and after commas, and use blank lines before function definitions.</p>\n\n<p>I think</p>\n\n<pre><code>*(char*)(buf+BUFSIZE)=0;\n</code></pre>\n\n<p>deserves a comment, but then again, my C is rusty.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T06:50:38.597", "Id": "41372", "Score": "0", "body": "It's actually not an answer. It's more like a comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T16:42:50.727", "Id": "41405", "Score": "5", "body": "@KokaChernov - comments are what CodeReview is all about. And the `buf+BUFSIZE` access is modifying the byte **beyond** the end of the buffer, so @DanRoss (+1) has identified an error, which is what the OP wanted." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T04:51:31.937", "Id": "26689", "ParentId": "26683", "Score": "2" } }, { "body": "<p>I don't know much about sockets, but here are some general C programming comments:</p>\n\n<p><strong>Bugs</strong></p>\n\n<ul>\n<li>You never free() the malloc'd memory of <code>resource</code>. And if you did, which you should, then <code>resource=\"/\";</code> would crash the program when you attempted to free() that memory. </li>\n</ul>\n\n<p><strong>Possible bugs</strong></p>\n\n<ul>\n<li><p><code>char ipstr[INET6_ADDRSTRLEN];</code> To declare an array with the size of a \"string length\" is fishy. Are you sure that this allocates enough room for a string null termination character?</p></li>\n<li><p><code>(char*)malloc</code> There is never a reason to cast the result of malloc in C. It is even potentially harmful in C90. You can find countless topics about this on <a href=\"https://stackoverflow.com/questions/1565496/specifically-whats-dangerous-about-casting-the-result-of-malloc\">Stack Overflow</a>.</p></li>\n</ul>\n\n<p><strong>Picky details and coding style</strong></p>\n\n<ul>\n<li><code>argC</code> is most often spelled with lower case, <code>argc</code>.</li>\n<li><p>It is always best to declare every variable on a line on its own, to make the code more readable and to avoid bugs like <code>int* ptr1, ptr2; // ptr2 is not a pointer as intended</code>.</p></li>\n<li><p><code>memset(&amp;hints,0,sizeof hints);</code> etc should be replaced with </p>\n\n<p><code>struct addrinfo hints = \n{\n .ai_family=AF_UNSPEC;\n .ai_socktype=SOCK_STREAM;\n};</code></p>\n\n<p>This makes the code easier to read and possibly slightly faster as well.</p></li>\n<li><code>return -1</code> should ideally be replaced with EXIT_FAILURE from stdlib.h. Similarly, <code>return 0</code> should ideally be replaced with EXIT_SUCCESS.</li>\n<li>Your code could do with a lot more empty rows, to separate parts of the program from each other. Or even better, split up that huge main() into separate functions. I think that would improve the program a lot.</li>\n<li>Use verbose variable naming. Names like <code>s</code>, <code>m</code>, <code>a</code>, <code>b</code>, <code>c</code> make the program hard to read and understand.</li>\n<li>Avoid assignment inside if statements, it is hard to read and there's a slight potential for bugs in case compiler warnings aren't properly enabled (= when intending ==).</li>\n<li><code>malloc(25+ ...</code>. The magic number 25 could be replaced with a macro such as <code>#define CONST_STRLEN (sizeof(\"GET \")-1 + sizeof(\" HTTP/1.0\\nHost: \")-1 + ... + 1)</code>, so that one actually understands what's going on.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T15:02:57.773", "Id": "26711", "ParentId": "26683", "Score": "3" } } ]
{ "AcceptedAnswerId": "26711", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T00:46:29.993", "Id": "26683", "Score": "2", "Tags": [ "c", "networking", "socket" ], "Title": "How is this for a \"Hello World\" of socket programming?" }
26683
<p>I have a method that returns either true or false based on a value contained by a <code>java.util.List</code>.</p> <pre><code>List&lt;Long&gt;list=new ArrayList&lt;Long&gt;(){{ add(1L); add(2L); add(3L); }}; public boolean checkId(Long id) { return list.contains(id); } </code></pre> <p>Based on the return value of this method and several other conditions a test is required to be performed.</p> <pre><code>boolean isIdChanged=true; boolean isAjaxRequest=true; Long id=1L; Test test = new Test(); if(id!=null &amp;&amp; id&gt;0 &amp;&amp; test.checkId(id) &amp;&amp; isIdChanged || id!=null &amp;&amp; id&gt;0 &amp;&amp; test.checkId(id) &amp;&amp; !isAjaxRequest) { //... do something } </code></pre> <p>Assuming <code>isIdChanged</code>, <code>isAjaxRequest</code> and <code>id</code> have dynamic values.</p> <p>In the <code>if</code> test, it can be noticed that the conditional expression <code>id!=null &amp;&amp; id&gt;0 &amp;&amp; test.checkId(id)</code> is combined (repeated) on both side of the short-circuit <code>||</code> operator.</p> <p>Is there a precise way to avoid this duplicate check?</p> <hr> <p>One way to assign the result of this test to a boolean variable first like so,</p> <pre><code>boolean check=id!=null &amp;&amp; id&gt;0 &amp;&amp; test.checkId(id); </code></pre> <p>and then the conditional test in the <code>if</code> statement can be trimmed like,</p> <pre><code>if(check &amp;&amp; isIdChanged || check &amp;&amp; !isAjaxRequest) { //... do something } </code></pre> <p>But I doubt it is still not sufficient. There should be a more precise way to achieve this.</p> <hr> <p>Based on the comment below, the actual code is as follows (it is related to the JSF component library, <a href="http://primefaces.org/" rel="nofollow noreferrer">Primefaces</a>).</p> <pre><code>@Override public List&lt;StateTable&gt; load(int first, int pageSize, String sortField, SortOrder sortOrder, Map&lt;String, String&gt; filters) { int rowCount = stateService.rowCount().intValue(); if(rowCount&lt;=currentPage(first, pageSize)*pageSize-pageSize) { first-=pageSize; } if(id!=null&amp;&amp;id&gt;0&amp;&amp;stateService.checkId(id)&amp;&amp;(isIdChanged||!FacesContext.getCurrentInstance().getPartialViewContext().isAjaxRequest())) { int currentRow=(int) (stateService.getCurrentRow(id)-1); // Returns the current row number from the database. final DataTable dataTable = (DataTable) FacesContext.getCurrentInstance().getViewRoot().findComponent("form:dataTable"); first=currentRow-(currentRow%pageSize); dataTable.setFirst(first); //Sets the starting index of the page holding the row based on the id supplied as a query-string. isIdChanged=false; } setRowCount(rowCount); return stateService.getList(first, pageSize, sortOrder, sortField); } </code></pre> <p>In this method <code>test</code> has been replaced by <code>stateService</code>. The method is intended to fetch data from a database in a page-wise manner. </p> <p>The first two parameters as their names imply, indicate the starting index where the rows are to be retrieved and the number of rows in a page - the page size respectively. The rest may be unrelated to the question.</p> <p>The first line inside the method returns the number of rows in a given table.</p> <p>The immediate conditional check evaluates to true only during the deletion of rows held by a table structure (Primefaces DataTable) on the client-side. When a user deletes rows on the last page, the previous page is opened automatically as soon as he/she deletes all of the rows in the last page.</p> <p>Afterwards the statements inside an <code>if</code> block are meant to highlight a row. When an <code>id</code> is supplied as a GET request parameter, the page containing that row should be opened automatically and the row corresponding to the <code>id</code> (supplied as a query-string) is highlighted by a different background colour of that row on the client-end. </p> <p>Something similar happens, when you click this <a href="https://stackoverflow.com/a/2013227/1037210">link</a> pointing to a question on StackOverflow which <strong>automatically</strong> opens up the fifth page containing the answer this link is pointing to.</p> <p>And finally, the number of rows are set by calling a super class method <code>setRowCount()</code> and the <code>List</code> is returned from the database.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T09:47:33.353", "Id": "41378", "Score": "1", "body": "What is the code _after_ that `if` condition?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T19:39:30.623", "Id": "41413", "Score": "0", "body": "After `if`, there is nothing other than a `return` statement as the edit I made indicates." } ]
[ { "body": "<p>Why don't you just write it like this? It should be logically equivalent.</p>\n\n<pre><code>if (id != null &amp;&amp; id &gt; 0 &amp;&amp; test.checkId(id) &amp;&amp; (isIdChanged || !isAjaxRequest))\n{\n // do stuff\n}\n</code></pre>\n\n<hr>\n\n<p>On a side note, I would move the null and positive id checks into your \"checkId\" method. In fact, I think in this case, these checks are redundant and unnecessary. You're just checking if an id is in an existing list that you're maintaining. If it's <code>null</code>, it's unlikely it will exist in the list (if you are preventing arbitrary values from being added). An id outside of the range of expected values will just not be in the list in the first place and therefore is unneeded as well.</p>\n\n<p>But, if you <em>must</em> perform these checks, do it within the <code>checkId</code> method instead.</p>\n\n<pre><code>public boolean checkId(Long id)\n{\n // we don't have null ids\n if (id == null)\n return false;\n // we're expecting positive ids\n if (id &lt;= 0)\n return false;\n\n return list.contains(id);\n}\n</code></pre>\n\n<p>This reduces your outer condition to simply:</p>\n\n<pre><code>if (test.checkId(id) &amp;&amp; (isIdChanged || !isAjaxRequest))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T19:42:00.870", "Id": "41414", "Score": "0", "body": "The call to the `checkId()` method is costly, since it may involve a remote method call like EJB. Therefore, right now, I cannot check for `null` and/or negative ids inside this method (depending upon my requirements only). Thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T00:41:00.060", "Id": "41419", "Score": "1", "body": "In that case, I would add a wrapper method so you can perform the checks and use that. That way you encapsulate any optimization logic that you may have which would lead to even less replication." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T04:32:37.090", "Id": "26688", "ParentId": "26686", "Score": "13" } } ]
{ "AcceptedAnswerId": "26688", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T04:12:24.880", "Id": "26686", "Score": "4", "Tags": [ "java" ], "Title": "Avoid duplicate conditional checks in multiple boolean conditions" }
26686
<p>I wrote this code to find the smallest possible integer ratio between two numbers:</p> <pre><code>void ratio(int a, int b) { int min = Math.min(a, b); int max = Math.max(a, b); if(max % min == 0) { System.out.println("1" + " " + max / min); return; } for (int i = 2; i &lt;= min; i++) { while(max % i == 0 &amp;&amp; min % i == 0) { max /= i; min /= i; } } System.out.println(max + " " + min); } </code></pre> <p>Is there any better/efficient way to do this? Am I missing any good algorithm?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T11:27:06.130", "Id": "41386", "Score": "5", "body": "are you referring to GCD (Greatest Common Divisor)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T11:28:44.050", "Id": "41387", "Score": "0", "body": "You're basically talking about finding and eliminating all of the common divisors. Look for algorithms for that. (Note that your algorithm above unnecessarily visits even divisors after eliminating 2.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T11:28:53.943", "Id": "41388", "Score": "1", "body": "I think, this code is efficient enough..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T11:29:54.380", "Id": "41389", "Score": "0", "body": "NO.. for example in GCD, the GCD between 480 & 800 is 1 but in my case I want to know the smallest possible integer ratio like ratio of 480 & 800 is 3:5.The function has to return the two number(3 & 5)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T11:31:04.123", "Id": "41390", "Score": "1", "body": "The GCD between 480 and 800 is at least 40. You can tell that much from simple inspection." } ]
[ { "body": "<p>You need to find the <a href=\"http://en.wikipedia.org/wiki/Greatest_common_divisor\">GCD</a> and then divide both numbers by that.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Euclidean_algorithm#Background_.E2.80.94_Greatest_common_divisor\">Euclid's algorithm</a> is the classic way to do this.</p>\n\n<pre><code>int gcd(int p, int q) {\n if (q == 0) return p;\n else return gcd(q, p % q);\n}\n\nvoid ratio(int a, int b) {\n final int gcd = gcd(a,b);\n System.out.println(a/gcd + \" \" + b/gcd);\n}\n</code></pre>\n\n<p>If you want to swap <code>a</code> and <code>b</code> to have the biggest first then that's easy too</p>\n\n<pre><code>void ratio(int a, int b) {\n final int gcd = gcd(a,b);\n if(a &gt; b) {\n showAnswer(a/gcd, b/gcd);\n } else {\n showAnswer(b/gcd, a/gcd);\n }\n}\n\nvoid showAnswer(int a, int b) {\n System.out.println(a + \" \" + b);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T11:38:24.043", "Id": "41391", "Score": "0", "body": "I thought about Euclid once but somehow rejected it while coding :(\nThanks for your answer :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T11:39:21.933", "Id": "41392", "Score": "1", "body": "It's an oldie but a goodie... (written in c.300BC it's over 2300 years old)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T11:31:22.937", "Id": "26698", "ParentId": "26697", "Score": "11" } } ]
{ "AcceptedAnswerId": "26698", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-26T11:25:45.597", "Id": "26697", "Score": "2", "Tags": [ "java" ], "Title": "Getting the smallest possible integer ratio between two numbers" }
26697
<p>Please, review my implementation of the F# pipeline operator in Scala</p> <pre><code>class PipelineContainer[F](value: F) { def |&gt;[G] (f: F =&gt; G) = f(value) } implicit def pipelineEnrichment[T](xs: T) = new PipelineContainer(xs) test("Find the last but one element in the list") { // example: penultimate(List(1,2,3,3,4,5)) // result: 4 def reverse[T](list: List[T]) = list.reverse def head[T](list: List[T]) = list.head def tail[T](list: List[T]) = list.tail def lastButOne[T](list: List[T]) = list |&gt; reverse |&gt; tail |&gt; head } </code></pre>
[]
[ { "body": "<p>There isn't much that can be reviewed. If you use Scala 2.10 then you should use an <a href=\"http://docs.scala-lang.org/sips/pending/implicit-classes.html\">implicit class</a> instead of an implicit conversion. Even better: use an implicit <a href=\"http://docs.scala-lang.org/sips/pending/value-classes.html\">value class</a>:</p>\n\n<pre><code>implicit class PipelineContainer[F](val value: F) extends AnyVal {\n def |&gt;[G] (f: F =&gt; G) = f(value)\n}\n</code></pre>\n\n<p>Furthermore, in Scala, type parameter are enumerated starting with an <code>A</code>, but this is more a style issue.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T14:58:31.413", "Id": "26710", "ParentId": "26707", "Score": "8" } } ]
{ "AcceptedAnswerId": "26710", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T14:15:47.277", "Id": "26707", "Score": "1", "Tags": [ "scala" ], "Title": "Pipeline operator in scala" }
26707
<p>Here's a test from a Rails app I'm working on. I want to know if I'm using <code>describe</code>, <code>let</code>, <code>before</code>, <code>expect</code>, etc in the proper way.</p> <p>It is an integration test using <code>capybara</code> and <code>FactoryGirl</code>:</p> <pre><code>require 'spec_helper' describe "UserPages" do subject {page} describe "profile page" do let(:user) {FactoryGirl.create(:user)} before do sign_in user end it { should have_selector('h1', text: user.name)} it { should have_selector('title', text: user.name)} describe "follow unfollow buttons" do let(:other_user) {FactoryGirl.create(:user)} describe "following another user" do it "should increment the followed user count" do visit user_path(other_user) expect do click_button "Follow" end.to change(user.followed_users, :count).by(1) end it "should increment the other user's followers count" do expect do click_button "Follow" end.to change(other_user.followers, :count).by(1) end describe "toggling the button" do before {click_button "Follow"} it {should have_selector('input', value: 'Unfollow')} end end describe "unfollowing a user" do before do user.follow!(other_user) visit user_path(other_user) end it "should decrement the followed user count" do expect do click_button "Unfollow" end.to change(user.followed_users, :count).by(-1) end it "should decrement the other user's followers count" do expect do click_button "Unfollow" end.to change(other_user.followers, :count).by(-1) end describe "toggling the button" do before { click_button "Unfollow"} it{should have_selector('input', value: 'Follow')} end end end end describe "if logged in" do let(:user) {FactoryGirl.create(:user)} before do sign_in(user) end describe "it should have a tweet box" do describe "posting a message" do let(:user) {FactoryGirl.create(:user)} before {visit user_path(user.id)} subject {page} it {should have_selector("input", type: "text-field")} end end describe "on another users page" do let(:user) {FactoryGirl.create(:user)} let(:other_user) {FactoryGirl.create(:user)} before do sign_in user visit user_path(other_user) end subject{page} it "should follow user after clicking button and unfollow after that" do expect {click_button "Follow"}.to change(other_user.followers, :count).by(1) expect {click_button "Unfollow"}.to change(other_user.followers, :count).by(-1) expect {click_button "Follow"}.to change(user.followed_user, :count).by(1) expect {click_button "Unfollow"}.to change(user.followed_users, :count).by(-1) end end describe "home page" do before do sign_in user visit "/users" click_link "Home" end it {page.should have_content "Your Timeline"} end end describe "if not logged in" do describe "on another users page" do let(:user) {FactoryGirl.create(:user)} let(:other_user) {FactoryGirl.create(:user)} before do visit user_path(other_user) end subject{page} end end describe "FollowUnfollows" do describe "Post to /relationships" do let (:other_user) {FactoryGirl.create(:user)} let (:user) {FactoryGirl.create(:user)} before do sign_in user end it "click Follow button" do visit user_path(other_user) end end end end </code></pre>
[]
[ { "body": "<ol>\n<li>Use contexts rather than describe on context.</li>\n<li>make sure to keep the same depth with same contexts (story -> login_state -> page -> user_action)</li>\n<li><p>dry your \"let, subject, before\"s</p>\n\n<pre><code>subject { page }\nlet (:other_user) { FactoryGirl.create(:user) }\nlet (:user) { FactoryGirl.create(:user) }\n\ncontexts \"logged in\" do\n before { sign_in user }\n\n describe \"other user's profile page\" do\n before {visit user_path(other_user.id)}\n ...\n end\n\n describe \"profile page\" do\n before {visit user_path(user.id)}\n ...\n end\n ...\nend\n\ncontexts \"logged out\" do\n ...\nend\n...\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-15T04:31:02.490", "Id": "27425", "ParentId": "26712", "Score": "2" } } ]
{ "AcceptedAnswerId": "27425", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T15:25:50.380", "Id": "26712", "Score": "2", "Tags": [ "ruby", "unit-testing", "ruby-on-rails", "rspec", "bdd" ], "Title": "Test for a Rails app" }
26712
<p>I'm currently learning JAVA in a class and we're using the <a href="http://jtf.acm.org/javadoc/student/index.html" rel="nofollow">ACM Graphics package</a>. I wanted some pointers on my code. To provide some context here is the assignment:</p> <blockquote> <p>Write a program that creates an array of 5 custom objects (cows, UFOs, cars, etc.) and then lines them up along the left edge of the window. Assign each object a random velocity, and then move the objects to the right edge of the window. When one of the objects (the "winner") reaches the right edge of the window, remove the other objects and cause the winner to flash on and off.</p> </blockquote> <p>This works just fine and fulfills all the requirements from the assignment. What I want to know is how can I improve this code while still remaining within the requirements. Also any reading materials/videos that you think would be useful for my learning please feel free to share them.</p> <p>Main Race file:</p> <pre><code>import acm.graphics.*; import acm.program.*; import acm.util.RandomGenerator; import java.awt.Color; public class Race extends GraphicsProgram { //Setting up variables private static final int WAIT = 20; private static final int WINDOWX = 400; private static final int WINDOWY = 600; private static final int UFO_COUNT = 5; private UFO[] ufos = new UFO[UFO_COUNT]; private boolean flag = true; private RandomGenerator rgen = new RandomGenerator(); public void init() { setSize(WINDOWX, WINDOWY); } public void run() { //Set up UFOs at start for (int i=0; i&lt;UFO_COUNT; i++) { ufos[i] = new UFO(0, i*100); ufos[i].alien.setColor(rgen.nextColor()); add(ufos[i]); } int winner = -1; waitForClick(); while(flag) { pause(WAIT); //Move Ufos for (int i=0; i&lt;ufos.length; i++ ) { ufos[i].move(rgen.nextInt(0, 2), 0); //Is there a winner? if(ufos[i].getX() &gt; WINDOWX){ winner = i; flag = false; } } } if(!flag) //Safeguard displayWinner(winner); } private void displayWinner(int winner) { //Hide others for (int i=0; i&lt;ufos.length; i++ ) { ufos[i].setVisible(false); } //Make the winner flash while(true) { ufos[winner].setVisible(false); pause(200); ufos[winner].setVisible(true); pause(200); } } } </code></pre> <p>UFO Constructor Class:</p> <pre><code>import acm.graphics.*; import java.awt.*; public class UFO extends GCompound { public GOval body, bubble, alien; public UFO(int x, int y){ //Draw ufo body = new GOval(100, 50); body.setFilled(true); body.setColor(Color.RED); bubble = new GOval(50, 50); alien = new GOval(20, 20); alien.setFilled(true); alien.setColor(Color.GREEN); add(bubble, x+26, y+0); add(alien, x+40, y+10); add(body, x+0, y+26); } } </code></pre>
[]
[ { "body": "<p>Overall, it looks pretty straightforward.</p>\n\n<p>One thing I would recommend is breaking some of the functions down to smaller functions. Several of the comments in the code scream \"move me into a separate function\"! Take <code>displayWinner()</code> for example. This function does two things, clearly indicated by the comments. Extract those two blocks out into separate functions and call them from <code>displayWinner()</code> instead. If the functions are named appropriately, this will also eliminate the need for the comments.</p>\n\n<p>Same thing for the <code>run()</code> method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T17:18:03.553", "Id": "26716", "ParentId": "26714", "Score": "2" } }, { "body": "<h1>Encapsulation</h1>\n\n<p>An object's behaviour should be with the object. This means that the UFO should control how it flashes (or blinks):</p>\n\n<pre><code>public class UFO ...\n public void blink() {\n setVisible(false);\n pause(200);\n setVisible(true);\n pause(200);\n }\n\n /** You will have to implement and test this method. */\n private void pause( int milliseconds ) {\n Thread.sleep( milliseconds);\n }\n}\n</code></pre>\n\n<h1>Information Hiding</h1>\n\n<p>The following code exposes the internals of how a UFO is piloted:</p>\n\n<pre><code>ufos[i].alien.setColor(rgen.nextColor());\n</code></pre>\n\n<p>Rather, this should be exposed as an accessor:</p>\n\n<pre><code>ufos[i].setPilotColor(rgen.nextColor());\n</code></pre>\n\n<p>Similarly, exposing the UFO's location is not necessary to determine the winner:</p>\n\n<pre><code>if(ufos[i].getX() &gt; WINDOWX){\n winner = i;\n flag = false;\n}\n</code></pre>\n\n<p>Rather, the above code is more clearly stated as:</p>\n\n<pre><code>if(ufos[i].crossedFinishLine( WINDOWX ) ){\n winner = i;\n flag = false;\n}\n</code></pre>\n\n<p>Only the UFO need know if it has crossed the finish line. The code is now self-documenting.</p>\n\n<p>Make the following attributes private:</p>\n\n<pre><code>public GOval body, bubble, alien;\n</code></pre>\n\n<p>Otherwise your code will be susceptible to <a href=\"https://stackoverflow.com/questions/2458217/why-does-this-code-sometimes-throw-a-nullpointerexception/2458257#2458257\">race conditions</a> (no pun intended) and be difficult to debug. This is because the UFO class has no control over when its data changes.</p>\n\n<h1>While True</h1>\n\n<p>In my <a href=\"https://stackoverflow.com/questions/1420029/how-to-break-out-of-a-loop-from-inside-a-switch/1420100#1420100\">opinion</a>, <code>while( true )</code> is poor form. Instead, add a condition that allows the loop to exit:</p>\n\n<pre><code> while( gameOver() ) {\n ufos[winner].blink();\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T08:45:50.090", "Id": "41440", "Score": "1", "body": "`UFO` doesn't have a `pause` method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T20:55:10.397", "Id": "41490", "Score": "0", "body": "Thanks for the pause reference but UFO does have access to the pause method since it's brought in with the import statement at the top. Also great pointers! I read all your links in the answer and wanted to ask if you could elaborate a bit on the `while(true)` part and how I can apply the concept from c++(as in your link) to JAVA." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T20:59:49.047", "Id": "41491", "Score": "0", "body": "Replace `while(true)` with a method that returns `true` or `false` depending on whether the loop should continue; all loops should terminate at some point. In the code shown, if `gameOver()` returns true, the winning UFO will blink. If `gameOver()` returns false (because the user has elected to play again or quit the program), then the UFO will stop blinking." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T21:06:49.307", "Id": "41492", "Score": "0", "body": "I get it. It's basically the same as I did with the main race loop where I put a flag in right? Are there any other tips/pointers you would like to add? Also when do I have to use the `this` keyword? Like in your first point you just invoke `setVisible()` without `this`. Is there any case that I would have to use `this`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T22:03:19.417", "Id": "41496", "Score": "0", "body": "Exactly. (Aside, `flag` could use a more meaningful name.) For `this`, see: http://stackoverflow.com/questions/2411270/when-should-i-use-this-in-a-class. Some advice: ask questions, be curious, code a lot, read the Pragmatic Programmer (http://pragprog.com/the-pragmatic-programmer), and devour anything by Martin Fowler (http://martinfowler.com/)." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T18:48:05.460", "Id": "26721", "ParentId": "26714", "Score": "5" } } ]
{ "AcceptedAnswerId": "26721", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T16:26:38.507", "Id": "26714", "Score": "3", "Tags": [ "java", "optimization" ], "Title": "Java Array Traversal Optimization" }
26714
<p>I have had to do a crash course in JSP, Servlets, and JDBC. I decided to attempt a Login System. I'm unsure if my use of try/catch is appropriate and if I am closing database connections correctly. There is one major flaw in the program which is if a user registering enters an ID that is not unique, then it causes an exception. I'm unsure how to solve this. I realize this is a lot of code to pore through, but any suggestions would be much appreciated.</p> <p><strong>Index.jsp</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt; &lt;title&gt;Insert title here&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h3&gt; Welcome to the Login Screen&lt;/h3&gt; &lt;br&gt; &lt;form action = 'login' method = "post"&gt; &lt;input type = "text" name = "userId"/&gt; &lt;br&gt; &lt;input type = "password" name = "password"/&gt; &lt;br&gt; &lt;input type = "submit"/&gt; &lt;/form&gt; &lt;br&gt; &lt;a href="registration.jsp"&gt;I dont have an account&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>Profile.jsp</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt; &lt;title&gt;Profile&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h3&gt;Welcome to the profile page&lt;/h3&gt; &lt;br&gt; &lt;jsp:useBean id="user" class = "com.calgar.service.User" scope = "session"&gt;&lt;/jsp:useBean&gt; Welcome &lt;jsp:getProperty property="firstName" name="user"/&gt; &lt;jsp:getProperty property="lastName" name="user"/&gt; &lt;br&gt;Your User ID : &lt;jsp:getProperty property="userId" name="user"/&gt; &lt;br&gt;Your Password is :&lt;jsp:getProperty property="password" name="user"/&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Registration.jsp</p> <pre class="lang-html prettyprint-override"><code>&lt;%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt; &lt;title&gt;Enter Your details here&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h3&gt;Enter User ID&lt;/h3&gt; &lt;br&gt; &lt;form action = "RegistrationServlet" method = "post"&gt; Enter User ID : &lt;input type = "text" name ="newUserId"/&gt; &lt;br&gt;Enter your Password : &lt;input type = "password" name ="newUserPassword"/&gt; &lt;br&gt;Enter your First Name :&lt;input type = "text" name = "newUserFirstName"/&gt; &lt;br&gt;Enter your Last Name : &lt;input type = "text" name ="newUserLastName"/&gt; &lt;br&gt;&lt;input type = "submit"/&gt; &lt;br&gt; &lt;%String name =(String)request.getAttribute("GenericSQLError"); %&gt; &lt;%=name %&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>Login Servlet</strong></p> <pre class="lang-java prettyprint-override"><code>package com.calgar.servlet; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.calgar.service.LoginService; import com.calgar.service.User; /** * Servlet implementation class LoginServlet */ @WebServlet("/login") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public LoginServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userId,password; userId = request.getParameter("userId"); password = request.getParameter("password"); Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; boolean authenticated = false; LoginService loginService = new LoginService(); try { connection=loginService.getConnection(connection); resultSet = loginService.getUserLoginCredentials(preparedStatement, connection, resultSet); authenticated = loginService.authenticate(userId,password,resultSet); if(authenticated) { User user = new User(); user = loginService.getUserDetails(userId, preparedStatement, connection, resultSet); request.getSession().setAttribute("user", user); response.sendRedirect("profile.jsp"); } else { loginService.closeDatabaseConnections(preparedStatement, connection, resultSet); response.sendRedirect("index.jsp"); } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } } </code></pre> <p><strong>Registration Servlet</strong></p> <pre class="lang-java prettyprint-override"><code>package com.calgar.servlet; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.calgar.service.LoginService; import com.calgar.service.User; /** * Servlet implementation class RegistrationServlet */ @WebServlet("/RegistrationServlet") public class RegistrationServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public RegistrationServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Connection connection = null; PreparedStatement preparedStatement = null; String newUserId, newUserPassword, newUserFirstName, newUserLastName; ResultSet resultSet = null; newUserId = request.getParameter("newUserId"); newUserPassword = request.getParameter("newUserPassword"); newUserFirstName= request.getParameter("newUserFirstName"); newUserLastName = request.getParameter("newUserLastName"); System.out.println(newUserId); try { LoginService loginService = new LoginService(); connection = loginService.getConnection(connection); loginService.addNewUser(preparedStatement, connection, newUserId, newUserPassword, newUserFirstName, newUserLastName); loginService.closeDatabaseConnections(preparedStatement, connection, resultSet); User user = new User(); user.setUserId(newUserId); user.setPassword(newUserPassword); user.setFirstName(newUserFirstName); user.setLastName(newUserLastName); request.getSession().setAttribute("user", user); response.sendRedirect("profile.jsp"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if(connection != null) try{connection.close();} catch(SQLException ignore){} if(preparedStatement != null) try{preparedStatement.close();} catch(SQLException ignore){} if(resultSet != null) try{resultSet.close();} catch(SQLException ignore){} } } } </code></pre> <p><strong>LoginService</strong></p> <pre class="lang-java prettyprint-override"><code>package com.calgar.service; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class LoginService { public Connection getConnection(Connection connection) throws ClassNotFoundException, SQLException { System.out.println("Connecting to database USERS"); Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/login","calgar","password"); System.out.println("Connection successful"); return connection; } public ResultSet getUserLoginCredentials(PreparedStatement ps,Connection connection, ResultSet rs) throws SQLException { ps =connection.prepareStatement("SELECT userId, password FROM users"); rs = ps.executeQuery(); return rs; } public boolean authenticate(String UserId, String password, ResultSet rs) throws SQLException { String userIdResultSet,passwordResultSet; //Boolean authenticated = false; while(rs.next()) { userIdResultSet = rs.getString(1); passwordResultSet = rs.getString(2); if(userIdResultSet.equals(UserId)) { if(passwordResultSet.equals(password)) { return true; } } } return false; } public User getUserDetails(String userId, PreparedStatement ps,Connection connection, ResultSet rs) throws SQLException { User user = new User(); ps = connection.prepareStatement("SELECT userId, password, userFirstName, userLastName FROM users WHERE userId = ?" ); ps.setString(1, userId); rs = ps.executeQuery(); while(rs.next()) { user.setUserId(rs.getString(1)); user.setPassword(rs.getString(2)); user.setFirstName(rs.getString(3)); user.setLastName(rs.getString(4)); } return user; } public void addNewUser(PreparedStatement ps, Connection connection, String newUserId, String newUserPassword,String newUserFirstName,String newUserLastname) throws SQLException { if (newUserId != null &amp;&amp; "".equals(newUserId.trim())){ newUserId = null; } if ((newUserPassword != null) &amp;&amp; (newUserPassword.trim().equals(""))){ newUserPassword = null; } ps = connection.prepareStatement("INSERT INTO users (userId ,password , userFirstName, userLastName)VALUES(?,?,?,?)"); ps.setString(1, newUserId); ps.setString(2, newUserPassword); ps.setString(3, newUserFirstName); ps.setString(4, newUserLastname); ps.executeUpdate(); } public void closeDatabaseConnections(PreparedStatement ps,Connection connection, ResultSet rs) throws SQLException { if(ps != null) { ps.close(); } if(connection!=null) { connection.close(); } if(rs != null) { rs.close(); } } } </code></pre> <p><strong>User</strong></p> <pre class="lang-java prettyprint-override"><code>package com.calgar.service; public class User { private String userId; private String password; private String firstName; private String lastName; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } </code></pre>
[]
[ { "body": "<p>Most of the functions in <code>LoginService</code> take unnecessary parameters. For example, <code>getConnection()</code> takes a <code>connection</code> parameter, but never uses it. It just reassigns and returns it. It could be written like this instead:</p>\n\n<pre><code>public Connection getConnection() throws ClassNotFoundException, SQLException {\n System.out.println(\"Connecting to database USERS\");\n Class.forName(\"com.mysql.jdbc.Driver\");\n Connection connection = DriverManager.getConnection(\"jdbc:mysql://localhost:3306/login\",\"calgar\",\"password\");\n System.out.println(\"Connection successful\");\n return connection;\n}\n</code></pre>\n\n<p>Same thing with <code>ps</code> and <code>rs</code> in <code>getUserLoginCredentials()</code>, etc.</p>\n\n<hr>\n\n<p>The database resources are not being closed properly. Make sure you wrap the use of each resource in a <code>try</code> and close it in the <code>finally</code>. This goes for all database resources, including <code>Connection</code>, <code>PreparedStatement</code> and <code>ResultSet</code>.</p>\n\n<pre><code>Connection connection = getConnection();\ntry {\n // use connection\n}\nfinally {\n connection.close()\n}\n</code></pre>\n\n<p>If you are using Java 7, you should check out the new <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow\">try-with-resources</a> statement. The above could be written like this:</p>\n\n<pre><code>try (Connection connection = getConnection()) {\n // use connection\n} // connection will automatically be closed here\n</code></pre>\n\n<hr>\n\n<p>Rather than declaring all variables at the top of a function, consider moving the variable declarations closer to where they are used. For example, rather than this:</p>\n\n<pre><code>String newUserId, newUserPassword, newUserFirstName, newUserLastName;\n...\n\nnewUserId = request.getParameter(\"newUserId\");\nnewUserPassword = request.getParameter(\"newUserPassword\");\nnewUserFirstName= request.getParameter(\"newUserFirstName\");\nnewUserLastName = request.getParameter(\"newUserLastName\");\n</code></pre>\n\n<p>Do this:</p>\n\n<pre><code>String newUserId = request.getParameter(\"newUserId\");\nString newUserPassword = request.getParameter(\"newUserPassword\");\nString newUserFirstName= request.getParameter(\"newUserFirstName\");\nString newUserLastName = request.getParameter(\"newUserLastName\");\n</code></pre>\n\n<p>This will eliminate several lines of code and make it a little easier to read.</p>\n\n<hr>\n\n<p>You could also get rid of the constructors in the servlet classes. They will be generated by the compiler automatically.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T22:21:29.270", "Id": "26727", "ParentId": "26717", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T17:43:55.013", "Id": "26717", "Score": "2", "Tags": [ "java", "authentication", "jdbc", "servlets", "jsp" ], "Title": "Am I using appropriate methods in this login system?" }
26717
<p>I was fiddling with animation in Java and wrote this:</p> <pre><code>import java.awt.Graphics; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.Timer; import javax.swing.ImageIcon; import javax.swing.JFrame; class Main extends JFrame implements ActionListener { private Timer timer = new Timer(500, this); private Image mario1 = new ImageIcon("C:/Users/User/workspace/Game Development/src/mario.jpg").getImage(); private Image mario2 = new ImageIcon("C:/Users/User/workspace/Game Development/src/mario2.jpg").getImage(); private int counter = 0; private ArrayList&lt;Image&gt; scenes = new ArrayList&lt;Image&gt;(); public Main() { setSize(500, 500); setVisible(true); addScene(mario1); addScene(mario2); timer.start(); } public void actionPerformed(ActionEvent e) { nextScene(); } public void addScene(Image image) { scenes.add(image); } public void nextScene() { counter++; repaint(); } @Override public void paint(Graphics g) { super.paint(g); if (!(counter &lt; 0 || counter &gt;= scenes.size())) g.drawImage(scenes.get(counter), 100, 100, null); } public static void main(String[] args) { new Main(); } } </code></pre> <p>Is this the correct approach or is this just bad practice?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T10:36:38.750", "Id": "41442", "Score": "0", "body": "You might have a look at double-buffering or page-flipping: http://docs.oracle.com/javase/tutorial/extra/fullscreen/doublebuf.html" } ]
[ { "body": "<p>Two recommendations:</p>\n\n<ul>\n<li>It is better that you don't \"do any action\" in the constructor; create, say, a <code>.start()</code> method and do <code>new Main().start()</code> in <code>main()</code>;</li>\n<li><p>rather than testing on <code>count</code> in animation, use this, where <code>nrImages</code> is the number of images:</p>\n\n<pre><code>count = (count + 1) % nrImages;\n</code></pre></li>\n</ul>\n\n<p>Also, declare your list as a <code>List</code>, not an <code>ArrayList</code>: use interfaces when available.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T15:03:06.110", "Id": "48170", "Score": "0", "body": "Why is it better to make a `start()` method? I've always seen `JFrame` initialization performed in the constructor." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T19:30:12.663", "Id": "26722", "ParentId": "26720", "Score": "2" } }, { "body": "<p>You have the right general idea for animation, yes. Basically you have created animation with 2 FPS (frames-per-second).</p>\n\n<p>I think the thing that can most improve your code is using a different data structure than a <code>List</code>. It's my final note at the end of this post because my sample code uses some of the other best-practices suggestions detailed throughout.</p>\n\n<pre><code>class Main \n</code></pre>\n\n<p>From a purist perspective, your class should explicitly be <code>public</code>.</p>\n\n<pre><code>class Main extends JFrame\n</code></pre>\n\n<p><code>JFrame</code> implements the <code>Serializable</code> interface, so it's a good practice to have a <code>serialVersionUID</code> like so: <code>private static final long serialVersionUID = 1L;</code>. (Not having this should produce a warning if you are using Eclipse as your IDE.)</p>\n\n<pre><code>private Image mario1 = new ImageIcon(\"C:/Users/User/workspace/Game Development/src/mario.jpg\").getImage();\nprivate Image mario2 = new ImageIcon(\"C:/Users/User/workspace/Game Development/src/mario2.jpg\").getImage();\n</code></pre>\n\n<p>Since you are pre-loading your images, consider making them <code>final</code>. This prevents you from accidentally overwriting them at some other point in your code, and it also makes it very clear for those reading your code that <code>mario1</code> reference will <em>always</em> point to the same <code>Image</code>. If you do this, these are essentially constants and should be renamed in all uppercase with words separated by underscores (such as <code>MARIO_1</code> and <code>MARIO_2</code>).</p>\n\n<p>I would also consider renaming these variables to something more meaningful in this case. What is unique about the images? For example, <code>private final Image MARIO_STILL</code> and <code>private final Image MARIO_JUMPING</code> are much more descriptive and improve your code's readability.</p>\n\n<p>And of course, if these images can be reused throughout all of your game instances, you can make them true constants and make them <code>static</code> as well.</p>\n\n<pre><code>public Main() {\n setSize(500, 500);\n setVisible(true);\n\n addScene(mario1);\n addScene(mario2);\n timer.start();\n}\n</code></pre>\n\n<p>Consider explicitly calling <code>super()</code> at the beginning of this constructor. Also, this doesn't make a huge difference with such a trivial animation, but I would perform your <code>addScene()</code> calls <em>before</em> the <code>setVisible(true)</code> call. Like I said, it doesn't make much difference in this specific scenario, but if <code>addScene()</code> performed a lot more processing which was heavy computationally, the user of your program would experience a lag time between when the frame became visible and when the animations actually began.</p>\n\n<pre><code>public void actionPerformed(ActionEvent e) {\n nextScene();\n}\n</code></pre>\n\n<p>It's implicit, but for style points you should explicitly add the <code>@Override</code> annotation. It's also a good idea to always check for the source of the <code>ActionEvent</code> (as in <code>if(e.getSource() == timer)</code>), since when your program gets more complex you will likely be receiving events from multiple objects.</p>\n\n<pre><code>@Override\npublic void paint(Graphics g) {\n super.paint(g);\n if (!(counter &lt; 0 || counter &gt;= scenes.size())) g.drawImage(scenes.get(counter), 100, 100, null);\n}\n</code></pre>\n\n<p>Consider calling <code>timer.stop()</code> when there are no more <code>Image</code>s left to display. This is just an efficiency concern and not really something crucial.</p>\n\n<p>Finally, a more advanced note. While the way you've implemented the frames here works fine, it's not the most convenient data structure for what you're trying to accomplish. I think a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Queue.html\" rel=\"nofollow\">Queue</a> would be more intuitive for you. A <code>Queue</code> is a <a href=\"http://en.wikipedia.org/wiki/FIFO\" rel=\"nofollow\">FIFO data structure</a> which will let you add and remove elements to it on a \"first-in, first-out\" basis. This prevents you from having to have a <code>counter</code> variable which you increment manually each time a scene is displayed. You can just keep adding <code>Image</code>s to the <code>Queue</code> and remove the next one each time the <code>Timer</code> fires.</p>\n\n<p>This greatly simplifies your code:</p>\n\n<pre><code>public void actionPerformed(ActionEvent e) {\n if(e.getSource() == timer) repaint();\n}\n\n@Override\npublic void paint(Graphics g) {\n super.paint(g);\n if (imageQueue.peek() != null) {\n g.drawImage(imageQueue.remove(), 100, 100, null);\n if(imageQueue.peek() == null) timer.stop();\n }\n}\n</code></pre>\n\n<p>Note that this also only works for <em>displaying</em> images. If you intend to ever do other processing while animating (like accepting user input from the keyboard), your animation will need to occur in a separate <code>Thread</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T14:43:08.253", "Id": "30308", "ParentId": "26720", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T18:27:43.113", "Id": "26720", "Score": "4", "Tags": [ "java", "animation" ], "Title": "Is this the correct approach to animation in Java?" }
26720
<p>I have written this code to be able to suspend (or to cancel) a worker executed in a separate thread in Qt.</p> <p>To do it, I have used an instance <code>QWaitCondition</code> and <code>QMutex</code>.</p> <pre class="lang-cpp prettyprint-override"><code>#ifndef MYWORKER_H #define MYWORKER_H #include &lt;QObject&gt; #include &lt;QMutex&gt; #include &lt;QWaitCondition&gt; class MyWorker : public QObject { Q_OBJECT public: explicit MyWorker(QObject *parent = 0); ~MyWorker(); void restart(); void pause(); signals: void finished(); public slots: void doWork(); void cancelWork(); private: QMutex m_continue; QWaitCondition m_pauseManager; bool m_cancelRequested; bool m_pauseRequired; }; #endif // MYWORKER_H </code></pre> <p>Here is the code of myworker.cpp</p> <pre><code>#include "myworker.h" #include &lt;QDebug&gt; MyWorker::MyWorker(QObject *parent) : QObject(parent), m_cancelRequested(false), m_pauseRequired(false) { } MyWorker::~MyWorker() { } void MyWorker::restart() { this -&gt; m_pauseRequired = false; this -&gt; m_pauseManager.wakeAll(); } void MyWorker::pause() { this -&gt; m_pauseRequired = true; } void MyWorker::doWork() { // Write your code here for(int i = 0; i &lt; 4000000000; i++) { if (i % 100000 == 0) { qDebug() &lt;&lt; i; } if (m_pauseRequired) { m_pauseManager.wait(&amp;m_continue); } if (this -&gt; m_cancelRequested()) { break; } } // Write your code above" emit finished(); } void MyWorker::cancelWork() { this -&gt; restart(); this -&gt; m_cancelRequested = true; } </code></pre> <p>Here is the snippet to use this code :</p> <pre><code>this -&gt; m_thread = new QThread(); this -&gt; m_worker = new MyWorker(); this -&gt; m_worker-&gt; moveToThread(this -&gt; m_thread); connect(m_thread, SIGNAL(started()), m_worker, SLOT(doWork())); connect(m_worker, SIGNAL(finished()), m_thread, SLOT(quit())); this -&gt; m_thread -&gt; start(); // To suspend the work this -&gt; m_worker -&gt; pause(); // To stop the work this -&gt; m_worker -&gt; cancelWork(); </code></pre> <p>Do you have any advice on improving this code, or do you have a better solution?</p>
[]
[ { "body": "<p>It's not at all clear why you've declared/defined this:</p>\n\n<pre><code>MyWorker::~MyWorker()\n{\n}\n</code></pre>\n\n<p>Unless there's something specific that this accomplishes (which I don't see) you're better off without it.</p>\n\n<pre><code>void MyWorker::restart()\n{\n this -&gt; m_pauseRequired = false;\n this -&gt; m_pauseManager.wakeAll();\n}\n</code></pre>\n\n<p>I know there are people here who disagree about this, but they're just wrong. Using <code>this -&gt;</code> without a <em>really</em> good reason is a terrible idea. It makes code noisy and hurts readability. Don't do it if you have any reasonable choice (and in this case, you do).</p>\n\n<pre><code>void MyWorker::pause()\n{\n this -&gt; m_pauseRequired = true;\n}\n</code></pre>\n\n<p>Same thing here, obviously.</p>\n\n<pre><code>void MyWorker::doWork()\n{\n // Write your code here\n for(int i = 0; i &lt; 4000000000; i++)\n {\n if (i % 100000 == 0) {\n</code></pre>\n\n<p>What (if anything) are the exact significance of <code>4000000000</code> and <code>100000</code>? If they're significant, document that significance by giving them meaningful names.</p>\n\n<p>It's not entirely clear, but based on the comments, <em>maybe</em> this code was intended to represent the work to be carried out by the \"client\" code. If so, it seems (to me) like it would be helpful (at least for review purposes) to point that out explicitly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-31T03:39:21.823", "Id": "79924", "Score": "1", "body": "I too don't see the need for that destructor. If C++11 was in use, then it could instead be `default`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-31T03:44:16.833", "Id": "79925", "Score": "1", "body": "@jamal: no real need for that either. `=default` is normally for *constructors* that would normally be synthesized by the compiler, but won't because you've defined some other constructor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-31T03:46:48.487", "Id": "79926", "Score": "0", "body": "Ah, okay. Would that still apply in cases where you need to maintain the Rule of Four/Five (since we're talking C++11)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-31T03:48:58.740", "Id": "79927", "Score": "0", "body": "@jamal: Not usually, anyway, no. For cases like that, you typically need a destructor and constructor to actually do things (e.g., manage memory owned by the class in question)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-31T03:50:11.940", "Id": "79928", "Score": "0", "body": "That is true. I was thinking of cases where you have pointers as members, but with no use of `new`/`delete`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-02-15T20:51:03.523", "Id": "294267", "Score": "1", "body": "I think `m_pauseRequired` should be something atomic." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-31T03:08:30.323", "Id": "45795", "ParentId": "26724", "Score": "8" } }, { "body": "<ol>\n<li>You're not locking <code>m_continue</code> before waiting with it.</li>\n</ol>\n\n<p>From <a href=\"http://doc.qt.io/qt-5/qwaitcondition.html#wait\" rel=\"nofollow noreferrer\">the docs</a> of <code>QWaitCondition::wait(QMutex *lockedMutex, ...)</code>:</p>\n\n<blockquote>\n <p>Releases the lockedMutex and waits on the wait condition. The lockedMutex must be initially locked by the calling thread. If lockedMutex is not in a locked state, the behavior is undefined.</p>\n</blockquote>\n\n<p>So at least you need to do:</p>\n\n<pre><code> // [...]\n m_continue.lock();\n if (m_pauseRequired) {\n m_pauseManager.wait(&amp;m_continue);\n // unlocks m_continue and blocks the thread until m_pauseManager.wakeAll()\n }\n m_continue.unlock();\n</code></pre>\n\n<ol start=\"2\">\n<li>I would make <code>m_pauseRequired</code> and <code>m_cancelRequested</code> atomic, e.g. <code>QAtomicInt</code> or <code>std::atomic&lt;bool&gt;</code>. Not much risk here (depending on compiler), but it makes your intentions clearer.</li>\n<li>In <code>MyWorker::cancelWork()</code>, set <code>m_cancelRequested</code> before restarting. Thus, if the worker is currently paused, it will find itself canceled as soon as the <code>QWaitCondition</code> resumes the thread. If it's currently running, chances are higher that the worker will not perform another loop.</li>\n</ol>\n\n<p>About your solution: Did you test it? Does it work as expected?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-17T10:39:38.093", "Id": "173242", "ParentId": "26724", "Score": "3" } }, { "body": "<p>The code you have is unsafe, because <code>pause()</code> and <code>cancelWork()</code> are called from outside the worker's thread, and they use no locking when modifying the worker's members.</p>\n\n<p>In general, prefer to interact with objects in other threads by invoking their slots via queued connections, unless there's a pressing reason to act immediately. This means you don't need any of the synchronization facilities inside the worker. This simplifies the coding, and makes it easier to test.</p>\n\n<p>To do that, the worker needs to periodically process events. I prefer to put this in a function of its own:</p>\n\n<pre><code>bool isCancelled() {\n auto dispatcher = QThread::currentThread()-&gt;eventDispatcher();\n if (!dispatcher) return false;\n dispatcher-&gt;processEvents();\n return m_cancelRequested;\n}\n</code></pre>\n\n<p>In the work method, this can be called every time you want to poll for cancellation.</p>\n\n<p>You need some protection against re-entering <code>doWork()</code> from this event queue. One way to manage this is with a tiny state-machine:</p>\n\n<pre><code>private:\n enum State { IDLE, RUNNING, PAUSED };\n State state = IDLE;\n</code></pre>\n\n<p>Used like this:</p>\n\n<pre><code>void MyWorker::doWork()\n{\n if (state == RUNNING)\n return;\n\n state = RUNNING;\n emit started();\n</code></pre>\n\n<hr>\n\n<p>Here's my complete, tested version - no locks or atomics, all the synchronization is managed by Qt:</p>\n\n<pre><code>#include &lt;QAbstractEventDispatcher&gt;\n#include &lt;QObject&gt;\n#include &lt;QThread&gt;\n#include &lt;QDebug&gt;\n\nclass Worker : public QObject\n{\n Q_OBJECT\n\npublic:\n explicit Worker(QObject *parent = 0)\n : QObject(parent)\n {\n }\n\nsignals:\n void started();\n void finished();\n\npublic slots:\n void pause()\n {\n auto const dispatcher = QThread::currentThread()-&gt;eventDispatcher();\n if (!dispatcher) {\n qCritical() &lt;&lt; \"thread with no dispatcher\";\n return;\n }\n\n if (state != RUNNING)\n return;\n\n state = PAUSED;\n qDebug() &lt;&lt; \"paused\";\n do {\n dispatcher-&gt;processEvents(QEventLoop::WaitForMoreEvents);\n } while (state == PAUSED);\n }\n\n void resume()\n {\n if (state == PAUSED) {\n state = RUNNING;\n qDebug() &lt;&lt; \"resumed\";\n }\n }\n\n void cancel() {\n if (state != IDLE) {\n state = IDLE;\n qDebug() &lt;&lt; \"cancelled\";\n }\n }\n\nprotected:\n\n enum State { IDLE, RUNNING, PAUSED };\n State state = IDLE;\n\n bool isCancelled() {\n auto const dispatcher = QThread::currentThread()-&gt;eventDispatcher();\n if (!dispatcher) {\n qCritical() &lt;&lt; \"thread with no dispatcher\";\n return false;\n }\n dispatcher-&gt;processEvents(QEventLoop::AllEvents);\n return state == IDLE;\n }\n\n};\n\n\nclass MyWorker : public Worker\n{\n Q_OBJECT\n\npublic:\n explicit MyWorker(QObject *parent = 0)\n : Worker(parent)\n {\n }\n\n void doWork()\n {\n if (state == PAUSED)\n // treat as resume\n state = RUNNING;\n\n if (state == RUNNING)\n return;\n\n state = RUNNING;\n qDebug() &lt;&lt; \"started\";\n emit started();\n\n // This loop simulates the actual work\n for (auto i = 0u; state == RUNNING; ++i) {\n QThread::msleep(100);\n if (isCancelled()) break;\n qDebug() &lt;&lt; i;\n }\n\n qDebug() &lt;&lt; \"finished\";\n emit finished();\n }\n};\n\n\n#include &lt;QCoreApplication&gt;\nint main(int argc, char **argv)\n{\n QCoreApplication app(argc, argv);\n\n QThread thread;\n auto worker = new MyWorker();\n worker-&gt;moveToThread(&amp;thread);\n QObject::connect(&amp;thread, &amp;QThread::started, worker, &amp;MyWorker::doWork);\n QObject::connect(worker, &amp;MyWorker::finished, worker, &amp;QObject::deleteLater);\n QObject::connect(worker, &amp;QObject::destroyed, &amp;thread, &amp;QThread::quit);\n QObject::connect(&amp;thread, &amp;QThread::finished, &amp;app, &amp;QCoreApplication::quit);\n\n thread.start();\n\n // To saved defining more signals, I'll just use invoke() here.\n // Normally, we connect some \"driver\" object's signals to the\n // pause/resume/cancel slots.\n auto const m = worker-&gt;metaObject();\n QThread::sleep(1);\n m-&gt;invokeMethod(worker, \"pause\");\n QThread::sleep(4);\n m-&gt;invokeMethod(worker, \"resume\");\n QThread::sleep(1);\n m-&gt;invokeMethod(worker, \"cancel\");\n\n app.exec();\n}\n</code></pre>\n\n<p>Sorry this is a bit rushed; I hope the principle is clear.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-21T07:33:54.373", "Id": "364682", "Score": "0", "body": "Undeniably the most useful response, correctly ignoring stylistic differences in favour of pointing out the obvious elephant in the room: namely, that Qt's queued signal-slot connections obviate the need for error-prone thread synchronization. The [current top answer](https://codereview.stackexchange.com/a/45795/124625) is particularly painful in this regard. Pedantic screeds against explicit `this->` usage reduce to \"this-> Considered Harmful!\" – a subjective (and dubious) claim at best." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-21T07:50:21.587", "Id": "364689", "Score": "1", "body": "Actually, this isn't simply useful; this is a *brilliant* general-purpose treatment of Qt-based multithreading. Your concrete `Worker` superclass is sufficiently versatile that I'm astonished Qt hasn't already implemented a similar core type (e.g., `QThreadWorker`). Existing StackOverflow questions on gracefully starting, pausing, resuming, and halting threads and threaded workers (e.g., [this](https://stackoverflow.com/questions/39232182), [this](https://stackoverflow.com/questions/33591705)) now reduce to referencing this canonical answer. **Bravo!**" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-08-17T13:54:51.133", "Id": "173258", "ParentId": "26724", "Score": "9" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T19:48:08.223", "Id": "26724", "Score": "11", "Tags": [ "c++", "multithreading", "qt" ], "Title": "Thread pausing/resuming/canceling with Qt" }
26724
<p>I've written a modulus-type program (using <code>std::vector</code>). The user inputs a number, and the program displays a modulus grid pertaining to that number.</p> <p>This is what it looks like (example program output with 12):</p> <blockquote> <pre><code>(0) 12 24 36 48 60 72 84 96 108 120 (1) 13 25 37 49 61 73 85 97 109 121 (2) 14 26 38 50 62 74 86 98 110 122 (3) 15 27 39 51 63 75 87 99 111 123 (4) 16 28 40 52 64 76 88 100 112 124 (5) 17 29 41 53 65 77 89 101 113 125 (6) 18 30 42 54 66 78 90 102 114 126 (7) 19 31 43 55 67 79 91 103 115 127 (8) 20 32 44 56 68 80 92 104 116 128 (9) 21 33 45 57 69 81 93 105 117 129 (10) 22 34 46 58 70 82 94 106 118 130 (11) 23 35 47 59 71 83 95 107 119 131 (12) 24 36 48 60 72 84 96 108 120 132 </code></pre> </blockquote> <p>Now, I've decided to make it nicer by using <code>std::map</code> and <code>std::array</code>. I get the same output as before, but with the same alignment issues (fixing those could complicate my display function).</p> <p>Is this an effective use of these containers (and am I using them correctly)? If not, what other containers could be used instead? I'm using <code>std::array</code> instead of <code>std::vector</code> here because I'm keeping the number of columns (array size) at 10.</p> <pre><code>#include &lt;iostream&gt; #include &lt;map&gt; #include &lt;array&gt; const unsigned NUM_ARR_ELEMS = 10; std::map&lt;unsigned, std::array&lt;unsigned, NUM_ARR_ELEMS&gt;&gt; getModGrid(unsigned); void displayModGrid(const std::map&lt;unsigned, std::array&lt;unsigned, NUM_ARR_ELEMS&gt;&gt;&amp;); int main() { std::map&lt;unsigned, std::array&lt;unsigned, NUM_ARR_ELEMS&gt;&gt; modGrid; unsigned mod; std::cout &lt;&lt; "\n\n&gt; Mod: "; std::cin &gt;&gt; mod; std::cout &lt;&lt; std::endl &lt;&lt; std::endl; modGrid = getModGrid(mod); displayModGrid(modGrid); std::cout &lt;&lt; std::endl &lt;&lt; std::endl; std::cin.ignore(); std::cin.get(); } std::map&lt;unsigned, std::array&lt;unsigned, NUM_ARR_ELEMS&gt;&gt; getModGrid(unsigned mod) { std::map&lt;unsigned, std::array&lt;unsigned, NUM_ARR_ELEMS&gt;&gt; modRow; std::array&lt;unsigned, NUM_ARR_ELEMS&gt; modValues; for (unsigned modIter = 0; modIter &lt;= mod; ++modIter) { for (unsigned arrIter = 0; arrIter &lt; NUM_ARR_ELEMS; ++arrIter) modValues[arrIter] = modIter + (mod * (arrIter+1)); modRow[modIter] = modValues; } return modRow; } void displayModGrid(const std::map&lt;unsigned, std::array&lt;unsigned, NUM_ARR_ELEMS&gt;&gt; &amp;modGrid) { for (auto rowIter = modGrid.cbegin(); rowIter != modGrid.cend(); ++rowIter) { std::cout &lt;&lt; " (" &lt;&lt; rowIter-&gt;first &lt;&lt; ") "; for (auto colIter = rowIter-&gt;second.cbegin(); colIter != rowIter-&gt;second.cend(); ++colIter) { std::cout &lt;&lt; *colIter &lt;&lt; " "; } std::cout &lt;&lt; std::endl; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T13:41:01.847", "Id": "41456", "Score": "0", "body": "How about using a range-based for loop?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T14:00:25.930", "Id": "41460", "Score": "0", "body": "My compiler doesn't seem to support it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T14:10:12.370", "Id": "41463", "Score": "0", "body": "How about using a vector of arrays instead of a map?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T14:13:05.110", "Id": "41464", "Score": "0", "body": "That's another option. I went with `std::map` at first because the left-hand column works well as key values. I'll try this out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T17:37:28.037", "Id": "41481", "Score": "0", "body": "@VaughnCato, I got it working. I even allowed the user to specify a number of columns (excluding the very first one). Should I post that code under the original, in case it may need further analysis?" } ]
[ { "body": "<p>After looking through my code output and thinking about the comments, I've decided that a map of arrays isn't best. I can see how a map can still display it in order (first column numbers as the keys), but that's about it. It does make more sense to use a vector of vectors, after deciding that it's okay to let the user control the number of columns calculated and displayed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T20:04:29.213", "Id": "26951", "ParentId": "26728", "Score": "1" } }, { "body": "<ul>\n<li><p><code>main()</code> can be defined lastly, so that the function prototypes can be removed. This will also allow <code>NUM_ARR_ELEMS</code> to be initialized within <code>main()</code>. The size of either the inner or outer structure can still be accessed via <code>size()</code>.</p></li>\n<li><p>For simple input like this, a command line argument is another option:</p>\n\n<pre><code>int main(int argc, char *argv[])\n{\n unsigned int mod;\n\n // only argument being the file name\n if (argc &lt; 2)\n {\n std::cin &lt;&lt; mod;\n }\n // more than the file name, where only the second is used\n else\n {\n mod = std::atoi(argv[1]);\n }\n}\n</code></pre>\n\n<p><strong>Warning:</strong> <code>std::atoi()</code> returns an <code>int</code>, but <code>mod</code> is an <code>unsigned int</code>. As this is a mismatch (and should be reported by the compiler), something else should be changed. Either the return value of <code>std::atoi()</code> should be cast to an <code>unsigned int</code>, or <code>mod</code> should just be changed to an <code>int</code> (and adjusted elsewhere). The latter may be a better option here, and the extra unsigned bit really isn't important. Input validation (to avoid a negative value) can be done as well.</p></li>\n<li><p>This type is quite long to copy in different places:</p>\n\n<blockquote>\n<pre><code>std::map&lt;unsigned, std::array&lt;unsigned, NUM_ARR_ELEMS&gt;&gt;\n</code></pre>\n</blockquote>\n\n<p>so it can become a <code>typedef</code>:</p>\n\n<pre><code>typedef std::map&lt;unsigned, std::array&lt;unsigned, NUM_ARR_ELEMS&gt;&gt; Grid;\n</code></pre></li>\n<li><p>Prefer <code>\"\\n\"</code> over <code>std::endl</code> for just a newline. The latter also flushes the buffer.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-04T15:00:44.947", "Id": "59027", "ParentId": "26728", "Score": "2" } } ]
{ "AcceptedAnswerId": "26951", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T23:36:02.330", "Id": "26728", "Score": "3", "Tags": [ "c++", "c++11", "matrix", "stl" ], "Title": "Utilizing std::map and std::array for displaying a modulus grid" }
26728
<p>You can <a href="https://sourceforge.net/projects/dangerworld/" rel="nofollow">download the Dangerworld game in pre-alpha version</a> and review the code. The particular issues I have are</p> <ol> <li>making the character walk over steps instead of sliding</li> <li>NPC AI how to make the enemy <a href="http://www.red3d.com/cwr/steer/" rel="nofollow">walk along a wall</a></li> </ol> <p></p> <pre><code>package adventure; import com.jme3.system.AppSettings; import java.io.File; import com.jme3.renderer.queue.RenderQueue; import com.jme3.renderer.queue.RenderQueue.ShadowMode; import com.jme3.animation.AnimChannel; import com.jme3.animation.AnimControl; import com.jme3.animation.AnimEventListener; import com.jme3.animation.LoopMode; import com.jme3.app.SimpleApplication; import com.jme3.asset.BlenderKey; import com.jme3.asset.plugins.HttpZipLocator; import com.jme3.asset.plugins.ZipLocator; import com.jme3.bullet.BulletAppState; import com.jme3.bullet.PhysicsSpace; import com.jme3.bullet.collision.shapes.CapsuleCollisionShape; import com.jme3.bullet.control.BetterCharacterControl; import com.jme3.bullet.control.RigidBodyControl; import com.jme3.input.ChaseCamera; import com.jme3.input.KeyInput; import com.jme3.input.controls.ActionListener; import com.jme3.input.controls.KeyTrigger; import com.jme3.light.AmbientLight; import com.jme3.light.DirectionalLight; import com.jme3.material.MaterialList; import com.jme3.math.ColorRGBA; import com.jme3.math.Vector3f; import com.jme3.post.FilterPostProcessor; import com.jme3.post.filters.BloomFilter; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.jme3.scene.plugins.ogre.OgreMeshKey; import com.jme3.input.controls.MouseButtonTrigger; import com.jme3.input.MouseInput; public class PyramidLevel extends SimpleApplication implements ActionListener, AnimEventListener { private Node gameLevel; private static boolean useHttp = false; private BulletAppState bulletAppState; private AnimChannel channel; private AnimControl control; // character private BetterCharacterControl goblinControl; private BetterCharacterControl ninjaControl; private BetterCharacterControl jamieControl; private BetterCharacterControl monsterControl; private Node ninjaNode; boolean rotate = false; private Vector3f walkDirection = new Vector3f(0, 0, 0); private Vector3f viewDirection = new Vector3f(1, 0, 0); private boolean leftStrafe = false, rightStrafe = false, forward = false, backward = false, leftRotate = false, rightRotate = false; private Node goblinNode; private Node jamieNode; private Node monsterNode; Spatial goblin; RigidBodyControl terrainPhysicsNode; // animation AnimChannel animationChannel; AnimChannel shootingChannel; AnimControl animationControl; float airTime = 0; // camera private boolean left = false, right = false, up = false, down = false, attack = false; ChaseCamera chaseCam; private boolean walkMode = true; FilterPostProcessor fpp; private Spatial sceneModel; private RigidBodyControl landscape; public static void main(String[] args) { File file = new File("quake3level.zip"); if (!file.exists()) { useHttp = true; } PyramidLevel app = new PyramidLevel(); AppSettings settings = new AppSettings(true); settings.setTitle("Dungeon World"); settings.setSettingsDialogImage("Interface/splash.png"); app.setSettings(settings); app.start(); } @Override public void simpleInitApp() { this.setDisplayStatView(false); bulletAppState = new BulletAppState(); bulletAppState.setThreadingType(BulletAppState.ThreadingType.PARALLEL); stateManager.attach(bulletAppState); bulletAppState.setDebugEnabled(false); setupKeys(); DirectionalLight dl = new DirectionalLight(); dl.setColor(ColorRGBA.White.clone().multLocal(2)); dl.setDirection(new Vector3f(-1, -1, -1).normalize()); rootNode.addLight(dl); AmbientLight am = new AmbientLight(); am.setColor(ColorRGBA.White.mult(2)); rootNode.addLight(am); if (useHttp) { assetManager .registerLocator( "http://jmonkeyengine.googlecode.com/files/quake3level.zip", HttpZipLocator.class); } else { assetManager.registerLocator("quake3level.zip", ZipLocator.class); } // create the geometry and attach it MaterialList matList = (MaterialList) assetManager .loadAsset("Scene.material"); OgreMeshKey key = new OgreMeshKey("main.meshxml", matList); gameLevel = (Node) assetManager.loadAsset(key); gameLevel.setLocalScale(0.1f); gameLevel.addControl(new RigidBodyControl(0)); getPhysicsSpace().addAll(gameLevel); rootNode.attachChild(gameLevel); getPhysicsSpace().addAll(gameLevel); createCharacters(); setupAnimationController(); setupChaseCamera(); setupFilter(); } private void createCharacters() { createNinja(); createGoblin(); createJamie(); createOto(); createMonster(); } private void setupFilter() { FilterPostProcessor fpp = new FilterPostProcessor(assetManager); BloomFilter bloom = new BloomFilter(BloomFilter.GlowMode.Objects); fpp.addFilter(bloom); viewPort.addProcessor(fpp); } private PhysicsSpace getPhysicsSpace() { return bulletAppState.getPhysicsSpace(); } private void setupKeys() { inputManager.addMapping("wireframe", new KeyTrigger(KeyInput.KEY_T)); inputManager.addListener(this, "wireframe"); inputManager.addMapping("CharLeft", new KeyTrigger(KeyInput.KEY_A)); inputManager.addMapping("CharRight", new KeyTrigger(KeyInput.KEY_D)); inputManager.addMapping("CharUp", new KeyTrigger(KeyInput.KEY_W)); inputManager.addMapping("CharDown", new KeyTrigger(KeyInput.KEY_S)); inputManager .addMapping("CharSpace", new KeyTrigger(KeyInput.KEY_SPACE)); inputManager.addMapping("attack", new MouseButtonTrigger( MouseInput.BUTTON_LEFT)); inputManager.addMapping("attack2", new MouseButtonTrigger( MouseInput.BUTTON_RIGHT)); inputManager.addListener(this, "CharLeft"); inputManager.addListener(this, "CharRight"); inputManager.addListener(this, "CharUp"); inputManager.addListener(this, "CharDown"); inputManager.addListener(this, "CharSpace"); inputManager.addListener(this, "attack"); inputManager.addListener(this, "attack2"); } private void createNinja() { ninjaNode = (Node) assetManager .loadModel("Models/Ninja/Ninja.mesh.xml"); ninjaNode.setShadowMode(RenderQueue.ShadowMode.CastAndReceive); ninjaNode.setLocalScale(0.06f); ninjaNode.setLocalTranslation(new Vector3f(55, 3.3f, -60)); ninjaControl = new BetterCharacterControl(1.7f, 4f, 0.5f);//(2, 4, 0.5f); ninjaControl.setJumpForce(new Vector3f(6, 6, 6)); ninjaNode.addControl(ninjaControl); rootNode.attachChild(ninjaNode); bulletAppState.getPhysicsSpace().add(ninjaControl); getPhysicsSpace().add(ninjaControl); animationControl = ninjaNode.getControl(AnimControl.class); animationChannel = animationControl.createChannel(); } private void createGoblin() { goblinNode = (Node) assetManager.loadModel("objects/goblin.j3o"); goblinNode.setShadowMode(RenderQueue.ShadowMode.CastAndReceive); goblinNode.setLocalScale(4f); goblinNode.setLocalTranslation(new Vector3f(51.5f, 3.3f, -60)); goblinControl = new BetterCharacterControl(2, 4, 0.5f); goblinControl.setJumpForce(new Vector3f(6, 6, 6)); goblinNode.addControl(goblinControl); rootNode.attachChild(goblinNode); bulletAppState.getPhysicsSpace().add(goblinControl); getPhysicsSpace().add(goblinControl); animationControl = goblinNode.getControl(AnimControl.class); animationChannel = animationControl.createChannel(); for (String anim : animationControl.getAnimationNames()) System.out.println("goblin can:" + anim); animationChannel.setAnim("idleA"); } private void createJamie() { jamieNode = (Node) assetManager.loadModel("Models/Jaime/Jaime.j3o"); jamieNode.setShadowMode(RenderQueue.ShadowMode.CastAndReceive); jamieNode.setLocalScale(5f); jamieNode.setLocalTranslation(new Vector3f(48f, 3f, -55)); jamieControl = new BetterCharacterControl(2, 4, 0.5f); jamieControl.setJumpForce(new Vector3f(6, 6, 6)); jamieNode.addControl(jamieControl); rootNode.attachChild(jamieNode); bulletAppState.getPhysicsSpace().add(jamieControl); getPhysicsSpace().add(jamieControl); animationControl = jamieNode.getControl(AnimControl.class); animationChannel = animationControl.createChannel(); for (String anim : animationControl.getAnimationNames()) System.out.println("jamie can:" + anim); animationChannel.setAnim("Idle"); } private void createMonster() { monsterNode = (Node) assetManager .loadModel("objects/creatures/monster/monster.packed.j3o"); monsterNode.setShadowMode(RenderQueue.ShadowMode.CastAndReceive); monsterNode.setLocalScale(2f); monsterNode.setLocalTranslation(new Vector3f(53f, 3f, -55)); monsterControl = new BetterCharacterControl(2, 4, 0.5f); monsterControl.setJumpForce(new Vector3f(6, 6, 6)); monsterNode.addControl(monsterControl); rootNode.attachChild(monsterNode); bulletAppState.getPhysicsSpace().add(monsterControl); getPhysicsSpace().add(monsterControl); // animationControl = monsterNode.getControl(AnimControl.class); // animationChannel = animationControl.createChannel(); // for (String anim : animationControl.getAnimationNames()) // System.out.println("goblin can:"+anim); // animationChannel.setAnim("walk"); } private void createOto() { BlenderKey blenderKey = new BlenderKey("Models/Oto/Oto.mesh.xml"); Spatial man = (Spatial) assetManager.loadModel(blenderKey); man.setLocalTranslation(new Vector3f(69, 15, -60)); man.setShadowMode(ShadowMode.CastAndReceive); rootNode.attachChild(man); } private void setupChaseCamera() { flyCam.setEnabled(false); chaseCam = new ChaseCamera(cam, ninjaNode, inputManager); chaseCam.setDefaultDistance(37); } private void setupAnimationController() { animationControl = ninjaNode.getControl(AnimControl.class); animationControl.addListener(this); animationChannel = animationControl.createChannel(); } @Override public void simpleUpdate(float tpf) { // goblinControl.setWalkDirection(goblin.getLocalRotation() // .mult(Vector3f.UNIT_Z).multLocal(0.4f)); Vector3f camDir = cam.getDirection().clone().multLocal(8f); Vector3f camLeft = cam.getLeft().clone().multLocal(8f); camDir.y = 0; camLeft.y = 0; walkDirection.set(0, 0, 0); if (left) { walkDirection.addLocal(camLeft); } if (right) { walkDirection.addLocal(camLeft.negate()); } if (up) { walkDirection.addLocal(camDir); } if (down) { walkDirection.addLocal(camDir.negate()); } // if (attack) { // animationChannel.setAnim("Attack1"); // animationChannel.setLoopMode(LoopMode.DontLoop); // } if (!ninjaControl.isOnGround()) { airTime = airTime + tpf; } else { airTime = 0; } if (walkDirection.length() == 0) { if (!"Idle1".equals(animationChannel.getAnimationName())) { animationChannel.setAnim("Idle1", 1f); } } else { ninjaControl.setViewDirection(walkDirection.negate()); if (airTime &gt; .3f) { if (!"stand".equals(animationChannel.getAnimationName())) { animationChannel.setAnim("Idle1"); } } else if (!"Walk".equals(animationChannel.getAnimationName())) { animationChannel.setAnim("Walk", 1f); } } ninjaControl.setWalkDirection(walkDirection); } /* * Ninja can: Walk Ninja can: Kick Ninja can: JumpNoHeight Ninja can: Jump * Ninja can: Spin Ninja can: Attack1 Ninja can: Idle1 Ninja can: Attack3 * Ninja can: Idle2 Ninja can: Attack2 Ninja can: Idle3 Ninja can: Stealth * Ninja can: Death2 Ninja can: Death1 Ninja can: HighJump Ninja can: * SideKick Ninja can: Backflip Ninja can: Block Ninja can: Climb Ninja can: * Crouch */ public void onAction(String binding, boolean value, float tpf) { if (binding.equals("CharLeft")) { if (value) { left = true; } else { left = false; } } else if (binding.equals("CharRight")) { if (value) { right = true; } else { right = false; } } else if (binding.equals("CharUp")) { if (value) { up = true; } else { up = false; } } else if (binding.equals("CharDown")) { if (value) { down = true; } else { down = false; } } else if (binding.equals("CharSpace")) { // character.jump(); ninjaControl.jump(); } else if (binding.equals("attack") &amp;&amp; value) { // bulletControl(); Vector3f origin = cam.getWorldCoordinates( inputManager.getCursorPosition(), 0.0f); Vector3f direction = cam.getWorldCoordinates( inputManager.getCursorPosition(), 0.0f); // direction.subtractLocal(origin).normalizeLocal(); // character.setWalkDirection(location); System.out.println("origin" + origin); System.out.println("direction" + direction); // character.setViewDirection(direction); animationChannel.setAnim("Attack3"); animationChannel.setLoopMode(LoopMode.DontLoop); } else if (binding.equals("attack2-") &amp;&amp; value) { // bulletControl(); Vector3f origin2 = cam.getWorldCoordinates( inputManager.getCursorPosition(), 0.0f); Vector3f direction2 = cam.getWorldCoordinates( inputManager.getCursorPosition(), 0.0f); // direction.subtractLocal(origin).normalizeLocal(); // character.setWalkDirection(location); System.out.println("origin" + origin2); System.out.println("direction" + direction2); // character.setViewDirection(direction); animationChannel.setAnim("SideKick"); animationChannel.setLoopMode(LoopMode.DontLoop); } } public void onAnimCycleDone(AnimControl control, AnimChannel channel, String animName) { if (channel == shootingChannel) { channel.setAnim("Idle1"); } } public void onAnimChange(AnimControl control, AnimChannel channel, String animName) { } public Node getGameLevel() { return gameLevel; } public void setGameLevel(Node gameLevel) { this.gameLevel = gameLevel; } public static boolean isUseHttp() { return useHttp; } public static void setUseHttp(boolean useHttp) { PyramidLevel.useHttp = useHttp; } public BulletAppState getBulletAppState() { return bulletAppState; } public void setBulletAppState(BulletAppState bulletAppState) { this.bulletAppState = bulletAppState; } public AnimChannel getChannel() { return channel; } public void setChannel(AnimChannel channel) { this.channel = channel; } public AnimControl getControl() { return control; } public void setControl(AnimControl control) { this.control = control; } public BetterCharacterControl getGoblincharacter() { return goblinControl; } public void setGoblincharacter(BetterCharacterControl goblincharacter) { this.goblinControl = goblincharacter; } public BetterCharacterControl getCharacterControl() { return ninjaControl; } public void setCharacterControl(BetterCharacterControl characterControl) { this.ninjaControl = characterControl; } public Node getCharacterNode() { return ninjaNode; } public void setCharacterNode(Node characterNode) { this.ninjaNode = characterNode; } public boolean isRotate() { return rotate; } public void setRotate(boolean rotate) { this.rotate = rotate; } public Vector3f getWalkDirection() { return walkDirection; } public void setWalkDirection(Vector3f walkDirection) { this.walkDirection = walkDirection; } public Vector3f getViewDirection() { return viewDirection; } public void setViewDirection(Vector3f viewDirection) { this.viewDirection = viewDirection; } public boolean isLeftStrafe() { return leftStrafe; } public void setLeftStrafe(boolean leftStrafe) { this.leftStrafe = leftStrafe; } public boolean isRightStrafe() { return rightStrafe; } public void setRightStrafe(boolean rightStrafe) { this.rightStrafe = rightStrafe; } public boolean isForward() { return forward; } public void setForward(boolean forward) { this.forward = forward; } public boolean isBackward() { return backward; } public void setBackward(boolean backward) { this.backward = backward; } public boolean isLeftRotate() { return leftRotate; } public void setLeftRotate(boolean leftRotate) { this.leftRotate = leftRotate; } public boolean isRightRotate() { return rightRotate; } public void setRightRotate(boolean rightRotate) { this.rightRotate = rightRotate; } public Node getModel() { return goblinNode; } public void setModel(Node model) { this.goblinNode = model; } public Spatial getGoblin() { return goblin; } public void setGoblin(Spatial goblin) { this.goblin = goblin; } public RigidBodyControl getTerrainPhysicsNode() { return terrainPhysicsNode; } public void setTerrainPhysicsNode(RigidBodyControl terrainPhysicsNode) { this.terrainPhysicsNode = terrainPhysicsNode; } public AnimChannel getAnimationChannel() { return animationChannel; } public void setAnimationChannel(AnimChannel animationChannel) { this.animationChannel = animationChannel; } public AnimChannel getShootingChannel() { return shootingChannel; } public void setShootingChannel(AnimChannel shootingChannel) { this.shootingChannel = shootingChannel; } public AnimControl getAnimationControl() { return animationControl; } public void setAnimationControl(AnimControl animationControl) { this.animationControl = animationControl; } public float getAirTime() { return airTime; } public void setAirTime(float airTime) { this.airTime = airTime; } public boolean isLeft() { return left; } public void setLeft(boolean left) { this.left = left; } public boolean isRight() { return right; } public void setRight(boolean right) { this.right = right; } public boolean isUp() { return up; } public void setUp(boolean up) { this.up = up; } public boolean isDown() { return down; } public void setDown(boolean down) { this.down = down; } public boolean isAttack() { return attack; } public void setAttack(boolean attack) { this.attack = attack; } public ChaseCamera getChaseCam() { return chaseCam; } public void setChaseCam(ChaseCamera chaseCam) { this.chaseCam = chaseCam; } public boolean isWalkMode() { return walkMode; } public void setWalkMode(boolean walkMode) { this.walkMode = walkMode; } public FilterPostProcessor getFpp() { return fpp; } public void setFpp(FilterPostProcessor fpp) { this.fpp = fpp; } public Spatial getSceneModel() { return sceneModel; } public void setSceneModel(Spatial sceneModel) { this.sceneModel = sceneModel; } public RigidBodyControl getLandscape() { return landscape; } public void setLandscape(RigidBodyControl landscape) { this.landscape = landscape; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T01:01:28.600", "Id": "41645", "Score": "5", "body": "Is that all one huge god class?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T05:16:54.040", "Id": "41652", "Score": "0", "body": "@HovercraftFullOfEels Yes, this is the level class it's just one class for one level. The API already has classes for charactercontrol and so, so I've done classes for personalities e.g. \"GoblinPersonality\" to distinguish them from the character and the control which are already defined in the API. It can be good to modularize the project more into cohesive classes and smaller unit, you're probably right if that's what you're thinking that my project can benefit from modularizing more into classes so I could have a class that is `SceneCreator.class` which creates the game scene." } ]
[ { "body": "<p>Overall, your code looks quite good. There is something however which you can simplify <strong>a lot</strong>.</p>\n\n<p>Consider these two code-parts:</p>\n\n<pre><code>if (!ninjaControl.isOnGround()) {\n airTime = airTime + tpf;\n} else {\n airTime = 0;\n}\n\nif (binding.equals(\"CharLeft\")) {\n if (value) {\n left = true;\n } else {\n left = false;\n }\n} else if (binding.equals(\"CharRight\")) {\n ...\n</code></pre>\n\n<p>All this follows the pattern</p>\n\n<pre><code>if (condition) { value = a; } else { value = b; }\n</code></pre>\n\n<p>which can be simplified using the <a href=\"http://en.wikipedia.org/wiki/%3F%3a\">Ternary operator</a> to</p>\n\n<pre><code>value = (condition ? a : b);\n</code></pre>\n\n<p>Using this operator, we can write:</p>\n\n<pre><code>airTime = (!ninjaControl.isOnGround() ? airTime + tpf : 0);\n\nif (binding.equals(\"CharLeft\")) {\n left = (value ? true : false);\n} else if (binding.equals(\"CharRight\")) {\n ...\n</code></pre>\n\n<p>However, since we set <code>left</code> to <code>true</code> if <code>value</code> is <code>true</code> and to <code>false</code> if <code>value</code> is <code>false</code>, we are essentially setting it <strong>to the same value as <code>value</code></strong>. So this series of if-else statements can be shortened to:</p>\n\n<pre><code>if (binding.equals(\"CharLeft\")) {\n left = value;\n} else if (binding.equals(\"CharRight\")) {\n right = value;\n} else if (binding.equals(\"CharUp\")) {\n up = value;\n} else if (binding.equals(\"CharDown\")) {\n down = value;\n}\n</code></pre>\n\n<p>Besides this, my only suggestion would be to split up methods when they become too long, there are some of your methods that are on the edge of what I would call \"too long\" so this can be something to think about.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-28T19:10:24.277", "Id": "36310", "ParentId": "26729", "Score": "11" } } ]
{ "AcceptedAnswerId": "36310", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T00:48:02.673", "Id": "26729", "Score": "6", "Tags": [ "java", "game", "ai" ], "Title": "Dangerworld game" }
26729
<p>I have a handful of objects that don't have references to each-other that all need to receive an update. </p> <p>From what I've read, it seems like a Publish-Subscribe Messaging Channel is an appropriate pattern. Searching for an existing solution mainly turned up messaging libraries for application integration (between processes). Those solutions were much more than what I needed, so I wrote this simple Publisher.</p> <p>Questions:</p> <ul> <li>Is there already something simple like this in the .NET framework that I overlooked? Or another light-weight library?</li> <li>Is this an appropriate implementation and application of the Pub/Sub pattern? What might be done to improve it?</li> <li>What gotchas are there? For example, I presume I need to Unsubscribe in the subscriber's finalizer.</li> </ul> <hr> <pre><code>public interface ISubscriber { void SubscriptionUpdate(object message); } public interface IPublisher { void Subscribe(ISubscriber subscriber, string channel); void Unsubscribe(ISubscriber subscriber, string channel); void Publish(string channel, object message); } public class Publisher : IPublisher { static Publisher _instance = new Publisher(); public static Publisher Instance { get { return _instance; } } Dictionary&lt;string, List&lt;ISubscriber&gt;&gt; _subscribers = new Dictionary&lt;string, List&lt;ISubscriber&gt;&gt;(); public void Subscribe(ISubscriber subscriber, string channel) { if (!Exists(channel)) _subscribers[channel] = new List&lt;ISubscriber&gt;(); if (!_subscribers[channel].Contains(subscriber)) _subscribers[channel].Add(subscriber); } public void Unsubscribe(ISubscriber subscriber, string channel) { if (Exists(channel)) _subscribers[channel].Remove(subscriber); } public void Publish(string channel, object message) { if (!Exists(channel)) return; foreach (var subscriber in _subscribers[channel]) subscriber.SubscriptionUpdate(message); } bool Exists(string channel) { return _subscribers.ContainsKey(channel); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T11:53:14.583", "Id": "41449", "Score": "0", "body": "\" I presume I need to Unsubscribe in the subscriber's finalizer.\" If not unsubscribing will prevent the subscriber from being GCed, who would call the finalizer? Maybe you want a `Dispose` instead? Or [Weak Event Pattern](http://msdn.microsoft.com/en-us/library/aa970850.aspx)?" } ]
[ { "body": "<p>Don't think it's a good approach.</p>\n\n<ul>\n<li><a href=\"http://blogs.msdn.com/b/scottdensmore/archive/2004/05/25/140827.aspx\" rel=\"nofollow\">Singletons are evil</a> by themselves </li>\n<li>Subscribers are likely to expect a specific type of message on specific channel</li>\n<li>Magic strings that specify the channel name are also potential source of bugs</li>\n<li>Incorrect messages or posts to wrong channels are detected at run-time only.</li>\n<li>Logical dependency between objects still exist, but is hidden.</li>\n</ul>\n\n<p>.NET already has a notion of in-process publish/subscribe, and (not that surprisingly) this functionality is covered by events... All you need to do is to wire up all your entities properly, and that's your actual challenge is.</p>\n\n<p>I would recommend using any of available IoC frameworks for that (I use Autofac at the moment).</p>\n\n<ul>\n<li>You will have a strictly-typed communication protocol between publisher and subscriber</li>\n<li>It will allow you to explicitly declare dependency on a certain external functionality in your classes. </li>\n<li>It will simplify unit-testing of your classes</li>\n</ul>\n\n<p>Unfortunately you haven't described specific use cases for your pub/sub requirement so it's hard to show this solution on specific example</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T20:09:15.053", "Id": "41488", "Score": "0", "body": "I did end up using an `event`, and the design is cleaner and safer as you suggest. However, it's worth pointing out that typical event usage forces filtering to be done by the receiver. An intermediary is nice to filter the events (which is one of the important features of the Publisher above)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T07:40:33.887", "Id": "41517", "Score": "0", "body": "You don't need to filter events, just create several events and raise only relevant ones... Treat each \"channel\" (in terms of your solution) as a separate event declaration on one of the interfaces" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T19:00:09.093", "Id": "41600", "Score": "0", "body": "In the context of this discussion (pub/sub), that may not work. Channel names can be data-driven." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T07:41:48.053", "Id": "26737", "ParentId": "26730", "Score": "2" } } ]
{ "AcceptedAnswerId": "26737", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T02:30:13.193", "Id": "26730", "Score": "2", "Tags": [ "c#", "design-patterns" ], "Title": "Local (In-Process) Publish/Subscribe" }
26730
<p>This is sort of a follow-up to a post I created about 10 days ago, but I have completed the implementation: <a href="https://codereview.stackexchange.com/questions/26331/designing-function-prototypes-for-a-singly-linked-list-api-in-c">Designing function prototypes for a singly-linked list API in C</a>.</p> <p>As I began to work on the implementation, I chose to change some of the functions and to move things around a little. This post includes source for the header, followed by the source code for the implementation.</p> <p>There are 10 API functions.</p> <p>Here is my number one concern: if I run Valgrind on a test file that does a lot of operations, I don't have any noticeable memory leaks, but Valgrind complains that <code>sllist_destroy()</code> performs an invalid <code>free()</code>. That is, it attempts to free something that is either already freed or not at the beginning of a heap block. This saddens me, as I cannot figure out why this is occurring. So please take careful notice of the <code>sllist_destroy()</code> function.</p> <p>I'm also interested in opinions on opaque versus non-opaque. I have left the structs visible in the header for now, but I'm open to suggestions.</p> <p>The third thing I'd like to have some feedback on is return points. I don't know how sane my choices are there, as I know some people advocate single exit points for functions.</p> <p><b>Header:</b> Please note that I am using Doxygen for documentation, so if you see something unfamiliar in my comments, it is because it is Doxygen syntax.</p> <p><code>sllist.h</code></p> <pre><code>#ifndef SLLIST_H #define SLLIST_H /** * @file sllist.h * @brief Stuctures and functions for a singly-linked list API. * * The user is provided with several different functions to manipulate lists * and associated data. */ /** * The node structure. * * The purpose of this structure is to actually hold the data or "payload" to be * stored in the list. The nodes are connected sequentially, and thus each node * requires a second field to store the address of the next node. */ struct lnode { void *data; struct lnode *next; }; /** * The list structure. * * Metadata is contained here. A pointer to the first and last nodes in the list * allows for several operations to be performed more quickly. There is also * another pointer-to-node member variable for storing the location of a * "current" or active node that presumably will have operations performed on * it. Finally there is a size variable containing the total number of nodes. * Note that the first index of the list is considered index zero. */ struct sllist { struct lnode *head; struct lnode *tail; struct lnode *current; int size; }; /** * Create a new list. * * Returns a pointer to a new, empty list. If allocation fails, returns NULL. */ struct sllist* sllist_create(void); /** * Destroy a list. * * Frees the memory of the list struct and all associated nodes. */ void sllist_destroy(struct sllist *sllist); /** * Prepend a node to the list: * * Adds a node to the front of the list. If allocation fails, returns -1, * otherwise returns 0. */ int sllist_push_front(struct sllist *sllist, void *data); /** * Append node to a list. * * Adds a node to the end of the list. If allocation fails, returns -1, * otherwise returns 0. */ int sllist_push_back(struct sllist *sllist, void *data); /** * Extract the first node. * * Remove the first node from the linked list, save a pointer to the data, free * the node (but do not free the data itself), and return a pointer to the data * so that it can be used. If the list is empty, returns NULL. */ void* sllist_pop_front(struct sllist *sllist); /** * Extract the last node. * * Remove the last node from the linked list, save a pointer to the data, free * the node (but do not free the data itself), and return a pointer to the data * so that it can be used. If the list is empty, returns NULL. */ void* sllist_pop_back(struct sllist *sllist); /** * Step through a list. * * Changes the current node to the node after the current node. Returns 1 if * the current node is NULL. */ int sllist_step(struct sllist *sllist); /** * Access data by index. * * Returns a pointer to the payload of the node at the location specified by the * passed index value. The passed index value is interpreted as an offset from * index zero, the first node of the list. Returns NULL if the list is empty or * the index is out of range. */ void* sllist_read_index(struct sllist *sllist, int index); /** * Insert a node after the node at the specified index. * * Adds a node after the passed node. If allocation fails, returns -1. If the * node doesn't exist in the list, returns 1. Otherwise, returns 0. */ int sllist_insert_after(struct sllist *sllist, int index, void *data); /** * Extract a node after the node at the specified index. * * Remove the specified node from the linked list, save a pointer to the data, * free the node (but do not free the data itself), and return a pointer to the * data so that it can be used. If the list is empty or the node doesn't exist * in the list, returns NULL. Attempting to extract after the tail will also * return NULL. */ void* sllist_extract_after(struct sllist *sllist, int index); #endif </code></pre> <p><b>Implementation:</b></p> <p><code>sllist.c</code></p> <pre><code>#include &lt;stdlib.h&gt; #include "sllist.h" struct sllist* sllist_create(void) { struct sllist *sllist; sllist = malloc(sizeof(struct sllist)); if (sllist != NULL) { sllist-&gt;head = NULL; sllist-&gt;tail = NULL; sllist-&gt;current = NULL; sllist-&gt;size = 0; } return sllist; } void sllist_destroy(struct sllist *sllist) { struct lnode *save_next; sllist-&gt;current = sllist-&gt;head; while(sllist-&gt;current != NULL) { save_next = sllist-&gt;current-&gt;next; free(sllist-&gt;current-&gt;data); free(sllist-&gt;current); sllist-&gt;current = save_next; } free(sllist); } int sllist_push_front(struct sllist *sllist, void *data) { struct lnode *lnode; lnode = malloc(sizeof(struct lnode)); if (lnode == NULL) return -1; lnode-&gt;data = data; lnode-&gt;next = sllist-&gt;head; sllist-&gt;head = lnode; if (sllist-&gt;size == 0) sllist-&gt;tail = lnode; sllist-&gt;size++; return 0; } int sllist_push_back(struct sllist *sllist, void *data) { struct lnode *lnode; lnode = malloc(sizeof(struct lnode)); if (lnode ==NULL) return -1; lnode-&gt;data = data; lnode-&gt;next = NULL; if (sllist-&gt;size == 0) { sllist-&gt;head = lnode; sllist-&gt;tail = lnode; } else { sllist-&gt;tail-&gt;next = lnode; sllist-&gt;tail = lnode; } sllist-&gt;size++; return 0; } void* sllist_pop_front(struct sllist *sllist) { if (sllist-&gt;size == 0) return NULL; void* data = sllist-&gt;head-&gt;data; struct lnode *save_head = sllist-&gt;head; if (sllist-&gt;size == 1) { sllist-&gt;head = NULL; sllist-&gt;tail = NULL; //Clear current since it shouldn't be used. sllist-&gt;current = NULL; } else { sllist-&gt;head = sllist-&gt;head-&gt;next; } free(save_head); sllist-&gt;size--; return data; } void* sllist_pop_back(struct sllist *sllist) { if (sllist-&gt;size == 0) return NULL; void *data = sllist-&gt;tail-&gt;data; struct lnode *save_tail = sllist-&gt;tail; if (sllist-&gt;size == 1) { sllist-&gt;head = NULL; sllist-&gt;tail = NULL; //Clear current since it shouldn't be used. sllist-&gt;current = NULL; } else { struct lnode *new_tail = sllist-&gt;head; while(new_tail-&gt;next-&gt;next != NULL) new_tail = new_tail-&gt;next; sllist-&gt;tail = new_tail; sllist-&gt;tail-&gt;next = NULL; } free(save_tail); sllist-&gt;size--; return data; } int sllist_step(struct sllist *sllist) { if (sllist-&gt;current == NULL) return 1; else { sllist-&gt;current = sllist-&gt;current-&gt;next; return 0; } } void* sllist_read_index(struct sllist *sllist, int index) { if ( ((sllist-&gt;size - index - 1) &lt; 0 ) || (index &lt; 0) ) return NULL; struct lnode *target; target = sllist-&gt;head; for(int i = 0; i &lt; index; i++) target = target-&gt;next; return (target-&gt;data); } int sllist_insert_after(struct sllist *sllist, int index, void *data) { if ( ((sllist-&gt;size - index - 1) &lt; 0 ) || (index &lt; 0) ) return 1; struct lnode *target; target = sllist-&gt;head; for(int i = 0; i &lt; index; i++) target = target-&gt;next; struct lnode *lnode; lnode = malloc(sizeof(struct lnode)); if (lnode == NULL) return -1; lnode-&gt;data = data; lnode-&gt;next = target-&gt;next; target-&gt;next = lnode; if (index == sllist-&gt;size - 1) //if inserting after tail sllist-&gt;tail = lnode; sllist-&gt;size++; return 0; } void* sllist_extract_after(struct sllist *sllist, int index) { if ( ((sllist-&gt;size - index - 2) &lt; 0 ) || (index &lt; 0) ) return NULL; struct lnode *target; target = sllist-&gt;head; for(int i = 0; i &lt; index; i++) target = target-&gt;next; if (index == sllist-&gt;size - 1) //if extracting tail sllist-&gt;tail = target; void *data = target-&gt;next-&gt;data; struct lnode *save_obsolete = target-&gt;next; target-&gt;next = target-&gt;next-&gt;next; free(save_obsolete); sllist-&gt;size--; return data; } </code></pre> <p>If you've made it this far, all I ask is for your most exacting criticism.</p> <p>As requested, here is the portion of do-nothing code that generates the Valgrind error:</p> <pre><code>#include &lt;stdlib.h&gt; #include "sllist.h" int main(void) { struct sllist *nums; nums = sllist_create(); int *number; for(int i = 0; i &lt; 2000; i++) { number = malloc(sizeof(int)); *number = i; sllist_push_front(nums, number); sllist_push_back(nums, number); } number = sllist_pop_front(nums); //testing multiple different things free(number); number = sllist_pop_back(nums); free(number); sllist_destroy(nums); } </code></pre> <p>Further, if anyone is interested in seeing the glib-2.0 testing API in action, I used it in this project to see how it works. Here is my unit test code:</p> <p><code>unit.c</code></p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;glib.h&gt; #include "sllist.h" /* Types of lists to test: * empty lists * lists with 1 element * lists with 2 elements * lists with multiple elements */ //Singly linked list fixture. A wrapper for sllist struct, for testing. struct sll_fix { struct sllist *sllist; }; //Prepare fixture for testing an empty list. static void sll_setup(struct sll_fix *sll_f, gconstpointer ignored) { sll_f-&gt;sllist = sllist_create(); } static void sll_teardown(struct sll_fix *sll_f, gconstpointer ignored) { sllist_destroy(sll_f-&gt;sllist); } //Prepare fixture for testing push_front operation. static void sll_setup_pf(struct sll_fix *sll_f, gconstpointer ignored) { sll_f-&gt;sllist = sllist_create(); int *testp; testp = malloc(sizeof(int) * 10); for(int i = 0; i &lt; 10; i++) testp[i] = i * 10; sllist_push_front(sll_f-&gt;sllist, testp); } //Prepare fixture for testing push_back operation. static void sll_setup_pb(struct sll_fix *sll_f, gconstpointer ignored) { sll_f-&gt;sllist = sllist_create(); int *testp; testp = malloc(sizeof(int) * 10); for(int i = 0; i &lt; 10; i++) testp[i] = i * 10; sllist_push_back(sll_f-&gt;sllist, testp); } //Prepare fixture for testing pop operation. static void sll_setup_pop(struct sll_fix *sll_f, gconstpointer ignored) { sll_f-&gt;sllist = sllist_create(); int *testp_1; int *testp_2; int *testp_3; testp_1 = malloc(sizeof(int) * 10); testp_2 = malloc(sizeof(int) * 10); testp_3 = malloc(sizeof(int) * 10); for(int i = 0; i &lt; 10; i++) { testp_1[i] = i * 10; testp_2[i] = i * 20; testp_3[i] = i * 30; } sllist_push_back(sll_f-&gt;sllist, testp_1); sllist_push_back(sll_f-&gt;sllist, testp_2); sllist_push_back(sll_f-&gt;sllist, testp_3); } //Prepare fixture for testing step operation. static void sll_setup_step(struct sll_fix *sll_f, gconstpointer ignored) { sll_f-&gt;sllist = sllist_create(); int *testp_1; int *testp_2; int *testp_3; testp_1 = malloc(sizeof(int) * 10); testp_2 = malloc(sizeof(int) * 10); testp_3 = malloc(sizeof(int) * 10); for(int i = 0; i &lt; 10; i++) { testp_1[i] = i * 10; testp_2[i] = i * 20; testp_3[i] = i * 30; } sllist_push_back(sll_f-&gt;sllist, testp_1); sllist_push_back(sll_f-&gt;sllist, testp_2); sllist_push_back(sll_f-&gt;sllist, testp_3); } //Prepare fixture for testing a lengthy list (100 elements.) static void sll_setup_lengthy(struct sll_fix *sll_f, gconstpointer ignored) { sll_f-&gt;sllist = sllist_create(); int *testp; for(int i = 0; i &lt; 100; i++) { testp = malloc(sizeof(int) * 10); for(int j = 0; j &lt; 10; j++) testp[j] = j * 10; sllist_push_back(sll_f-&gt;sllist, testp); } } //Procedure for testing an empty list static void check_create(struct sll_fix *sll_f, gconstpointer ignored) { sll_setup(sll_f, ignored); g_assert(sll_f-&gt;sllist-&gt;head == NULL); g_assert(sll_f-&gt;sllist-&gt;tail == NULL); g_assert(sll_f-&gt;sllist-&gt;current == NULL); g_assert(sll_f-&gt;sllist-&gt;size == 0); } //Procedure for testing a push_front operation on an empty list. static void check_pf(struct sll_fix *sll_f, gconstpointer ignored) { sll_setup_pf(sll_f, ignored); int *int_arr; int_arr = sll_f-&gt;sllist-&gt;head-&gt;data; g_assert(sll_f-&gt;sllist-&gt;size == 1); for(int i = 0; i &lt; 10; i++) g_assert(int_arr[i] == i * 10); } //Procedure for testing a push_back operation on an empty list static void check_pb(struct sll_fix *sll_f, gconstpointer ignored) { sll_setup_pb(sll_f, ignored); int *int_arr; int_arr = sll_f-&gt;sllist-&gt;head-&gt;data; g_assert(sll_f-&gt;sllist-&gt;size == 1); for(int i = 0; i &lt; 10; i++) g_assert(int_arr[i] == i * 10); } //Procedure for testing a pop_front operation on a list with 3 elements. static void check_popf(struct sll_fix *sll_f, gconstpointer ignored) { sll_setup_pop(sll_f, ignored); int* int_arr; int loop_ctr = 1; while ((int_arr = sllist_pop_front(sll_f-&gt;sllist))) { for(int i = 0; i &lt; 10; i++) g_assert(int_arr[i] == 10 * loop_ctr * i); loop_ctr++; } } //Procedure for testing a pop_back operation on a list with 3 elements. static void check_popb(struct sll_fix *sll_f, gconstpointer ignored) { sll_setup_pop(sll_f, ignored); int* int_arr; int loop_ctr = 3; while((int_arr = sllist_pop_back(sll_f-&gt;sllist))) { for(int i = 0; i &lt; 10; i++) g_assert(int_arr[i] == 10 * loop_ctr * i); loop_ctr--; } } //Procedure for testing a step operation on a list with 3 elements. static void check_step(struct sll_fix *sll_f, gconstpointer ignored) { sll_setup_step(sll_f, ignored); int *int_arr_1; int *int_arr_2; int *int_arr_3; int_arr_1 = sll_f-&gt;sllist-&gt;head-&gt;data; int_arr_2 = sll_f-&gt;sllist-&gt;head-&gt;next-&gt;data; int_arr_3 = sll_f-&gt;sllist-&gt;head-&gt;next-&gt;next-&gt;data; g_assert(sll_f-&gt;sllist-&gt;size == 3); for(int i = 0; i &lt; 10; i++) { g_assert(int_arr_1[i] == i * 10); g_assert(int_arr_2[i] == i * 20); g_assert(int_arr_3[i] == i * 30); } int *int_arr; int loop_ctr = 1; sll_f-&gt;sllist-&gt;current = sll_f-&gt;sllist-&gt;head; while(sll_f-&gt;sllist-&gt;current != NULL) { int_arr = sll_f-&gt;sllist-&gt;current-&gt;data; for(int i = 0; i &lt; 10; i++) g_assert(int_arr[i] == 10 * loop_ctr * i); sllist_step(sll_f-&gt;sllist); loop_ctr++; } } //Procedure for testing a read_index operation on a list with 100 elements. static void check_ri(struct sll_fix *sll_f, gconstpointer ignored) { sll_setup_lengthy(sll_f, ignored); int *int_arr; sll_f-&gt;sllist-&gt;current = sll_f-&gt;sllist-&gt;head; for(int i = 0; i &lt; sll_f-&gt;sllist-&gt;size; i++) { int_arr = sllist_read_index(sll_f-&gt;sllist, i); for(int j = 0; j &lt; 10; j++) g_assert(int_arr[j] == j * 10); sllist_step(sll_f-&gt;sllist); } } //Procedure for testing an insert_after operation on a list with 100 elements. static void check_ia(struct sll_fix *sll_f, gconstpointer ignored) { sll_setup_lengthy(sll_f, ignored); int *int_arr; int_arr = malloc(sizeof(int) * 10); for(int i = 0; i &lt; 10; i++) int_arr[i] = 314159 * i; g_assert(!sllist_insert_after(sll_f-&gt;sllist, 0, int_arr)); g_assert(!sllist_insert_after(sll_f-&gt;sllist, 1, int_arr)); g_assert(!sllist_insert_after(sll_f-&gt;sllist, 50, int_arr)); g_assert(!sllist_insert_after(sll_f-&gt;sllist, 102, int_arr)); int_arr = sllist_read_index(sll_f-&gt;sllist, 0); for(int i = 0; i &lt; 10; i++) g_assert(int_arr[i] == i * 10); int_arr = sllist_read_index(sll_f-&gt;sllist, 1); for(int i = 0; i &lt; 10; i++) g_assert(int_arr[i] == 314159 * i); int_arr = sllist_read_index(sll_f-&gt;sllist, 2); for(int i = 0; i &lt; 10; i++) g_assert(int_arr[i] == 314159 * i); int_arr = sllist_read_index(sll_f-&gt;sllist, 51); for(int i = 0; i &lt; 10; i++) g_assert(int_arr[i] == 314159 * i); int_arr = sllist_read_index(sll_f-&gt;sllist, 52); for(int i = 0; i &lt; 10; i++) g_assert(int_arr[i] == i * 10); int_arr = sllist_read_index(sll_f-&gt;sllist, 103); for(int i = 0; i &lt; 10; i++) g_assert(int_arr[i] == 314159 * i); } //Procedure for testing an extract_after operation on a list with 100 elements. static void check_ea(struct sll_fix *sll_f, gconstpointer ignored) { sll_setup_lengthy(sll_f, ignored); int *int_arr = malloc(sizeof(int) * 10); int_arr = sllist_extract_after(sll_f-&gt;sllist, 98); g_assert(sll_f-&gt;sllist-&gt;size == 99); g_assert(int_arr != NULL); int_arr = sllist_extract_after(sll_f-&gt;sllist, 98); g_assert(int_arr == NULL); } //Run tests in the order they appear in this file. int main(int argc, char *argv[]) { g_test_init(&amp;argc, &amp;argv, NULL); g_test_add("/test/sll_create test", struct sll_fix, NULL, sll_setup, check_create, sll_teardown); g_test_add("/test/sll_push_front test", struct sll_fix, NULL, sll_setup_pf, check_pf, sll_teardown); g_test_add("/test/sll_push_back test", struct sll_fix, NULL, sll_setup_pb, check_pb, sll_teardown); g_test_add("/test/sll_pop_front test", struct sll_fix, NULL, sll_setup_pop, check_popf, sll_teardown); g_test_add("/test/sll_pop_back test", struct sll_fix, NULL, sll_setup_pop, check_popb, sll_teardown); g_test_add("/test/sll_step test", struct sll_fix, NULL, sll_setup_step, check_step, sll_teardown); g_test_add("/test/sll_read_index test", struct sll_fix, NULL, sll_setup_lengthy, check_ri, sll_teardown); g_test_add("/test/sll_insert_after test", struct sll_fix, NULL, sll_setup_lengthy, check_ia, sll_teardown); g_test_add("/test/sll_extract_after test", struct sll_fix, NULL, sll_setup_lengthy, check_ea, sll_teardown); return g_test_run(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T16:59:43.117", "Id": "41479", "Score": "0", "body": "I don't see a problem with _sllist_destroy_. Do you have a minimal program that uses your library to elicit the Valgrind complaint? If you do, could you please attach it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T20:27:22.427", "Id": "41489", "Score": "0", "body": "Hi Wayne, I've added the code that causes the invalid free() error. Thanks for your time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T00:53:16.877", "Id": "41498", "Score": "0", "body": "OK, I see the memory error. I'll amend my answer. By the way, I can tell you from personal experience that if you run valgrind with `valgrind test` instead of `valgrind ./test`, you will be horribly confused as to why it doesn't seem to have any memory problems. :)" } ]
[ { "body": "<p>This is a clean and well documented API: There is little reason to have to read to the code to know how to use it. The only thing I see missing from the comment is any mention of what happens to the cursor (<em>sllist.current</em>) when the list is modified.</p>\n\n<p>The memory error is because your code is pushing the same node onto the list twice:</p>\n\n<pre><code>sllist_push_front(nums, number);\nsllist_push_back(nums, number);\n</code></pre>\n\n<p>In order for that to work, the second push will need its own malloc.</p>\n\n<p>Multiple return points are only a problem if a function is too large for them to be easy to spot. The solution: Don't write large functions. Your functions are not too large, so it's not a problem.</p>\n\n<p>The only suggestion I have would be not minor surgery, but a complete redesign. I'll mention it here not because it has anything to do with your question, but because you may not have considered it. Below the fold:</p>\n\n<hr>\n\n<p>If you are able to switch to a doubly linked with with a dummy (root) node to serve as the head/tail, then linked list code can be simplified considerably, and most operations--such as insertion before or after an arbitrary node, or removing a node from a list--can be done very efficiently without any linear searches over the list, and with very little conditional logic.</p>\n\n<pre><code>struct Node {\n struct void *data;\n struct Node *prev;\n struct Node *next;\n};\n</code></pre>\n\n<p>A special node is the \"dummy\" node, which serves as both the head and tail of the list (in this sketch I will ignore dynamic allocation). The root node is initialized like so:</p>\n\n<pre><code>void init_list(Node * node) {\n node-&gt;prev = node;\n node-&gt;next = next;\n node-&gt;data = NULL; \n}\n</code></pre>\n\n<p>The dummy/root node always has a NULL data pointer. A non-dummy node always has a <em>non</em>-NULL data pointer.</p>\n\n<p>insertion after an arbitrary node is trivial:</p>\n\n<pre><code>void insert_after(Node * pred, Node * node) {\n node-&gt;pred = pred;\n node-&gt;next = pred-&gt;next;\n pred-&gt;next-&gt;pred = node;\n pred-&gt;next = node;\n}\n</code></pre>\n\n<p>insertion before an arbitrary node:</p>\n\n<pre><code>void insert_before(Node * next, Node * node) {\n insert_after(next-&gt;pred, node);\n}\n</code></pre>\n\n<p>The node being inserted before or after can be the dummy (root) node--the same logic works. Whether inserting at the head or tail, or before or after an arbitrary node, no list traversal is needed.</p>\n\n<p>Return true if the node is a dummy (root) node. This is used to detect the end of list:</p>\n\n<pre><code>bool dummy_node(Node * node) {\n node-&gt;data == NULL;\n}\n</code></pre>\n\n<p>One advantage of this structure is that no separate cursor (<em>current node</em>) is needed. Every node pointer is automatically a cursor.</p>\n\n<pre><code>Node * next_node(Node * node) {return node-&gt;next;}\nNode * prev_node(Node * node) {return node-&gt;prev;}\n\nNode * node = next_node(dummy);\nwhile(!dummy_node(node))\n node = next_node(node);\n</code></pre>\n\n<p>The big disadvantage of this approach, compared to yours, is that a cursor is not integrated into the list. That means a cursor cannot be automatically invalidated when the list changes, as your code does. In every other way, I believe this approach to be simpler and more efficient to implement. It is, however, necessarily a complete redesign of the API. That's why it is out of scope in answering your original question.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T17:43:50.507", "Id": "41482", "Score": "0", "body": "Thank you for you well-reasoned reply. I am glad that you pointed out that the documentation makes no mention of what happens to the `current` node. I will add this to the documentation. You have also brought to my attention that in the function `sllist_extract_after()` I forget to check whether I need to invalidate `current`, since my intention was to assign a NULL pointer to any invalid node references to make errors more obvious. Regarding your redesign, I have definitely given it much thought, and I actually intended from the beginning to do a full API suite involving dllists, hashes, etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T02:49:49.133", "Id": "41502", "Score": "0", "body": "About the memory error: Wow, now I feel silly. I don't know why I didn't realize that. I just wrote the test very quickly and thought, hm, I'll just reuse this same data. Yeah, thanks for keeping me sane." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T04:14:18.687", "Id": "41509", "Score": "0", "body": "@oddlogic, I'll bet you didn't feel as silly as I felt when I realized I had been running Valgrind on a Unix utility instead of your code. :) I'm just glad we got it sorted out. By the way, your code caused gcc to emit _no_ warnings even on the strict settings I prefer. Nice job!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T07:31:51.540", "Id": "41516", "Score": "0", "body": "Thanks for the kind words. I usually compile with -Wall as well. Also, I didn't even know there was a utility called 'test', but I typed 'man test', and there it was!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T16:44:54.543", "Id": "26758", "ParentId": "26732", "Score": "4" } }, { "body": "<p>The code looks nice and compiles cleanly. One thing that I guess you have\nheard before is to use braces on conditions (etc) even when strictly unnecessary. </p>\n\n<pre><code>if (lnode == NULL) {\n return -1;\n}\n</code></pre>\n\n<p>Yes, it is ugly, but it is generally accepted as being safer. I hate doing it too,\nbut sometimes ugly really is better...</p>\n\n<hr>\n\n<p>I prefer to see variables initialised immediately where possible, so for example:</p>\n\n<pre><code>struct sllist *sllist;\nsllist = malloc(sizeof(struct sllist));\n</code></pre>\n\n<p>is written:</p>\n\n<pre><code>struct sllist *sllist = malloc(sizeof(struct sllist));\n</code></pre>\n\n<hr>\n\n<p>In <code>sllist_pop_back</code>, I'd prefer to see the loop that finds the end of the\nlist extracted into a separate static inline function.</p>\n\n<hr>\n\n<p>Your last three functions all contain an expression that determines whether\n<code>index</code> exceeds the list size:</p>\n\n<pre><code>if ( ((sllist-&gt;size - index - 1) &lt; 0 ) || (index &lt; 0) )\n</code></pre>\n\n<p>Wouldn't it be easier to say:</p>\n\n<pre><code>if ((index &gt;= sllist-&gt;size) || (index &lt; 0))\n</code></pre>\n\n<hr>\n\n<p>Your last three functions all contain code to find a given entry in the list:</p>\n\n<pre><code>struct lnode *target = sllist-&gt;head;\nfor (int i = 0; i &lt; index; i++) {\n target = target-&gt;next;\n}\n</code></pre>\n\n<p>This should really be extracted into a static function.</p>\n\n<hr>\n\n<p>Nits: </p>\n\n<ul>\n<li><code>sllist_read_index</code> return statement has brackets. No other function has\nthem.</li>\n<li>I see no purpose in the <code>current</code> field. Nothing really uses it.</li>\n<li>The structures are not opaqe (and hence are open to client manipulation)</li>\n<li>You free all of the data pointers when destroying the list, which assumes\nthat the data was dynamically allocated. Best to state this restriction in\nthe interface. </li>\n<li>How does the client determine which 'index' to use in those functions taking\nan index? </li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T18:18:37.847", "Id": "41628", "Score": "0", "body": "All solid advice. I'll start with the \"nits\": I believe my rationale for 'index' is that the user conceivably have their own reasons for accessing a particular index. For example, if the list is created with some kind of order, say a list of prime numbers or something, index 6 would contain the 7th prime number.\nI think I am going to add some accessor functions and move the structs into the implementation. This would make `current` more sensible because it would provide an opaque way to move through the list, via `sllist_step`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T18:28:19.210", "Id": "41631", "Score": "0", "body": "The condition \n`if (abs(index) >= sllist->size)` treats negative values greater than or equal to `-index` as acceptable, but if I change it to \n`if ((abs(index) >= sllist->size) || (index < 0)` then I believe we've created a statement that more clearly expresses my intent than `if ( ((sllist->size - index - 1) < 0 ) || (index < 0) )` On the other hand, I then have to include `cmath.h`. I don't believe this is much of a problem, however. What are your thoughts? Everything else you've said I more or less totally agree with." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T23:40:53.300", "Id": "41644", "Score": "0", "body": "oops! Yes, `abs` is clearly wrong. You could use `(unsigned) index >= sllist->size` but that will provoke a conversion warning. I will change the answer..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T02:57:26.613", "Id": "26865", "ParentId": "26732", "Score": "1" } } ]
{ "AcceptedAnswerId": "26758", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T03:58:38.080", "Id": "26732", "Score": "4", "Tags": [ "c", "unit-testing", "linked-list", "memory-management", "library" ], "Title": "Singly-linked list library" }
26732
<p>Here I have two <code>DataTable</code>s:</p> <ul> <li>dtTotalDateRangeExcludeSundays </li> <li>dtAbsentsLeavesHolidaysWorks</li> </ul> <p>Each has 10k+ values, and I need to delete matched rows.</p> <pre><code>foreach (DataRow rw in dtTotalDateRangeExcludeSundays.Select()) { DateTime dateFromRange=Convert.ToDateTime(rw[0].ToString()); string strPrnt = dateFromRange.ToShortDateString(); foreach (DataRow row in dtAbsentsLeavesHolidaysWorks.Select()) { DateTime getDate = Convert.ToDateTime(row[0].ToString()); string strchild = getDate.ToShortDateString(); if (strPrnt == strchild) { rw.Delete(); } } } </code></pre> <p>I want to know if any better alternative suggestion, because the <code>foreach</code> loop takes time when bulk data is there. I am not good with Linq, so I want to know if any Linq tricks work.</p>
[]
[ { "body": "<p>Assuming that you load the data into your <code>DataTable</code> instances from database, it's better to issue a direct <code>DELETE FROM ...</code> query over database rather than iterate on a client.</p>\n\n<p>As a side note - it is an awful practice to compare dates by comparing strings. If your table has a <code>DateTime</code> column it's much better to cast the value to <code>DateTime</code> and compare typed dates like that:</p>\n\n<pre><code>DateTime dateFromRange = ((DateTime)rw[0]).Date;\n....\n\n DateTime getDate = ((DateTime)row[0]).Date;\n if (dateFromRange == getDate)\n....\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T07:57:25.583", "Id": "26738", "ParentId": "26736", "Score": "2" } }, { "body": "<p>First and foremost:</p>\n\n<ul>\n<li><p>Don't <code>Select()</code>. It's useless.<br>\n<code>foreach (var c in collection)</code> is equivalent to:<br>\n<code>foreach (var c in collection.Select())</code>, which is also the same as:<br>\n<code>foreach (var c in collection.Select(a =&gt; a).Select().Select().Select(b =&gt; b))</code>.</p></li>\n<li><p>Don't use column indexes. Column names are less error prone.</p></li>\n<li><p>Don't <code>ToString</code> a date to parse it immediately after in order to stringify it again. I imagine that this is what you do with the first row.</p></li>\n<li><p>Use uniform style. For example, putting spaces before and after <code>'='</code> in some places but not in others doesn't increase readability. <a href=\"http://stylecop.codeplex.com/\" rel=\"nofollow\">StyleCop</a> may help.</p></li>\n<li><p>Don't use Hungarian notation (you can read <a href=\"http://www.joelonsoftware.com/articles/Wrong.html\" rel=\"nofollow\">the article by Joel Spolsky</a> among others to know why).</p></li>\n<li><p>Use meaningless names for variables. There is no need to use cryptic names like <code>prnt</code>: they don't help understanding the code, and making a longer, more explicit name is not something hard to do. The same comes from <code>rw</code> and <code>row</code>: in general, <code>rw</code> is an abbreviation for read/write; if you use it for \"row\", what does <code>row</code> mean in your code? <code>strchild</code> is a terrible name too.</p></li>\n</ul>\n\n<p>Using suggestions below, this gives:</p>\n\n<pre><code>foreach (var allDaysRecord in this.totalDateRangeExcludeSundays)\n{\n var allDaysRecordDay = ((DateTime)allDaysRecord[\"Date\"]).Date;\n foreach (var absence in this.absentsLeavesHolidaysWorks)\n {\n var absenceDay = ((DateTime)absence[\"Date\"]).Date;\n if (allDaysRecordDay == absenceDay)\n {\n allDaysRecord.Delete();\n }\n }\n}\n</code></pre>\n\n<p>You can, if you want, LINQify that:</p>\n\n<pre><code>foreach (var allDaysRecord in this.totalDateRangeExcludeSundays)\n{\n var allDaysRecordDay = ((DateTime)allDaysRecord[\"Date\"]).Date;\n var hasAbsence = this.absentsLeavesHolidaysWorks\n .Select(c =&gt; ((DateTime)c[\"Date\"]).Date)\n .Contains(allDaysRecordDay);\n\n if (hasAbsence)\n {\n allDaysRecord.Delete();\n }\n}\n</code></pre>\n\n<p>You can go further:</p>\n\n<pre><code>var matches = from allDaysRecord in this.totalDateRangeExcludeSundays\n let allDaysRecordDay = ((DateTime)allDaysRecord[\"Date\"]).Date\n where this.absentsLeavesHolidaysWorks\n .Select(c =&gt; ((DateTime)c[\"Date\"]).Date)\n .Contains(allDaysRecordDay)\n select allDaysRecord;\n\nforeach (var m in matches.ToList())\n{\n m.Delete();\n}\n</code></pre>\n\n<p>The code is cleaner, but you won't gain in terms of performance. If performance matters in this case, why aren't you doing the same thing as a single SQL query?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T21:06:08.980", "Id": "26954", "ParentId": "26736", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T07:38:55.977", "Id": "26736", "Score": "1", "Tags": [ "c#", "performance", "asp.net", ".net-datatable" ], "Title": "Remove matched Rows from two Datatable" }
26736
<p>There is a function that converts region code strings (1 to 4 characters and null terminator) to 32 bit integers codes to be used in maps as keys or values.</p> <p>Blindly casting char* to int* is bad as it can be less than 4 bytes including null terminator.</p> <p>Currently the code is like this</p> <pre><code>uint32_t region_code_key(const char* region_code) { unsigned char buf[4] = "\0"; strncpy(buf, region_code, 4); return *((int*)buf); } </code></pre> <p>I believe that buf may be not well aligned causing problems on some platforms. Is it a valid concern? The endianity is not a concern as such numbers are used only on local machines, only as keys.</p> <p>It's a very simple function but If alignment concern is valid I see two ways to rewrite it. Here we just convert it byte by byte</p> <pre><code>uint32_t region_code_key(const char* region_code) { unsigned char* region_code_iter; unsigned char* region_code_end = region_code+4; uint32_t code_as_int = 0; for (region_code_iter = region_code; region_code_iter!=region_code_end &amp;&amp; (*region_code_iter); ++region_code_iter) { code_as_int = (code_as_int&lt;&lt;8) | (*region_code_iter); } return code_as_int; } </code></pre> <p>Alternatively use union to ensure better alignment:</p> <pre><code>uint32_t region_code_key(const char* region_code) { union { char[sizeof(uint32_t)] as_string; uint32_t as_int; } region = {0, 0, 0, 0}; strncpy(region.as_string, region_code, sizeof (region_code)); return region.as_int; } </code></pre> <p>Is alignment a valid concern? If so which alternative seems less ugly to you?</p>
[]
[ { "body": "<p>Even if the <code>char</code> array is not aligned, your <code>*((uint32_t *)buf)</code> will be correct: the compiler will ensure the necessary operations are performed.</p>\n\n<p>Note that I used <code>unit32_t</code>: the C standard does not guarantee the size of an <code>int</code>.</p>\n\n<p>One thing: since these are 4 byte integers, you can use an endianness-independent way of doing things by using <code>htonl()</code>/<code>ntohl()</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T11:00:49.803", "Id": "41444", "Score": "1", "body": "On some microprocessors, an unaligned access is not legal, even though you get away with it on x86." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T11:01:36.840", "Id": "41445", "Score": "0", "body": "For such microprocessors however, the compiler will do the right thing anyway, right? ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T11:09:12.943", "Id": "41447", "Score": "1", "body": "For a procedure with a single parameter, as shown here, the compiler/runtime would take care to align the stack frame, so the code would work. However, the compilers I’ve seen will **not** generate special code for the cast as such, they will assume the programmer knew `buf` was aligned properly, and if it was not, the program will crash." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-27T15:16:45.273", "Id": "148843", "Score": "0", "body": "On some systems the cast `*((uint32_t *)buf)` when buf is not properly aligned will lead to a crash" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T08:34:28.457", "Id": "26740", "ParentId": "26739", "Score": "2" } }, { "body": "<p>The <code>buf</code> array is on the stack. The compiler is not going to put misaligned variables on the stack. The stack frame created on a function call will put CPU registers on the stack, so if your processor has 32-bit registers (or greater), your first solution is okay for uint32_t alignment.</p>\n\n<p>Note that the size in the 3rd solution <code>strcpy</code> is wrong:</p>\n\n<pre><code>strncpy(region.as_string, region_code, sizeof (region_code));\n</code></pre>\n\n<p>should be </p>\n\n<pre><code>strncpy(region.as_string, region_code, sizeof region);\n</code></pre>\n\n<p>For what it is worth, here is another solution :-)</p>\n\n<pre><code>static uint32_t region_code_key(const char *region_code)\n{\n const uint32_t mask[] = {0, 0xff, 0xffff, 0xffffff, 0xffffffff};\n size_t len = strlen(region_code);\n if (len &gt; 4) {\n len = 4;\n }\n const uint32_t code =\n (uint32_t)region_code[0] |\n (uint32_t)region_code[1] &lt;&lt; 8 |\n (uint32_t)region_code[2] &lt;&lt; 16 |\n (uint32_t)region_code[3] &lt;&lt; 24;\n return code &amp; mask[len];\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T20:35:29.653", "Id": "26819", "ParentId": "26739", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T08:26:24.580", "Id": "26739", "Score": "6", "Tags": [ "c", "casting" ], "Title": "Converting a region code (short string up to 4 characters) to a 32-bit integer" }
26739
<p>I want to provide, in the the spirit of C++11/boost make_shared and C++14 make_unique, a production-ready make_auto for C++03 compilers.</p> <p>So, inspired boost's make_shared implementation for C++03 compilers, I provide N overloads (0 to 10, currently) of the same make_auto function.</p> <pre><code>template &lt;typename T&gt; inline std::auto_ptr&lt;T&gt; make_auto() { return std::auto_ptr&lt;T&gt;(new T()) ; } template &lt;typename T, typename T_0&gt; inline std::auto_ptr&lt;T&gt; make_auto(const T_0 &amp; p_0) { return std::auto_ptr&lt;T&gt;(new T(p_0)) ; } template &lt;typename T, typename T_0, typename T_1&gt; inline std::auto_ptr&lt;T&gt; make_auto(const T_0 &amp; p_0, const T_1 &amp; p_1) { return std::auto_ptr&lt;T&gt;(new T(p_0, p_1)) ; } // etc. </code></pre> <p><b>Is there something wrong with this code?</b></p> <p><b>Implementation details:</b></p> <ul> <li>the const reference is inspired by boost's shared_ptr. After trying multiple alternatives (including <a href="https://stackoverflow.com/users/87234/gmannickg">GManNickG</a>'s excellent answer <a href="https://stackoverflow.com/questions/3582001/advantages-of-using-forward">here</a>), I had to gave up because of some <i>challenged</i> compilers. To pass non-const references, I'll use boost::ref.</li> <li>the <code>inline</code> keyword is mandatory for reasons that have nothing to do with the problem.</li> </ul> <p><b>Background info:</b></p> <p>I need this for multiple reasons, among them:</p> <ul> <li>I am stuck with C++03 compilers (and I suspect some of them of not even being that... I'm looking at you, SunStudio). This means <b>even C++03 emulations of unique_ptr don't work</b> (we tried)</li> <li>avoiding writing new/delete in my C++ code (see Stroustrup's <a href="http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Keynote-Bjarne-Stroustrup-Cpp11-Style" rel="nofollow noreferrer">C++11 style video</a>)</li> <li>offering my coworkers the means to use a more modern C++ coding style despite aforementioned compilers limitations (RAII, that is)</li> <li>more exception safety</li> <li>I need a lightweight smart pointer with unique-ownership semantics, able to transfer ownership, so <b>boost::shared_ptr and boost::scoped_ptr are not an option</b></li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-08T14:42:57.367", "Id": "42185", "Score": "0", "body": "Can’t you use Boost.PP to generate that code for you rather than writing it manually? Additionally: why are the Boost smart pointers unsuitable?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-09T15:35:10.367", "Id": "42215", "Score": "0", "body": "@KonradRudolph : I did not think about Boost.PP. I'm not even sure I have access to it: When I arrived at my current job, I saw that Boost (in our third-party libraries folder) had been amputated from most of its content. I currently have no choice on that matter. Anyway, the code *is* automatically generated via script. As for the boost smart pointers, as I explained, I needed a smart pointer which is both lightweight (thus, NOT shared_ptr) and transfer-of-ownerhip-enabled (thus, NOT scopted_ptr)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-09T15:53:16.440", "Id": "42217", "Score": "0", "body": "Not sure what you mean by lightweight but I don’t find `shared_ptr` very heavy at all. The one thing I dislike is the non-configurable thread-safety." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-10T10:12:40.297", "Id": "42267", "Score": "0", "body": "@KonradRudolph : shared_ptr's problem is its weight (half the time, there will be a separate allocation for the reference counters because the user won't use make_shared, not mentioning the atomic counters) and its semantics (shared ownership, which is not desired in most cases). Herb Sutter has a full discussion on the comparison between shared_ptr and unique_ptr, which IMHO, applies in C++03 with shared_ptr vs. auto_ptr. I updated my question to add the \"unique-ownership\" need." } ]
[ { "body": "<p><strong>Disclaimer</strong>: this is not an attempt to answer your technical question, but suggesting alternatives to reach some compromise of your stated goals. It wouldn't fit in a comment :-)</p>\n\n<p>I am not sure it is a good idea to actually write a <code>make_auto</code>. It is akin to <a href=\"http://en.wiktionary.org/wiki/rearrange_the_deck_chairs_on_the_Titanic\" rel=\"nofollow noreferrer\">rearranging the deck chairs on the Titanic</a>. After it <a href=\"https://stackoverflow.com/questions/111478/why-is-it-wrong-to-use-stdauto-ptr-with-standard-containers\">hit the iceberg</a>.</p>\n\n<p>You'd be better off with emulating a <code>std::unique_ptr</code> using C++98/03 features. Howard Hinnant has <a href=\"http://home.roadrunner.com/~hinnant/unique_ptr03.html\" rel=\"nofollow noreferrer\">one version</a> on his website. You might even get lucky and get its macro variadic version to work nicely with the <code>std::make_unique</code> <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3588.txt\" rel=\"nofollow noreferrer\">proposal</a> by Stephan T. Lavavej.</p>\n\n<p>I'd take that as the preferred option, with using <code>boost::shared_ptr</code> or <code>boost_scoped_ptr</code> as the preferred alternative option. If you insist on keeping <code>std::auto_ptr</code>, make its use as painful as possible. Without pain, you'll find it more difficult <a href=\"http://channel9.msdn.com/posts/C-and-Beyond-2012-Panel-Convincing-your-Colleagues\" rel=\"nofollow noreferrer\">to convince your colleagues</a> to upgrade to C++11.</p>\n\n<p>Please also make sure to introduce your team to the other <a href=\"http://www.boost.org/doc/libs/?view=category_Emulation\" rel=\"nofollow noreferrer\">language emulation features</a> that Boost provides (Foreach, Move).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-08T12:38:32.510", "Id": "42180", "Score": "0", "body": "We tried Howard Hinnant's approach, both the version from Boost and the one from on his website. The problem is that some of our mentally-challenged C++ compilers didn't compile it. . . As for convincing colleagues, it's more like convincing customers, and that path is definitively closed: We will upgrade the compilers according to the platform evolution, nothing more." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-08T12:41:30.413", "Id": "42181", "Score": "0", "body": "Thus: 1. We need auto_ptr because it's cheaper and more correct in single-ownership semantics than shared_ptr, it has transfer of ownership semantics, which scoped_ptr does not, and is more or less supported on our compilers, which is not the case for unique_ptr. . . 2. As the rationale for make_auto, it is to avoid naked new calls (search for Stroustrup's abundant comments on that) . . . believe me: Using current alternative on my day job is my fondest professional dream... but it is still a dream, and I must cope with the reality, and thus teach colleagues how to use correctly auto_ptr." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-08T12:47:43.590", "Id": "42182", "Score": "0", "body": "Nice links, BTW (STL's proposition, and boost language emulation). I'll read ASAP." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-08T12:57:45.980", "Id": "42183", "Score": "1", "body": "@paercebal OK, I understand your position. Good luck with your implementation. I think the `make_unique` proposal is \"simple\" enough to try to mimic, if at least you drop the overloads for `T[n]` etc." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-07T12:22:15.570", "Id": "27141", "ParentId": "26742", "Score": "4" } }, { "body": "<p>I think it's OK.</p>\n\n<p>You could try providing both const and non-const references version if you need non-const references for dependency injection.</p>\n\n<p>Boost.PP would help with the boilerplate. Amputated boost is usually selected parts imported using the <code>bcp</code> tool that comes with Boost. Usually that's done simply to limit the size of the working directory. So it should be possible to import more of it, test that it works with all compilers you have to support and go with it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-20T09:49:42.187", "Id": "29987", "ParentId": "26742", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T09:03:49.953", "Id": "26742", "Score": "11", "Tags": [ "c++", "c++11", "smart-pointers", "c++03" ], "Title": "make_auto implementation for C++03 compilers" }
26742
<p>My main goal is to perform the conversion on a list of strings. Is this a sensible approach or should I refactor?</p> <p>Please note that I cannot use Boost in my work.</p> <pre><code>#include &lt;iostream&gt; #include &lt;list&gt; #include &lt;string&gt; #include &lt;algorithm&gt; char fix_delim(char ch) { return ch == '\\' ? '/' : ch; } std::string&amp; fix_str(std::string&amp; str) { std::transform(str.begin(), str.end(), str.begin(), fix_delim); return str; } int main() { std::list&lt;std::string&gt; files; files.push_back("folder\\file1"); files.push_back("folder\\file2"); //simple example of fix_delim std::string one("folder\\file1"); std::transform(one.begin(), one.end(), one.begin(), fix_delim); //Is this a good way to solve this problem of replacing all instances of \ with / in a list of strings? std::transform(files.begin(), files.end(), files.begin(), fix_str); return 0; } </code></pre>
[]
[ { "body": "<p>With C++11 you can use lambda, otherwise make the helper function static. </p>\n\n<p>If you're tied to std::string and no stock solution, this one is about as good as it gets. I suggest naming it properly like fix_path_separators or along the lines describing its <em>purpose</em>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T10:53:12.470", "Id": "26745", "ParentId": "26743", "Score": "3" } }, { "body": "<p>Seems to me that the right algorithm for this job is <code>std::replace</code>:</p>\n\n<pre><code>std::replace(input.begin(), input.end(), '\\\\', '/');\n</code></pre>\n\n<p>The easiest way to apply to a collection of strings is probably to use <code>std::for_each</code> with a lambda:</p>\n\n<pre><code>std::for_each(files.begin(), files.end(), \n [](std::string &amp;s) { std::replace(s.begin(), s.end(), '\\\\', '/'); });\n</code></pre>\n\n<p>If you can't use a lambda, you can write a tiny function object instead:</p>\n\n<pre><code>class path_dos2unix {\n void operator()(std::string &amp;s) { \n std::replace(s.begin(), s.end(), '\\\\', '/');\n }\n};\n</code></pre>\n\n<p>...and then invoke that:</p>\n\n<pre><code>std::for_each(files.begin(), files.end(), path_dos2unix());\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T09:58:59.733", "Id": "41523", "Score": "0", "body": "In our work, with multiple platforms to support and waiting for other depts to upgrade it will be a long time till we can use lambdas. But I would love to be able to." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T01:47:01.610", "Id": "26779", "ParentId": "26743", "Score": "8" } } ]
{ "AcceptedAnswerId": "26745", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T09:22:02.723", "Id": "26743", "Score": "2", "Tags": [ "c++", "strings" ], "Title": "Replace all instances of \\ with /" }
26743
<p>I am making a web app that will have a "my files" area and to do so I am writing my own html and jQuery to control the opening and closing of each folder (or <code>ul li</code>). I want to make sure that this web app is as efficient as I can make it as it may have to deal with a large amount of hierarchy.</p> <p><a href="http://jsfiddle.net/dbBZj/" rel="nofollow noreferrer">jsFiddle</a></p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8" /&gt; &lt;meta name="viewport" content="width=device-width" /&gt; &lt;title&gt;Title&lt;/title&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"&gt;&lt;/script&gt; &lt;style&gt; li { cursor: pointer; line-height: 20px; list-style: none; } li ul { display: none; } .active { } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="tree-wrapper"&gt; &lt;ul class="tree"&gt; &lt;li&gt; &lt;a href="#"&gt;Animals&lt;/a&gt; &lt;ul&gt; &lt;li&gt; &lt;a href="#"&gt;Birds&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#"&gt;Mammals&lt;/a&gt; &lt;ul&gt; &lt;li&gt;Elephant&lt;/li&gt; &lt;li&gt;Mouse&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#"&gt;Reptiles&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Plants &lt;ul&gt; &lt;li&gt; &lt;a href="#"&gt;Flowers&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Rose&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Tulip&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Trees&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;script&gt; var folderToggle = $(".tree li &gt; a"); $(function () { folderToggle.click(function(e) { e.preventDefault(); $(this).find("+ ul").toggle("slow"); $(this).toggleClass("active"); }); }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>Step 1: Fix your markup. You have the \"plants\"-list nested inside the link, which is invalid</p>\n\n<p>Step 2: Fix your JS. You correctly add the click handler after the document's ready, but you set the <code>folderToggle</code> variable when the script's run, regardless of whether the document's been loaded. It still works because you have the script at the end of your page, but still. Keep everything inside the <code>$(...)</code> - it'll also keep the <code>folderToggle</code> var out of the global scope.</p>\n\n<p>Step 2: Cache jQuery objects. Don't write <code>$(this)</code> twice.</p>\n\n<p>Step 3: Don't use <code>find()</code> for this. While I can't speak to an exact performance difference, it's more precise to use <code>next()</code>, as the nested list will be the next element/sibling relative to the link.</p>\n\n<pre><code>$(function () {\n $(\".tree li &gt; a\").click(function(e) {\n var link = $(this);\n e.preventDefault();\n link.next().toggle(\"slow\");\n link.toggleClass(\"active\");\n });\n});\n</code></pre>\n\n<p>Step 4: If you're going to be adding more stuff to the tree via ajax or something, you'll probably want to rewrite the click handler to handle clicks for links added later:</p>\n\n<pre><code>$(\".tree\").on(\"click\", \"li &gt; a\", function (event) {\n ...\n});\n</code></pre>\n\n<p>Step 5: You'll probably want to add a class to the \"branch\" links in the tree. Otherwise \"leaf\" links will also attempt to open a nested list, which doesn't make much sense, as there won't be one.</p>\n\n<p>Step 6: Use <code>OL</code> (ordered list) unless your lists are actually \"unordered\". But if they're file lists, they're probably ordered somehow. Minor thing, but semantics matter.</p>\n\n<p>All that said, there's nothing terribly inefficient in your code. If anything's going to lag, it's the toggle animation, but that can't really be sped up, as it's a single function call to jQuery. It's either there or not there.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T16:02:10.797", "Id": "41476", "Score": "2", "body": "Its also a slight performance increase to use 'return false' rather than 'e.preventDefault' (jsperf showed a 6% benefit, not earth shattering, but still)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T12:53:45.643", "Id": "26749", "ParentId": "26744", "Score": "3" } } ]
{ "AcceptedAnswerId": "26749", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T09:24:41.283", "Id": "26744", "Score": "4", "Tags": [ "javascript", "jquery", "html", "css" ], "Title": "jQuery File Tree Toggle" }
26744
<p>Here is a function that checks whether an alement <code>a</code> is a member of every set in list <code>l-set</code>.</p> <p>I don't like the fact that it returns <code>#t</code> for an empty list of sets. What would be a clean fix to this problem?</p> <pre><code>(define memberall (lambda (a l-set) (cond ((null? l-set) #t) ((not (member a (car l-set))) #f) (else (memberall a (cdr l-set)))))) </code></pre>
[]
[ { "body": "<p>so this is not a question about code, but about conventions. Usually to say \"a condition holds for all elements of a set\" is the same as \"there's no such element in the set that the condition doesn't hold for it\". Which there clearly is no such element, in an <em>empty</em> set. So by convention all such \"all-are-true\" predicates hold for an empty set. </p>\n\n<p>But if you want your function to return <code>#f</code> in such a case, just add simple entry check for this, and convert what you have right now into an inner (nested) definition:</p>\n\n<pre><code>(define memberall\n (lambda (a l-set) \n (and (not (null? l-set))\n (letrec ((alltrue \n (lambda (l-set)\n (cond\n ((null? l-set) #t)\n ((not (member a (car l-set))) #f)\n (else (alltrue (cdr l-set)))))))\n (alltrue l-set)))))\n</code></pre>\n\n<p>Or with named <code>let</code>:</p>\n\n<pre><code>(define memberall\n (lambda (a l-set) \n (and (not (null? l-set))\n (let alltrue ((l-set l-set))\n (cond\n ((null? l-set) #t)\n ((not (member a (car l-set))) #f)\n (else (alltrue (cdr l-set))))))))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-17T14:50:00.780", "Id": "28603", "ParentId": "26748", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T12:11:51.813", "Id": "26748", "Score": "1", "Tags": [ "scheme" ], "Title": "Check if element is a member of all sets in Scheme" }
26748
<p>I found this old color fading function in my snippets folder and would like to implement it to one of my projects. It can be used to fade one color to another. It's a very long one-liner:</p> <pre><code>D3DCOLOR GetFadedColor(D3DCOLOR from, D3DCOLOR to, float factor) { return (factor&lt;0.0f)?from:((factor&gt;1.0f)?to:(((((from&gt;&gt;24)&gt;(to&gt;&gt;24))?((from&gt;&gt;24)- (D3DCOLOR)(factor*(float)((from&gt;&gt;24)-(to&gt;&gt;24)))):((from&gt;&gt;24)+(D3DCOLOR)(factor*(float) ((to&gt;&gt;24)-(from&gt;&gt;24)))))&lt;&lt;24)|(((((from&lt;&lt;8)&gt;&gt;24)&gt;((to&lt;&lt;8)&gt;&gt;24))?(((from&lt;&lt;8)&gt;&gt;24)- (D3DCOLOR)(factor*(float)(((from&lt;&lt;8)&gt;&gt;24)-((to&lt;&lt;8)&gt;&gt;24)))):(((from&lt;&lt;8)&gt;&gt;24)+(D3DCOLOR) (factor*(float)(((to&lt;&lt;8)&gt;&gt;24)-((from&lt;&lt;8)&gt;&gt;24)))))&lt;&lt;16)|(((((from&lt;&lt;16)&gt;&gt;24)&gt; ((to&lt;&lt;16)&gt;&gt;24))?(((from&lt;&lt;16)&gt;&gt;24)-(D3DCOLOR)(factor*(float)(((from&lt;&lt;16)&gt;&gt;24)- ((to&lt;&lt;16)&gt;&gt;24)))):(((from&lt;&lt;16)&gt;&gt;24)+(D3DCOLOR)(factor*(float)(((to&lt;&lt;16)&gt;&gt;24)- ((from&lt;&lt;16)&gt;&gt;24)))))&lt;&lt;8)|(((((from&lt;&lt;24)&gt;&gt;24)&gt;((to&lt;&lt;24)&gt;&gt;24))?(((from&lt;&lt;24)&gt;&gt;24)-(D3DCOLOR) (factor*(float)(((from&lt;&lt;24)&gt;&gt;24)-((to&lt;&lt;24)&gt;&gt;24)))):(((from&lt;&lt;24)&gt;&gt;24)+(D3DCOLOR)(factor* (float)(((to&lt;&lt;24)&gt;&gt;24)-((from&lt;&lt;24)&gt;&gt;24)))))))); } </code></pre> <p><code>D3DCOLOR</code> is just a <code>DWORD</code> (<code>unsigned long</code>). A color can for example be 0xAARRGGBB (A-alpha, R-red, G-green, B-blue), but works with other compositions aswell.</p> <p>Obviously it's a total mess.</p> <p>I actually don't know how it works and don't remember where I have it from, so I would ask for a review to improve the code and make it readable and understandable.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T14:14:43.130", "Id": "41465", "Score": "0", "body": "Since we don't deal with code errors, you can post about them on Stack Overflow. After getting them fixed, you could make those changes here and we'll help with the readability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T14:28:45.630", "Id": "41466", "Score": "0", "body": "@JamalA Thanks, I managed to get the code working now. It's still kind of ugly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T14:34:10.870", "Id": "41467", "Score": "0", "body": "No problem. Someone may be able to help with that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T17:56:14.347", "Id": "41483", "Score": "0", "body": "There were still some errors in the code. It is fully working now. I also made it better visible in the post." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-29T14:51:58.513", "Id": "124584", "Score": "0", "body": "Asking for a rewrite of someone else's code is off-topic for Code Review. Also, the code was posted without attribution." } ]
[ { "body": "<p>This is the reason why some people want ternary operators removed from the language. It's not quite the worst abuse I've seen, but it's pretty close. This took quite a while to disentangle. I'm going to go through it in steps:</p>\n\n<p>First step: make it slightly more readable. Break up everything:</p>\n\n<pre><code>return (factor&lt;0.0f)\n?\nfrom \n: \n((factor&gt;1.0f)\n?\nto\n:\n(((((from &gt;&gt; 24) &gt; (to &gt;&gt; 24))\n?\n((from&gt;&gt;24)-(D3DCOLOR)(factor*(float)((from&gt;&gt;24)-(to&gt;&gt;24))))\n:\n((from&gt;&gt;24)+(D3DCOLOR)(factor*(float)((to&gt;&gt;24)-(from&gt;&gt;24)))))&lt;&lt;24)\n|\n(((((from&lt;&lt;8)&gt;&gt;24)&gt;((to&lt;&lt;8)&gt;&gt;24))\n?\n(((from&lt;&lt;8)&gt;&gt;24)-(D3DCOLOR)(factor*(float)(((from&lt;&lt;8)&gt;&gt;24)-((to&lt;&lt;8)&gt;&gt;24))))\n:\n(((from&lt;&lt;8)&gt;&gt;24)+(D3DCOLOR)(factor*(float)(((to&lt;&lt;8)&gt;&gt;24)-((from&lt;&lt;8)&gt;&gt;24)))))&lt;&lt;16)\n|\n(((((from&lt;&lt;16)&gt;&gt;24)&gt;((to&lt;&lt;16)&gt;&gt;24))\n?\n(((from&lt;&lt;16)&gt;&gt;24)-(D3DCOLOR)(factor*(float)(((from&lt;&lt;16)&gt;&gt;24)-((to&lt;&lt;16)&gt;&gt;24))))\n:\n(((from&lt;&lt;16)&gt;&gt;24)+(D3DCOLOR)(factor*(float)(((to&lt;&lt;16)&gt;&gt;24)-((from&lt;&lt;16)&gt;&gt;24)))))&lt;&lt;8)\n|\n(((((from&lt;&lt;24)&gt;&gt;24)&gt;((to&lt;&lt;24)&gt;&gt;24))\n?\n(((from&lt;&lt;24)&gt;&gt;24)-(D3DCOLOR)(factor*(float)(((from&lt;&lt;24)&gt;&gt;24)-((to&lt;&lt;24)&gt;&gt;24))))\n:\n(((from&lt;&lt;24)&gt;&gt;24)+(D3DCOLOR)(factor*(float)(((to&lt;&lt;24)&gt;&gt;24)-((from&lt;&lt;24)&gt;&gt;24))))))));\n</code></pre>\n\n<p>Not a hell of a lot of improvement, but we can at least start to see some of the shifting operations here and (sort) of what they're being applied to.</p>\n\n<p>Second step: make some utility functions - </p>\n\n<pre><code>typedef unsigned long D3DCOLOR;\n\nD3DCOLOR Alpha(D3DCOLOR color)\n{\n return (color &gt;&gt; 24);\n}\n\nD3DCOLOR Red(D3DCOLOR color)\n{\n return (color &lt;&lt; 8) &gt;&gt; 24;\n}\n\nD3DCOLOR Green(D3DCOLOR color)\n{\n return (color &lt;&lt; 16) &gt;&gt; 24;\n};\n\nD3DCOLOR Blue(D3DCOLOR color)\n{\n return (color &lt;&lt; 24) &gt;&gt; 24;\n}\n</code></pre>\n\n<p>Effectively, what's being done here is masking out each part (A, R, G, B) one at a time. I'm assuming it's in this format: it doesn't really matter if it isn't, because it's doing the same thing to each byte in the long. The only thing that will change is the order, but we'll stick with these function names for now. Let's add this into the mix:</p>\n\n<pre><code>return (factor&lt;0.0f)\n?\nfrom \n: \n((factor&gt;1.0f)\n?\nto\n:\n(Alpha(from) &gt; Alpha(to))\n?\n(Alpha(from) - (D3DCOLOR)(factor * (float)(Alpha(from) - Alpha(to)))\n:\n((Alpha(from) + (D3DCOLOR)(factor * (float)((Alpha(to)- Alpha(from))))))) &lt;&lt; 24\n|\n(Red(from) &gt; Red(to))\n?\n((Red(from) - (D3DCOLOR)(factor * (float)(Red(from) - Red(to))))\n:\n(Red(from) + (D3DCOLOR)(factor * (float)((Red(to) - Red(from)))))) &lt;&lt; 16\n|\n(Green(from) &gt; Green(to))\n?\n((Green(from) - (D3DCOLOR)(factor*(float)(Green(from) - Green(to)))\n:\n(Green(from) + (D3DCOLOR)(factor * (float)((Green(to) - Green(from)))))) &lt;&lt; 8\n|\n(Blue(from) &gt; Blue(to))\n?\n((Blue(from) - (D3DCOLOR)(factor * (float)(Blue(from) - Blue(to)))\n:\n(Blue(from) + (D3DCOLOR)(factor * (float)((Blue(to) - (Blue(from)))))) &gt;&gt; 24;\n</code></pre>\n\n<p>Ok, getting there. It's almost readable now. Note the parens here are something of a pain, and we must be careful to get them correct.</p>\n\n<p>We can now do the (laborious) task of replacing ternary operators with <code>if/else</code>:</p>\n\n<pre><code>D3DCOLOR GetFadedColor(D3DCOLOR from, D3DCOLOR to, float factor)\n{\n D3DCOLOR col = 0;\n\n if (factor &lt; 0.0f) {\n col = from; \n }\n else if (factor &gt; 1.0f) {\n col = to;\n }\n else {\n if(Alpha(from) &gt; Alpha(to)) {\n col = (Alpha(from) - (D3DCOLOR)(factor * (float)((Alpha(from) - Alpha(to))))) &lt;&lt; 24;\n } \n else {\n col = (Alpha(from) + (D3DCOLOR)(factor * (float)((Alpha(to)- Alpha(from))))) &lt;&lt; 24;\n }\n\n if(Red(from) &gt; Red(to)) {\n col |= (Red(from) - (D3DCOLOR)(factor * (float)((Red(from) - Red(to))))) &lt;&lt; 16;\n }\n else {\n col |= (Red(from) + (D3DCOLOR)(factor * (float)((Red(to) - Red(from))))) &lt;&lt; 16;\n }\n\n if(Green(from) &gt; Green(to)) {\n col |= (Green(from) - (D3DCOLOR)(factor * (float)((Green(from) - Green(to))))) &lt;&lt; 8;\n } \n else {\n col |= (Green(from) + (D3DCOLOR)(factor * (float)((Green(to) - Green(from))))) &lt;&lt; 8;\n }\n\n if(Blue(from) &gt; Blue(to)) {\n col |= (Blue(from) - (D3DCOLOR)(factor * (float)((Blue(from) - Blue(to)))));\n }\n else {\n col |= (Blue(from) + (D3DCOLOR)(factor * (float)((Blue(to) - (Blue(from))))));\n }\n }\n\n return col;\n}\n</code></pre>\n\n<p>Ok, so now it's readable. This can likely be simplified further - there's quite a bit of duplication here. All that really changes are some shift values. Hopefully this is enough that you can do that simplification yourself, however.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T03:16:16.960", "Id": "41503", "Score": "0", "body": "Not the worst abuse you've seen? Wow. This still makes me think twice about using it in my own programs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T03:22:26.957", "Id": "41504", "Score": "0", "body": "@JamalA When I say it's not the worst, it's mainly the [IOCCC](http://www.ioccc.org/) that I'm thinking of. That being said, I'd never, ever let something like this get past any kind of code review." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T03:32:13.230", "Id": "41505", "Score": "0", "body": "Interesting link. It seems to me that abusing the operator \"doesn't count\" there since it's a goal. As for actual code review, like you said, this is a no-no. I'm sort of obsessed with simple code, so I can't comprehend anything like this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T14:38:53.553", "Id": "41532", "Score": "0", "body": "The conditionals (`if (Alpha(from) > Alpha(to))`) can also be omitted. In `a - f * (a - b)`, where a is greater than b, `a - b` is +ve; and where a is less than b, `a - b` is negative." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-08T20:14:27.743", "Id": "126474", "Score": "0", "body": "It could be much more improved for readability. Names are awfully incomprehensible. In such cases, using `x(y) {\\n}` is not a good idea.." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T03:08:18.593", "Id": "26781", "ParentId": "26750", "Score": "6" } }, { "body": "<p>@Yuushi has a really good answer here, but I am going to point out some slightly different things that I would do to make this better code</p>\n\n<ol>\n<li>Whitespace between operators</li>\n<li>Newline characters</li>\n</ol>\n\n\n\n<pre><code>return (factor &lt; 0.0f) ? from \n : ((factor &gt; 1.0f) ? to \n : (((((from &gt;&gt; 24) &gt; (to &gt;&gt; 24)) ? ((from &gt;&gt; 24) - (D3DCOLOR)(factor*(float)((from &gt;&gt; 24)-(to &gt;&gt; 24)))) \n : ((from &gt;&gt; 24) + (D3DCOLOR)(factor*(float)((to &gt;&gt; 24)-(from &gt;&gt; 24))))) &lt;&lt; 24) \n | (((((from &lt;&lt; 8) &gt;&gt; 24) &gt; ((to &lt;&lt; 8) &gt;&gt; 24)) ? (((from &lt;&lt; 8) &gt;&gt; 24) - (D3DCOLOR)(factor*(float)(((from &lt;&lt; 8) &gt;&gt; 24) - ((to &lt;&lt; 8) &gt;&gt; 24)))) \n : (((from &lt;&lt; 8) &gt;&gt; 24) + (D3DCOLOR)(factor*(float)(((to &lt;&lt; 8) &gt;&gt; 24) - ((from &lt;&lt; 8) &gt;&gt; 24))))) &lt;&lt; 16) \n | (((((from &lt;&lt; 16) &gt;&gt; 24) &gt; ((to &lt;&lt; 16) &gt;&gt; 24)) ? (((from &lt;&lt; 16) &gt;&gt; 24) - (D3DCOLOR)(factor*(float)(((from &lt;&lt; 16) &gt;&gt; 24) - ((to &lt;&lt; 16) &gt;&gt; 24)))) \n : (((from &lt;&lt; 16) &gt;&gt; 24) + (D3DCOLOR)(factor*(float)(((to &lt;&lt; 16) &gt;&gt; 24) - ((from &lt;&lt; 16) &gt;&gt; 24))))) &lt;&lt;8) | \n (((((from &lt;&lt; 24) &gt;&gt; 24) &gt; ((to &lt;&lt; 24) &gt;&gt; 24)) ? (((from &lt;&lt; 24) &gt;&gt; 24) - (D3DCOLOR)(factor*(float)(((from &lt;&lt; 24) &gt;&gt; 24) - ((to &lt;&lt; 24) &gt;&gt; 24))))\n : (((from &lt;&lt; 24) &gt;&gt; 24) + (D3DCOLOR)(factor*(float)(((to &lt;&lt; 24) &gt;&gt; 24) - ((from &lt;&lt; 24) &gt;&gt; 24))))))));\n</code></pre>\n\n<p>we can still go a little farther</p>\n\n<pre><code>return (factor &lt; 0.0f) ? from \n : ((factor &gt; 1.0f) ? to \n : (((((from &gt;&gt; 24) &gt; (to &gt;&gt; 24)) ? \n ((from &gt;&gt; 24) - (D3DCOLOR)(factor*(float)((from &gt;&gt; 24) - (to &gt;&gt; 24)))) \n : ((from &gt;&gt; 24) + (D3DCOLOR)(factor*(float)((to &gt;&gt; 24) - (from &gt;&gt; 24))))) &lt;&lt; 24) \n | (((((from &lt;&lt; 8) &gt;&gt; 24) &gt; ((to &lt;&lt; 8) &gt;&gt; 24)) ?\n (((from &lt;&lt; 8) &gt;&gt; 24) - (D3DCOLOR)(factor*(float)(((from &lt;&lt; 8) &gt;&gt; 24) - ((to &lt;&lt; 8) &gt;&gt; 24)))) \n : (((from &lt;&lt; 8) &gt;&gt; 24) + (D3DCOLOR)(factor*(float)(((to &lt;&lt; 8) &gt;&gt; 24) - ((from &lt;&lt; 8) &gt;&gt; 24))))) &lt;&lt; 16) \n | (((((from &lt;&lt; 16) &gt;&gt; 24) &gt; ((to &lt;&lt; 16) &gt;&gt; 24)) ? \n (((from &lt;&lt; 16) &gt;&gt; 24) - (D3DCOLOR)(factor*(float)(((from &lt;&lt; 16) &gt;&gt; 24) - ((to &lt;&lt; 16) &gt;&gt; 24)))) \n : (((from &lt;&lt; 16) &gt;&gt; 24) + (D3DCOLOR)(factor*(float)(((to &lt;&lt; 16) &gt;&gt; 24) - ((from &lt;&lt; 16) &gt;&gt; 24))))) &lt;&lt;8) \n | (((((from &lt;&lt; 24) &gt;&gt; 24) &gt; ((to &lt;&lt; 24) &gt;&gt; 24)) ? \n (((from &lt;&lt; 24) &gt;&gt; 24) - (D3DCOLOR)(factor*(float)(((from &lt;&lt; 24) &gt;&gt; 24) - ((to &lt;&lt; 24) &gt;&gt; 24))))\n : (((from &lt;&lt; 24) &gt;&gt; 24) + (D3DCOLOR)(factor*(float)(((to &lt;&lt; 24) &gt;&gt; 24) - ((from &lt;&lt; 24) &gt;&gt; 24))))))));\n</code></pre>\n\n<p>all I did was add Newline Characters and indentation to make your code more readable.</p>\n\n<p>Another thing that I would suggest is to create variables for these numbers</p>\n\n<ul>\n<li>8</li>\n<li>16</li>\n<li>24</li>\n</ul>\n\n<p>and</p>\n\n<p>Change the name of your <code>from</code> and <code>to</code> variables, I am guessing that they could be more descriptive.</p>\n\n<p>and I am sure that you could clean this up a little bit more if you used the utility functions that @Yuushi talks about as well</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-29T14:27:47.057", "Id": "68278", "ParentId": "26750", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T13:05:25.153", "Id": "26750", "Score": "2", "Tags": [ "c", "bitwise" ], "Title": "Color fading function" }
26750
<p>I have written some sort routines for PROGRESS 4GL/ABL and wanting to get some input whether these sorts can be improved. And whether my sorts are true to name. And I would also be very interested in any suggestions how to change the Quick sort to do a proper numeric sort as well. The combsort was easy enough to write for ASCII sort and to make a version to do numeric sorts.</p> <p>I found the Comb sort to be about 3 - 5 times faster than Bubble Sort and the Quick Sort to be about 7 - 9 times faster than the bubble sort. The Numeric Comb sort is a bit slower than the normal comb sort, due to having to convert data from string to integer and placing it in an array and then converting back to string list.</p> <p>All the Sort functions receive a comma delimited list of data and returns data in same way after sort.</p> <p>I have found CombSort to be </p> <p>funcFloor - basically a function to return Floor funcCeiling - basically a function to return Ceiling </p> <p>/<em>============================================================</em>/</p> <pre><code>FUNCTION funcBubbleSort RETURNS CHARACTER (INPUT pcList AS CHARACTER): DEFINE VARIABLE cTempValue AS CHARACTER NO-UNDO. /* holding place for swap */ DEFINE VARIABLE i AS INTEGER NO-UNDO. /* outer loop counter */ DEFINE VARIABLE j AS INTEGER NO-UNDO. /* inner loop counter */ /* if 0 or 1 item in list then list is sorted */ IF NUM-ENTRIES(pcList) &lt; 2 THEN RETURN pcList. DO i = NUM-ENTRIES(pcList) TO 1 BY -1: DO j = 1 TO i - 1: IF ENTRY(j, pcList) &gt; ENTRY(j + 1, pcList) THEN DO: cTempValue = ENTRY(j, pcList). ENTRY(j, pcList) = ENTRY(j + 1, pcList). ENTRY(j + 1, pcList) = cTempValue. END. END. END. RETURN TRIM(pcList,","). END FUNCTION. </code></pre> <p>/* ======================================================== */</p> <pre><code>FUNCTION funcCombSort RETURNS CHARACTER (INPUT pcList AS CHARACTER): DEFINE VARIABLE cTempValue AS CHARACTER NO-UNDO. DEFINE VARIABLE dShrink AS DECIMAL NO-UNDO. DEFINE VARIABLE iNumEntries AS INTEGER NO-UNDO. DEFINE VARIABLE iGap AS INTEGER NO-UNDO. DEFINE VARIABLE i AS INTEGER NO-UNDO. DEFINE VARIABLE lSwapped AS LOGICAL NO-UNDO. /* if 0 or 1 item in list then list is sorted */ IF NUM-ENTRIES(pcList) &lt; 2 THEN RETURN pcList. /* be careful with dShrink size too large and too small are both bad */ ASSIGN dShrink = 1.3 iNumEntries = NUM-ENTRIES(pcList) iGap = iNumEntries lSwapped = TRUE . DO WHILE lSwapped = TRUE OR iGap &gt; 1 : /*update the gap value for a next comb.*/ ASSIGN iGap = funcFloor(iGap / dShrink) i = 1 lSwapped = FALSE. IF iGap &lt; 1 THEN iGap = 1. /*minimum gap is 1 */ /* a single "comb" over the input list */ DO WHILE (i + iGap) &lt;= iNumEntries: IF ENTRY(i, pcList) &gt; ENTRY((i + iGap), pcList) THEN DO: ASSIGN cTempValue = ENTRY(i, pcList) ENTRY(i, pcList) = ENTRY((i + igap), pcList) ENTRY((i + iGap), pcList) = cTempValue lSwapped = TRUE /* Flag a swap has occurred */ . END. i = i + 1. END. END. RETURN TRIM(pcList, ","). END FUNCTION. </code></pre> <p>/* ==================================================== */</p> <pre><code>FUNCTION funcNumCombSort RETURNS CHARACTER (INPUT pcList AS CHARACTER): DEFINE VARIABLE iTempValue AS INTEGER NO-UNDO. DEFINE VARIABLE dShrink AS DECIMAL NO-UNDO. DEFINE VARIABLE iNumEntries AS INTEGER NO-UNDO. DEFINE VARIABLE iGap AS INTEGER NO-UNDO. DEFINE VARIABLE i AS INTEGER NO-UNDO. DEFINE VARIABLE lSwapped AS LOGICAL NO-UNDO. DEFINE VARIABLE iArray AS INTEGER NO-UNDO EXTENT. DEFINE VARIABLE cList AS CHARACTER NO-UNDO. /* if 0 or 1 item in list then list is sorted */ IF NUM-ENTRIES(pcList) &lt; 2 THEN RETURN pcList. EXTENT (iArray) = NUM-ENTRIES(pcList). /* be careful with dShrink size too large and too small are both bad */ ASSIGN dShrink = 1.3 iNumEntries = NUM-ENTRIES(pcList) iGap = iNumEntries lSwapped = TRUE. /* populate array from list */ DO i = iNumEntries TO 1 BY -1: iArray[i] = INTEGER(ENTRY(i,pcList)). END. DO WHILE lSwapped = TRUE OR iGap &gt; 1 : /*update the gap value for a next comb.*/ ASSIGN iGap = funcFloor(iGap / dShrink) i = 1 lSwapped = FALSE. IF iGap &lt; 1 THEN iGap = 1. /*minimum gap is 1 */ /* a single "comb" over the input list - reverse order */ DO WHILE (i + iGap) &lt;= iNumEntries: IF iArray[i] &lt; iArray[i + iGap] THEN DO: ASSIGN iTempValue = iArray[i] /* swap two values */ iArray[i] = iArray[i + iGap] iArray[i + iGap] = iTempValue lSwapped = TRUE. /* Flag a swap has occurred */ END. i = i + 1. END. END. iNumEntries = EXTENT(iArray). DO i = iNumEntries TO 1 BY -1: IF cList = "" THEN cList = STRING(iArray[i]). ELSE cList = cList + "," + STRING(iArray[i]). END. RETURN cList. END FUNCTION. </code></pre> <p>/* =============================================================== */</p> <pre><code>FUNCTION funcQuickSort RETURNS CHARACTER (INPUT pcList AS character): DEFINE VARIABLE cListLess AS CHARACTER NO-UNDO. DEFINE VARIABLE cListGreater AS CHARACTER NO-UNDO. DEFINE VARIABLE cListMiddel AS CHARACTER NO-UNDO. DEFINE VARIABLE cPivot AS CHARACTER NO-UNDO. DEFINE VARIABLE iPivotPosition AS INTEGER NO-UNDO. DEFINE VARIABLE iNumEntries AS INTEGER NO-UNDO. DEFINE VARIABLE i AS INTEGER NO-UNDO. /* if 0 or 1 item in list then list is sorted */ IF NUM-ENTRIES(pcList) &lt; 2 THEN RETURN pcList. ASSIGN iNumEntries = NUM-ENTRIES(pcList) iPivotPosition = INTEGER (iNumEntries / 2) cPivot = ENTRY(iPivotPosition, pcList). DO i = 1 TO iNumEntries: IF ENTRY(i, pcList) &lt; cPivot THEN IF cListLess = "" THEN cListless = ENTRY(i, pcList). ELSE cListLess = cListLess + "," + ENTRY(i, pcList). IF ENTRY(i, pcList) &gt; cPivot THEN IF cListGreater = "" THEN cListGreater = ENTRY(i, pcList). ELSE cListGreater = cListGreater + "," + ENTRY(i, pcList). IF ENTRY(i, pcList) = cPivot THEN IF cListMiddel = "" THEN cListMiddel = ENTRY(i, pcList). ELSE cListMiddel = cListMiddel + "," + ENTRY(i, pcList). END. RETURN (TRIM(funcQuickSort(cListLess),",") + "," + cListMiddel + "," + TRIM(funcQuickSort(cListGreater),",")). END FUNCTION. /* funcQuickSort */ </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T19:55:16.853", "Id": "41603", "Score": "0", "body": "Why not use a temp-table?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-05T07:16:09.873", "Id": "41886", "Score": "0", "body": "Because temp-tables are over used for this. A temp table is the only way in Progress to sort data when you have more than 1 field in a record and want to maybe even sort on multiple fields. A list or array sort is basically used to sort a list of values quickly and efficiently with as little resources as possible." } ]
[ { "body": "<p>Depending on how long strings you have to work with I really would consider sorting via TEMP-TABLE instead. On longer strings (lets say 1000 integers or more) the TEMP-TABLE sort is around twice as quick. For short strings (10 integers) quicksort is faster. Also the difference between the largest and lowest value to sort seems to impact quicksort quite a alog (but not sorting via TEMP-TABLE).</p>\n\n<p>I'm really not sure that any one of those sorting algorithms really use less resources than a sort via TEMP-TABLES (especially not recursive ones) but that would need be verified.</p>\n\n<p>I've tested using this code:</p>\n\n<pre><code>DEFINE TEMP-TABLE ttSort NO-UNDO\n FIELD val AS INTEGER\n INDEX id1 IS PRIMARY val .\n\n\nFUNCTION funcTempTableSort RETURNS CHARACTER\n (INPUT pcList AS CHARACTER):\n\n EMPTY TEMP-TABLE ttSort.\n\n DEFINE VARIABLE i AS INTEGER NO-UNDO.\n DEFINE VARIABLE cReturn AS CHARACTER NO-UNDO.\n\n DO i = 1 TO NUM-ENTRIES(pcList).\n CREATE ttSort.\n ASSIGN ttSort.val = INTEGER(ENTRY(i, pcList)).\n END.\n\n FOR EACH ttSort NO-LOCK BY ttSort.val:\n cReturn = cReturn + STRING(ttSort.val) + \",\".\n END.\n\n RETURN TRIM(cReturn, \",\").\n\nEND FUNCTION.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T18:32:45.723", "Id": "57318", "Score": "0", "body": "+1 made it into a decimal sort, I also created a character version. But writing code to solve various algorithms are not always the same as doing something the fastest :-) It is more like solving puzzles. I am still new to Progress (7 months) and learning a lot, but I know there are some issues with temp tables in large systems using a lot of them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T21:37:25.767", "Id": "57339", "Score": "0", "body": "Feel free to use code as you like of course. Note that you can use INT64 instead of DECIMAL if large numbers is what your after and not decimals. No issues with temp tables as far as I know, they have (like all things) some kind of impact on your system." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-06T11:55:02.613", "Id": "33921", "ParentId": "26751", "Score": "2" } }, { "body": "<p>as a sample made the quicksort into a class and a static method:</p>\n\n<p>class common.util.strings:</p>\n\n<pre><code>method public static character AddToList(input cNew as character, input cOld as character ) :\n return AddToList(cNew, cOld, ','). \nend method. \n\nmethod public static character AddToList(input cNew as character, input cOld as character, input cSep as character ) :\n\n if cNew = '' then return cOld. \n\n if cOld = '' then return cNew. \n\n return substitute('&amp;1&amp;2&amp;3', cOld,cSep,cNew). \n\nend method. \n\nmethod public static character QuickSortListOfIntegers (input ListToSort as character):\n define variable ListLesser as character no-undo. \n define variable ListGreater as character no-undo. \n define variable ListMiddle as character no-undo.\n\n define variable Pivot as integer no-undo. \n define variable PivotPosition as integer no-undo. \n define variable NumEntries as integer no-undo. \n define variable Work as integer no-undo. \n define variable WorkVal as integer no-undo.\n\n assign NumEntries = num-entries(ListToSort).\n /* if 0 or 1 item in list then list is sorted */\n if NumEntries &lt; 2 then return ListToSort.\n\n assign PivotPosition = integer(NumEntries / 2)\n Pivot = integer(entry(PivotPosition, ListToSort)).\n\n do Work = 1 to NumEntries:\n WorkVal = integer(entry(Work, ListToSort)). \n if WorkVal &lt; Pivot then ListLesser = AddToList(ListLesser,string(WorkVal)).\n else if WorkVal &gt; Pivot then ListGreater = AddToList(ListGreater,string(WorkVal)).\n else if WorkVal = Pivot then ListMiddle = AddToList(ListMiddle,string(WorkVal)).\n end.\n\n return trim((trim(QuickSortListOfIntegers(ListLesser),\",\":U) + \",\":U + trim(ListMiddle,\",\":U) + \",\":U + trim(QuickSortListOfIntegers(ListGreater),\",\":U)),\",\":U).\nend method. \n</code></pre>\n\n<p>end class.</p>\n\n<p>Als fixed a small feature when the pivot is also the smallest or largest element in the intial pass you would return a additional , </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T18:02:17.257", "Id": "57314", "Score": "0", "body": "I actually changed my quicksort to also pass in a delimiter and I am busy making a numeric quick sort version using an array (decimal) instead of a list." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T13:22:38.950", "Id": "35358", "ParentId": "26751", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T13:06:50.353", "Id": "26751", "Score": "1", "Tags": [ "sorting", "quick-sort", "progress-4gl" ], "Title": "Suggestions on improving Sorting Algorithm (Progress ABL/4GL)" }
26751
<p>I have this method that reads a file into a hashmap. I feel like there are too many levels in this code with all these tries, ifs and so on. How do you think this can be improved?</p> <pre><code>public static ExchangeHistory loadHistory(String path){ Map&lt;Integer, Date&gt; rtcHistory = new HashMap&lt;Integer, Date&gt;(); Map&lt;Integer, Date&gt; almHistory = new HashMap&lt;Integer, Date&gt;(); ExchangeHistory exchHist = new ExchangeHistory(rtcHistory, almHistory); File file = new File(path); BufferedReader reader = null; try{ reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); String line; int lineNumber = 1; // read file line by line while ((line = reader.readLine()) != null){ String[] tokens = line.split("\\s"); if (tokens.length != 3){ log.error("Unable to parse exchange history file at line: " + lineNumber); continue; } // try to parse line. if parsing fails, just skip it try { int id = Integer.parseInt(tokens[1]); long timeInMillis = Long.parseLong(tokens[2]); if (tokens[0].equals(System.RTC)){ rtcHistory.put(id, new Date(timeInMillis)); } else if (tokens[0].equals(System.ALM)){ almHistory.put(id, new Date(timeInMillis)); } } catch (Exception e){ log.error("Unable to parse exchange history file at line:" + lineNumber, e); } lineNumber++; } } catch (FileNotFoundException e){ // try to create a new file in case it doesn't exist log.warn("No exchange history file found at " + path); try { file.createNewFile(); log.info("Created new exchange history file at " + path); } catch (IOException ioe){ log.error("Unable to create exchange history file at " + path + ". Exchange session info won't be saved", ioe); } // return an empty history list cause there are no records in new file return exchHist; } catch (IOException e) { log.error("Unable to read exchange history file at " + path + ". All items will be synchronized anew", e); return exchHist; } finally{ if (reader != null){ try { reader.close(); } catch (IOException e) { log.error("Unable to close input stream. Resource leak possible", e); } } } return exchHist = new ExchangeHistory(rtcHistory, almHistory); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T13:32:15.300", "Id": "41454", "Score": "0", "body": "Ok, I guess I need to remove the file creation part as it makes no sense here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T13:48:43.400", "Id": "41458", "Score": "1", "body": "Short note: you could do `new BufferedReader(new FileReader())` instead of `new BufferedReader(new InputStreamReader(new FileInputStream()))`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T06:23:19.243", "Id": "41512", "Score": "0", "body": "You can get a `Reader` in as the input parameter and remove almost all resource management concerns (including closing the reader) elsewhere right away. What does it matter if the characters come from a file or http or loaded from classpath or telepathied. As long as it implements `Reader`, you're good." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T07:10:17.607", "Id": "41514", "Score": "1", "body": "See : Joshua Bloch in Effective Java : Item 7: Avoid finalizers - DO NOT change other things, your code is readable, everybody can point out where is a bug at debugging" } ]
[ { "body": "<p>You can reduce the inner try/catch block in your while loop. For instance:</p>\n\n<pre><code>int id;\nlong timeInMillis;\n\nwhile (...) {\n // ...\n\n try {\n id = Integer.parseInt(tokens[1]); \n timeInMillis = Long.parseLong(tokens[2]);\n } catch (NumberFormatException e) {\n // Note that the specific exception is caught instead of Exception\n }\n\n // ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T13:40:24.157", "Id": "41455", "Score": "0", "body": "Does moving the if() part out of the try/catch block make much difference? As for the `Exception` I'm not sure if `NumberFormatException` is the only one that can be thrown and I must be sure that the app keeps running." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T13:43:10.777", "Id": "41457", "Score": "1", "body": "As to `.parseInt()` and `.parseLong()`, this is guaranteed to be the only exception as per the javadoc. `NullPointerException` cannot be thrown here. Moving the `if` out of it just makes the try block thinner, no real difference ;) But I like my try blocks small." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T13:34:28.593", "Id": "26753", "ParentId": "26752", "Score": "2" } }, { "body": "<p>This is indeed way too complex. In fact I think there's enough responsibilities in this one method to be spread over a few classes.</p>\n\n<ul>\n<li>managing the history file</li>\n<li>parsing history records</li>\n<li>processing history records</li>\n<li>counting lines</li>\n<li>logging</li>\n</ul>\n\n<p>These points may map to simply a helper method or a separate class.</p>\n\n<p>Try organizing this behavior in several levels of abstraction. Try checking the existence of the file prior to tryig to parse its contents. Making a class that models the content of one record will definitely help. It'll make a good home for some of the validation and parsing logic. Don't be afraid to make private helper methods. They can greatly improve readability and lower complexity per method significantly.</p>\n\n<p>The top level version of this method could look like this :</p>\n\n<pre><code>public ExchangeHistory loadHistory(String path) {\n List&lt;HistoryRecord&gt; records = new ArrayList&lt;&gt;();\n for (String line : new LineIterable(getHistoryReader(path))) {\n records.add(HistoryRecord.fromTokenizedString(line));\n }\n return ExchangeHistory.fromHistoryRecords(nonNulls(records));\n}\n</code></pre>\n\n<p>In which </p>\n\n<ul>\n<li><code>getHistoryReader(path)</code> will fetch or create the file and wrap it as a reader.</li>\n<li><code>LineIterable</code> abstracts reading the BufferedReader to an Iterable (enabling the advanced for loop)</li>\n<li><code>HistoryRecord</code> parses the tokens of a line, and can be queried for the parsed data.\n<ul>\n<li><code>fromTokenizedString(line)</code> returns a valid <code>HistoryRecord</code> or <code>null</code></li>\n</ul></li>\n<li><code>nonNulls()</code> filters nulls out of a List</li>\n<li><code>ExchangeHistory.fromHistoryRecords()</code> creates the <code>ExchangeHistory</code> based on a <code>List</code>/<code>Iterable</code> of <code>HistoryRecords</code></li>\n</ul>\n\n<p>As for logging, it always clutters code. Your error logging currently seems to be a placeholder for decent exception handling. The other logging appears to be used for debugging. I like <a href=\"http://en.wikipedia.org/wiki/Aspect-oriented_programming\" rel=\"nofollow\">AOP</a> to do logging, since it allows you to focus on the code, and the logging can be coded separately.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T21:45:30.303", "Id": "41495", "Score": "0", "body": "Won't there be too many classes in this case, each with like 10 lines of code? I think there is no need to separate points 2-4 in this case. And as for logging, could you please provide a small example of what you mean?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T05:12:42.777", "Id": "41510", "Score": "0", "body": "I've edited the answer to address this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-14T04:39:54.860", "Id": "42578", "Score": "1", "body": "@DaveJarvis `ConcurrentSkipListSet` throws `NullPointerException` when adding `null`s, while my intent is just to filter `null`s out. Aside from that : `nonNulls()` could indeed be implemented by copying into a `Collection` that ignores adding nulls." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-14T04:56:31.783", "Id": "42580", "Score": "0", "body": "I should have read the documentation more carefully, bowmore. I thought it failed silently." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T21:11:23.580", "Id": "26772", "ParentId": "26752", "Score": "6" } }, { "body": "<p>I like it. It's the best looking Java code I've seen posted here in a while. I have to disagree with @bowmore. For a hundred lines of code, it's quicker to code, easier to read, and easier to maintain in one little method like you have it. Keep it simple. Make classes <a href=\"http://www.youtube.com/watch?v=o9pEzgHorH0\" rel=\"nofollow\">only when you exhaust</a> what you can do the way you are coding now.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T07:09:20.953", "Id": "41513", "Score": "1", "body": "This is a method returning an instance of `ExchangeHistory`. How probable you think that it is not part of a much bigger enterprisey system? As for \" easier to read, and easier to maintain in one little method like you have it\" I disagree with all three points. And even if you are doing procedural programming, you still need to follow single responsibility principle, except only this time your components are procedures." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T07:26:01.650", "Id": "41515", "Score": "0", "body": "+1 *I agree* : old programmers write clear, readable code easy to debug, and they are able to make it evolve **only** if needed (*I agree* also with http://programmers.stackexchange.com/users/1130/rachel , a very good link)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T03:09:23.070", "Id": "26782", "ParentId": "26752", "Score": "1" } }, { "body": "<p>One thing you could do in a situation like this is to move the meat of the <code>try</code> block into an overloaded function that takes the <code>reader</code> as an argument. This would not only reduce the nesting a bit, but it would also separate the parsing logic from the file/reader handling.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T12:15:27.523", "Id": "26794", "ParentId": "26752", "Score": "3" } }, { "body": "<p>I would rewrite it like this:</p>\n\n<pre><code>public static ExchangeHistory loadHistory(String path) {\n File file = new File(path);\n\n BufferedReader reader = null;\n try {\n reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));\n\n return parseHistory(reader);\n } catch (FileNotFoundException e) {\n log.warn(\"No exchange history file found at \" + path);\n\n createNewFile(file);\n return ExchangeHistory.EMPTY; \n } catch (IOException e) {\n log.error(\"Unable to read exchange history file at \" + path\n + \". All items will be synchronized anew\", e);\n return ExchangeHistory.EMPTY;\n } finally {\n closeOrLog(reader);\n }\n}\n\nprivate static ExchangeHistory parseHistory(Reader reader) {\n Map&lt;Integer, Date&gt; rtcHistory = new HashMap&lt;Integer, Date&gt;();\n Map&lt;Integer, Date&gt; almHistory = new HashMap&lt;Integer, Date&gt;();\n\n String line;\n int lineNumber = 1;\n\n while ((line = reader.readLine()) != null){\n String[] tokens = line.split(\"\\\\s\");\n if (tokens.length != 3){\n log.error(\"Unable to parse exchange history file at line: \" + lineNumber);\n continue;\n }\n\n try {\n ExchangeHistoryEntry entry = parseEntry(tokens);\n\n if (entry.isRTC()) {\n rtcHistory.put(entry.getID(), entry.getDate());\n } else if (entry.isALM()) {\n almHistory.put(entry.getID(), entry.getDate());\n }\n } catch (NumberFormatException e) {\n log.error(\"Unable to parse exchange history file at line:\" + lineNumber, e);\n }\n\n lineNumber++;\n }\n\n return new ExchangeHistory(rtcHistory, almHistory);\n}\n\nprivate static ExchangeHistoryEntry parseEntry(String[] tokens) throws NumberFormatException {\n int id = Integer.parseInt(tokens[1]);\n long timeInMillis = Long.parseLong(tokens[2]);\n\n return new ExchangeHistoryEntry(tokens[0], id, new Date(timeInMillis));\n}\n\nprivate static void createNewFile(File file) {\n try {\n file.createNewFile();\n log.info(\"Created new exchange history file at \" + path);\n } catch (IOException ioe){ \n log.error(\"Unable to create exchange history file at \" + path \n + \". Exchange session info won't be saved\", ioe);\n }\n}\n\nprivate static void closeOrLog(Reader reader) {\n if (reader != null){\n try {\n reader.close();\n } catch (IOException e) {\n log.error(\"Unable to close input stream. Resource leak possible\", e);\n }\n }\n}\n</code></pre>\n\n<p>Basically, I've done the following:</p>\n\n<ul>\n<li>Removed a bunch of comments because they were completely redundant. We can all read code -- there's no need to describe what it does if it's plain to see. </li>\n<li>Split the method into a few different methods. Now, each method has one responsibility, and all the code in each method works on a similar abstraction level. Now, it's very easy to see what the <code>loadHistory</code> method does without reading a screenful of code. Each individual method can be read and understood at a glance, and it's easy to verify that it does what it claims.</li>\n<li>Reduced the scope of a rtcHistory and almHistory by introducing ExchangeHistory.EMPTY.</li>\n<li>Introduced a helper class (<code>ExchangeHistoryEntry</code>) to reduce complexity and help further break the code down. It should be trivial to implement if you so choose.</li>\n</ul>\n\n<p>(Disclaimer: this is completely untested code.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-13T09:48:05.570", "Id": "27343", "ParentId": "26752", "Score": "2" } } ]
{ "AcceptedAnswerId": "26772", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T13:16:49.867", "Id": "26752", "Score": "3", "Tags": [ "java", "parsing", "logging" ], "Title": "Parsing a tabular log file into a hashmap" }
26752
<p>I came across the following code in our code base:</p> <pre><code>public interface ICloneable&lt;T&gt; { T Clone(); } public class MyObject : ICloneable&lt;MyObject&gt; { public Stuff SomeStuff { get; set; } T Clone() { return new MyObject { SomeStuff = this.SomeStuff }; } } </code></pre> <p>The pattern of using a generic interface and then doing <code>class A : Interface&lt;A&gt;</code> looks pretty bizarre to me. I have a feeling it's either useless or that it could be changed into something less intricated. Can someone explain if this is right/wrong, and how it should be changed?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T14:39:00.367", "Id": "41469", "Score": "3", "body": "Implementation of the `Clone` should return `MyObject` not `T`." } ]
[ { "body": "<p>This pattern is called a <a href=\"http://en.wikipedia.org/wiki/Prototype_pattern\" rel=\"nofollow\">Prototype object creation pattern</a>. Usually it is used to do a deep cloning of objects (that is if <code>Stuff</code> is a reference type then it should also be cloned).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T14:00:46.650", "Id": "41461", "Score": "0", "body": "almaz, what I don't get is why make the interface generic" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T14:08:55.703", "Id": "41462", "Score": "0", "body": "So that you get a typed instance. If you declare interface as non-generic, return value would be `object`. When you're cloning a `MyObject` instance it's logical to have a `MyObject` return value" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T14:35:51.380", "Id": "41468", "Score": "0", "body": "almaz: yes I understand the intent, but isnt'it disturbing to have `class A : I<A>`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T14:44:56.840", "Id": "41470", "Score": "0", "body": "and doesn't it violate the prototype object creation pattern to know the type of A? I mean that `((ICloneable) obj).Clone()` doesn't need to know the type of the underlying object. But `((ICloneable<MyObject>) obj).Clone()` does know the object, so why not create the method MyObject Clone() directly on the object itself, and not use any interface..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T15:40:47.277", "Id": "41474", "Score": "0", "body": "If you mark type parameter as covariant (`public interface ICloneable<out T>`) then you would be able to do the following assignment `ICloneable<object> generalClonable = new MyObject();`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T15:43:35.157", "Id": "41475", "Score": "1", "body": "ok, but if MyObject was ICloneable, I could do that too" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T16:20:34.617", "Id": "41477", "Score": "1", "body": "Generic interface gives you ability to use result either generally (as `object`) or as specific type (when you know it). Non-generic `ICloneable` interface will require you to cast result in case you know the type." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T13:57:51.943", "Id": "26755", "ParentId": "26754", "Score": "0" } }, { "body": "<p>You see this same pattern in the framework for <code>IEquatable&lt;T&gt;</code>. The most frequent use case for this is writing a generic method where you constrain the generic parameter type to implement the interface. This then allows you to write code in terms of a statically typed method <code>Equals&lt;T&gt;</code>. Another example is <code>IComparable&lt;T&gt;</code>, which is very handy for implementing methods relying on sorting without having to use the older style of providing an external Comparator class. For instance, the default comparison mechanism for the LINQ <code>OrderBy</code> method uses <code>IComparable&lt;T&gt;</code>, if it's available. In both of these cases, it's very natural to say that an instance of a type is comparable or equatable to other instances of the same type.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T14:00:40.680", "Id": "41531", "Score": "0", "body": "good point, it definitely makes sense it that case. Thanks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T13:52:33.597", "Id": "26802", "ParentId": "26754", "Score": "1" } } ]
{ "AcceptedAnswerId": "26802", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T13:47:09.983", "Id": "26754", "Score": "2", "Tags": [ "c#", "design-patterns", "generics" ], "Title": "Generically typed interface" }
26754
<p>ABAP is the programming language of the SAP R/3 system. It is a proprietary language that is used to write both the fundamental SAP R/3 system itself and the standardized business applications that run on top of this system. It can be used for customer extensions of the system or entirely new software applications as well. The on-line language reference is available at no cost from the <a href="http://help.sap.com/saphelp_nw2004s/helpdata/en/43/41341147041806e10000000a1553f6/frameset.htm" rel="nofollow">SAP Help Portal</a>. Another great community - almost as rewarding as StackOverflow - is the <a href="http://scn.sap.com" rel="nofollow">SAP Community Network</a>.</p> <p>Useful links:-</p> <ul> <li><a href="http://en.wikipedia.org/wiki/ABAP" rel="nofollow">ABAP Wikipedia</a> </li> <li><a href="http://programmers.stackexchange.com/questions/119190/pros-and-cons-of-taking-an-abap-job">pros and cons of taking an ABAP job</a></li> <li><a href="http://sap-install.blogspot.com/2008/09/mini-sap.html" rel="nofollow">mini-sap</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T17:30:56.597", "Id": "26760", "Score": "0", "Tags": null, "Title": null }
26760
ABAP is the programming language of the SAP R/3 system.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T17:30:56.597", "Id": "26761", "Score": "0", "Tags": null, "Title": null }
26761
<p>I've written this snippet to extract a review request status from review-board in python. It works well but i'm very new to python and i would like to know if i could write this any better.<br> Should i put <code>conn.close</code> in it's own try statement ?</p> <p>This script is supposed to run as part of a post-commit hook in mercurial. If the review-board server is not responding i still want to be able to commit without any issues. If the commit is non existent then an empty string is ok.</p> <pre><code>import httplib import json def getReviewStatus(reviewboardUrl, id): try: conn = httplib.HTTPConnection(reviewboardUrl, 80) headers = { 'Accept': 'application/json', 'Content-Type': 'application/json; charset=UTF-8' } conn.request("GET", "/api/review-requests/%s/" % id, headers=headers) return json.loads(conn.getresponse().read())['review_request']['status'] except: return "" finally: conn.close() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T09:45:54.560", "Id": "41520", "Score": "1", "body": "is this a standalone script? if so I'd let it blow on errors, don't catch any exceptions (specially don't *silently* catch *all* exceptions)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T09:52:39.370", "Id": "41522", "Score": "0", "body": "i amended my question" } ]
[ { "body": "<p>Looks pretty good to me. Regarding <code>conn.close()</code>, definitely don't put this in its own <code>try</code> statement, because if there's a problem with the earlier code, the connection might not get closed. I know you're not using Python 3, but ss an alternative, you might consider using the <code>with</code> statement and let Python handle the closing for you. See <a href=\"http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects\" rel=\"nofollow\">http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects</a> (end of section) and <a href=\"http://docs.python.org/2/library/contextlib.html#contextlib.closing\" rel=\"nofollow\">http://docs.python.org/2/library/contextlib.html#contextlib.closing</a></p>\n\n<p>Your code might look like this:</p>\n\n<pre><code>import httplib\nimport json\nfrom contextlib import closing\n\ndef getReviewStatus(reviewboardUrl, id):\n try:\n with closing(httplib.HTTPConnection(reviewboardUrl, 80)) as conn:\n headers = {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json; charset=UTF-8'\n }\n conn.request(\"GET\", \"/api/review-requests/%s/\" % id, headers=headers)\n return json.loads(conn.getresponse().read())['review_request']['status']\n except:\n return \"\"\n</code></pre>\n\n<p>I find it's good to get into the habit of using <code>with</code> to open resources so don't have to worry about forgetting to close the connection.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T17:35:01.893", "Id": "41548", "Score": "0", "body": "Wow, this is exactly what i had in mind ! Thanks a bunch !! i knew about `with` but i didn't knew about `from contextlib import closing`, absolutely brilliant !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T17:39:55.947", "Id": "41550", "Score": "1", "body": "Out of interest, what would happen with this code if the `requests` throws an exception and the implicit `close` call throws an exception as well ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T18:01:16.837", "Id": "41552", "Score": "0", "body": "That's a good question! This would be difficult to test. Maybe ask on Stack Overflow? I personally have never seen an exception thrown while trying to close a file/socket. Are you getting one, or just trying to code defensively?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T22:47:55.630", "Id": "41560", "Score": "0", "body": "just trying to be defensive :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T16:55:30.843", "Id": "26814", "ParentId": "26762", "Score": "1" } } ]
{ "AcceptedAnswerId": "26814", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T18:04:10.567", "Id": "26762", "Score": "2", "Tags": [ "python" ], "Title": "python httplib snippet" }
26762
<p>My code already works 100%, just trying to figure out if there is an easier, better or speedier way to do this. Outputs to an HTML table to display results.</p> <p>Something that took me a while to figure out was how to select the correct parts of the following arrays ($name, $business, $email, $orderstatus) because you end up with the same number of keys in all arrays, except for $orderid -- which you are filtering down to only unique results. So you end up with less keys/rows in the $orderid array compared to the others. This creates the need for "as $key => $value" in the display section to match up the correct order ID's with the correct customer information.</p> <p>I was also wondering if this is a secure way to handle log ons.</p> <pre><code>&lt;?php session_start(); if (!isset($_SESSION['username'])){ header("location:login.php"); } // DB Credentials $dbusername = 'xxxx'; $dbpassword = 'xxxx'; // Connect to order database $conn = new PDO('mysql:host=localhost;dbname=xxxx_orders', $dbusername, $dbpassword); $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); // Select Order IDs from database try { $stmt = $conn-&gt;prepare('SELECT * FROM orders'); $stmt-&gt;execute(); } catch (Exception $e) { echo '&lt;p&gt;', $e-&gt;getMessage(), '&lt;/p&gt;'; } // Add results to array $orderid foreach ($stmt as $row) { // If array $orderid does not exist, create it. Otherwise, add results to existing array if (is_array($orderid)) { $orderid[] = $row['orderid']; } else { $orderid = array($row['orderid']); } // Filter out duplicate order ID numbers from the array. $orderid = array_unique($orderid); // If array $email does not exist, create it. Otherwise, add results to existing array if (is_array($email)) { $email[] = $row['email']; } else { $email = array($row['email']); } // If array $orderstatus does not exist, create it. Otherwise, add results to existing array if (is_array($orderstatus)) { $orderstatus[] = $row['orderstatus']; } else { $orderstatus = array($row['orderstatus']); } } // Close PDO connection $conn = null; // Connect to customer database $conn = new PDO('mysql:host=localhost;dbname=xxxx_customers', $dbusername, $dbpassword); $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); // For each e-mail in the array $email, run the following code. foreach ($email as $value) { // Select all first names, last names, and business names from customers database by email provided in $email $stmt = $conn-&gt;prepare('SELECT fname,lname,business FROM customers WHERE email = :email'); $stmt-&gt;bindParam(':email',$value,PDO:: PARAM_INT); $stmt-&gt;execute(); // For each result found in database foreach ($stmt as $row) { // If array $name does not exist, create it. Otherwise, add results to existing array. // Also appends first name and last name from database together to create 1 full name if (is_array($name)) { $name[] = $row['fname'] . " " . $row['lname']; } else { $name = array($row['fname'] . " " . $row['lname']); } // If array $business does not exist, create it. Otherwise, add results to existing array if (is_array($business)) { $business[] = $row['business']; } else { $business = array($row['business']); } } } ?&gt; &lt;?php // For each order ID (which has been filtered to unique IDs...) run the following code. $key is equal to the key in array $orderid // and $value is equal to the actual string/value from the array $orderid foreach ($orderid as $key =&gt; $value) { echo "&lt;tr&gt;"; // Display First/Last name from array $name with $key being equal to the corresponding key from array $orderid. // The key is necessary to properly display the correct result echo "&lt;td align=center&gt;" . $name[$key] . "&lt;/td&gt;"; // Display business name from array $name with $key being equal to the corresponding key from array $orderid. // The key is necessary to properly display the correct result echo "&lt;td align=center&gt;" . $business[$key] . "&lt;/td&gt;"; // Display email from array $name with $key being equal to the corresponding key from array $orderid. // The key is necessary to properly display the correct result echo "&lt;td align=center&gt;" . $email[$key] . "&lt;/td&gt;"; // Display order status from array $name with $key being equal to the corresponding key from array $orderid. // The key is necessary to properly display the correct result echo "&lt;td align=center&gt;" . $orderstatus[$key] . "&lt;/td&gt;"; // Display First/Last name from array $name with $key being equal to the corresponding key from array $orderid. // The key is necessary to properly display the correct result echo "&lt;td align=center&gt;&lt;a href=editorder.php?q=" . $orderid[$key] . "&gt;" . $orderid[$key] . "&lt;/a&gt;&lt;/td&gt;"; echo "&lt;/tr&gt;"; } ?&gt; </code></pre>
[]
[ { "body": "<p>You should look at how your accessing the data from both <code>orders</code> and <code>customers</code>. Your code is currently looping through the result of <code>SELECT * FROM orders</code> to retreive additional data from <code>customers</code> by <code>SELECT fname,lname,business FROM customers WHERE email = :email</code>.</p>\n\n<p>You can perform these queries by using a JOIN and use less overhead on all this looping / variable array creation.</p>\n\n<p><strong>Improved Query</strong></p>\n\n<pre><code>SELECT o.*, c.fname, c.lname, c.business \nFROM xxx_orders.orders o, xxx_customers.customers c \nWHERE c.email = o.email;\n</code></pre>\n\n<p>From here, you can loop through it from <code>$stmt-&gt;execute()</code> and have all your data in one single array to output in your DOM.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T19:32:40.477", "Id": "26767", "ParentId": "26765", "Score": "3" } } ]
{ "AcceptedAnswerId": "26767", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T19:13:55.900", "Id": "26765", "Score": "-1", "Tags": [ "php", "mysql", "pdo", "session" ], "Title": "Can this code be improved upon?" }
26765
<p>Here's the <a href="https://github.com/bevacqua/ponyfoo/blob/master/src/frontend/js/plugin/jquery.readingTime.js" rel="nofollow"><strong>full source</strong></a> to a plugin I'm developing, the relevant code I want to refactor is:</p> <pre><code>function measure($element, $bubble){ var scrollTop = $window.scrollTop(), viewportHeight = $window.height(), readableTop = $element.position().top, readableHeight = $element.height(), readableBottom = readableTop + readableHeight, scrollHeight = viewportHeight / readableHeight * viewportHeight, progress = (scrollTop - readableTop) / (readableHeight - viewportHeight), total = getTotalMinutes($element), remaining = Math.ceil(total - (total * progress)), distanceProgress = (scrollTop - readableTop) / readableHeight, distanceLiteral = readableTop + distanceProgress * readableHeight + viewportHeight / 2 - $bubble.height() / 2, distance = Math.max(readableTop, Math.min(distanceLiteral, readableBottom)); return { remaining: remaining, progress: progress, distance: distance }; } </code></pre> <p>How might I make this calculation more understandable? I'm not terribly good at math, so I got there by trial and error, pretty much.</p> <p>Now I'd like to refactor into something more readable or at least trim the repetitive nonsense, but I have no clue where to start.</p> <p>Could you lend me a hand or give me any advice on how to tackle this?</p>
[]
[ { "body": "<p>Strictly in terms of code readability, you want to break down a function like this into it's core parts. Additionally, to reduce repetitive behavior you could make it more of a prototype and use some object oriented style to get to your result without a block of math.</p>\n\n<p><strong>Things to Consider</strong></p>\n\n<ul>\n<li><a href=\"http://en.wikipedia.org/wiki/Law_Of_Demeter\" rel=\"nofollow\">Law of Demeter</a> -\nPassing into your function only what you need and not entire objects.</li>\n<li>Breaking your function into segments, why not use methods to\nsystematically get to your answer? Easily readable/maintainable.</li>\n<li>Reduce the amount of variable creation, you dont need to set each\nvalue to a new variable when one is already passed in from the\nfunction arguments. Law of Demeter helps here, too.</li>\n<li>Keeping your code expandable.</li>\n</ul>\n\n<p>Here's an example of a function that follows the three above rules, a simple example that leaves you to put in your mathematics.</p>\n\n<p><strong>Example</strong></p>\n\n<pre><code>var measure = function(elementHeight, elementPositionTop, bubbleHeight) {\n var remaining = 0, progress = 0, distance = 0;\n\n return {\n init: function() {\n measure.buildRemaining();\n measure.buildProgress();\n measure.buildDistance();\n },\n buildRemaining: function() {\n remaining = elementHeight * bubbleHeight;\n },\n buildProgress: function() {\n progress = remaining / 2.5;\n },\n buildDistance: function() {\n distance = (elementPositionTop - progress) + remaining;\n },\n result: function() {\n measure.init();\n return {\n remaining: remaining,\n progress: progress,\n distance: distance\n }\n }\n }\n}($element.height(), $element.position().top, $bubble.height());\n</code></pre>\n\n<p><strong>Accessing the Function</strong></p>\n\n<pre><code>measure.result();\n</code></pre>\n\n<p><strong>Returns</strong></p>\n\n<pre><code>Object { remaining=5850, progress=2340, distance=3582 }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T20:28:01.280", "Id": "26770", "ParentId": "26766", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T19:30:13.297", "Id": "26766", "Score": "1", "Tags": [ "javascript" ], "Title": "Math calculation refactoring in JavaScript" }
26766
<pre><code>#!/usr/bin/env ruby require 'pivotal-tracker' require 'yaml' TEMP_DIR = "#{ENV['HOME']}/.pivotal/" TEMP_FILE = TEMP_DIR + "temp.yml" CONFIG_FILE = TEMP_DIR + "config.yml" unless File.directory? TEMP_DIR Dir::mkdir TEMP_DIR end unless File.file? TEMP_FILE f = File.open(TEMP_FILE, 'w') f.write("id: -1") end unless File.file? CONFIG_FILE f = File.open(CONFIG_FILE, 'w') f.write("") end # TEMP FILE format: # current_story_id: 123 OR -1 def story_info story puts story.name puts "id:\t\t#{story.id}" puts "notes:\t\t#{story.description}" puts "status:\t\t#{story.current_state}" puts "estimate:\t#{(story.estimate == -1) ? 'unestimated' : story.estimate}" end def is_next string string == 'next' end def id string !string.match(/^[\d]+(\.[\d]+){0,1}$/).nil? end def current string string == 'current' end def story_has_been_started f = YAML.load_file(TEMP_FILE) @current_id = f['id'] f['id'] != -1 end def update_id id f = File.open(TEMP_FILE, 'w') f.write("id: #{id}") @current_id = id end def set_config key, value config = YAML::load(File.read(CONFIG_FILE)) || {} config[key.to_sym] = value open(CONFIG_FILE, 'w') { |f| YAML::dump(config, f) } end def authenticate config = YAML::load(File.read(CONFIG_FILE)) || {} has_email = true, has_password = true unless config.has_key? :email puts "\033[33mUse pivotal set email EMAIL to set your pivotal tracker email\033[0m\n" has_email = false end unless config.has_key? :password puts "\033[33mUse pivotal set password PASSWORD to set your pivotal tracker email\033[0m\n" has_password = false end unless has_email and has_password exit 0 end PivotalTracker::Client.token(config[:email], config[:password]) end @current_id = nil begin unless ARGV[0] == 'set' authenticate aidin = PivotalTracker::Project.all.first end rescue puts "\033[33mInvalid Credentials\033[0m\n" exit 0 end case ARGV[0] when "info" # pivotal info next # pivotal info id # pivotal info current if is_next(ARGV[1]) puts "\033[32mDisplaying information for next story\033[0m\n" story_info(aidin.stories.all(owner: 'Chintan Parikh', state: 'unstarted').first) elsif id(ARGV[1]) story = aidin.stories.find(Integer(ARGV[1])) unless story.nil? puts "\033[32mDisplaying information for story #{ARGV[1]}\033[0m\n" story_info(story) else puts "\033[33mNo story with id #{ARGV[1]} exists\033[0m\n" end elsif current(ARGV[1]) if story_has_been_started story = aidin.stories.find(@current_id) puts "\033[32mDisplaying information for current story\033[0m\n" story_info(story) else puts "\033[33mNo story has been started. Use pivotal start to start a story first\033[0m\n" end end when "estimate" # pivotal estimate next 1-8 # pivotal estimate id 1-8 # pivotal estimate current 1-8 when "start" # pivotal start next # pivotal start id if story_has_been_started current_branch = `git branch | grep "*" | sed "s/* //"`.chomp status = `git status -s` if !status.empty? puts "\033[33mYou are currently working on story #{@current_id} and have uncommitted changes on #{current_branch}. If you continue, your uncommitted changes will be lost. Continue? (Y/N)\033[0m\n" continue = false while (!continue) option = $stdin.gets.chomp if option == 'N' exit 1 elsif option != 'Y' puts "Please enter either Y or N" else continue = true; end end end end `git stash` `git stash drop` `git checkout develop` `git pull` if is_next(ARGV[1]) story = aidin.stories.all(owner: 'Chintan Parikh', state: 'unstarted').first new_branch = "feature/#{story.id}_#{story.name.downcase.gsub(' ', '_').gsub(/[^0-9A-Za-z_]/, '')}" `git checkout -b #{new_branch}` elsif id(ARGV[1]) story = aidin.stories.find(Integer(ARGV[1])) unless story.nil? new_branch = "feature/#{story.id}_#{story.name.downcase.gsub(' ', '_').gsub(/[^0-9A-Za-z_]/, '')}" `git checkout -b #{new_branch}` else puts "\033[33mNo story with id #{ARGV[1]} exists\033[0m\n" end end update_id(story.id) unless story.nil? story.update(current_state: 'started') puts "\033[32mStory #{story.id} has been started\033[0m\n" story_info(story) when "complete" if story_has_been_started story = aidin.stories.find(@current_id) branch = "feature/#{story.id}_#{story.name.downcase.gsub(' ', '_').gsub(/[^0-9A-Za-z_]/, '')}" `git push origin #{branch}` story.update(current_state: 'finished') story.update(current_state: 'delivered') puts "\033[32mStory #{story.id} has been completed\033[0m\n" update_id(-1) else puts "\033[33mNo story has been started. Use pivotal start to start a story first\033[0m\n" end when 'abandon' if story_has_been_started story = aidin.stories.find(@current_id) story.update(current_state: 'unstarted') puts "\033[32mStory #{story.id} has been abandoned\033[0m\n" update_id(-1) else puts "\033[33mNo story has been started. Use pivotal start to start a story first\033[0m\n" end when 'list' stories = aidin.stories.all(owner: 'Chintan Parikh', current_state: ['unstarted', 'started', 'finished', 'delivered']) stories.each do |story| story_info(story) end when 'set' # set email # set password set_config(ARGV[1], ARGV[2]) puts "\033[32m#{ARGV[1]} has been set to #{ARGV[2]}\033[0m\n" end </code></pre> <p>It's a pretty basic application to simplify my workflow where I'm interning. I'd like to chuck it on my github, but I'd rather the code was a little nicer before I throw it up for the world to see. Any idea where, or how I should start refactoring?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T21:40:30.747", "Id": "41494", "Score": "2", "body": "wants code to be \"nicer before I throw it up for the world to see\" - posts code on the internet anyway :) But in all seriousness, I'd probably start by removing the hard coded name. I'm thinking it should be possible to get your name via the pivotal library you're using, since you already give it an email and password (and that config might work better as environment variables or a ~/.pivotalconfig - or something - file)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-17T10:57:56.723", "Id": "164960", "Score": "0", "body": "You should really try rubocop, it is fascinating!" } ]
[ { "body": "<p>I haven't used Pivotal Tracker, so I can't really say what's \"right\" to do, purpose-wise. However, skimming through your code, I have a few ideas:</p>\n\n<h3>1. Extend PivotalTracker's classes for fun and profit</h3>\n\n<p>Instead of a global method like <code>story_info</code> (which I'd prefer was called <code>print_story_info</code> as that what it does), I'd probably extend the <code>PivotalTracker::Story</code> class with an <code>info</code>, <code>inspect</code>, or <code>to_s</code> method, so you can simply write <code>puts story.info</code> when necessary. Something like</p>\n\n<pre><code>module PivotalTracker\n class Story\n def info\n &lt;&lt;-EOT\n #{name}\n ID: #{id}\n Notes: #{description}\n Status: #{story.current_state}\n Estimate: #{estimate == -1 ? 'none' : estimate}\n EOT\n end\n end\nend\n</code></pre>\n\n<p>Do the same to add a class method for finding \"your\" stories, and whatever else you need to do with Pivotal.</p>\n\n<h3>2. Those string-checking functions...</h3>\n\n<p>Your <code>is_next</code>, <code>id</code> and <code>current</code> methods smell pretty grim. For one, it should - if anything - be <code>next?</code>, <code>id?</code>, and <code>current?</code>, but really there's no need for them to begin with. You only use them twice in your code. Yes, yes, DRY and all that, but honestly, a simple <code>string == \"next\"</code> comparison does not need to be abstracted into a method.</p>\n\n<p>Now, if you were doing something more fault-tolerant like downcasing before comparing, or allowing short-hand args like \"n\" for \"next\", then <em>maybe</em>. But even so, the methods would still smell. Remember, in Ruby you can use regular expressions directly in string switches, e.g.</p>\n\n<pre><code>case some_string\nwhen /^n(ext)?$/i\n # do stuff\ncase...\n</code></pre>\n\n<p>That said, your code could absolutely benefit from encapsulating its logic in more methods and classes, but this isn't the place to start.</p>\n\n<p>I'd recommend using an option/command line switch parser to do the ARGV-checking/-translation heavy-lifting, and in general restructuring stuff. Right now, your script is basically bash written in Ruby, with big, global switches and all. But it could be a lot cleaner with more OOP and a few helpful gems.</p>\n\n<h3>3. Hand-coded terminal styling</h3>\n\n<p>Hand-coding the styles makes the code harder to read and more error-prone (cosmetic errors, but still). Use <a href=\"https://www.ruby-toolbox.com/categories/Terminal_Coloring\" rel=\"nofollow\">a coloring gem</a> of some sort to do that stuff for you (and to check if the terminal even supports colors and styles!)</p>\n\n<h3>4. Check that shell commands actually succeed</h3>\n\n<p>In your <code>start</code>, er, \"function\", you perform a lot of git commands, some very destructive. I'd do some serious checking before and after that. In particular I'd at least check <code>$?.success?</code> a few times to make sure that a command actually succeeded before running the next one.</p>\n\n<h3>5. The <code>estimate</code> argument</h3>\n\n<p>All commented out → just remove it.<br>\nJust saying :)</p>\n\n<p>Also see the comment I posted to your question (i.e. don't hardcode your name in there)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T01:43:47.260", "Id": "41501", "Score": "0", "body": "Brilliant, thanks so much! I'll get to work :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T22:09:38.170", "Id": "26776", "ParentId": "26768", "Score": "4" } } ]
{ "AcceptedAnswerId": "26776", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T20:04:46.203", "Id": "26768", "Score": "1", "Tags": [ "ruby" ], "Title": "Quick and dirty command line application in Ruby. Now it's time to refactor, where should I start?" }
26768
<p>I am developing a large .NET app. The previous developer used Martin Fowlers Transaction script design pattern. Please see the code below:</p> <pre><code>Public Class TypeStudent Private _Name As String Private _Type As String 'Undergraduate or postgraduate Public Property Name() As String Get Return _Name End Get Set(ByVal value As String) _Name = value End Set End Property Public Property Type() As String Get Return _Type End Get Set(ByVal value As String) _Type = value End Set End Property End Class Public Class Students Public Sub Add(ByVal typeStudent As TypeStudent) End Sub Public Sub Remove(ByVal typeStudent As TypeStudent) End Sub Public Sub Enrol(ByVal typeStudent As TypeStudent) If typeStudent.Type = "U" Then 'Undergraduate specific logic ElseIf typeStudent.Type = "P" Then 'Postgraduate specific logic End If End Sub End Class </code></pre> <p>Notice that there is one Student class and Student.Enrol has to check the type of student before executing the appropriate logic. Now please see the refactored code below, which uses a domain model approach:</p> <pre><code>Public Class Student Private Name As String Private Type As String Public Sub Add() End Sub Public Sub Remove() End Sub End Class Public Class Undergraduate Inherits Student Public Sub Enrol() End Sub End Class Public Class Graduate Inherits Student Public Sub Enrol() End Sub End Class </code></pre> <p>Notice that Undergraduate and PostGraduate has its own implementation of Enrol. I want to refactor more code so that it is like sample B to make it more reuseable and maintainable. My question is; is it a bad idea to mix and match domain logic patterns in the same application i.e. part of the app written using Transaction Script and another part using domain model?</p>
[]
[ { "body": "<p>I don't think that there is inherently anything \"wrong\" with having multiple patterns like this in a single application, especially during a refactoring exercise. I would strongly suggest documenting the patterns that you are changing from and to and the reason for the modification so that future developers understand what is happening.</p>\n\n<p>I would make one substantial modification to your proposed implementation, however: define Enrol at the Student level as an Overridable method. </p>\n\n<p>If there is no default implementation for all students, change Overridable to MustOverride. This will in turn force Student to be declared as MustInherit, but this is ok if you can only call Enrol on instances of Undergraduate or Graduate.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T21:54:58.303", "Id": "41774", "Score": "0", "body": "Thanks. +1 for the last paragraph. Have you mixed and matched domain layer patterns I.e. transaction script and domain model, in your own apps?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T22:58:49.983", "Id": "41776", "Score": "0", "body": "Yes, we have done this quite a bit. In some cases, we use the transaction script intentionally to make the classes easier to consume by external users (XML or json serialization, for example, where the method differences don't matter). For internal-only classes, our preferred pattern is domain, but we do have a lot of legacy code that has not been transitioned yet (if it isn't broken...)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-04T06:25:47.577", "Id": "41792", "Score": "0", "body": "Thanks. How does transaction script make serialisation easier?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T21:20:35.273", "Id": "26955", "ParentId": "26769", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T20:09:28.550", "Id": "26769", "Score": "1", "Tags": [ "design-patterns", "vb.net" ], "Title": "Mixing Fowlers patterns" }
26769
<p>Can I make any further improvements to simplify / speed up this code? My reason for creating new arrays for the variables <code>$name</code>, <code>$business</code>, <code>$email</code>, <code>$orderstatus</code> is because when displaying results there will be identical order ID numbers stored in $orderid.</p> <p>My script filters out the duplicates then with the remaining results matches up the keys from <code>$orderid</code> with the correct key in <code>$name</code>, <code>$business</code>, <code>$email</code>, <code>$orderstatus</code></p> <pre><code> &lt;?php session_start(); if (!isset($_SESSION['username'])){ header("location:login.php"); } // DB Credentials $dbusername = 'xxxx'; $dbpassword = 'xxxx'; // Connect to order database $conn = new PDO('mysql:host=localhost;dbname=xxxx_orders', $dbusername, $dbpassword); $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Select Order IDs from database try { $stmt = $conn-&gt;prepare('SELECT o.*, c.fname, c.lname, c.business FROM xxxx_orders.orders o, xxxx_customers.customers c WHERE c.email = o.email'); $stmt-&gt;execute(); } catch(PDOException $e) { echo "I'm sorry, xxxx. I'm afraid I can't do that."; file_put_contents('PDOErrors.txt', $e-&gt;getMessage(), FILE_APPEND); } // For each result create or add to the arrays $orderid,$name,$business,$email,$orderstatus foreach ($stmt as $result) { $orderid[]=$result['orderid']; $name[]=$result['fname'] . " " . $result['lname']; $business[]=$result['business']; $email[]=$result['email']; $orderstatus[]=$result['orderstatus']; } // Filter out duplicate order IDs from $orderid array $orderid = array_unique($orderid); // Display results section foreach ($orderid as $key =&gt; $value) { echo "&lt;tr&gt;"; // Display First/Last name from array $name with $key being equal to the corresponding key from array $orderid. // The key is necessary to properly display the correct result echo "&lt;td align=center&gt;" . $name[$key] . "&lt;/td&gt;"; // Display business name from array $name with $key being equal to the corresponding key from array $orderid. // The key is necessary to properly display the correct result echo "&lt;td align=center&gt;" . $business[$key] . "&lt;/td&gt;"; // Display email from array $name with $key being equal to the corresponding key from array $orderid. // The key is necessary to properly display the correct result echo "&lt;td align=center&gt;" . $email[$key] . "&lt;/td&gt;"; // Display order status from array $name with $key being equal to the corresponding key from array $orderid. // The key is necessary to properly display the correct result echo "&lt;td align=center&gt;" . $orderstatus[$key] . "&lt;/td&gt;"; // Display First/Last name from array $name with $key being equal to the corresponding key from array $orderid. // The key is necessary to properly display the correct result echo "&lt;td align=center&gt;&lt;a href=editorder.php?q=" . $orderid[$key] . "&gt;" . $orderid[$key] . "&lt;/a&gt;&lt;/td&gt;"; echo "&lt;/tr&gt;"; } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T08:04:05.650", "Id": "41570", "Score": "1", "body": "You set the location to _login.php_ but then you don't `exit`. So you send the data to the unauthorized user and hope the browser redirects quick enough before he sees it? I hope I am missing something not having done php in years." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T04:07:19.580", "Id": "41649", "Score": "0", "body": "Rob Apodaca's answer is spot-on. See also: http://codereview.stackexchange.com/questions/26803/php-dont-repeat-yourself/26810#26810" } ]
[ { "body": "<p>First, since you're only going to print one HTML table row per order, make sure your query only returns one database row per order. That way there's no need for extra complexity and throwing away bandwidth and memory. This <em>should</em> be doable by adding a simple <code>DISTINCT</code> after the <code>SELECT</code> keyword.</p>\n\n<p>Some other things:</p>\n\n<ul>\n<li>There is no way production code requires that much commenting.</li>\n<li>You can use a <code>foreach (array($name, $business, $email, $orderstatus) as $array)</code> to reduce the duplication in the loop.</li>\n<li>DB credentials, host and name should be in a configuration file.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T11:54:37.590", "Id": "41525", "Score": "0", "body": "Thank you. The reasoning behind all the notes is for my own personal use -- as I am new to coding, it just makes it so much easier to understand the logic. It's also my own web page so nobody else will see it.\n\nLooking in to the other stuff." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T15:37:47.103", "Id": "41535", "Score": "0", "body": "`DISTINCT` gives you distinct rows, no matter what the contents of your database. Of course, if you have multiple duplicate IDs in `xxxx_orders.orders` your DB has bigger problems." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T15:39:02.883", "Id": "41536", "Score": "0", "body": "I am not sure if this will work because the same order ID is replicated many times in the orders database. When a customer places an order, each order has unique product ID, but will have the same order ID for each row. If they order 10 products, 10 identical order IDs are inserted in to the orders database but they all have a different product ID. The e-mail for the specific customer is then added to each of the 10 rows so when the customer logs in there is a reference point (their e-mail) to pull up their order history, but I only want to display each order ID 1 time to the customer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T15:43:37.467", "Id": "41537", "Score": "0", "body": "Also I should say the order ID is not based on the default ID automatically assigned by mySQL (id column) -- it is assigned by using sha1(uniqid(mt_rand(), true)) and there is an actual column called orderid. I used sha1(uniqid(mt_rand(), true)) not for security just wanted something that would not have much chance of duplicating an order ID across 2 unrelated orders" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T08:26:27.810", "Id": "26786", "ParentId": "26771", "Score": "1" } }, { "body": "<p>Use explicit joins with the columns to join on in an ON clause. In this case it will make little difference but when queries are more complex it makes things easier to understand. Better to get into the habit now.</p>\n\n<p>Don't use SELECT * in real code. It is a useful shortcut when testing but can cause a potential problem in future.</p>\n\n<p>Best to use an integer unique key of the customer on the orders table rather than the email address. This should be faster, take less space and will not cause problems should 2 customers have the same email address, or should a customer change their email address.</p>\n\n<p>Orderid looks like the primary key of the orders table and as I would suspect that an order can only apply to one customer you should not have any duplicates to worry about removing.</p>\n\n<p>If Orderid is unique then you can just do all the processing of the rows in a single foreach, with no need to store copies of the data in an array.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T13:02:44.293", "Id": "26799", "ParentId": "26771", "Score": "0" } }, { "body": "<p>There are several major problems.</p>\n\n<ul>\n<li>You've mixed presentation with logic.</li>\n<li>You have some error/exception handling but not enough.</li>\n<li>Where is your PDOErrors.txt being written to? It looks like it's being written to your web directory. This allows someone to visit <a href=\"http://yoursite.com/PDOErrors.txt\" rel=\"nofollow\">http://yoursite.com/PDOErrors.txt</a> and view information that may allow them to compromise your site.</li>\n<li>You read from variables without ensuring they've been initialized. Even though php does not require variables to be initialized, I've found that this is a great place for bugs to live.</li>\n<li>The way you are iterating over query results and creating arrays makes no sense. I know you've mentioned there are duplicates to remove but your solution is not the way to handle that situation. As others have mentioned, you either have problems with your schema that should be corrected, or you should use sql to return the proper result set.</li>\n<li>You should not display unlimited result sets. The app might seem like it works now but, when your data grows the app will eventually crash due to either time or memory exhaustion. Result sets should be paginated with sane limits.</li>\n<li>Your code is vulnerable to cross site scripting (or at least broken html). Whenever you do <code>echo $foo</code>, you should instead do <code>echo htmlspecialchars($foo)</code>.</li>\n</ul>\n\n<p>I know you've stated you are new to programming so I understand and sympathize with wanting to write code this way. You get quick results and from your perspective and I'm sure it seems like it works. But, as your app grows, you will find that this style is completely un-maintainable. Even you, the author will not be able to follow or understand it (not to mention the poor sap who comes after you).</p>\n\n<p>Additionally, you have introduced some major security vulnerabilities without even realizing it. My advice is that you should immediately abandon this script and look to one of the many excellent frameworks for php (symfony or zend to name a few). These kinds of frameworks already contain what you need to write secure and organized applications. Although it would take time to learn how to use a framework, it is far less time than you would spend maintaining scripts written this way and dealing with the security problems.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T04:51:10.727", "Id": "41703", "Score": "0", "body": "Thanks Rob!\n\nI'm actually designing this page for my own company.\n\nIs there a way to put PDOErrors.txt below the public directory?\n\nI'm not too worried about the security of this page since I'm the only one who will view/use it's functions, but will be good practice to implement these tips.\n\nI see a lot of people talking about mixing presentation with logic... does it create a security vulnerability or is it just frowned upon because it's messy?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T05:00:29.213", "Id": "41704", "Score": "0", "body": "I'm still unsure if people understand my reasoning for iterating the results this way.\n\nSay I have order ID 12345 which contains products A, B, and C. There is a line in the database with order ID 12345, product A, a line with order ID 12345 product B, and another line with order ID 12345 and product C. There are also many other variables that may differ on each line... you could even have order ID 12345, product C, broken and order ID 12345, product C, working. I could not think of another way to display the results correctly as I only want each order ID display once (order history)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T05:08:01.960", "Id": "41706", "Score": "0", "body": "Since I am using array_unique the keys in the array change to say for example, 1,5,7,9 after filtering out duplicate order IDs and I need keys 1,5,7,9 from name,business,email,orderstatus to be displayed... otherwise I end up with keys 2,3,4 (from the first order) showing on the next 3 orders instead of keys 5, 7 and 9 which will display the correct information. That is why I did foreach $orderid as $key => $value because it lines everything up properly. Now if there is an SQL query that can handle all that for me I need to learn it... as I can see how it will shorten the code a lot" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-06T20:29:47.543", "Id": "42053", "Score": "0", "body": "@GarrettBurke yes, you can and should put log files outside of the webroot. As I metioned, the various frameworks do this for you already. If you must, try `file_put_contents(__DIR__ . '/../PDOErrors.txt', /*...*/);`" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T13:00:20.280", "Id": "26874", "ParentId": "26771", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T20:56:59.733", "Id": "26771", "Score": "1", "Tags": [ "php", "mysql", "pdo" ], "Title": "Displaying orders and customers in a table, filtering out duplicates" }
26771
<p>This function counts the number of times each letter appears in a string, then display the one that appears the most, and the number of times it appears. If there's a tie, it shows all of them, like "bz,5".</p> <p>I've got the feeling this could be done much better. Suggestions?</p> <pre><code>private static void LinqTest() { const string testString = "abbsabwertbfacsfgggdfgascd"; var count = 0; var charGroups = (from c in testString group c by c into g select new { c = g.Key, count = g.Count(), }).OrderByDescending(c =&gt; c.count); foreach (var @group in charGroups.Where(@group =&gt; count &lt;= @group.count)) { Console.WriteLine(@group.c + ": " + @group.count); count = @group.count; } } </code></pre>
[]
[ { "body": "<p>The trick is to group by the character, as you are doing, then do a <em>second</em> grouping by the count:</p>\n\n<pre><code>var testString = \"abbsabwertbfacsfgggdfgasc\";\n\nvar characterCounts =\n from character in testString\n group character by character into characterGroup\n group characterGroup.Key by characterGroup.Count() into countedCharacterGroup\n orderby countedCharacterGroup.Key descending\n select new\n {\n Characters = new string(countedCharacterGroup.ToArray()),\n Count = countedCharacterGroup.Key\n };\n\nvar topCharacterCount = characterCounts.First();\n\nConsole.WriteLine(\"{0},{1}\", topCharacterCount.Characters, topCharacterCount.Count);\n</code></pre>\n\n<p><strong>Breakdown</strong></p>\n\n<p>First, we do the same initial grouping:</p>\n\n<pre><code>from character in testString\ngroup character by character into characterGroup\n</code></pre>\n\n<p>Next, we group the characters by the number of times they appear:</p>\n\n<pre><code>group characterGroup.Key by characterGroup.Count() into countedCharacterGroup\n</code></pre>\n\n<p>Then, we order based on the character counts:</p>\n\n<pre><code>orderby countedCharacterGroup.Key descending\n</code></pre>\n\n<p>Finally, we create a string for each set of characters with the same count:</p>\n\n<pre><code>select new\n{\n Characters = new string(countedCharacterGroup.ToArray()),\n Count = countedCharacterGroup.Key\n}\n</code></pre>\n\n<p>We can also get rid of the loop, instead grabbing the top count and writing the joined character string:</p>\n\n<pre><code>var topCharacterCount = characterCounts.First();\n\nConsole.WriteLine(\"{0},{1}\", topCharacterCount.Characters, topCharacterCount.Count);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T23:28:38.327", "Id": "26778", "ParentId": "26775", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-29T21:58:58.107", "Id": "26775", "Score": "4", "Tags": [ "c#", "strings", "linq" ], "Title": "Counting the occurrence of each letter in a string" }
26775
<p>I have to make project for school in C# which has to use database and web service. I have made a program which starts a web service and gets a function from there which is used for connecting to a website. I am using HTML Agility Pack for parsing info from that website. Website info is then written in textbox and stored in database.</p> <p>Here is one function from project, and the rest is <a href="https://gist.github.com/anonymous/ae6759fa85a5ac7e6455" rel="nofollow">here</a>.</p> <pre><code> public void HtmlParser() { Encoding enc = Encoding.UTF8; HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument(); htmlDoc.Load(client.Request(), enc); HtmlNode root = htmlDoc.DocumentNode; HtmlNodeCollection jobNode = root.SelectNodes("//div[@class='jobBox']"); HtmlNodeCollection headerNode = root.SelectNodes("//div[@class='jobBox']/h1"); HtmlNodeCollection contentNode = root.SelectNodes("//div[@class='jobBox']/div[@class='content']"); HtmlNodeCollection linkNode = root.SelectNodes("//div[@class='jobBox']/a"); jobs = new List&lt;string&gt;(); headers = new List&lt;string&gt;(); content = new List&lt;string&gt;(); links = new List&lt;string&gt;(); full_links = new List&lt;Uri&gt;(); foreach (HtmlNode node in jobNode) { jobs.Add(node.InnerText); } foreach (HtmlNode node in headerNode) { headers.Add(node.InnerText.Trim()); } foreach (HtmlNode node in contentNode) { content.Add(node.InnerText.Trim()); } foreach (HtmlNode node in linkNode) { links.Add(node.GetAttributeValue("href", null).Trim()); Uri temp = new Uri(link + node.GetAttributeValue("href", null).Trim()); full_links.Add(temp); } htmlDoc.Save("file.htm", enc); StringParser(); } </code></pre> <p>Some variables are in Croatian, so don't get confused. I am looking for helpful reviews and tips on how I can make my code better.</p>
[]
[ { "body": "<p>One comment I'd have is that there is a LOT going on in that method... but for the most part \neach section is the same... </p>\n\n<ul>\n<li>GetNodeCollection</li>\n<li>Loop Through it</li>\n<li>Add it to a list</li>\n</ul>\n\n<p>You could probably pull that out into a method to shorten your code.</p>\n\n<pre><code>public List&lt;string&gt; ParseSection(HtmlNode root, string nodePath, bool isLink = false)\n{\n HtmlNodeCollection nodes = root.SelectNodes(nodePath);\n List&lt;string&gt; parsedNodes = new List&lt;string&gt;();\n foreach (HtmlNode node in nodes)\n {\n if(isLink)\n {\n parsedNodes.Add(node.GetAttributeValue(\"href\", null).Trim());\n }\n else\n {\n parsedNodes.Add(node.InnerText.Trim());\n }\n }\n return parsedNodes;\n}\n\npublic void HtmlParser()\n{\n Encoding enc = Encoding.UTF8;\n HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();\n htmlDoc.Load(client.Request(), enc);\n HtmlNode root = htmlDoc.DocumentNode;\n HtmlNodeCollection linkNode = root.SelectNodes();\n\n List&lt;string&gt; jobs = ParseSection(root, \"//div[@class='jobBox']\");\n List&lt;string&gt; headers = ParseSection(root, \"//div[@class='jobBox']/h1\");\n List&lt;string&gt; content = ParseSection(root, \"//div[@class='jobBox']/div[@class='content']\");\n List&lt;string&gt; links = ParseSection(root, \"//div[@class='jobBox']/a\", true); //TRUE\n List&lt;Uri&gt; fullLinks = links.Select(l =&gt; new Uri(l));\n\n htmlDoc.Save(\"file.htm\", enc);\n StringParser();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T09:48:29.513", "Id": "41521", "Score": "0", "body": "yea there are a lot of thing going on in that function :D thanks for tips, ill try to change something" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T09:40:42.183", "Id": "26791", "ParentId": "26787", "Score": "5" } } ]
{ "AcceptedAnswerId": "26791", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T08:31:10.093", "Id": "26787", "Score": "4", "Tags": [ "c#", "parsing" ], "Title": "Parsing website info with a database and web service" }
26787
<p><a href="http://projecteuler.net/problem=37" rel="nofollow">Project Euler problem 37</a> says:</p> <blockquote> <p>The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.</p> </blockquote> <p>Going right to left is trivial enough as you just keep dividing by 10:</p> <pre><code>IEnumerable&lt;long&gt; RTL (long x) { while(x &gt; 10) { x /= 10; yield return x; } } </code></pre> <p>Going left to right was a little trickier. Just wondering if there's a more optimal way to do this.</p> <pre><code>IEnumerable&lt;long&gt; LTR (long x) { while(x &gt; 10) { long y = x; //take a copy of current value of x; int powerten = 0; //variable to count what the 10^n value is while(y &gt; 10){ //calculate powerten by repeated dividing y / 10 y /= 10; // for 3797 this would be '3' i.e. 3.797 * 10^3 powerten++; } long p = (long)Math.Pow(10, powerten); // 10 ^ 3 = 1000 long z = (x/p)*p; // 3797/1000*1000 = 3000 x = (x - z); // subtract from x yield return x; } } </code></pre> <p>It runs pretty fast but I'm just wondering is there a more optimal way to remove the leftmost significant digit of a number on each iteration without all the "gymnastics".</p>
[]
[ { "body": "<p>I would suggest returning the truncations in order of increasing lengths for truncation from the left (checking the shorter tails for primality is faster, so if the number is not a left-truncatable prime, that should be detected faster on average when the tails are yielded in that order),</p>\n\n<pre><code>IEnumerable&lt;long&gt; LTR (long x)\n{\n long powerOfTen = 10;\n while(powerOfTen &lt;= x)\n {\n long tail = x % powerOfTen;\n powerOfTen *= 10;\n yield return tail;\n }\n}\n</code></pre>\n\n<p>is nice and short if you know that the argument <code>x</code> is never so large that the next larger power of 10 exceeds <code>long</code> range. I f <code>x</code> may be that large, you need to guard against overflow, slightly longer:</p>\n\n<pre><code>IEnumerable&lt;long&gt; LTR(long x)\n{\n // if (x &lt; 10) return ??;\n long bound = x/10, lastPowerOfTen = 1;\n while(lastPowerOfTen &lt;= bound)\n lastPowerOfTen *= 10; // doesn't overflow\n }\n long powerOfTen = 1;\n do\n {\n powerOfTen *= 10;\n yield return x % powerOfTen;\n }while(powerOfTen &lt; lastPowerOfTen);\n}\n</code></pre>\n\n<p>If you want to return the truncations in order of decreasing lengths, you can easily modify the last:</p>\n\n<pre><code>IEnumerable&lt;long&gt; LTR(long x)\n{\n // if (x &lt; 10) return ??;\n long bound = x/10, powerOfTen = 1;\n while(powerOfTen &lt;= bound)\n powerOfTen *= 10; // doesn't overflow\n }\n while(powerOfTen &gt; 1)\n {\n x %= powerOfTen;\n powerOfTen /= 10;\n yield return x;\n }\n}\n</code></pre>\n\n<p>Note: If the decimal representation of <code>x</code> contains at least one zero other than the last digit, these would all return the same value more than once. Since no (right or left) truncatable prime can have a zero digit in its decimal expansion, I did not care about that. If you do, in the last (decreasing length) version, you could easily avoid that by replacing</p>\n\n<pre><code>powerOfTen /= 10;\n</code></pre>\n\n<p>with a loop</p>\n\n<pre><code>do {\n powerOfTen /= 10;\n}while(powerOfTen &gt; 1 &amp;&amp; powerOfTen &gt; x);\n</code></pre>\n\n<p>In the increasing-length versions, that would not be as simple.</p>\n\n<p>Further note:</p>\n\n<pre><code>long p = (long)Math.Pow(10, powerten);\n</code></pre>\n\n<p>Don't use floating point functions for integer arithmetic. In this case, if the called <code>Math.Pow</code> function operates on <code>double</code>s [I'm not sure how that is in C#], it will not lead to wrong results, but it could produce wrong results if it operates on <code>float</code>s, and also in general (for other bases) even if <code>double</code> is used.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T12:34:33.597", "Id": "41526", "Score": "0", "body": "excellent :-) cheers for review" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T12:28:30.437", "Id": "26795", "ParentId": "26788", "Score": "3" } } ]
{ "AcceptedAnswerId": "26795", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T09:19:24.500", "Id": "26788", "Score": "4", "Tags": [ "c#", "performance", "programming-challenge", "mathematics" ], "Title": "Truncating an integer from left to right and right to left" }
26788
<p>How can I improve the following two views? Should the action listeners stay in the views?</p> <p><strong>StudentView.java</strong></p> <pre><code>package com.studentenverwaltung.view; import com.studentenverwaltung.controller.StudentController; import com.studentenverwaltung.helpers.MyTableCellRenderer; import com.studentenverwaltung.model.User; import com.studentenverwaltung.persistence.PerformanceDAO; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Observable; import java.util.Observer; import javax.swing.*; import javax.swing.table.DefaultTableModel; public class StudentView implements IView { private final static String WELCOME = "Herzlich Willkommen"; private final static String MEDIAN = "Notendurchschnitt"; private final static Object[] COLUMNS = {"Vorlesung", "Note"}; public JPanel contentPane; private JLabel lblWelcome; private JButton btnChangePassword; private JButton btnLogout; private JTextField txtId; private JTextField txtPassword; private JTextField txtDegreeProgram; private JLabel lblMedian; private JTable tblPerformance; private StudentController studentController; private User user; public StudentView(StudentController studentController, User user) { this.studentController = studentController; this.user = user; this.user.addObserver(new ModelObserver()); this.btnChangePassword.addActionListener(new ChangePasswordListener()); this.btnLogout.addActionListener(new LogoutListener()); } @Override public JPanel getContentPane() { return this.contentPane; } private double calculateMedian(DefaultTableModel tableModel) { int i = 0, rows = tableModel.getRowCount(); double total = 0; while (i &lt; rows) { total += (Double) tableModel.getValueAt(i, 1); i++; } return total / tableModel.getRowCount(); } private void updateMedian(StudentView view, DefaultTableModel tableModel) { view.lblMedian.setText(String.format("%s: %.2f", MEDIAN, calculateMedian(tableModel))); } private void updateTable(StudentView view, DefaultTableModel tableModel) { view.tblPerformance.setDefaultRenderer(Object.class, new MyTableCellRenderer()); view.tblPerformance.setModel(tableModel); } private DefaultTableModel createDefaultTableModel(StudentView view) { PerformanceDAO performanceDAO = new PerformanceDAO("Files/noten.csv"); Object[][] myData = performanceDAO.getPerformance(view.user.getId()); return new DefaultTableModel(myData, StudentView.COLUMNS); } private void updateLabelsAndTextFields(StudentView view) { view.lblWelcome.setText(String.format("%s, %s", WELCOME, view.user.toString())); view.txtId.setText(view.user.getId()); view.txtPassword.setText(view.user.getPassword()); view.txtDegreeProgram.setText(view.user.getDegreeProgram()); } private class ChangePasswordListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { StudentView view = StudentView.this; view.studentController.changePassword(); } } private class LogoutListener implements ActionListener { public static final String TITLE = "Beenden"; public static final String MESSAGE = "Sollen die Aenderungen gespeichert werden?"; @Override public void actionPerformed(ActionEvent e) { StudentView view = StudentView.this; int result = JOptionPane.showConfirmDialog(view.contentPane, MESSAGE, TITLE, JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { // TODO: save data } view.studentController.logout(); } } private class ModelObserver implements Observer { @Override public void update(Observable o, Object arg) { StudentView view = StudentView.this; updateLabelsAndTextFields(view); DefaultTableModel tableModel = createDefaultTableModel(view); updateTable(view, tableModel); updateMedian(view, tableModel); } } } </code></pre> <p><strong>LecturerView.java</strong></p> <pre><code>package com.studentenverwaltung.view; import com.studentenverwaltung.controller.LecturerController; import com.studentenverwaltung.model.User; import com.studentenverwaltung.persistence.PerformanceDAO; import com.studentenverwaltung.persistence.UserDAO; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Collection; import java.util.Observable; import java.util.Observer; import javax.swing.*; public class LecturerView implements IView { public static final String WELCOME = "Herzlich Willkommen"; public JPanel contentPane; private JLabel lblWelcome; private JButton btnChangePassword; private JButton btnLogout; private JTextField txtId; private JTextField txtPassword; private JTextField txtDegreeProgram; private JComboBox&lt;Object&gt; boxCourses; private JComboBox&lt;Object&gt; boxUsers; private JTextField txtGrade; private JButton btnSave; private JButton btnCalculateMedian; private JList lstBadStudents; private LecturerController lecturerController; private User user; public LecturerView(LecturerController lecturerController, User user) { this.lecturerController = lecturerController; this.user = user; this.user.addObserver(new ModelObserver()); this.btnChangePassword.addActionListener(new ChangePasswordListener()); this.btnLogout.addActionListener(new LogoutListener()); this.btnSave.addActionListener(new SaveGradeListener()); } @Override public JPanel getContentPane() { return this.contentPane; } private class ChangePasswordListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { LecturerView view = LecturerView.this; view.lecturerController.changePassword(); } } private class SaveGradeListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { // TODO: refactoring String course = LecturerView.this.boxCourses.getModel().getSelectedItem().toString(); User student = (User) LecturerView.this.boxUsers.getSelectedItem(); String id = student.getId(); double grade = Double.parseDouble(LecturerView.this.txtGrade.getText()); PerformanceDAO performanceDAO = new PerformanceDAO("Files/noten.csv"); performanceDAO.createOrUpdatePerformance(id, course, grade); } } private class LogoutListener implements ActionListener { public static final String TITLE = "Beenden"; public static final String MESSAGE = "Sollen die Aenderungen gespeichert werden?"; @Override public void actionPerformed(ActionEvent e) { LecturerView view = LecturerView.this; int result = JOptionPane.showConfirmDialog(view.contentPane, MESSAGE, TITLE, JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { // TODO: save data } view.lecturerController.logout(); } } private class ModelObserver implements Observer { @Override public void update(Observable o, Object arg) { // TODO: refactoring LecturerView view = LecturerView.this; view.lblWelcome.setText(String.format("%s, %s", WELCOME, view.user.toString())); view.txtId.setText(view.user.getId()); view.txtPassword.setText(view.user.getPassword()); view.txtDegreeProgram.setText(view.user.getDegreeProgram()); Object[] courses = view.user.getCourse() == null ? new Object[0] : view.user.getCourse().toArray(); DefaultComboBoxModel courseModel = new DefaultComboBoxModel&lt;Object&gt;(courses); view.boxCourses.setModel(courseModel); UserDAO userDAO = new UserDAO("Files/stud_info.csv"); Collection&lt;User&gt; studentCollection = userDAO.getUsersByRole("Student"); Object[] students = studentCollection == null ? new Object[0] : studentCollection.toArray(); DefaultComboBoxModel studentModel = new DefaultComboBoxModel&lt;Object&gt;(students); view.boxUsers.setModel(studentModel); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T11:10:32.243", "Id": "41524", "Score": "0", "body": "While I am not fluent with graphics programming, I am not sure it is a good idea to add listeners in the constructors..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T07:24:09.010", "Id": "41567", "Score": "1", "body": "I want to congratulate you for not having your view classes _extend_ `JPanel` or anything." } ]
[ { "body": "<p>Both of these classes have <code>ChangePasswordListener</code> and <code>LogoutListener</code> inner classes, each of which are almost identical. Both call the same functions in the corresponding controller classes, so there may be duplication there as well. See if there is a way you can eliminate this duplication.</p>\n\n<p>Extracting them as top level classes that can reused across views may be an option, but you would need to replace the direct class references with some common abstraction in order to do this.</p>\n\n<p>As an example, <code>LogoutListener</code> uses the view to get <code>view.contentPane</code>. It looks like <code>getContentPane()</code> is declared in <code>IView</code> (which the views already implement). In this case, you could add a constructor to <code>LogoutListener</code> that takes an <code>IView</code> that <code>actionPerformed()</code> can use to call <code>getContentPane()</code>.</p>\n\n<p>If there is a similar common abstraction for the controller functions, then you could do the same thing for that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T12:50:56.800", "Id": "26797", "ParentId": "26789", "Score": "0" } }, { "body": "<p><ul>\n<li><p>Things that are not view related should be moved elsewhere. View should not know anything about DAOs etc. It just should call methods on the controller. \nFor example:</p></p>\n\n<pre><code>PerformanceDAO performanceDAO = new PerformanceDAO(\"Files/noten.csv\");\nperformanceDAO.createOrUpdatePerformance(id, course, grade);\n</code></pre>\n\n<p>should just have been </p>\n\n<pre><code>LecturerView.this.lecturerController.createOrUpdatePerformance(id, course, grade);\n</code></pre></li>\n<li><p>You can refer to fields of the <strong>outer class</strong> from (non-static) <strong>inner class</strong> directly. The line above can be shortened to:</p>\n\n<pre><code>lecturerController.createOrUpdatePerformance(id, course, grade);\n</code></pre></li>\n<li><p>Since many of your <code>ActionListener</code> should be one-liners, it is more practical to implement them as <strong>anonymous inner classes</strong>. You can remove <code>ChangePasswordListener</code> class by changing the following line from :</p>\n\n<pre><code>this.btnChangePassword.addActionListener(new ChangePasswordListener());\n</code></pre>\n\n<p>to</p>\n\n<pre><code>this.btnChangePassword.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n lecturerController.changePassword();\n }\n});\n</code></pre>\n\n<p>Because you have a parameter named <code>lecturerController</code> which refers to the same object with, but hides the field <code>lecturerController</code> you would have to mark the parameter <code>final</code>. (Which is good practice anyways).</p>\n\n<p><ul>\n<li>You should not do anything more complicated that calling a method (or 2) in an action Listener. Look at your <code>LogoutListener</code>. Your specification (user story whatever) for that case might have been something like:</p>\n\n<blockquote>\n <p>When <em>Lecturer</em> <strong>Logs Out</strong>; he is prompted for saving chages, before he is logged out.</li>\n </ul>\n You call the <code>logout</code> method on <code>LecturerCotroller</code>, which is excellent. But why don't you call a method <code>promptForSaveChanges</code> for the first part of the spec. It only makes sense. You would not have to dig through codes; if spec changed such that \"<em>prompt user for changes if only unsaved changes exist</em>\" or \"<em>prompt for saving changes when user tries to close the main window</em>\"</p>\n</blockquote>\n\n<ul>\n<li>You should not instantiate your DAOs and services etc in listeners. They should be instantiated <em>once</em> in the <code>Main</code> class and passed to other components as constructor arguments. Just as you passed your controllers as constructor argument to your views; your controllers should get their DAOs etc in the same way.</li>\n</ul></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T07:17:03.560", "Id": "26834", "ParentId": "26789", "Score": "1" } } ]
{ "AcceptedAnswerId": "26834", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T09:35:08.673", "Id": "26789", "Score": "1", "Tags": [ "java", "swing" ], "Title": "Student and Lecturer views" }
26789
<p>I have an xml file from which I want to extract the value of attribute <code>custName</code> from the very first child. The code below works where I am using the dom parser. Is there a third-party library with which I can do the same with less code and more neatly?</p> <pre><code>import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = (Document) db.parse(new File( tempDir)); Node node = ((Document) document).getFirstChild(); String custName= node.getAttributes() .getNamedItem("custName") .getNodeValue(); assertEquals( "scott",custName); </code></pre> <p>Update:- Did the above approach use DOM4J (sorry but I am not sure)?</p>
[]
[ { "body": "<p>I think you should look into using a different parser for this particular situation. <a href=\"https://stackoverflow.com/questions/373833/best-xml-parser-for-java\">this page</a>\ncontains good comparisons between java xml parsers. Maybe SAX or StAX is more suitable here?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T10:12:33.943", "Id": "26792", "ParentId": "26790", "Score": "1" } }, { "body": "<p>You could use the Java XPath API:</p>\n\n<pre><code>import javax.xml.xpath.XPath;\nimport javax.xml.xpath.XPathFactory;\nimport org.xml.sax.InputSource;\n\nXPath xpath = XPathFactory.newInstance().newXPath();\nInputSource inputSource = new InputSource(???); // ??? = InputStream or Reader\nString custName = xpath.evaluate(\"//*[1]/@custName\", inputSource);\n</code></pre>\n\n<p>There is a lot more information in this article: <a href=\"http://www.ibm.com/developerworks/library/x-javaxpathapi/index.html\" rel=\"noreferrer\">http://www.ibm.com/developerworks/library/x-javaxpathapi/index.html</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-02T06:50:52.680", "Id": "154343", "Score": "0", "body": "Hello @joe-f, the link to the article is broken, can you update it please?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T13:16:04.707", "Id": "26801", "ParentId": "26790", "Score": "5" } }, { "body": "<p>You can typecast the node to Element and then use getAttribute.\nEg:</p>\n\n<pre><code>String attributeValue = ((Element)yourNode).getAttribute(\"yourAttribute\");\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-02-09T09:17:43.747", "Id": "154889", "ParentId": "26790", "Score": "1" } } ]
{ "AcceptedAnswerId": "26801", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T09:40:31.673", "Id": "26790", "Score": "3", "Tags": [ "java", "parsing", "xml" ], "Title": "Better way to get the XML attribute value?" }
26790
<p><a href="http://plugins.trac.wordpress.org/browser/seo-content-helper/tags/1.1/get-data.php" rel="nofollow">Entire Code Here</a></p> <p><strong>Don't repeat yourself</strong></p> <p>I know of the "Don't repeat yourself". Still it's getting messy in some places. The code below contains three blocks of code.</p> <p>They are similar in some ways and different in others. It doesn't follow the same pattern in all ways.</p> <p><strong>What it does</strong></p> <p>It creates an array that I loop out on the frontend.</p> <p><strong>Question</strong></p> <p>Is there any better way to do this kind of stuff? Less messy, better structure?</p> <pre><code>$message_start = '&lt;strong&gt;h2 tags&lt;/strong&gt; - '; $message_end = '&lt;span class="counter"&gt;' . $this-&gt;count_h2 . '&lt;/span&gt;'; if( $this-&gt;count_h2 == 0 ) { $message = 'No tags found. Add some!'; $array['content_editor']['count_h2']['status'] = 2; } elseif( $this-&gt;count_h2 == 1 ) { $message = 'Some found. Too few!'; $array['content_editor']['count_h2']['status'] = 1; } else { $message = 'Many found. Great!'; $array['content_editor']['count_h2']['status'] = 0; } $array['content_editor']['count_h2']['message'] = $message_start . $message . $message_end; $array['content_editor']['count_h2']['count'] = $this-&gt;count_h2; $message_start = '&lt;strong&gt;h3-h6 tags&lt;/strong&gt; - '; $h2_h6 = $this-&gt;count_h3 + $this-&gt;count_h4 + $this-&gt;count_h5 + $this-&gt;count_h6; $counter = ( $h2_h6 == 0 ) ? '' : $h2_h6; $message_end = '&lt;span class="counter"&gt;' . $counter . '&lt;/span&gt;'; if( $h2_h6 == 0 ) { $message = 'No found. Add some!'; $array['content_editor']['count_h3_h6']['status'] = 1; } else { $message = 'Found, great!'; $array['content_editor']['count_h3_h6']['status'] = 0; } $array['content_editor']['count_h3_h6']['message'] = $message_start . $message . $message_end; $array['content_editor']['count_h3_h6']['count'] = $this-&gt;h2_h6; $message_start = '&lt;strong&gt;Title keywords&lt;/strong&gt; - '; $counter = ( $this-&gt;found_keywords1_post_title == 0 ) ? '' : $this-&gt;found_keywords1_post_title; $message_end = '&lt;span class="counter"&gt;' . $counter . '&lt;/span&gt;'; if( count( $this-&gt;keywords1 ) == 0 ) { $message = 'No primary added.'; $array['content_editor']['missing_keywords1_post_title']['status'] = 2; } elseif( $this-&gt;found_keywords1_post_title == 0 ) { $message = 'No primary found.'; $array['content_editor']['missing_keywords1_post_title']['status'] = 2; } else { $s = ( $this-&gt;found_keywords1_post_title != 1 ) ? 's' : ''; $message = 'Primary found.'; $array['content_editor']['missing_keywords1_post_title']['status'] = 0; } $array['content_editor']['missing_keywords1_post_title']['message'] = $message_start . $message . $message_end; $array['content_editor']['missing_keywords1_post_title']['count'] = $this-&gt;found_keywords1_post_title; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T17:36:57.037", "Id": "41549", "Score": "0", "body": "I haven't done enough Wordpress plugin development to recommend the _best_ way of implementing this, but trying to follow the MVC pattern would probably help here. A quick google returned this: http://www.renegadetechconsulting.com/tutorials/an-mvc-inspired-approach-to-wordpress-plugin-development You could try this approach to decouple your view and controller code. Finally, while it's probably a bad idea to include something like the Twig templating library in a Wordpress plugin, you might consider this." } ]
[ { "body": "<p>There's duplication between <code>$message</code> and <code>$array['content_editor']['count_h2']['status']</code> in the first block and its counterpoints in the other blocks - <em>they both convey the same information</em>. Instead of using <code>$message</code> you can use <code>$array['content_editor']['count_h2']['status']</code> as an <em>index into a constant array of messages</em>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T14:52:03.440", "Id": "26805", "ParentId": "26803", "Score": "0" } }, { "body": "<p>Architecturally, I'm adverse to hard-coding HTML tags within PHP code. If, for example, you wanted to migrate the code base from PHP to another language (<a href=\"http://www.oracle.com/technetwork/java/\" rel=\"nofollow noreferrer\">Java</a>, <a href=\"http://www.python.org/\" rel=\"nofollow noreferrer\">Python</a>, <a href=\"http://www.ruby-lang.org/\" rel=\"nofollow noreferrer\">Ruby</a>, <a href=\"http://golang.org/\" rel=\"nofollow noreferrer\">Go</a>, <a href=\"http://haxe.org/\" rel=\"nofollow noreferrer\">Haxe</a>, whatever) then you have to rewrite both the logic (PHP) and the presentation (PHP) code.</p>\n\n<p>Consider decoupling the logic from the presentation so that you can change how the data appears without having to change how the data is retrieved. This simplifies switching implementation languages and opens the possibility to create different views of the same data for different devices.</p>\n\n<p>To do this, you have to create an interface or contract between the logic and the system that renders the logic for the user. Fortunately, this is where XML excels.</p>\n\n<p>Instead of hard-coding <code>&lt;strong&gt;</code>, you would create an XML document that represents the information you want to display. The XML document becomes <a href=\"http://relaxng.org/\" rel=\"nofollow noreferrer\">the contract</a> between the logic and presentation, which allows both to vary independently. Once the XML document is in place you can pass it to an XSLT Processor to generate the desired HTML content.</p>\n\n<p>This offers the following advantages:</p>\n\n<ul>\n<li><strong>Decoupled.</strong> The presentation logic moves to XSLT, completely decoupling it from the PHP code.</li>\n<li><strong>Migration.</strong> Migrating from PHP to another language means the presentation logic need not change.</li>\n<li><strong>Devices.</strong> It becomes trivial to change the presentation for different devices (use a new template).</li>\n<li><strong>DRY.</strong> With display logic in a central location, duplicated code is easier to eliminate.</li>\n<li><strong>Databases.</strong> Many databases now allow constructing XML documents within stored procedures, eliminating complex code readily expressed in <a href=\"http://www.postgresql.org/docs/current/static/functions-xml.html\" rel=\"nofollow noreferrer\">SQL</a>.</li>\n<li><strong>SaaS.</strong> It simplifies creating a SaaS API -- <a href=\"https://code.google.com/p/xml2json-xslt/\" rel=\"nofollow noreferrer\">transforming XML to JSON</a> is <s>fairly easy</s> a solved problem.</li>\n</ul>\n\n<p>This has the following disadvantages:</p>\n\n<ul>\n<li><strong>Effort.</strong> Migrating to an XML/XSLT solution for presentation takes a lot of work.</li>\n<li><strong>Knowledge.</strong> Introduces a second programming language (XSLT) into the software.</li>\n<li><strong>Developers.</strong> Far fewer developers know XSLT than PHP.</li>\n<li><strong>XSLT 1.0.</strong> Using PHP, the processor is limited to <a href=\"https://stackoverflow.com/questions/2085632/will-xpath-2-0-and-or-xslt-2-0-be-implemented-in-php\">XSLT v1.0</a> (many great features are in XSLT 2.0).</li>\n<li><strong>Bugs.</strong> The XSLT Processor has some pesky <a href=\"https://bugs.php.net/bug.php?id=64137\" rel=\"nofollow noreferrer\">known bugs</a>, which could be avoided by moving to <a href=\"http://php-java-bridge.sourceforge.net/pjb/\" rel=\"nofollow noreferrer\">XSLT 2.0</a> with the <a href=\"http://saxon.sourceforge.net/\" rel=\"nofollow noreferrer\">SAXON</a> processor.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T17:26:02.080", "Id": "41547", "Score": "2", "body": "Dave, while XML/XSLT is often recommended as a solution to problems like this, I think it's impractical. The disadvantages you listed yourself cannot be understated. I think the more common solution to the OP's problem is to use a template library like Twig; however, it looks like this is for a Wordpress module, and Wordpress has it's own template layer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T17:55:30.407", "Id": "41551", "Score": "0", "body": "If this is a Wordpress module, then definitely XML/XSLT cannot be used." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T13:12:41.467", "Id": "41618", "Score": "0", "body": "But the advice in general is good. +1" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T16:12:19.663", "Id": "26810", "ParentId": "26803", "Score": "2" } }, { "body": "<p>Here is my take on it...</p>\n<pre><code>&lt;style type=&quot;text/css&quot;&gt;\n.section-title{\n font-weight: bold;\n}\n \n&lt;/style&gt;\n\n&lt;?php \n $h2_array['message'] = '&lt;span class=&quot;section-title&quot;&gt;h2 tags&lt;/span&gt; - ';\n\n switch ($this-&gt;count_h2) {\n case 0:\n $h2_array['message'] .= 'No tags found. Add some!';\n $h2_array['status'] = 2;\n break;\n case '1':\n $h2_array['message'] .= 'Some found. Too few!';\n $h2_array['status'] = 1;\n break;\n default:\n $h2_array['message'] .= 'Many found. Great!';\n $h2_array['status'] = 0;\n break;\n }\n \n $h2_array['message'] .= '&lt;span class=&quot;counter&quot;&gt;' \n . $this-&gt;count_h2 \n . '&lt;/span&gt;';\n\n $h2_array['count'] = $this-&gt;count_h2; // Why?\n\n \n\n // BIG COMMENT SERVES AS A VISUAL DIVIDER OF SECTIONS\n \n $h3_h6_array['message'] = '&lt;span class=&quot;section-title&quot;&gt;h3-h6 tags&lt;/span&gt; - ';\n \n $h3_h6_array['count'] = $this-&gt;count_h3 \n + $this-&gt;count_h4 \n + $this-&gt;count_h5 \n + $this-&gt;count_h6;\n\n // Realizing there are only two options,\n // this should be an if statement, not a switch.\n switch ($h3_h6_array['count']) {\n case 0:\n $h3_h6_array['message'] .= 'No found. Add some!';\n $h3_h6_array['status'] = 1;\n break;\n default:\n $h3_h6_array['message'] .= 'Found, great!';\n $h3_h6_array['status'] = 0;\n break;\n }\n\n if ($h3_h6_array['count']) \n {\n $h3_h6_array['message'] .= '&lt;span class=&quot;counter&quot;&gt;' \n . $h3_h6_array['count'] \n . '&lt;/span&gt;';\n }\n?&gt;\n</code></pre>\n<p>Now, I only did the first two sections, but I think you get the idea and can repeat it on the third. I echo other comments here about mixing presentation with logic, but I also recognize you are just getting into coding and sometimes practical application is more important.</p>\n<h2>What I did:</h2>\n<ul>\n<li><p>I cleaned up the arrays. Even with autocomplete in my IDE, typing all those array names was a nightmare. It doesn't have to be so complicated.</p>\n</li>\n<li><p>I got rid of quite a few unnecessary variables. Message start and end just didn't make sense. Variables are values you want to reuse. But you were only using them one time. I also moved them so they were assigned in the order of the final output. This just gave it a more logical flow to me.</p>\n</li>\n<li><p>I switched your <code>strong</code> tags to <code>spans</code> with classes.</p>\n</li>\n</ul>\n<h2>A few techniques to note:</h2>\n<ol>\n<li><p>Comment your code. Don't be afraid to be verbose. Write what you were thinking when you wrote the code and why you make specific decision. That reference will help you tremendously down the road.</p>\n</li>\n<li><p>When you use an <code>if</code> statement, know that <code>false</code>, <code>null</code>, <code>0</code>, empty strings and empty arrays will <strong>ALL</strong> will equate to <code>false</code>. So, instead of <code>if($this-&gt;count_h2 == 0){ ... }</code> you can just write <code>if($this-&gt;count_h2){ ... }</code>.</p>\n<p>Now, I don't know what your count_h2 method returns. Many methods/functions will return <code>false</code> or <code>null</code> when there is an error, in which case NEITHER of the above methods would work. If you want to make sure you are testing for the numeral zero and not for the boolean value <code>false</code>, you need to use three equal signs: <code>if($this-&gt;count_h2 === 0){ ... }</code></p>\n</li>\n<li><p>When you echo all of this to the browser, it's going to look ugly and run together on a single line, making it difficult to read. Let me share with you a method I wish more php developers would use. It makes the output a bit prettier, without putting <code>\\n</code> chars all through your code:</p>\n</li>\n</ol>\n<hr />\n<pre><code>&lt;?php\n// Make an array, adding a new value for each line you want to print to the browser.\n$message[] = '&lt;span class=&quot;section-title&quot;&gt;Title keywords&lt;/span&gt; - ';\n$message[] = 'No primary added.';\n$message[] = '&lt;span class=&quot;counter&quot;&gt;' . $count . '&lt;/span&gt;';\n\n// Echo using implode, which joins each item in the array together to form a string. Each item is separated by a &quot;new line&quot;.\necho implode(&quot;\\n&quot;, $message);\n?&gt;\n</code></pre>\n<p>I hope that helps some. Good luck to you and keep learning. You will hit a point where it all gets much easier.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-13T05:45:06.713", "Id": "27334", "ParentId": "26803", "Score": "0" } }, { "body": "<p>All the other guys are in general right, so I will skip this part. If you just want to reduce code duplication and as a side effect increase testability and readability please have a look at the following code.</p>\n\n<p>I guess there is no doubt, that you would benefit from an object containing the <code>status</code>, <code>message</code> and <code>count</code> as they somehow belong together.</p>\n\n<pre><code>&lt;?php\n$f=new Foo();\nvar_dump($f-&gt;foo());\n\nclass Foo\n{\n private $count_h2=1;\n private $count_h3=1;\n private $count_h4=0;\n private $count_h5=0;\n private $count_h6=1;\n private $keywords1=2;\n private $found_keywords1_post_title=3;\n\n public function foo()\n {\n list($status,$message,$count)=$this-&gt;evaluateH2Count();\n $this-&gt;storeMessage($array,'count_h2',\"h2 tags\", $count, $message, $status);\n list($status,$message,$count)=$this-&gt;evaluateHXCount();\n $this-&gt;storeMessage($array,'count_h3_h6',\"h3-h6 tags\", $count, $message, $status);\n list($status,$message,$count)=$this-&gt;evaluateKeywordCount();\n $this-&gt;storeMessage($array,'missing_keywords1_post_title',\"Title keywords\", $count, $message, $status);\n return $array;\n }\n\n private function evaluateH2Count()\n {\n if( $this-&gt;count_h2 == 0 ) {\n $message = 'No tags found. Add some!';\n $status = 2;\n } elseif( $this-&gt;count_h2 == 1 ) {\n $message = 'Some found. Too few!';\n $status = 1;\n } else {\n $message = 'Many found. Great!';\n $status = 0;\n }\n return array($status,$message,$this-&gt;count_h2);\n }\n\n private function evaluateHXCount()\n {\n $h2_h6 = $this-&gt;count_h3 + $this-&gt;count_h4 + $this-&gt;count_h5 + $this-&gt;count_h6;\n if( $h2_h6 == 0 ) {\n $message = 'No found. Add some!';\n $status = 1;\n } else {\n $message = 'Found, great!';\n $status = 0;\n }\n return array($status,$message,$h2_h6);\n }\n\n private function evaluateKeywordCount()\n {\n if( count( $this-&gt;keywords1 ) == 0 ) {\n $message = 'No primary added.';\n $status = 2;\n } elseif( $this-&gt;found_keywords1_post_title == 0 ) {\n $message = 'No primary found.';\n $status = 2;\n } else {\n $message = 'Primary found.';\n $status = 0;\n }\n return array($status,$message,$this-&gt;found_keywords1_post_title);\n }\n\n //encapsulate the array access\n private function storeMessage(&amp;$array,$key,$title,$count,$message,$status)\n {\n $array['content_editor'][$key]['message'] = $this-&gt;formatMessage($title, $count, $message);\n $array['content_editor'][$key]['count'] = $count;\n $array['content_editor'][$key]['status'] = $status;\n }\n\n private function formatMessage($title,$count,$message) // actually moved to a template\n {\n $count=$count==0?'':$count; //assuming this is a bug in your h2 handling\n $message=$this-&gt;pluralize($message); //anything for template engine offers for handling appending Ss etc.\n return \"&lt;strong&gt;$title&lt;/strong&gt; - $message &lt;span class=\\\"counter\\\"&gt;$count&lt;/span&gt;\";\n }\n\n //dummy\n private function pluralize ($message)\n {\n return $message;\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-14T07:19:11.560", "Id": "42591", "Score": "0", "body": "I ended up doing it much like this structure." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-13T12:13:59.520", "Id": "27347", "ParentId": "26803", "Score": "2" } } ]
{ "AcceptedAnswerId": "27347", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T14:37:58.607", "Id": "26803", "Score": "4", "Tags": [ "php", "design-patterns", "array" ], "Title": "Creating an array that loops out on the frontend - Don't Repeat Yourself?" }
26803
<p>This is a project about a domotics control system based on arduino. Nothing great; it's only for testing myself and making stuff.</p> <p>Before I started coding this, I searched on the net for some useful tips to use in my code, but I still remain a novice in programming.</p> <p>The project is about 1600 lines long. I'm obligated to load it on an external site <a href="http://www.mediafire.com/?j6ldzeydrev86jp" rel="nofollow">here</a>.</p> <p><strong>DomoS.h</strong></p> <pre><code>#ifndef DomoS_H #define DomoS_H #include &lt;arduino.h&gt; class DomoS { private: static const byte STRINGMAXLEN = 64; //Maximum length for the command string static const byte SUBSTRINGMAXLEN = 16; //Maximum length for a single command static const byte MAXADDRESSPIN = 8; //Maximum number of adressing pin static const byte MAXNAMELEN = 10; //Maximum length for a peripheral name static const byte FILEVER = 0; //The version of the file type /* The DomoS setting file is made of two parts 1) The header of the file which contains all of the configuration parameters of the DomoS module and the version of the file type 2) The body of the file which contains all the settings for the different peripherals [for a explanation go to the declaration of the type] These are stored in sequential order With version 0 the different arduino EEPROM can contain up to: ATmega168 and ATmega8 [512byte]: 45 peripherals ATmega328 [1024byte]: 91 peripherals ATmega1280 and ATmega2560 [4096byte]: 371 peripherals */ struct DomoSFileHeader //size 13byte { //The order here is also the order in the EEPROM //RESPECT THIS ORDER //The "EEPROM #" on the right of the variable name is the standard position in the EEPROM //Version of the file type, in case of change through developement byte fileVer; //EEPROM 2 //Copy of the configuration parameters byte numPeripheral; //EEPROM 3 byte numAddressPin; //EEPROM 4 byte addressPin[MAXADDRESSPIN]; //EEPROM 5-12 byte outputPin; //EEPROM 13 byte writeToEeprom; //EEPROM 14 }; struct DomoSFileBody //size 11byte { char name[MAXNAMELEN]; //The name of the peripheral byte number; //The number of the peripheral and the addressing parameter }; //Setup function void GetConfigurationDataFromEeprom(); //Gets the configurations data from the EEPROM void FirstStart(); //Starts all the magic before the first start boolean CheckSetupData(); //Checks if the system has been already setupped void ClearEeprom(); //Clears all the EEPROM void WriteSetupData(); //Writes to the first two cells of EEPROM the setup check values void AskData(DomoSFileHeader &amp; data); //Asks to the user the configuration parameters void WriteConfigurationDataToEeprom (DomoSFileHeader data); //Writes the data variables into the EEPROM void Initialize(); //Initializes the DomoS module void UpdateNumPeripheral(char type); //Updates the peripheral number boolean ConvertDecimalToBinary(int number, boolean result[]); //Converts a decimal number to an array of boolean, return false if the number is greater than what the module can handle, else true void SetAddressing(boolean addressing[]); //Sets up the addressing lines byte SeparateCommandBySpace(); //Separates the _command string into two strings, the first is the first word before the space, the second is the original string with the first word deleted, returns the number of char written in _subCommand byte CompareSubCommand(); //Compares a command with the commands' dictionary boolean FetchCommand(); //Fetches a command from the serial port void DoCommand(byte numCommand); //Executes a command byte GetCommand(char* command); //Gets the number of a command void CommandToLowerCase(); //Converts the _command string to lower case void SubCommandShiftLeft(); //Shifts left of one position all the character in the _subCommand string byte SearchPeripheralByName(char peripheral[]); //Searches the peripheral by name void GetPeripheralName(byte numPeripheral, char name[]); //Writes in char name[] the name of numPeripheral-th peripheral boolean SearchDuplicatedPeripheral(DomoSFileBody &amp; peripheral, boolean nameCustom, boolean numberCustom); //Checks if the peripheral is unique else tries to make it unique void GetPeripheralNumber(byte numPeripheral, byte &amp; number); //Writes in "number" the number of numPeripheral-th peripheral byte ConvertBinaryStringToDecimal(); void BlankNewPeripheral(DomoSFileBody &amp; peripheral); boolean CreateParameterCheck(DomoSFileBody &amp; peripheral); boolean WritePeripheral(DomoSFileBody peripheral, byte position); byte SearchPeripheralByNumber(byte number); void ComposeStringPeripheral(DomoSFileBody peripheral, byte phrase); byte GetError(); boolean WritePeripheralToEeprom(DomoSFileBody peripheral, byte position); //Writes the peripheral to the EEPROM //boolean WritePeripheralToSd(DomoSFileBody peripheral, byte position); //Function not yet developed void Create(); //Create a peripheral void Turn(); //Activate a peripheral void Delete(); //Delete a peripheral, probably this wont be developed void Exit(); //Turn off DomoS module void Reset(); //Resets the DomoS module void List(); //Give a list of all the installed peripheral int parseInt(); void ThrownError(); //Declaration of configuration variables byte _numAddressPin; //Number of pins used for addressing peripherals byte _addressPin[MAXADDRESSPIN]; //Pins used for addressing byte _outputPin; //The pin used for the output, pin 6 will automatically be selected byte _writeToEeprom; //-1 if DomoS must store the peripheral settings in the EEPROM, else the CSPin where the SD card is connected for storing the settings in DomoS.dat file byte _numPeripheral; //Number of peripheral created by user byte _fileVer; //The version of the file type boolean _on; //Tell if DOMOS system is on byte _lastError; //Tell the last error thrown by DomoS /* Declaration of strings constant Inizialization in DomoS.cpp */ static const byte NCOMMAND = 8; //number of commands allowed static const char* COMMAND[NCOMMAND]; //Array of commands, for explanation go to inizialization static const int NPHRASE = 12; //Number of phrases, for eventually translation static const char* PHRASE[NPHRASE]; static const int NERROR = 24; static const char* ERROR[NERROR]; static const int START = 2; static const byte SETUP[START]; //These two values are stored in the first two cell of EEPROM, if already present the system have been already setup, if not launch the first start procedure static const int RCLOAD = 300; //Number of millisecond necessary for charging of RC circuit //String for fetching and checking commands char _command[STRINGMAXLEN]; char _subCommand[SUBSTRINGMAXLEN]; public: //Constructor DomoS(); void Work(); boolean IsOn(); //Control if the module is ready to handle new request //Errors constant static const byte OK = 0; static const byte COMMANDSTRINGTOOLONG = 1; static const byte SUBCOMMANDSTRINGTOOLONG = 2; static const byte COMMANDNOTRECOGNIZED = 3; static const byte NOCOMMANDPARAMETERS = 4; static const byte SUBCOMMANDNOTRECOGNIZED = 5; static const byte NAMENOTDEFINED = 6; static const byte NAMETOOLONG = 7; static const byte ASNOTDEFINED = 8; static const byte BINARYNUMBERTOOLONG = 9; static const byte EEPROMISFULL = 10; static const byte PERIPHERALNOTFOUND = 11; static const byte STRANGETURNPARAMETER = 12; static const byte BADTHINGSHAPPEN = 13; static const byte PERIPHERALZERONOTALLOWED = 14; static const byte PERIPHERALMAXIMUMNUMBERREACH = 15; static const byte PERIPHERALNAMENOTUNIQUE = 16; static const byte PERIPHERALNUMBERNOTUNIQUE = 17; static const byte CANTFINDFREENAME = 18; static const byte CANTFINDFREENUMBER = 19; static const byte VOLTAGETOOLOW = 20; static const byte VOLTAGETOOHIGH = 21; static const byte DECIMALNUMBERTOOBIG = 22; static const byte THEREAREZEROPERIPHERAL = 23; }; #endif </code></pre> <p><strong>DomoS.cpp</strong></p> <p><a href="http://pastebin.com/B1L5P1Pd" rel="nofollow">This is too long and doesn't fit in the post</a>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T11:12:06.197", "Id": "45310", "Score": "1", "body": "You are very unlikely to get a good review unless you pick out the relevant parts you want reviewed and add them to the post." } ]
[ { "body": "<p>I am not familiar with Arduino, but as a general C++ developer, I've noticed the following issues (looking only at the code in the question, not the one behind links):</p>\n\n<ul>\n<li><p>No const-correctness.</p>\n\n<p>The biggest problem in the code, one which would cause me to return it back to the developer if I were reviewing this at work.</p>\n\n<p>None of your member functions are classified as <code>const</code>, meaning they will not be callable on a <code>const</code> object of type <code>DomoS</code>, or such an object accessed through a <code>const</code>-qualified path (such as a <code>const DomoS &amp;</code>).</p>\n\n<p>Even more importantly, your functions which take a pointer or reference parameter do not use <code>const</code> on the destination type either, which again means <code>const</code> objects or, even worse, temporaries cannot be used as arguments for those parameters. This way, you also deprive yourself of a great opportunity for self-documenting code, creating space for confusion of the user (or future maintainer) of the class. Example:</p>\n\n<pre><code>byte GetCommand(char* command); //Gets the number of a command\n</code></pre>\n\n<p>Based on its signature, this function:</p>\n\n<ol>\n<li>returns a <code>byte</code>. Given the comment, I expect this to be a number of the <code>command</code></li>\n<li>can write something into the string pointed to by <code>command</code>. As a user, I am confused. Will it do so? What if the buffer I pass in is not large enough for what the function will write? How do I determine what \"large enough\" is? Why can't I use a string literal as the argument (string literals are of type <code>const char[]</code>, and thus passing one here would cast away constness)?</li>\n<li>can modify the <code>DomoS</code> object on which it's invoked. This is definitely not something I would expect from a function whose name starts with <code>Get</code>.</li>\n</ol>\n\n<p>Instead, I would expect the function's signature to be:</p>\n\n<pre><code>byte GetCommand(const char* command) const; //Returns the number of a command\n</code></pre>\n\n<p>The same applies to many other functions in the class, of course. This was just an example.</p>\n\n<p>Writing const-correct code also prevents some programmer errors, such as accidentally modifying an input-only parameter.</p>\n\n<p>Last but not least, it is a real pain to integrate a non-const-correct module into otherwise const-correct code. You have to use <code>const_cast</code>s everywhere, which is 1) tedious to write, 2) a great source of bugs and 3) a maintenance nightmare. I understand this is less of an issue here since almost all of the class's functions are <code>private</code>, but it's a general principle worth mentioning anyway. From the external interface at least, <code>IsOn()</code> should definitely be <code>const</code>.</p>\n\n<p>A quick summary of \"const-correctness\":</p>\n\n<ul>\n<li>A member function which does not modify the observable state of the object it's invoked on should be marked as <code>const</code>, so that it can be called on <code>const</code>-qualified objects.</li>\n<li>A function taking a parameter by reference and not modifying the parameter should take the parameter by <code>const &amp;</code>. This is particularly important because it allows temporary objects to be bound to the reference (temporaries can bind to <code>const</code>-references, but not to non-<code>const</code> references).</li>\n<li>A function taking a parameter by pointer and not modifying the object pointed to should declare the parameter as pointer to <code>const</code>.</li>\n</ul>\n\n<p>Imagine this code:</p>\n\n<pre><code>void prettyPrint(const std::string &amp;s) {\n std::cout &lt;&lt; s.size() &lt;&lt; ' ' &lt;&lt; s &lt;&lt; '\\n';\n}\n\nstd::string x = \"Hello\";\nstd::string y = \" World!\";\n\nprettyPrint(x + y);\n</code></pre>\n\n<p>If there was no <code>const</code> in the signature of <code>print()</code>, this wouldn't compile, as <code>x + y</code> returns a temporary. If the purely observing member function <code>size()</code> of <code>std::string</code> wasn't marked as <code>const</code>, we couldn't call <code>s.size()</code> inside <code>prettyPrint()</code> because <code>s</code> is a <code>const</code>-reference.</p></li>\n<li><p>Taking structures by value.</p>\n\n<p>Some of your functions take parameters of type <code>DomoSFileBody</code> by value. This can be OK if the function does any internal modification on the arguments passed in: copying at call site can be more efficient than copying internally, as discussed in this <a href=\"http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/\" rel=\"nofollow\">great article</a>.</p>\n\n<p>However, if the function does not modify its argument, you can save a significant amount of copying by passing these arguments as <code>const DomoSFileBody &amp;</code> instead.</p></li>\n<li><p>Hand-crafted enumeration for the error code.</p>\n\n<p>The error constants would be perfectly represented as an enumeration. This has a distinct advantage of creating a full-fledged type, so that overload resolution can be used and code is more self-documenting. Function signature <code>byte GetError();</code> doesn't really tell me much, but <code>ErrorCode GetError();</code> clearly says what values I can expect.</p>\n\n<p>In C++11 (and many compilers support this even before that), you can explicitly specify the underlying type for an enumeration, so it could be a <code>byte</code> even so. The definition would then look like this:</p>\n\n<pre><code>//Errors constant\nenum ErrorCode {\n OK,\n COMMANDSTRINGTOOLONG,\n SUBCOMMANDSTRINGTOOLONG,\n COMMANDNOTRECOGNIZED,\n NOCOMMANDPARAMETERS,\n SUBCOMMANDNOTRECOGNIZED,\n NAMENOTDEFINED,\n NAMETOOLONG,\n ASNOTDEFINED,\n BINARYNUMBERTOOLONG,\n EEPROMISFULL,\n PERIPHERALNOTFOUND,\n STRANGETURNPARAMETER,\n BADTHINGSHAPPEN,\n PERIPHERALZERONOTALLOWED,\n PERIPHERALMAXIMUMNUMBERREACH,\n PERIPHERALNAMENOTUNIQUE,\n PERIPHERALNUMBERNOTUNIQUE,\n CANTFINDFREENAME,\n CANTFINDFREENUMBER,\n VOLTAGETOOLOW,\n VOLTAGETOOHIGH,\n DECIMALNUMBERTOOBIG,\n THEREAREZEROPERIPHERAL,\n NERROR\n};\n</code></pre>\n\n<p>Note the inclusion of <code>NERROR</code> as the last enumerator. This has the advantage of keeping this value always <code>1 + last enumerator</code>, so that you cannot forget to increase the value if you later need to add further error codes.</p>\n\n<p>I would also introduce underscores to separate words in the enumerators (e.g. <code>COMMAND_STRING_TOO_LONG</code>), but that is mostly a matter of personal preference.</p></li>\n<li><p>Using signed types for sizes.</p>\n\n<p><code>NPHRASE</code> and <code>START</code> (and also <code>NERROR</code>, but see above for that) are defined with type <code>const int</code>, even though they represent non-negative quantities (a number of something). The ideal type for this is <code>std::size_t</code>, which is again self-documenting as \"this variable holds a size or count.\"</p>\n\n<p>If you cannot use this for reasons of type size (i.e. it's too big), at least use <code>const unsigned int</code> for the constants. That way, you clearly document they store non-negative quantities. It also prevents potential signed/unsigned issues when interacting with the standard library, which correctly uses unsigned types (<code>std::size_t</code>, actually) to represent sizes and counts.</p></li>\n<li><p>Inconsistent usage of <code>char* p</code> and <code>char p[]</code> in function arguments.</p>\n\n<p>These are semantically equivalent, but you should preferably pick one and stick to it.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T16:56:30.163", "Id": "52096", "Score": "0", "body": "0)Someone modified the tag of the question from c to c++, in fact the code use only c construct beside of the main class\n1)Is the first time i hear the word \"const correctnes\", i took a look at wikipedia but i didn't understand well what you mean and how should i use this\n2)Thanks for the tip, i'll use this in my next works\n3)the arduino compiler don't support enumerator, i tried to implement it but without success" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T16:59:45.523", "Id": "52097", "Score": "0", "body": "@user92608 So? The class is C++ (class, references etc.). And pretty much all the points are valid for C code as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T17:08:09.667", "Id": "52098", "Score": "0", "body": "4)Yes, you're right, that should only be a typo, these should also be byte const [already unsigned]\n5)Luckily only one function use the char* p style, maybe another typo" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T17:28:18.917", "Id": "52100", "Score": "0", "body": "@user92608 I've elaborated a bit more on const-correctness. If enumerations are not supported by the compiler, then your approach is the best that can be done. You might at least introduce a `typedef` for the error code type. While it will not be type-safe, it will at least be self-documenting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-12T15:20:59.853", "Id": "52138", "Score": "0", "body": "Then, if i understood well i should write\nboolean CheckSetupData(); -> const boolean CheckSetupData(); because this function don't modify the internal state of the class.\nBut this function byte SeparateCommandBySpace(); can't be const because it modify some internal variables.\n\nInstead in this function void WriteConfigurationDataToEeprom (DomoSFileHeader data); i should write (const DomoSFileHeader & data) for avoid the copying of the structure\n\nHave I understood well??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-13T09:24:23.557", "Id": "52175", "Score": "0", "body": "@user92608 Almost. `CheckSetupData()` would become `boolean CheckSetupData() const;`. `const` before the function name applies to the return type, `const` after the function parameter parentheses applies to the member function itself. For the other 2 cases (`SeparateCommandBySpace` and `WriteConfigurationDataToEeprom`), you've summarised it perfectly." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-11T12:42:56.377", "Id": "32571", "ParentId": "26811", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T16:17:42.147", "Id": "26811", "Score": "6", "Tags": [ "c++", "beginner", "arduino" ], "Title": "Domotics control system" }
26811
<p>The program basically takes a polynomial and does some simple calculations with it.</p> <p>With a couple of hours of work I managed to get my first console application to work (aside from the obligatory "Hello, World!", of course). However, I'm in total doubt that the style and habits I've used are even close to being correct.</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;algorithm&gt; #include &lt;math.h&gt; #include &lt;cmath&gt; using namespace std; class Polynomial { float a, b, c, value; public: Polynomial (); void functionDefine(Polynomial poly); void functionValue(Polynomial poly); void functionZero(Polynomial poly); }; namespace Utils { void mainMenu(Polynomial poly); void skipToMenu(); string save(string str); int exitProgram(); void mainMenu(Polynomial poly) { int choice = 0; cout &lt;&lt; " ---------- Main Menu ----------" &lt;&lt; endl; cout &lt;&lt; "1: ---- Define New Polynomial ----" &lt;&lt; endl; cout &lt;&lt; "2: ------ Solve for x-value ------" &lt;&lt; endl; cout &lt;&lt; "3: --------- Find roots ----------" &lt;&lt; endl; cout &lt;&lt; "4: ------------ Exit -------------" &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; "Enter the value of the submenu you want to enter: "; cin &gt;&gt; choice; cout &lt;&lt; endl; switch(choice) { case 1: poly.functionDefine(poly); break; case 2: poly.functionValue(poly); break; case 3: poly.functionZero(poly); break; case 4: exitProgram(); break; } } void skipToMenu() { cout &lt;&lt; "Press enter to return to the main menu."&lt;&lt; endl &lt;&lt; endl; system("pause &gt; nul"); } string save(string str) { string saved = "Yes or no"; // To do. return saved; } int exitProgram() { return 0; } } Polynomial::Polynomial() { a = 0; b = 0; c = 0; } void Polynomial::functionDefine (Polynomial poly) { char currentChar = 'a'; cout &lt;&lt; "---- Define New Polynomial ----" &lt;&lt; endl; for (int i = 0; i &lt; 3; i++) { cout &lt;&lt; "Enter a value for " &lt;&lt; currentChar &lt;&lt; ": "; switch(i) { case 0: cin &gt;&gt; poly.a; break; case 1: cin &gt;&gt; poly.b; break; case 2: cin &gt;&gt; poly.c; break; } if (!cin) { cout &lt;&lt; "Please enter a number instead." &lt;&lt; endl; system("pause"); } currentChar = static_cast&lt;char&gt;(currentChar + 1); } cout &lt;&lt; endl; cout &lt;&lt; "The function is: f(x) = " &lt;&lt; poly.a &lt;&lt; "x^2 + " &lt;&lt; poly.b &lt;&lt; "x + " &lt;&lt; poly.c &lt;&lt; "." &lt;&lt; endl &lt;&lt; endl; Utils::skipToMenu(); Utils::mainMenu(poly); } void Polynomial::functionValue(Polynomial poly) { int input; cout &lt;&lt;"------ Solve for x-value ------" &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; "Enter the x-value that you would like to evaluate the equation for: "; cin &gt;&gt; input; value = poly.a * pow(input, 2) + poly.b * input + poly.c; cout &lt;&lt; "The value of the function for x = " &lt;&lt; input &lt;&lt; " is " &lt;&lt; value &lt;&lt; endl &lt;&lt; endl; Utils::mainMenu(poly); } void Polynomial::functionZero(Polynomial poly) { float d = pow(poly.b, 2) - 4 * poly.a * poly.c; if (d &gt; 0) { float result = ((-poly.b) + sqrt(abs(d))) / (2 * poly.a); float secondResult = (-poly.b - sqrt(abs(d))) / (2 * poly.a); cout &lt;&lt; "The polynomials roots are at x = " &lt;&lt; result &lt;&lt; " and x = " &lt;&lt; secondResult &lt;&lt; "." &lt;&lt; endl &lt;&lt; endl; } else if (d == 0) { float result = ((-b) + sqrt(abs(d))) / (2 * a); cout &lt;&lt; "The polynomials root is at x = " &lt;&lt; result &lt;&lt; "." &lt;&lt; endl &lt;&lt; endl; } else { cout &lt;&lt; "The polynomial has no roots." &lt;&lt; endl &lt;&lt; endl; } Utils::mainMenu(poly); } int main () { Polynomial poly; Utils::mainMenu(poly); return 0; } </code></pre> <p>I was told it would be a good idea to create different namespaces for my "calculations" and my "utilities". Creating a class with the utility functions wouldn't make sense as there would never be created an instance of this...</p> <p>I'm open to all the critique you have. If anybody wants the Pastebin link it's <a href="http://pastebin.com/et4wAVbM" rel="nofollow">here</a>.</p>
[]
[ { "body": "<p>First, your program has no need for these Libraries:</p>\n\n<pre><code>#include &lt;fstream&gt;\n#include &lt;algorithm&gt;\n#include &lt;math.h&gt;\n</code></pre>\n\n<p>The &lt;<strong>math.h</strong>> is redundant due to the use of &lt;<strong>cmath</strong>>. &lt;<strong>cmath</strong>> is the C++ way. Another example is &lt;<strong>cstdlib</strong>> instead of &lt;<strong>stdlib.h</strong>>. The C libraries are deprecated in C++, mainly they're just for compatibility. &lt;<strong>fstream</strong>> is for file streams, your program doesn't use any.</p>\n\n<p>Secondly, I would avoid using system(\"pause\"), it is EXTREMELY resource heavy compared to what it does. There are many ways to implement a pause into your program, the easiest however do not allow you to press any key to continue, you have to generate a new line to continue (Press Enter). If you include the &lt;<strong>limits</strong>> library you can do something like the following:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;limits&gt;\n\nint main()\n{\n int test;\n\n std::cout &lt;&lt; \"Var: \";\n std::cin &gt;&gt; test;\n\n std::cin.clear();\n std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(),'\\n');\n std::cin.get();\n return 0;\n}\n</code></pre>\n\n<p>Make sure you pay attention to these lines:</p>\n\n<pre><code>std::cin.clear();\nstd::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(),'\\n');\nstd::cin.get();\n</code></pre>\n\n<p>The first 2 lines clear the buffer, which is important. Without those lines there is still a '\\n' character in the buffer from the previous input. When your program reaches:</p>\n\n<pre><code>std::cin.get();\n</code></pre>\n\n<p>It will read that '\\n' character and then continue. By clearing the buffer first, the program will get input until it receives a '\\n' from the user by pressing enter.</p>\n\n<p>I usually create a void function out of the first 2 lines.</p>\n\n<p>Lastly, you should read this: <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Why is “using namespace std;” considered bad practice?</a></p>\n\n<p>Hope that helps a bit.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T10:59:34.647", "Id": "41613", "Score": "1", "body": "Thanks for the input. I included fstream because I was saving all the calculations to a textfile, just removed that functionality again :)\n\nWell, I guess I won't use system(\"pause\") in the future again then ^^\n\nStill interested in having the style/habits reviewed by someone if possible!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T00:00:55.687", "Id": "26862", "ParentId": "26817", "Score": "4" } }, { "body": "<p>I don't think your style here is bad, although, if I were you I would move your class into a separate header file. Use function prototypes at the top of this file and move the Utils namespace below main.</p>\n\n<p>One thing I did notice though is you should use initialization lists for your constructors.</p>\n\n<p>You can remove:</p>\n\n<pre><code>Polynomial::Polynomial() {\n a = 0;\n b = 0;\n c = 0;\n\n}\n</code></pre>\n\n<p>And in your class declaration change the constructor line to:</p>\n\n<pre><code>Polynomial () : a(0), b(0), c(0) {}\n</code></pre>\n\n<p>Just my 2 cents.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T00:08:05.373", "Id": "26901", "ParentId": "26817", "Score": "2" } }, { "body": "<p>Don't overrefactor. Do you really need <code>exitProgram</code>? That already exists in the standard library as <code>exit</code>. Why can't you just use <code>exit(0)</code>? </p>\n\n<p>I think a lot of C++ books teach you to make everything and anything it's own everything, but that isn't really practical in large scale applications or codebases. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T02:57:11.910", "Id": "41697", "Score": "0", "body": "Plus, it is useless since all it does is terminate itself, not the program. I've been told that `exit()` isn't preferred either, unless there's no other way of falling back to `main()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T13:31:05.067", "Id": "41726", "Score": "0", "body": "@Jamal: all good points, I might add them later." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T13:31:29.680", "Id": "41727", "Score": "0", "body": "@wizH: sure. Glad to help." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T02:38:35.513", "Id": "26904", "ParentId": "26817", "Score": "1" } }, { "body": "<p>As others have mentioned, you should get into the habit of breaking up function definitions and declarations (effectively, function signatures and implementations) into separate files. In this case, the header file should look something like:</p>\n\n<pre><code>class Polynomial \n{\n float a, b, c, value;\n\npublic:\n Polynomial ();\n void functionDefine(Polynomial poly);\n void functionValue(Polynomial poly);\n void functionZero(Polynomial poly);\n};\n\nnamespace Utils\n{\n void mainMenu(Polynomial poly);\n void skipToMenu();\n string save(string str);\n int exitProgram();\n}\n</code></pre>\n\n<p>This is then <strong>included</strong> in the file with the class/function implementations - so if we called it something like <code>Poly.h</code>, in the implementation file we'd have:</p>\n\n<pre><code>#include \"Poly.h\"\n</code></pre>\n\n<p>Let's go through the <code>Polynomial</code> class definition, because there's some room for improvement there. Firstly, the way it currently stands, they're effectively all just <code>static</code> functions that take a <code>Polynomial</code> as a parameter. This goes against the idea of what classes are meant to do. Classes are supposed to be a grouping of functions and data together, where the functions act (ideally) only on the data contained within an <strong>instance</strong> of the class. This means that you construct a given <code>Polynomial</code>, and then call methods on that particular instance. I'd rewrite this as follows:</p>\n\n<pre><code>class Polynomial \n{\n float a, b, c;\n\npublic:\n Polynomial();\n Polynomial(float a_, float b_, float c_);\n void functionValue() const;\n void functionZero() const;\n};\n</code></pre>\n\n<p>There's a few new things here. Firstly, I've removed <code>value</code> because it doesn't really get used anywhere, and it isn't really an attribute itself of the given <code>Polynomial</code>. Secondly, I've replaced the <code>functionDefine</code> with a second constructor, which takes 3 float parameters. Note also the <code>const</code> on the end of <code>functionValue()</code> and <code>functionZero()</code>. This says that calling these functions should not change the values in the current polynomial instance, which they shouldn't (finding the roots of a polynomial shouldn't modify any of the <code>a</code>, <code>b</code>, or <code>c</code> values). The constructors are then defined as:</p>\n\n<pre><code>Polynomial::Polynomial()\n : a(0), b(0), c(0) \n{ }\n\nPolynomial::Polynomial(float a_, float b_, float c_)\n : a(a_), b(b_), c(c_)\n{ }\n</code></pre>\n\n<p>The current program structure passes a given <code>Polynomial</code> around everywhere, it's threaded through the entire program. We're going to remove a lot of that because it's mostly unneeded. Firstly, we're going to change the <code>mainMenu</code> function a bit:</p>\n\n<pre><code>void mainMenu() \n{\n int choice = 0;\n Polynomial poly;\n bool finished = false;\n\n while(!finished) {\n cout &lt;&lt; \" ---------- Main Menu ----------\" &lt;&lt; endl;\n cout &lt;&lt; \"1: ---- Define New Polynomial ----\" &lt;&lt; endl;\n cout &lt;&lt; \"2: ------ Solve for x-value ------\" &lt;&lt; endl;\n cout &lt;&lt; \"3: --------- Find roots ----------\" &lt;&lt; endl;\n cout &lt;&lt; \"4: ------------ Exit -------------\" &lt;&lt; endl &lt;&lt; endl;\n\n cout &lt;&lt; \"Enter the value of the submenu you want to enter: \";\n\n cin &gt;&gt; choice;\n cout &lt;&lt; endl;\n\n switch(choice) {\n case 1:\n poly = functionDefine();\n break;\n case 2:\n poly.functionValue();\n break;\n case 3:\n poly.functionZero();\n break;\n case 4:\n finished = true;\n break;\n default:\n std::cout &lt;&lt; \"That is not a valid selection\\n\\n\";\n break;\n }\n }\n}\n</code></pre>\n\n<p>There are a few changes here. Firstly, we create a <code>Polynomial</code> instance up the top of this function. Since we always return to the main menu after a selection (except on exit), this will never falls out of scope and can be utilized for the entire program. When we want to assign a new value to it, we use <code>poly = functionDefine()</code>. When we want to calculate some value at a given point or find zeros, we call the functions <code>poly.functionValue()</code> and <code>poly.functionZero()</code> on it. This is all put into a <code>while</code> loop so that we never exit the <code>mainMenu</code> function until we are done. Finally, we've added a <code>default</code> value to the <code>switch</code> statement which will simply print an error and return us to the <code>mainMenu</code> if the user selects some value outside of 1 - 4.</p>\n\n<p>The functions themselves are pretty similar, except <code>functionDefine</code> is now a free-standing function, while <code>functionZero</code> and <code>functionValue</code> operate on a polynomial instance:</p>\n\n<pre><code>Polynomial functionDefine() \n{\n static const int maxDegree = 2;\n float a, b, c;\n char currentChar = 'a';\n int filled = 0;\n\n cout &lt;&lt; \"---- Define New Polynomial ----\" &lt;&lt; endl;\n\n while(filled &lt; maxDegree + 1) {\n cout &lt;&lt; \"Enter a value for \" &lt;&lt; static_cast&lt;char&gt;(currentChar + filled) \n &lt;&lt; \": \";\n\n switch(filled)\n {\n case 0:\n cin &gt;&gt; a; \n break;\n case 1:\n cin &gt;&gt; b; \n break;\n case 2:\n cin &gt;&gt; c; \n break;\n }\n\n if(!cin) {\n cout &lt;&lt; \"Please enter a number instead.\" &lt;&lt; endl;\n cin.clear();\n std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(),'\\n');\n } else {\n ++filled;\n }\n }\n\n cout &lt;&lt; endl;\n cout &lt;&lt; \"The function is: f(x) = \" &lt;&lt; a &lt;&lt; \"x^2 + \" &lt;&lt; b &lt;&lt; \"x + \" &lt;&lt; c &lt;&lt; \".\" &lt;&lt; endl &lt;&lt; endl;\n\n return Polynomial(a, b, c);\n}\n</code></pre>\n\n<p><code>functionDefine</code> now returns an instance of a Polynomial, and also makes use of the suggested fix from @h4ck.b0x7.</p>\n\n<pre><code>void Polynomial::functionValue() const\n{\n int input;\n double value;\n\n cout &lt;&lt;\"------ Solve for x-value ------\" &lt;&lt; endl &lt;&lt; endl;\n\n cout &lt;&lt; \"Enter the x-value that you would like to evaluate the equation for: \";\n cin &gt;&gt; input;\n\n value = a * pow(input, 2) + b * input + c;\n cout &lt;&lt; \"The value of the function for x = \" &lt;&lt; input &lt;&lt; \" is \" &lt;&lt; value &lt;&lt; endl &lt;&lt; endl;\n}\n</code></pre>\n\n<p>Note that this should also do some error checking on <code>cin &gt;&gt; input</code>. It doesn't crash currently (which is good), but if the user enters a non-number, you should probably tell them and then try again.</p>\n\n<pre><code>void Polynomial::functionZero() const\n{\n float d = pow(b, 2) - 4 * a * c;\n\n if (d &gt; 0) {\n\n float result = ((-b) + sqrt(abs(d))) / (2 * a);\n float secondResult = (-b - sqrt(abs(d))) / (2 * a);\n cout &lt;&lt; \"The polynomials roots are at x = \" &lt;&lt; result &lt;&lt; \" and x = \" &lt;&lt; secondResult &lt;&lt; \".\" &lt;&lt; endl &lt;&lt; endl;\n }\n\n else if (d == 0) {\n float result = ((-b) + sqrt(abs(d))) / (2 * a);\n cout &lt;&lt; \"The polynomials root is at x = \" &lt;&lt; result &lt;&lt; \".\" &lt;&lt; endl &lt;&lt; endl;\n }\n\n else {\n cout &lt;&lt; \"The polynomial has no roots.\" &lt;&lt; endl &lt;&lt; endl;\n }\n}\n</code></pre>\n\n<p>Finally, <code>exitMenu()</code> and <code>skipToMenu()</code> are gone, as they didn't really need to be there. Our <code>main</code> function is then:</p>\n\n<pre><code>int main () \n{\n Utils::mainMenu();\n return 0;\n}\n</code></pre>\n\n<p>As a final note, I think the names could do with a bit of work - they're not particularly descriptive. Perhaps <code>solveForX()</code> instead of <code>functionValue()</code>, and <code>findZeros()</code> instead of <code>functionZero()</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T06:08:50.737", "Id": "41711", "Score": "0", "body": "You're the man. Will award the bounty when I can :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T17:02:06.480", "Id": "41754", "Score": "0", "body": "@wizH, this is what Code Review is all about. :-) Feel free to come back whenever you have more programs needing a review. Not a bad start for a beginner (I'd barely even consider myself intermediate)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T04:38:30.443", "Id": "26908", "ParentId": "26817", "Score": "4" } }, { "body": "<p>I would very strongly urge you to separate all of the input/output functionality from the <code>Polynomial</code> class itself.</p>\n\n<p>That class should only contain the basics relating to the polynomial calculations, allowing other code to capture the input and display the output, e.g:</p>\n\n<pre><code>#include &lt;cmath&gt;\n#include &lt;vector&gt;\n\nclass Polynomial {\n float a, b, c;\n\npublic:\n Polynomial();\n Polynomial(float a, float b, float c);\n void setCoefficients(float a, float b, float c);\n float evaluate(float x) const;\n std::vector&lt;float&gt; roots() const;\n};\n\nPolynomial::Polynomial()\n : a(0), b(0), c(0)\n{}\n\nPolynomial::Polynomial(float _a, float _b, float _c)\n : a(_a), b(_b), c(_c)\n{}\n\nvoid Polynomial::setCoefficients(float _a, float _b, float _c)\n{\n a = _a;\n b = _b;\n c = _c;\n}\n\nfloat Polynomial::evaluate(float x) const\n{\n return a * (x * x) + b * x + c;\n}\n\nstd::vector&lt;float&gt; Polynomial::roots() const\n{\n std::vector&lt;float&gt; result;\n float det = b * b - 4 * a * c;\n if (det &gt; 0) {\n float sd = sqrt(det);\n result.push_back((-b + sd) / (2 * a));\n result.push_back((-b - sd) / (2 * a));\n } else if (det == 0) {\n result.push_back(-b / (2 * a));\n }\n return result;\n}\n</code></pre>\n\n<p>The use of the <code>std::vector&lt;float&gt;</code> as the return type from the <code>roots()</code> function allows the return of 0, 1 or 2 results, depending on the coefficients.</p>\n\n<p>This class can now be used for non-interactive calculations - in fact I might even build something like this into my ray tracer since I've currently got a sphere intersection test that requires a quadratic solver but I'm expecting to need that solver in some more places too.</p>\n\n<p>Also note that separating out this functionality and removing the interactivity allows the class to be trivially \"unit tested\".</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-06T08:27:40.050", "Id": "115983", "ParentId": "26817", "Score": "0" } } ]
{ "AcceptedAnswerId": "26908", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T19:17:41.890", "Id": "26817", "Score": "10", "Tags": [ "c++", "performance", "beginner", "mathematics" ], "Title": "Polynomial program" }
26817
<p>I'm writing unit tests for a library which parses colors from user input (example: the user input “#f00” gives a red color; the user input “60,100%,100%” gives a yellow color, etc.)</p> <p>One of the conditions is that the method <code>Parse</code> returns <code>null</code> when there is actually nothing to parse, i.e. when the input is either an empty string or its length is inferior to four characters. Those are the two unit tests:</p> <pre><code>[TestMethod] public void SubmitEmptyText() { var actual = new ColorParser().Parse(string.Empty); Assert.IsNull(actual); } [TestMethod] public void SubmitShortText() { Assert.IsTrue(new[]{"#", "#f", "#ff"}.All(c =&gt; !new ColorParser().Parse(c).HasValue)); } </code></pre> <ul> <li>Is the second method doing too much?</li> <li>Am I expected to create three method? Seriously?!</li> <li>Is the usage of functional programming here justified, or should I instead stick to the most basic way to write the tests?</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T21:06:04.283", "Id": "41557", "Score": "3", "body": "I guess a potential problem with this is if one of the items fail you won't easily know which one is the culprit" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T21:34:01.283", "Id": "41559", "Score": "3", "body": "There has to be a better way where the test method takes a parameter and you then decorate it such that these values are fed in somehow. MbUnit had this since 2004; MsTest does have an alternative but it sucks in comparison. http://haacked.com/archive/2004/10/20/row_based_testing.aspx This question shows the alternative. http://stackoverflow.com/questions/347535/how-to-rowtest-with-mstest http://blogs.msdn.com/b/vstsqualitytools/archive/2009/09/04/extending-the-visual-studio-unit-test-type-part-2.aspx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T07:34:15.877", "Id": "41568", "Score": "4", "body": "NUnit has [Parameterized Tests](http://nunit.org/index.php?p=values&r=2.5)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T21:34:40.753", "Id": "41772", "Score": "0", "body": "@abuzittin gillifirca, if that code compiles and works, then my mind is blown. I did not realize that one can slap attributes onto method arguments." } ]
[ { "body": "<p>What you need is passing parameters to common test method and supplying it with informative error message.</p>\n\n<pre><code> [TestMethod]\n public void SubmitShortText()\n {\n var colorCodes = new[] { \"#\", \"#f\", \"#ff\" };\n DoAssertion(colorCodes);\n }\n\n private void DoAssertion(string[] colorCodes)\n {\n var parser = new ColorParser();\n foreach (var code in colorCodes)\n {\n var hasValue = parser.Parse(code).HasValue;\n Assert.IsTrue(hasValue, string.Format(\"Failed to parse color code '{0}'.\", code));\n }\n }\n</code></pre>\n\n<p>Parametrized tests are also supported in <strong>XUnit</strong>:</p>\n\n<pre><code> [Theory]\n [InlineData(\"#\")]\n [InlineData(\"#f\")]\n [InlineData(\"#ff\")]\n public void SubmitShortText(string code)\n {\n var parser = new ColorParser();\n var hasValue = parser.Parse(code).HasValue;\n Assert.True(hasValue, string.Format(\"Failed to parse color code '{0}'.\", code));\n }\n</code></pre>\n\n<p>Tests will be executed one by one. Execution will be stopped on the first failed test.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-04T14:56:56.743", "Id": "41819", "Score": "2", "body": "+1. You do not want the growing volume of test code to over-burden your ability to maintain it. Design, build, refactor, just as if it were as important as your \"money\" code. Because it is." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-04T10:27:22.543", "Id": "26976", "ParentId": "26820", "Score": "3" } } ]
{ "AcceptedAnswerId": "26976", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T20:49:58.667", "Id": "26820", "Score": "4", "Tags": [ "c#", "linq", "functional-programming", "unit-testing" ], "Title": "Is a unit test which uses LINQ to check multiple values acceptable?" }
26820
<p>I've read most of the posts I could find on optimizing SQLite3 performance, such as:</p> <ul> <li><a href="https://stackoverflow.com/questions/1711631/how-do-i-improve-the-performance-of-sqlite">How do I improve the performance of SQLite?</a>, </li> <li><a href="https://stackoverflow.com/questions/1609637/is-it-possible-to-insert-multiple-rows-at-a-time-in-an-sqlite-database?lq=1">Is it possible to insert multiple rows at a time in an SQLite database?</a></li> <li><a href="https://stackoverflow.com/questions/784173/what-are-the-performance-characteristics-of-sqlite-with-very-large-database-file">What are the performance characteristics of sqlite with very large database files?</a></li> </ul> <p>Which are good, but they have not been updated for a few SQLite releases, so I went for "<em>testing before believing</em>". In the "testing" I became suspicious of whether my approach to benchmarking of the modes of using SQLite is correct? The reason for asking is that I get a much lower threshold difference in performance - which is slightly <strong>contrary</strong> to the posts I've read, where some report orders of magnitude in difference.</p> <p>for example <a href="http://www.sqlite.org/pragma.html#pragma_journal_mode" rel="nofollow noreferrer">http://www.sqlite.org/pragma.html#pragma_journal_mode</a> comments:</p> <blockquote> <p>The TRUNCATE journaling mode commits transactions by truncating the rollback journal to zero-length instead of deleting it. <strong>On many systems, truncating a file is much faster than deleting the file since the containing directory does not need to be changed</strong>.</p> </blockquote> <p>But I cannot replicate the drop/increase in performance which should be "expected" from performing single transactions in different modes. <strong>So I wonder: Has SQLite3 evolved so much that these differences become a legend of the past?</strong> - or did I just miss something?</p> <p><strong>Update</strong>: Yes something was missing: The <a href="http://docs.python.org/2/library/sqlite3.html#controlling-transactions" rel="nofollow noreferrer">documentation</a> states that:</p> <blockquote> <p>By default, the sqlite3 module opens transactions implicitly before a Data Modification Language (DML) statement (i.e. INSERT/UPDATE/DELETE/REPLACE), and commits transactions implicitly before a non-DML, non-query statement (i. e. anything other than SELECT or the aforementioned).</p> <p>So if you are within a transaction and issue a command like CREATE TABLE ..., VACUUM, PRAGMA, <strong>the sqlite3 module will commit implicitly before executing that command</strong>.</p> </blockquote> <p>This might not to be the case, as pysqlite appears cycles through the operation without executing a commit between "execute" statements. <strong>I don't know how to test for this?</strong></p> <p><H2>Results summary</H2></p> <pre><code> Using SQLite 3.6.21 and pysqlite version 2.6.0 and python 2.7.5 </code></pre> <p><img src="https://i.stack.imgur.com/6IVWr.jpg" alt="summary overview of the test of sqlite3 operating modes."></p> <p><H2>Code</H2> <strong><em>Update 22:26 31/05/2013: Generator added: Creates synthetic data for review if file is not available.</em></strong></p> <pre><code>#!/usr/bin/python27 import sys import csv import time import sqlite3 from datetime import time as Time # used only for generating data if file is absent from random import randint # used only for generating data if file is absent def get_the_data(): msg = """ Thanks to http://opendata.toronto.ca/TTC/routes/ OpenData_TTC_Schedules.zip/stop_times.txt for the data. """ print msg """ Returns a list with this: trip_id,arrival_time,departure_time,stop_id,stop_sequence,stop_headsign,pickup_type,drop_off_type,shape_dist_traveled 19985180,6:15:00,6:15:00,14146,1,,0,0, 19985180,6:16:41,6:16:41,3807,2,,0,0,0.5355 19985180,6:17:41,6:17:41,6904,3,,0,0,0.8543 ... (many lines later) ... 20064514,25:41:41,25:41:41,7531,65,,0,0,17.6094 20064514,25:42:00,25:42:00,13118,66,,1,1,17.6794 """ data=[] start = time.clock() try: with open(r'D:\OpenData_TTC_Schedules\stop_times.txt') as fi: for row in csv.reader(fi, delimiter=','): data.append(tuple(row)) # SQLite's "executemany()" needs tuples. data.pop(0) # get rid of headers. except IOError: print "\tfile not found - generating data..." data=syntheticData() end = time.clock() wall_time = end - start print "\tFetched %d lines of data, or %.3f Mb, in %.3f seconds" %(len(data), sys.getsizeof(data)/float(10**6), wall_time) print "\t(Reading csv from disk = %d rows per second)." %(len(data)/wall_time) return data def syntheticData(length=4*10**5): alist=[] for i in range(length): trip_id = 19985180+i arrival_time = Time(randint(0,23),randint(0,59),randint(0,59)).isoformat() departure_time = Time(randint(0,23),randint(0,59),randint(0,59)).isoformat() stop_id = randint(1,15000) stop_sequence = randint(1,66) stop_headsign = '' pickup_type = randint(0,1) drop_off_type = randint(0,1) shape_dist_traveled = round(float(randint(5000,25000)/1000),4) row=tuple([trip_id,arrival_time,departure_time,stop_id,stop_sequence,stop_headsign,pickup_type,drop_off_type,shape_dist_traveled]) alist.append(row) return alist def transaction(data, DB, SQL_create_table, SQL, PRAGMA="ON", JOURNAL="", BATCH=True): con = sqlite3.connect(DB) cur = con.cursor() if PRAGMA=="OFF": cur.execute("PRAGMA synchronous = OFF") if JOURNAL!="": cur.execute("PRAGMA journal_mode = %s" %(JOURNAL)) cur.execute(SQL_create_table) # Create the table. start = time.clock() if BATCH==True: cur.executemany(SQL, data) # Do the insert test # Save (commit) the changes con.commit() ### else: for row in data[:100000]: # We have patience for 100k rows. cur.execute(SQL, row) # Save (commit) the changes con.commit() ### if time.clock()-start &gt; 300: break end = time.clock() cur.execute("SELECT IFNULL(MAX(id),1) FROM TTC;") rows=cur.fetchone()[0] wall_time = (end-start) if JOURNAL=="": JOURNAL="(default)" if BATCH==True: MODE="EXECUTEMANY" else: MODE="EXECUTE" print "\t%.2f rows per second with PRAGMA=%s and JOURNAL=%s using %s in %s" %(int(rows/wall_time),PRAGMA, JOURNAL, MODE, DB) SQL = "DROP TABLE IF EXISTS TTC;" # wipe the junk cur.execute(SQL) con.commit() con.close() if __name__ == '__main__': data = get_the_data() print "\n\tUsing SQLite %s and pysqlite version %s" %(sqlite3.sqlite_version, sqlite3.version) SQL_create_table = "CREATE TABLE IF NOT EXISTS TTC (id INTEGER PRIMARY KEY, trip_id TEXT, arrival_time TEXT, departure_time TEXT, stop_id INTEGER, stop_sequence INTEGER, stop_headsign TEXT, pickup_type TEXT, drop_off_type TEXT, shape_dist_traveled REAL);" SQL_data_operation = "INSERT INTO TTC VALUES(Null,?,?,?,?,?,?,?,?,?)" # the Null keyword permits SQLite to autoincrement. DB = 'sqlite3_speedtest.db' print "\tSingle Transactions using EXECUTE To DISK" transaction(data, DB, SQL_create_table, SQL_data_operation, BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "ON", BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "ON", "DELETE", BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "ON", "TRUNCATE", BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "ON", "MEMORY", BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "ON", "WAL", BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "ON", "OFF", BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF", BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF", "DELETE", BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF", "TRUNCATE", BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF", "MEMORY", BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF", "WAL", BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF", "OFF", BATCH=False) print "\tBatched Transactions using EXECUTEMANY To DISK" transaction(data, DB, SQL_create_table, SQL_data_operation) transaction(data, DB, SQL_create_table, SQL_data_operation, "ON") transaction(data, DB, SQL_create_table, SQL_data_operation, "ON", "DELETE") transaction(data, DB, SQL_create_table, SQL_data_operation, "ON", "TRUNCATE") transaction(data, DB, SQL_create_table, SQL_data_operation, "ON", "MEMORY") transaction(data, DB, SQL_create_table, SQL_data_operation, "ON", "WAL") transaction(data, DB, SQL_create_table, SQL_data_operation, "ON", "OFF") transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF") transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF", "DELETE") transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF", "TRUNCATE") transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF", "MEMORY") transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF", "WAL") transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF", "OFF") DB = ':memory:' print "\tSingle Transactions using EXECUTE To MEMORY" transaction(data, DB, SQL_create_table, SQL_data_operation, BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "ON", BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "ON", "DELETE", BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "ON", "TRUNCATE", BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "ON", "MEMORY", BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "ON", "WAL", BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "ON", "OFF", BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF", BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF", "DELETE", BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF", "TRUNCATE", BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF", "MEMORY", BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF", "WAL", BATCH=False) transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF", "OFF", BATCH=False) print "\tBatched Transactions using EXECUTEMANY To MEMORY" transaction(data, DB, SQL_create_table, SQL_data_operation) transaction(data, DB, SQL_create_table, SQL_data_operation, "ON") transaction(data, DB, SQL_create_table, SQL_data_operation, "ON", "DELETE") transaction(data, DB, SQL_create_table, SQL_data_operation, "ON", "TRUNCATE") transaction(data, DB, SQL_create_table, SQL_data_operation, "ON", "MEMORY") transaction(data, DB, SQL_create_table, SQL_data_operation, "ON", "WAL") transaction(data, DB, SQL_create_table, SQL_data_operation, "ON", "OFF") transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF") transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF", "DELETE") transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF", "TRUNCATE") transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF", "MEMORY") transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF", "WAL") transaction(data, DB, SQL_create_table, SQL_data_operation, "OFF", "OFF") print "\tTest Completed" </code></pre> <p><H2>Output</H2></p> <pre><code> Thanks to http://opendata.toronto.ca/TTC/routes/ OpenData_TTC_Schedules.zip/stop_times.txt for the data. Fetched 4624024 lines of data, or 20.108 Mb, in 8.170 seconds (Reading csv from disk = 565958 rows per second). Using SQLite 3.6.21 and pysqlite version 2.6.0 Single Transactions using EXECUTE To DISK 289.00 rows per second with PRAGMA=ON and JOURNAL=(default) using EXECUTE in sqlite3_speedtest.db 134.00 rows per second with PRAGMA=ON and JOURNAL=(default) using EXECUTE in sqlite3_speedtest.db 136.00 rows per second with PRAGMA=ON and JOURNAL=DELETE using EXECUTE in sqlite3_speedtest.db 157.00 rows per second with PRAGMA=ON and JOURNAL=TRUNCATE using EXECUTE in sqlite3_speedtest.db 527.00 rows per second with PRAGMA=ON and JOURNAL=MEMORY using EXECUTE in sqlite3_speedtest.db 137.00 rows per second with PRAGMA=ON and JOURNAL=WAL using EXECUTE in sqlite3_speedtest.db 522.00 rows per second with PRAGMA=ON and JOURNAL=OFF using EXECUTE in sqlite3_speedtest.db 564.00 rows per second with PRAGMA=OFF and JOURNAL=(default) using EXECUTE in sqlite3_speedtest.db 560.00 rows per second with PRAGMA=OFF and JOURNAL=DELETE using EXECUTE in sqlite3_speedtest.db 2145.00 rows per second with PRAGMA=OFF and JOURNAL=TRUNCATE using EXECUTE in sqlite3_speedtest.db 5579.00 rows per second with PRAGMA=OFF and JOURNAL=MEMORY using EXECUTE in sqlite3_speedtest.db 563.00 rows per second with PRAGMA=OFF and JOURNAL=WAL using EXECUTE in sqlite3_speedtest.db 11311.00 rows per second with PRAGMA=OFF and JOURNAL=OFF using EXECUTE in sqlite3_speedtest.db Batched Transactions using EXECUTEMANY To DISK 192030.00 rows per second with PRAGMA=ON and JOURNAL=(default) using EXECUTEMANY in sqlite3_speedtest.db 164718.00 rows per second with PRAGMA=ON and JOURNAL=(default) using EXECUTEMANY in sqlite3_speedtest.db 177257.00 rows per second with PRAGMA=ON and JOURNAL=DELETE using EXECUTEMANY in sqlite3_speedtest.db 167466.00 rows per second with PRAGMA=ON and JOURNAL=TRUNCATE using EXECUTEMANY in sqlite3_speedtest.db 181955.00 rows per second with PRAGMA=ON and JOURNAL=MEMORY using EXECUTEMANY in sqlite3_speedtest.db 166388.00 rows per second with PRAGMA=ON and JOURNAL=WAL using EXECUTEMANY in sqlite3_speedtest.db 212319.00 rows per second with PRAGMA=ON and JOURNAL=OFF using EXECUTEMANY in sqlite3_speedtest.db 246463.00 rows per second with PRAGMA=OFF and JOURNAL=(default) using EXECUTEMANY in sqlite3_speedtest.db 245461.00 rows per second with PRAGMA=OFF and JOURNAL=DELETE using EXECUTEMANY in sqlite3_speedtest.db 243850.00 rows per second with PRAGMA=OFF and JOURNAL=TRUNCATE using EXECUTEMANY in sqlite3_speedtest.db 246533.00 rows per second with PRAGMA=OFF and JOURNAL=MEMORY using EXECUTEMANY in sqlite3_speedtest.db 245036.00 rows per second with PRAGMA=OFF and JOURNAL=WAL using EXECUTEMANY in sqlite3_speedtest.db 245244.00 rows per second with PRAGMA=OFF and JOURNAL=OFF using EXECUTEMANY in sqlite3_speedtest.db Single Transactions using EXECUTE To MEMORY 85012.00 rows per second with PRAGMA=ON and JOURNAL=(default) using EXECUTE in :memory: 85393.00 rows per second with PRAGMA=ON and JOURNAL=(default) using EXECUTE in :memory: 85461.00 rows per second with PRAGMA=ON and JOURNAL=DELETE using EXECUTE in :memory: 85249.00 rows per second with PRAGMA=ON and JOURNAL=TRUNCATE using EXECUTE in :memory: 85315.00 rows per second with PRAGMA=ON and JOURNAL=MEMORY using EXECUTE in :memory: 84864.00 rows per second with PRAGMA=ON and JOURNAL=WAL using EXECUTE in :memory: 25705.00 rows per second with PRAGMA=ON and JOURNAL=OFF using EXECUTE in :memory: 83249.00 rows per second with PRAGMA=OFF and JOURNAL=(default) using EXECUTE in :memory: 85097.00 rows per second with PRAGMA=OFF and JOURNAL=DELETE using EXECUTE in :memory: 84700.00 rows per second with PRAGMA=OFF and JOURNAL=TRUNCATE using EXECUTE in :memory: 85441.00 rows per second with PRAGMA=OFF and JOURNAL=MEMORY using EXECUTE in :memory: 84724.00 rows per second with PRAGMA=OFF and JOURNAL=WAL using EXECUTE in :memory: 25521.00 rows per second with PRAGMA=OFF and JOURNAL=OFF using EXECUTE in :memory: Batched Transactions using EXECUTEMANY To MEMORY 284543.00 rows per second with PRAGMA=ON and JOURNAL=(default) using EXECUTEMANY in :memory: 285171.00 rows per second with PRAGMA=ON and JOURNAL=(default) using EXECUTEMANY in :memory: 285505.00 rows per second with PRAGMA=ON and JOURNAL=DELETE using EXECUTEMANY in :memory: 285609.00 rows per second with PRAGMA=ON and JOURNAL=TRUNCATE using EXECUTEMANY in :memory: 285056.00 rows per second with PRAGMA=ON and JOURNAL=MEMORY using EXECUTEMANY in :memory: 285799.00 rows per second with PRAGMA=ON and JOURNAL=WAL using EXECUTEMANY in :memory: 286359.00 rows per second with PRAGMA=ON and JOURNAL=OFF using EXECUTEMANY in :memory: 286316.00 rows per second with PRAGMA=OFF and JOURNAL=(default) using EXECUTEMANY in :memory: 285607.00 rows per second with PRAGMA=OFF and JOURNAL=DELETE using EXECUTEMANY in :memory: 285506.00 rows per second with PRAGMA=OFF and JOURNAL=TRUNCATE using EXECUTEMANY in :memory: 285671.00 rows per second with PRAGMA=OFF and JOURNAL=MEMORY using EXECUTEMANY in :memory: 285624.00 rows per second with PRAGMA=OFF and JOURNAL=WAL using EXECUTEMANY in :memory: 285707.00 rows per second with PRAGMA=OFF and JOURNAL=OFF using EXECUTEMANY in :memory: Test Completed </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T21:29:25.890", "Id": "41610", "Score": "0", "body": "@JanneKarila : Synthetic data generator added in code in lines 48-62 :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T17:43:32.683", "Id": "41668", "Score": "0", "body": "Commit each insert and you'll see differences in times. Now you don't commit anything." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T18:18:42.930", "Id": "41676", "Score": "0", "body": "Hi Janne,\nIn the documentation http://docs.python.org/2/library/sqlite3.html#controlling-transactions it is stated that:\n\"*if you are within a transaction and issue a command like CREATE TABLE ..., VACUUM, PRAGMA, the sqlite3 module will **commit implicitly** before executing that command.*\"\n\n\n- So why would I add an additional commit operation if SQLite commits implicitly? Is that not just bad practice?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T18:24:35.137", "Id": "41679", "Score": "0", "body": "In the part of code that you are timing, you only execute inserts. No implicit commit there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T18:42:27.140", "Id": "41680", "Score": "0", "body": "Hi Janne, i added **con.commit()** straight after cur.execute/executemany and get 82119 rows/second on execute versus 297689 rows/second on executemany: factor of **1.00:3.62**, which is far far away from *85 inserts-per-second* in other posts (what I expected in terms of orders of magnitude)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T18:54:25.307", "Id": "41683", "Score": "0", "body": "Now we are onto something. I added the *con.commit()* with commit to disk: Performance dropped to ~113 rows per second. In memory I still get the performance above." } ]
[ { "body": "<p>I have just had a similar experience using <a href=\"http://code.google.com/p/apsw/\">Another Python SQLite Wrapper (APSW)</a>, which is an alternative to pysqlite that tends to be a bit faster. The PRAGMA options make practically no difference on a database of ~2 million rows (6 columns, also doing some string formatting on the values being entered):</p>\n\n<ul>\n<li>753,347 rows/minute with all PRAGMAs at default (i.e. nothing set)</li>\n<li>764,967 rows/minute with:\n<ul>\n<li>synchronous = OFF</li>\n<li>locking_mode = Exclusive</li>\n<li>page_size = 4096</li>\n<li>journal_mode = WAL</li>\n</ul></li>\n</ul>\n\n<p>Tests were run three times, values averaged. I determined the PRAGMA values for each of these settings iteratively by testing a range of values, each of which was <em>slightly</em> faster, but the overall improvement is negligible.</p>\n\n<p>Although not exactly relevant to your post (but relevant to people using Python with SQLite), one thing that makes a <strong>massive</strong> performance difference is generating table indexes after adding values. Including the time to create two indexes on the table after the values are inserted, the numbers above drop to:</p>\n\n<ul>\n<li>691,774 rows/minute with all PRAGMAs at default (i.e. nothing set)</li>\n<li>711,995 rows/minute with PRAGMAs set as described above</li>\n</ul>\n\n<p>However, creating two indexes on the table <em>before</em> adding the values, and running the same tests as above, I get a ~7-fold reduction:</p>\n\n<ul>\n<li>119,005 rows/minute with all PRAGMAs at default (i.e. nothing set)</li>\n<li>114,209 rows/minute with PRAGMAs set as described above</li>\n</ul>\n\n<p>This shows a speed decrease with the PRAGMAs set, however that could just be within the margin of error (due to disk loading, file fragmentation, etc...?) as I only ran this latter test once for each condition.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-07T20:12:00.683", "Id": "44128", "Score": "0", "body": "Hi is the 7 fold reduction conditional to the data being sorted or is it consistent even with random data?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-09T22:42:21.927", "Id": "44320", "Score": "0", "body": "@BHM I do not have the ability to test this for the given dataset, unfortunately. Interesting question though! Furthermore, if the data is unsorted, what is the total time to sort manually then add then index, vs. add unsorted then index?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-04T06:28:27.100", "Id": "28112", "ParentId": "26822", "Score": "8" } } ]
{ "AcceptedAnswerId": "28112", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T21:40:56.247", "Id": "26822", "Score": "17", "Tags": [ "python", "optimization", "sqlite" ], "Title": "Myth-busting SQLite3 performance w. pysqlite" }
26822
<p>I made myself this code to read CSV files as I want to delve into machine learning. I do think that my code design is poor but I can't quite see why. The syntax of it does not feel right. I want to be able to iterate both over rows and columns but I'd rather not make two different kinds of iterators. </p> <p>I'm sorry the code is a bit long to post on here but I'd really like a review on this. </p> <p>What I hate the most is how I need to cast my iterators. I tried to avoid having to call a method to retrieve the value but I'm thinking this is probably one of the first things I would have to change :\</p> <p><strong>CSVFileReader.h</strong></p> <pre><code>//============================================================================== // CSVLine // - Holds information on a specific row of a pre-loaded CSV file. //============================================================================== class CSVLine { public: CSVLine(); CSVLine(const CSVLine&amp;); void Reset(); void AddValue(std::string); unsigned int Size() const; const CSVLine&amp; operator=(const CSVLine&amp;); std::string&amp; operator[](int); private: std::vector&lt;std::string&gt; line; }; //============================================================================== // CSVIterator (TEMPLATE) // - Can iterate on CSV classes (CSVData, CSVLine) if they provide // overloading for [] operator as well as return their size through Size() //============================================================================== template &lt;class T_ITERABLE, class T_RETVAL&gt; class CSVIterator { public: CSVIterator(T_ITERABLE&amp; obj) : my_obj(obj), location(0) { /* blank */ } T_RETVAL GetFirst() { return my_obj[0]; } T_RETVAL GetLast() { return my_obj[my_obj.Size() - 1]; } T_RETVAL At(unsigned int index) { location = index; return my_obj[location]; } bool End() { return (location == my_obj.Size()); } bool Begin() { return (location == 0); } CSVIterator&lt;T_ITERABLE, T_RETVAL&gt;&amp; obj) { out &lt;&lt; obj; return out;} operator T_ITERABLE() { return my_obj; } operator T_RETVAL () { return my_obj[location]; } T_RETVAL operator++(int) { return my_obj[location++]; } T_RETVAL operator--(int) { return my_obj[location--]; } private: T_ITERABLE my_obj; int location; }; class CSVData; // Pre-declaration for typedefs typedef CSVIterator&lt;CSVData, CSVLine&gt; CSVRowIterator; typedef CSVIterator&lt;CSVLine, std::string&gt; CSVColIterator; //============================================================================== // CSVData // - Holds the entire "array" of data. Allows data read-access to the user // through the CSVIterator class and its CSVRowIterator and CSVColIterator // pre-defined typedefs; //============================================================================== class CSVData { public: void AddLine(CSVLine); unsigned int Size(); CSVLine&amp; operator[] (int); private: std::vector&lt;CSVLine&gt; contents; }; </code></pre> <p><strong>CSVFileReader.cpp</strong></p> <pre><code>//============================================= // CSVLine //============================================= CSVLine::CSVLine() { /* Blank */ } CSVLine::CSVLine(const CSVLine&amp; copy) { line.resize(copy.line.size()); std::copy(copy.line.begin(), copy.line.end(), line.begin()); } void CSVLine::Reset() { line.clear(); } void CSVLine::AddValue(std::string value) { line.push_back(value); } unsigned int CSVLine::Size() const { return line.size(); } const CSVLine&amp; CSVLine::operator=(const CSVLine&amp; copy) { line.clear(); line.resize(copy.line.size()); std::copy(copy.line.begin(), copy.line.end(), line.begin()); return *this; } std::string&amp; CSVLine::operator[](int index) { if(index &lt; line.size() &amp;&amp; index &gt;= 0 &amp;&amp; line.size() &gt; 0) { return line[index]; } else throw std::out_of_range("Error: Accessing CSVLine out of bounds"); } //============================================= // CSVData //============================================= void CSVData::AddLine(CSVLine line) { contents.push_back(line); } unsigned int CSVData::Size() { return contents.size(); } CSVLine&amp; CSVData::operator[] (int index) { if(index &lt; contents.size() &amp;&amp; index &gt;= 0 &amp;&amp; contents.size() &gt; 0) { return (contents[index]); } else throw std::out_of_range("Error: Accessing CSVLine out of bounds"); } //============================================= // CSVFileReader //============================================ CSVFileReader::~CSVFileReader() { /* ... */ } void CSVFileReader::OpenFile(std::string file_name) { /* ... */ } void CSVFileReader::LoadIntoMemory() { /* ... */ } CSVData&amp; CSVFileReader::GetData() { return file_data; } </code></pre> <p><strong>This is an example of how I can manipulate a CSV file with it</strong></p> <pre><code>int main(int argc, char** argv) { CSVReaderFactory csvrf; CSVFileReader* csvfr = csvrf.CreateFileReader(); csvfr-&gt;OpenFile("C:\\Users\\Alexandre\\Documents\\test.csv"); csvfr-&gt;LoadIntoMemory(); CSVData&amp; d = csvfr-&gt;GetData(); std::cout &lt;&lt; std::endl; CSVRowIterator row_iter(d); for(row_iter.GetFirst(); !row_iter.End(); row_iter++) { CSVColIterator col_iter((CSVLine)row_iter); for(col_iter.GetFirst(); !col_iter.End(); col_iter++) { std::cout &lt;&lt; ((std::string)col_iter).c_str(); } std::cout &lt;&lt; std::endl; } csvrf.ReleaseFileReader(csvfr); std::cin.get(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T17:56:28.920", "Id": "41671", "Score": "0", "body": "Looks familiar." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T17:57:21.347", "Id": "41672", "Score": "0", "body": "Don't use ALL CAPS Identifiers. Theses are reserved for macros and using them opens up your code to being stomped on by them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T18:48:00.113", "Id": "41681", "Score": "0", "body": "I don't know that this is true. Do you have any source on this bit of information ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T18:49:16.073", "Id": "41682", "Score": "0", "body": "About the \"Looks familiar\", yes I got part of the idea on SO but I can't find the link to credit the author. I did not copy the code though, I only used it as an inspiration. It probably was better than what I did to be honest." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T19:51:48.753", "Id": "41765", "Score": "0", "body": "Are you questioning the bit about ALL CAPS. See any text book on C (usually chapter 1). This has been a convention from the beginning of C. The problem is that macros have no scope (and thus will trample on anything). Thus we manually scope them by defining macros so they can not overlap with other identifiers. The way we manually scope them is by reserving identifiers with ALL CAPS as macros." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T19:56:15.383", "Id": "41766", "Score": "0", "body": "http://programmers.stackexchange.com/a/113565/12917" } ]
[ { "body": "<p>Your design seems rather confused. You generally want iterators to be retrievable only from member functions of a class - the user shouldn't have to manually \"create\" an iterator. Secondly, you don't really need to create your own iterator types here. Your classes are fairly simple wrappers around <code>std::vector</code>, so just utilize the fact that it already provides iterators.</p>\n\n<pre><code>class CSVLine \n{\nprivate:\n typedef std::vector&lt;std::string&gt;::iterator iterator;\n typedef std::vector&lt;std::string&gt;::const_iterator const_iterator;\n\npublic:\n /* .... */\n\n iterator begin()\n {\n return line.begin();\n }\n\n const_iterator begin() const\n {\n return line.begin();\n }\n\n iterator end()\n {\n return line.end();\n }\n\n const_iterator end() const\n {\n return line.end(); \n }\n\nprivate:\n std::vector&lt;std::string&gt; line;\n};\n</code></pre>\n\n<p>And pretty much exactly the same thing with <code>CSVData</code>:</p>\n\n<pre><code>class CSVData \n{\nprivate:\n typedef std::vector&lt;CSVLine&gt;::iterator iterator;\n typedef std::vector&lt;CSVLine&gt;::const_iterator const_iterator;\n //...\n};\n</code></pre>\n\n<p>There's a few other things you should probably fix with your code as well. <code>void AddValue(std::string);</code> should take a <code>const std::string&amp;</code>, so it doesn't end up copying the string twice (adding to a <code>vector</code> already performs a copy of the underlying data).</p>\n\n<p><code>unsigned int Size() const;</code> should be returning a <code>typename std::vector&lt;std::string&gt;::size_type</code>, which is usually a <code>std::size_t</code>. I'd simply add that as a <code>typedef</code> in your class:</p>\n\n<pre><code>typedef std::vector&lt;std::string&gt;::size_type size_type;\n....\nsize_type Size() const;\n</code></pre>\n\n<p><code>std::string&amp; operator[](int);</code> should again be taking a <code>size_type</code>. You can't pass a negative parameter to <code>[]</code> for <code>vector</code>, so having it take a signed int makes no sense. You should also have <code>const</code> overloads of these methods:</p>\n\n<pre><code>const std::string&amp; operator[](size_type i) const\n</code></pre>\n\n<p>Finally, it's hard to tell since there isn't any code for it, but <code>CSVFileReader* csvfr = csvrf.CreateFileReader();</code> is never freed, at least not in <code>main</code>. This may or may not be a memory leak, depending on how it is declared and what <code>csvrf.ReleaseFileReader(csvfr);</code> does.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T03:00:27.733", "Id": "41563", "Score": "0", "body": "That does feel better. Also, yes my design is confused, because I am confused ! I'll wait a bit to see if there are other reviews but your answer is a good candidate for check mark ! Thanks :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T18:00:37.013", "Id": "41673", "Score": "0", "body": "`You generally want iterators to be retrievable only from member functions of a class` Don't agree. `std::begin()` and `std::end()` for eaxample. Or `std::istream_iterator<>` or `std::ostream_iterator<>` or any pointer type." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T02:48:56.790", "Id": "26827", "ParentId": "26825", "Score": "3" } }, { "body": "<p>First I agree with @Yuushi in this situation you probably should not be writing your own iterator. The ones provided by the vector class should work fine.</p>\n\n<p>But if you are in the situation to write your own iterator you need to do a few more things.</p>\n\n<p>There a set of types that you should be defining (either inside the class or via traits)</p>\n\n<pre><code> typedef std::input_iterator_tag iterator_category;\n typedef XXXXXX value_type;\n typedef YYYYYY difference_type;\n typedef ZZZZZZ pointer;\n typedef AAAAAA reference;\n</code></pre>\n\n<p>Also you seem to be missing the fundamental requirements for an iterator:</p>\n\n<pre><code> operator*()\n operator-&gt;()\n</code></pre>\n\n<p>And I don't think your iterator confirms to any of the standard iterator types. You want to look at that so people know how to use your iterators correctly.</p>\n\n<p>See <a href=\"http://www.sgi.com/tech/stl/Iterators.html\" rel=\"nofollow noreferrer\">http://www.sgi.com/tech/stl/Iterators.html</a> for details.</p>\n\n<p>More information here: <a href=\"https://stackoverflow.com/a/1120224/14065\">https://stackoverflow.com/a/1120224/14065</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T18:09:17.200", "Id": "26896", "ParentId": "26825", "Score": "2" } } ]
{ "AcceptedAnswerId": "26827", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T02:06:09.693", "Id": "26825", "Score": "1", "Tags": [ "c++", "csv" ], "Title": "Custom template iterator on CSV reading class" }
26825
<p>So far, the below code appears to work well. It operates pretty fast, but I was wondering if it's possible to make it faster. I'm also looking for general tips on what I might be doing wrong and what I could do better. I have added in comments to explain certain decisions.</p> <p><strong>b64.h</strong> </p> <pre><code>#include &lt;math.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; static const char encode_table[] = \ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; char *ascii_to_base64(char *asciistr) { int asciistrlen = strlen(asciistr); int convertedlen = 4 * ceil((double)asciistrlen / 3.0); char *asciibuff = (char*)malloc(convertedlen + 1); if (asciibuff == NULL) goto exception; char *converted = malloc(convertedlen + 1); if (converted == NULL) goto exception; /* * By zero-ing out, I can just check 0x00 bytes and convert to padding * without any extra checks. */ memset(asciibuff, 0x00, asciistrlen + 1); memset(converted, 0x00, convertedlen + 1); /* * Can't realloc the asciistr var so have to create individual buffer * with same values. */ strcpy(asciibuff, asciistr); /* * Allows me to loop through original string input AND be able to check * for null bytes and pad accordingly without running into overwriting * problems caused by using the "converted" variable for both jobs. */ int i, j; for (i = 0, j = 0; i &lt; convertedlen; i+=4, j+=3) { converted[i+3] = encode_table[asciibuff[j+2] != 0x00 ? asciistr[j+2] &amp; 0xbf : 64]; converted[i+2] = encode_table[asciibuff[j+1] != 0x00 ? ((asciistr[j+1] &amp; 0x0f) &lt;&lt; 2) + (asciibuff[j+2] &gt;&gt; 6) : 64]; converted[i+1] = encode_table[asciibuff[j] != 0x00 ? ((asciistr[j] &amp; 0x03) &lt;&lt; 4) + (asciibuff[j+1] &gt;&gt; 4) : 64]; converted[i] = encode_table[asciibuff[j] != 0x00 ? asciibuff[j] &gt;&gt; 2 : 64]; } free(asciibuff); return (converted); exception: return (NULL); } /* Derive encoding index */ static unsigned int enci(int base64ascii) { if (base64ascii &lt;= 0x5a &amp;&amp; base64ascii &gt;= 0x41) return ((unsigned)(base64ascii - 0x41)); else if (base64ascii &lt;= 0x7a &amp;&amp; base64ascii &gt;= 0x61) return ((unsigned)(base64ascii - 0x47)); else if (base64ascii &lt;= 0x39 &amp;&amp; base64ascii &gt;= 0x30) return ((unsigned)(base64ascii + 0x04)); else if (base64ascii == 0x2b) return ((unsigned)0x3e); else if (base64ascii == 0x2f) return ((unsigned)0x3f); else if (base64ascii == 0x3d) return ((unsigned)0x00); else return ((unsigned)0xff); } char *base64_to_ascii(char *base64str) { int base64strlen = strlen(base64str); int convertedlen = (base64strlen / 4) * 3; /* If an end character is '=', there is one less byte to be generated. */ if (base64str[base64strlen - 1] == '=') convertedlen--; if (base64str[base64strlen - 2] == '=') convertedlen--; char *converted = (char*)malloc(base64strlen + 1); if (converted == NULL) goto exception; memset(converted, 0x00, base64strlen + 1); int i, j; for (i = 0, j = 0; i &lt; base64strlen; i+=4, j+=3) { converted[j] = (enci(base64str[i]) &lt;&lt; 2) + (enci(base64str[i+1]) &gt;&gt; 4); converted[j+1] = ((enci(base64str[i+1]) &amp; 0x0f) &lt;&lt; 4) + (enci(base64str[i+2]) &gt;&gt; 2); converted[j+2] = ((enci(base64str[i+2]) &amp; 0x03) &lt;&lt; 6) + enci(base64str[i+3]); } /* * By making "converted" as long as the base64 encoded string * (when it really should be smaller.) I can loop through the base64 * encoding with no invalid writes or reads and just cut off the excess * bytes with a realloc. Don't know if this is the best solution, but it * satiates valgrind. After running through many inputs, it appears to * always cut the converted string with its null-terminating character. * I always get valid c-strings. */ converted = realloc(converted, convertedlen + 1); return (converted); exception: return (NULL); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T02:38:46.890", "Id": "41561", "Score": "0", "body": "I thought we have abundance of stock base64 implementations and no one recreates the wheel. Do you have a reason to think those are too slow or that yours needs actual speed optimization? I think the first rule of the latter is still \"don't do it' followed by second rule adding yet, and before measurements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T02:44:17.593", "Id": "41562", "Score": "1", "body": "@BalogPal Oh yes, there are plenty.\n\nI'm currently working through some crypto exercises, and it asked to implement base64 encode/decode functions. It's more a learning experience than anything. It's taught me tons about bit manipulation, but just wondering if I made any glaring errors or did something stupidly and if there are any speed optimizations I can make (just for knowledge's sake.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T20:57:03.413", "Id": "41607", "Score": "1", "body": "Okay, learning is definitely a good goal, I suggest you state it in the question. Especially as performance op is normally at the far end of learning curve, first you write code that works correctly all the way, then code that is also elegant to the eye and easy to work with, *then*, *IF* optimization done by compiler is lacking in requirements you profile and possibly adjust. The code you presented is pretty far from the second goal and for that reason hard to tell if meets the first. As it's a commonly solved problem I suggest to read the alternatives you find,compare,adjust then ask again" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T04:23:53.877", "Id": "41702", "Score": "0", "body": "@BalogPal To be fair, my code isn't *that* bad. I've looked at other implementations and mine fits in with the structure of two of the many that I've seen. But yeah, as William Morris pointed out, I made a lot of rookie mistakes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T11:11:04.997", "Id": "41717", "Score": "1", "body": "the point is that you learn :)" } ]
[ { "body": "<p>I only really looked at <code>ascii_to_base64</code>.</p>\n\n<p>Firstly, you say that the code is \"pretty fast\", but why is that a\nconsideration? Don't assume that execution speed is necessarily important.\nReadability and correctness are more so.</p>\n\n<p>On correctness, your code does not handle padding correctly. Given the string\n\"1\" your code produces \"MQ=K\" where it should produce \"MQ==\" (with \"11\" it\ncorrectly produces \"MTE=\"). This seems to come from using the wrong length in\nthe first memset:</p>\n\n<pre><code>memset(asciibuff, 0x00, asciistrlen + 1);\nmemset(converted, 0x00, convertedlen + 1);\n</code></pre>\n\n<p>If you use <code>convertedlen</code> for both, the problem is resolved. Better still,\nuse <code>calloc</code> instead of <code>malloc</code> followed by <code>memset</code>.</p>\n\n<p>Another point is that you use <code>strcpy</code> to copy the input string, but you\nalready know its length; <code>memcpy</code> is more efficient when the length is known.</p>\n\n<p>Note that it is possible to encode the input string without copying it into a bigger buffer - you just have to be careful not to access beyond the end of the input string.</p>\n\n<p>On readability, I have a little trouble with the function. The variable names\nare too long for my liking (they are local to a short function) and the four\nexpressions in the for-loop are difficult to read. I dislike your use of the\nternary operator (?:) in these expressions as it makes them hard to\ndecode. And you mix access to <code>asciibuff</code> and <code>asciistr</code> (all should be to the\nformer). </p>\n\n<p>Your bit-twiddling is okay, with good use of bracketing, although the 0xbf\nshould be 0x3f in the 1st line of the for-loop. I would prefer to see you\ncombining the values with '|' not '+'; both will work but when combining\nnon-numeric values '|' is more logical.</p>\n\n<p>I prefer not to use <code>goto</code>, as you have. And if I were to use it I'd make\nsure not to leak <code>asciibuff</code> if allocation of <code>converted</code> failed. </p>\n\n<p>Finally, your use of floating point to round-up when computing <code>convertedlen</code>\nis unnecessary. Instead of your:</p>\n\n<pre><code>int convertedlen = 4 * ceil((double)asciistrlen / 3.0);\n</code></pre>\n\n<p>I would expect something like:</p>\n\n<pre><code>int convertedlen = 4 * ((asciistrlen + 2) / 3);\n</code></pre>\n\n<p>BTW, your code has all sorts of singed/unsigned and loss of precision conversion warnings (gcc option -Wconversion).</p>\n\n<p><hr>\n<strong>EDIT</strong> : Variable naming is difficult. It is also open to argument, so I can only give\nyou my preferences which are based on the widely found advice that the length\nof names should related to their scope. So variables in a small function can\nbe small; those in a large function can be longer (but large functions should\ngenerally be avoided anyway). Global variables need to be larger still. But\nthese are guidlelines, not fixed rules. If <code>t1</code> has global significance to\nyour application then using <code>t1</code> as a global might be sensible; you wouldn't after\nall call <code>pi</code> anything but <code>pi</code>.</p>\n\n<p>In the case of a smallish function like <code>ascii_to_base64</code>, I would call the\ninput string <code>s</code> - the function name says it is an ASCII string so no need to\nrepeat that. For the copy of <code>s</code>, which is used everywhere, I'd use <code>ascii</code>.\nThe converted value I'd call <code>base64</code>. For the lengths: the length of <code>s</code> is\nused just once and needs no variable; the length of the conversion I'd call\njust <code>len</code> or maybe, <code>len64</code>. And the base-64 coding table, which in your\nexample is used only in this function and so should be local to the function,\nnot global, I'd call <code>coding</code>.</p>\n\n<p>Really small names, such as your loop variables <code>i</code> and <code>j</code> are also okay (in\nfact they are preferable for small loops), but when mixed together can be\ndifficult to tell apart. I have this problem with your for-loop, as it is not\neasy to tell at a glance that <code>i</code> is used only in the left-hand side of each\nline. You might use <code>i</code> and <code>k</code>, which are more easily distinguished. Or you\ncould refactor the loop to avoid having two indices.</p>\n\n<pre><code>const char *a = ascii;\nfor (int i = 0; i &lt; len; i += 4, a += 3)\n{\n base64[i+3] = coding[a[2] != 0 ? a[2] &amp; 63 : 64];\n base64[i+2] = coding[a[1] != 0 ? ((a[1] &amp; 15) &lt;&lt; 2) | (a[2] &gt;&gt; 6) : 64];\n base64[i+1] = coding[*a != 0 ? ((*a &amp; 3) &lt;&lt; 4) | (a[1] &gt;&gt; 4) : 64];\n base64[i] = coding[*a != 0 ? *a &gt;&gt; 2 : 64];\n}\n</code></pre>\n\n<p>(but note that I wouldn`t have coded the loop that way in the first place).</p>\n\n<p>Note also that <code>0</code> is just as good as <code>0x00</code> and <code>3</code> is as good as <code>0x03</code>; the\nshorter versions are easier to read.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T03:50:10.507", "Id": "41700", "Score": "0", "body": "Which compiler are you using? I've been using gcc with -Wall flag and got no precision loss warnings." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T04:04:58.900", "Id": "41701", "Score": "0", "body": "Also: how should I name my variables? I'm trying not to fall into the bad habit of sentences for variable names but isn't explicitness the best policy?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T14:40:32.240", "Id": "41741", "Score": "0", "body": "-Wall does not in fact give 'all' warnings. -Wconversion will give you conversion warnings. The clang compiler with -Wconversion will give some more. These warnings can be quite annoying and are mostly harmless but I think it is worth knowing about them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T15:44:48.177", "Id": "41749", "Score": "1", "body": "I have added some thoughts on variable naming to the answer" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T21:27:33.263", "Id": "26860", "ParentId": "26826", "Score": "5" } }, { "body": "<p>Just a couple of comments:</p>\n\n<ol>\n<li>Always use <code>{ }</code> for single line <code>if</code>s (and <code>for</code>, <code>while</code> etc), even if it's not required. It'll save a lot of time one day...</li>\n<li>Rather than <code>malloc</code> and then <code>memset(...0...)</code>, you might consider using <code>calloc</code> instead to do it automatically.</li>\n<li><code>if (converted == NULL)\n goto exception;</code> leaves <code>asciibuff</code> still allocated, and hence a memory leak. Either free it in the <code>if</code> block, or use another <code>goto</code> label and free it there.</li>\n<li><p>I would avoid for statements with multiple controlling variables like</p>\n\n<pre><code>for (i = 0, j = 0; i &lt; convertedlen; i+=4, j+=3) \n{\n // stuff\n}\n</code></pre>\n\n<p>and reword it to the following to make it easier to read (imo) and maybe even split the loop contents into another (<code>deci</code>) function:</p>\n\n<pre><code>j = 0;\nfor (i = 0; i &lt; convertedlen; i += 4)\n{\n deci( &amp;asciibuff[j], &amp;asciistr[j], &amp;converted[i] );\n j += 3;\n}\n</code></pre></li>\n<li>Use <code>(unsigned int)</code> instead of <code>(unsigned)</code> to be more explicit.</li>\n<li>There's no real need to do the final <code>converted = realloc(converted, convertedlen + 1);</code>; <code>strlen</code>, <code>strcpy</code> etc will work fine without it.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T21:29:48.517", "Id": "26861", "ParentId": "26826", "Score": "1" } } ]
{ "AcceptedAnswerId": "26860", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T02:21:12.077", "Id": "26826", "Score": "4", "Tags": [ "optimization", "c", "base64" ], "Title": "Speed optimisation and general tips for base64 encoding/decoding functions in C" }
26826
<p>I'm implementing a "tags" features to an already working solution. </p> <p>Final users need to be able to add tags to three separate sections of the solution:</p> <ul> <li><code>Posts</code></li> <li><code>Accounts</code></li> <li><code>Groups</code></li> </ul> <p>Each section has its corresponding table in the database, and each table contains a unique ID:</p> <ul> <li><code>PostID</code></li> <li><code>AccountID</code></li> <li><code>GroupID</code></li> </ul> <p>I'm thinking about implementing a tag schema similar to the one that Wordpress uses, where I'll have:</p> <ul> <li>A <code>tagmap</code> table that will contain a unique ID for each "tagmap".</li> <li>A foreign key to each section's table ID.</li> <li>Another foreign key to the ID of the tag.</li> </ul> <p></p> <pre><code>CREATE TABLE Posts( PostID int(2) NOT NULL AUTO_INCREMENT, Content varchar(255), PRIMARY KEY(PostID) ); CREATE TABLE Groups( GroupID int(2) NOT NULL AUTO_INCREMENT, GroupName varchar(255), PRIMARY KEY(GroupID) ); CREATE TABLE Links( LinkID int(2) NOT NULL AUTO_INCREMENT, href varchar(255), PRIMARY KEY(LinkID) ); CREATE TABLE tagmap( TagmapID int(2) NOT NULL AUTO_INCREMENT, PostID int(2), GroupID int(2), LinkID int(2), TagID int(2) NOT NULL, PRIMARY KEY(TagmapID) ); CREATE TABLE tags( TagID int(2) NOT NULL AUTO_INCREMENT, TagName varchar(255) NOT NULL, PRIMARY KEY(TagID) ); </code></pre> <p>I like this approach because it is decently normalized, but queries might get a bit complex. Also, it will have a lot of <code>NULL</code> columns every time a tag is assigned to a post but not to an account or to a group, so I'm unsure how it will behave performance-wise (the table will hold around 100,000 records almost immediately). </p> <p>Is there a better alternative to this? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T08:29:36.217", "Id": "41572", "Score": "1", "body": "You have to split your `tagmap` table to `tag_post`, `tag_group` and `tag_account`.\n\nThis is also evident from: \"_Final users need to be able to add tags to three different sections of the solution: Posts, Accounts, and Groups_\"" } ]
[ { "body": "<p>As @abuzittingillifirca said, this isn't very normalized. Summarizing my own opinion and what I've generally gathered from the net, you'll want to normalize it completely, test it with real data, then optimize the heck out of your configuration and queries before thinking about denormalization. With proper optimization, in my experience you should be able to get to millions of rows before queries start being less than humanly instantaneous.</p>\n\n<p>Also, have you studied other tagging solutions and their requirements? There's probably a lot of stuff that's already been figured out...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T16:22:05.733", "Id": "41588", "Score": "0", "body": "I've researched other tagging solutions, but the \"tagmap\" solution I think is the one that best suit our needs for now.\n\nBut I'm more than happy to research more options! If you have a resource that you think I should check out, I'll happily do it!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T11:16:12.343", "Id": "26842", "ParentId": "26828", "Score": "2" } }, { "body": "<p>A simple solution is to include a table reference in the tagmap instead of many id columns.</p>\n\n<pre><code>CREATE TABLE tagmap(\n TagmapID int(2) NOT NULL AUTO_INCREMENT,\n RefTable varchar(255) NOT NULL,\n RefID int(2),\n TagID int(2) NOT NULL,\n PRIMARY KEY(TagmapID),\n INDEX(RefTable, RefID),\n UNIQUE(RefTable, RefID, TagID)\n);\n</code></pre>\n\n<p>With that approach, you can easily make other tables taggable. To retrieve the tags for a post, you'd just say</p>\n\n<pre><code>SELECT TagName FROM tags\nLEFT JOIN tagmap USING TagID\nWHERE RefTable = 'posts' AND RefID = 42\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T18:09:40.660", "Id": "41599", "Score": "0", "body": "I think that'll work nice... I'm going to benchmark this solution and the one that I already implemented and see how it goes! Thanks a bunch!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T17:49:33.310", "Id": "26855", "ParentId": "26828", "Score": "3" } }, { "body": "<p>While this may seem \"decently normalized\", it's not. As you said yourself, there will be a lot of (redundant) NULL values, but also, relationships will not be enforced correctly, as this schema allows for duplicate <code>tagmap</code> records for any combination of Post/Group/Link and Tag. For instance, you could have two tagmap records with the same <code>TagID</code> and <code>PostID</code>. </p>\n\n<p>Now, while you could add a compound key consisting of PostID, GroupID, LinkID, and TagID, then you have another problem: a single record can contain more than one (non-tag) Post/Group/Link relation. e.g. a tagmap record with <code>TagID</code>= 1, <code>PostID</code>= 1, AND <code>GroupID</code>= 1. This can lead to update anomalies. See <a href=\"http://en.wikipedia.org/wiki/Second_normal_form\" rel=\"nofollow\">Second normal form</a>.</p>\n\n<p>A normalized solution would be to have three separate tag-relation tables as abuzittin gillifirca suggested: <code>tag_post</code>, <code>tag_group</code>, and <code>tag_link</code>. Doing so will eliminate all the redundant NULL values and allow you to enforce relations correctly.</p>\n\n<p>Having said that, I'm guessing you came up with this design, because you want to use a single query to fetch all entities assigned to one or more tags. You can still do this with multiple tag-relation tables like so:</p>\n\n<pre><code>SELECT everything.Type, everything.Id, everything.Content\nFROM (\n SELECT 'post' as Type, PostID as Id, Content \n FROM Posts \n JOIN TagPosts ON TagPosts.PostID = Posts.PostID \n WHERE TagPosts.TagID = ?\n\n UNION ALL\n\n SELECT 'group' as Type, GroupID as Id, GroupName as Content \n FROM Groups \n JOIN TagGroups ON TagGroups.GroupID = Groups.GroupID \n WHERE TagGroups.TagID = ?\n\n UNION ALL\n\n SELECT 'link' as Type, LinkID as Id, href as Content \n FROM Links \n JOIN TagLinks ON TagLinks.LinkID = Links.LinkID \n WHERE TagLinks.TagID = ?\n) AS everything;\n</code></pre>\n\n<p>This would return records like:</p>\n\n<pre><code>\"post\", 1, \"Some content of a post\"\n\"post\", 2, \"Content for another post\"\n\"group\", 1, \"Group name\"\n\"link\", 1, \"http://johntron.com\"\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-19T17:18:50.273", "Id": "205015", "Score": "0", "body": "What are the performance implication of the N:N junction tables to entities? Considering that each entity you need to query will require an additional Union." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-12T19:10:39.557", "Id": "210664", "Score": "1", "body": "@AmadeoGallardo it would depend on the query plan, but performance should be a secondary priority - data consistency is paramount, so proper normalization is where I always start. True, many SQL engines do a poor job with the derived table, but this is something that could be improved with tuning. In really extreme circumstances, denormalization may be necessary, but I would avoid this if at all possible. Just monitor the performance of your database (a list of queries descending-sorted by execution time for instance), and make the decision when it's necessary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-12T20:47:51.527", "Id": "210696", "Score": "0", "body": "As a wrapper for the conversation, ended up implementing multiple join tables, each one with a foreign key associating the tables. It is working well and through an abstraction the application model hides the data complexity." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-15T21:05:29.323", "Id": "211359", "Score": "1", "body": "@AmadeoGallardo that's great!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T18:20:47.087", "Id": "26856", "ParentId": "26828", "Score": "3" } } ]
{ "AcceptedAnswerId": "26856", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T02:54:25.820", "Id": "26828", "Score": "4", "Tags": [ "sql", "mysql" ], "Title": "Schema for allowing adding tags to entities in unrelated tables" }
26828
<p>Is there a better way to do this? If I ever have to worry about earlier images not being loaded before the later images, i.e. image[3] being loaded after image[21]. I have to load about 100 images at the start.</p> <pre><code>for (var i = 0; i &lt; 22; i++) { images[i] = new Image(); images[i].src = whatever[i] + ".png"; if (i == 21) { images[21].onload = function() { for (var j = 0; j &lt; 22; j++) { context.drawImage( images[j], (test * 60), (240 + ((Math.floor(j * 0.25)) * 70)) ); } test ++; if(test &gt; 4) { test = 1; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T08:06:30.803", "Id": "41571", "Score": "1", "body": "Are you sure this works? Can we see a demo?" } ]
[ { "body": "<h1>Sprite!</h1>\n\n<p>I suggest you place the images in a single image, like a \"sprite sheet\". This means that you need to pre-assemble the images into one image, load that single image and draw it on the canvas. </p>\n\n<p>That way:</p>\n\n<ul>\n<li>You only load one image, thus reducing your http requests to the server to one only.</li>\n<li>You draw to the canvas only once. No more loops, no more multiple <code>drawImage</code>.</li>\n</ul>\n\n<h1>Order in the court!</h1>\n\n<p>Loading images are async, thus the need for the event handler. This also means that the images will arrive in any order, and not necessarily in the order you called them down. In your case, the image at index 21 might come earlier than you'd expect, even before all others have loaded.</p>\n\n<p>I suggest you add an <code>onload</code> to each image and have it check if all images have been loaded before doing anything with them. A simple way to do this is to increment a counter and check if the counter value matches the expected number.</p>\n\n<p>When the count is equal to the expected length, run the code you want to run.</p>\n\n<h1>No aftershocks?</h1>\n\n<p>If the entire operation was just to load into the canvas the images, it's fine. </p>\n\n<p>However, you aren't loading them for no reason now are you? You are loading them for something. I suggest you wrap this operation in a function, have it accept your url array, and a callback that runs when it finishes loading and rendering all your images on the canvas.</p>\n\n<p>Something like:</p>\n\n<pre><code>loadImagesToCanvas([\n //urls\n],function(renderedCanvas){\n //run when done\n});\n</code></pre>\n\n<h1>Math.floor() is slow and long</h1>\n\n<p>In some browsers, <code>Math.floor()</code> is a slow way to trim off the decimal places of a number. Try bitwise OR (<code>|</code>) instead:</p>\n\n<pre><code>var wholeNumber = decimalNumber | 0;\n</code></pre>\n\n<h1>Unnecessary math</h1>\n\n<p>If some consecutive operations use some value resulting from some math operation, cache that value in a variable rather than doing the math again.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T15:39:47.380", "Id": "41586", "Score": "0", "body": "Wow thanks a lot for your thorough input! I can't believe I forgot about sprites. Thanks once again for all the different tips, really helpful!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T08:32:09.867", "Id": "26835", "ParentId": "26833", "Score": "4" } } ]
{ "AcceptedAnswerId": "26835", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T06:11:20.867", "Id": "26833", "Score": "2", "Tags": [ "javascript", "image", "html5" ], "Title": "Using a single for loop to load multiple images in a canvas" }
26833
<p>For a session implementation I needed a <em>property</em> that caches its getter (since it involves a database lookup) but still allows modifications (e.g. assigning a new user and storing that user's id in the session). To make this as comfortable as possibly I subclassed <code>property</code> and added the caching logic to the descriptor methods.</p> <p>While it works fine and I <em>think</em> I covered all important cases with my unittest I'd prefer if someone else looked over it, too, just in case I missed something.</p> <h1>The code</h1> <pre><code>def cached_writable_property(cache_attr, cache_on_set=True): class _cached_writable_property(property): def __get__(self, obj, objtype=None): if obj is not None and self.fget and hasattr(obj, cache_attr): return getattr(obj, cache_attr) value = property.__get__(self, obj, objtype) setattr(obj, cache_attr, value) return value def __set__(self, obj, value): property.__set__(self, obj, value) if cache_on_set: setattr(obj, cache_attr, value) else: try: delattr(obj, cache_attr) except AttributeError: pass def __delete__(self, obj): property.__delete__(self, obj) try: delattr(obj, cache_attr) except AttributeError: pass return _cached_writable_property </code></pre> <h1>The unittest</h1> <pre><code>if __name__ == '__main__': import unittest class CannotSet(Exception): pass class _Test(dict): def __init__(self, *args, **kw): dict.__init__(self, *args, **kw) self.log = [] @cached_writable_property('_a', True) def a(self): self.log.append('get a') return self['a'][0] @a.setter def a(self, val): self.log.append('set a') self['a'] = (val, 'xyz') @a.deleter def a(self): self.log.append('del a') del self['a'] @cached_writable_property('_b', False) def b(self): self.log.append('get b') return self['b'][0] @b.setter def b(self, val): self.log.append('set b') self['b'] = (val, 'lol') @cached_writable_property('_c') def c(self): self.log.append('get c') return self['c'][0] @c.setter def c(self, val): self.log.append('set c') raise CannotSet class TestCachedWritableProperty(unittest.TestCase): def test_cwp(self): _log = [] def _expect_log(obj, entry): if entry is not None: _log.append(entry) self.assertEqual(obj.log, _log) t = _Test(b=('initial-b',)) # Does not exist =&gt; error from getter self.assertRaises(KeyError, lambda: t.a) _expect_log(t, 'get a') # Exists but not cached =&gt; result from getter self.assertEquals(t.b, 'initial-b') _expect_log(t, 'get b') # Exists and cached =&gt; result from cache self.assertEquals(t.b, 'initial-b') _expect_log(t, None) # Modify, cache on set t.a = 'new-a' _expect_log(t, 'set a') # Read, from cache self.assertEquals(t.a, 'new-a') _expect_log(t, None) # Read, from cache again self.assertEquals(t.a, 'new-a') _expect_log(t, None) # Delete, should be removed from cache, too del t.a _expect_log(t, 'del a') self.assertRaises(KeyError, lambda: t.a) self.assertRaises(KeyError, lambda: t['a']) _expect_log(t, 'get a') # Modify, do not cache on set t.b = 'new-b' _expect_log(t, 'set b') # Read, not from cache self.assertEquals(t.b, 'new-b') _expect_log(t, 'get b') # Read, from cache self.assertEquals(t.b, 'new-b') _expect_log(t, None) # Test failing setters self.assertRaises(KeyError, lambda: t.c) _expect_log(t, 'get c') self.assertRaises(CannotSet, lambda: setattr(t, 'c', 'nope')) _expect_log(t, 'set c') t['c'] = ('initial-c',) self.assertEquals(t.c, 'initial-c') _expect_log(t, 'get c') self.assertRaises(CannotSet, lambda: setattr(t, 'c', 'nope')) _expect_log(t, 'set c') self.assertEquals(t.c, 'initial-c') _expect_log(t, None) unittest.main() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-12T05:32:15.703", "Id": "46858", "Score": "0", "body": "Not sure if this'll be used in a multi-threaded context, but if so you may want to a) lock around the cache accesses and b) invalidate the cache before setting/deleting, instead of before." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-17T13:25:50.203", "Id": "50065", "Score": "1", "body": "Django has an implementation of a cached property here: https://docs.djangoproject.com/en/dev/ref/utils/#django.utils.functional.cached_property. You can set it and clear it by deleting the attribute on the object. I don't think it has an dependencies in Django, so you may be able to just take the code and use it in any python project." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-17T12:30:46.460", "Id": "62270", "Score": "0", "body": "Django's `cached_property` modifies the instance to *replace* the property with the cached value ([see the source](https://github.com/django/django/blob/4cfe6ba6a3d16a16f0561f2f3c5b56d117f8a60d/django/utils/functional.py#L43)). So it can only ever be used once, whereas the cached property in the OP can be deleted, which will cause it to be re-computed on the next lookup." } ]
[ { "body": "<p>If you can afford to make your class <code>hash</code>able, and you read more often than you need to update the values inside (because an update to any property will invalidate the cache for all the other ones, and for this reason I set the <code>maxsize</code> to 1), it's probably much simpler to just combine <code>property</code> and <code>functools.lru_cache</code></p>\n\n<pre><code>from functools import lru_cache\n\nif __name__ == '__main__':\n import unittest\n\n class CannotSet(Exception):\n pass\n\n class _Test(dict):\n def __init__(self, *args, **kw):\n dict.__init__(self, *args, **kw)\n self.log = []\n\n def __hash__(self):\n return hash(tuple(sorted(self.items())))\n\n @property\n @lru_cache(1)\n def a(self):\n self.log.append('get a')\n return self['a'][0]\n @a.setter\n def a(self, val):\n self.log.append('set a')\n self['a'] = (val, 'xyz')\n @a.deleter\n def a(self):\n self.log.append('del a')\n del self['a']\n\n\n @property\n @lru_cache(1)\n def b(self):\n self.log.append('get b')\n return self['b'][0]\n @b.setter\n def b(self, val):\n self.log.append('set b')\n self['b'] = (val, 'lol')\n\n @property\n @lru_cache(1)\n def c(self):\n self.log.append('get c')\n return self['c'][0]\n @c.setter\n def c(self, val):\n self.log.append('set c')\n raise CannotSet\n\n\n class TestCachedWritableProperty(unittest.TestCase):\n def test_cwp(self):\n _log = []\n def _expect_log(obj, entry):\n if entry is not None:\n _log.append(entry)\n self.assertEqual(obj.log, _log)\n\n t = _Test(b=('initial-b',))\n # Does not exist =&gt; error from getter\n self.assertRaises(KeyError, lambda: t.a)\n _expect_log(t, 'get a')\n # Exists but not cached =&gt; result from getter\n self.assertEquals(t.b, 'initial-b')\n _expect_log(t, 'get b')\n # Exists and cached =&gt; result from cache\n self.assertEquals(t.b, 'initial-b')\n _expect_log(t, None)\n\n # Modify, cache on set\n t.a = 'new-a'\n _expect_log(t, 'set a')\n # Read\n self.assertEquals(t.a, 'new-a')\n _expect_log(t, 'get a')\n # Read, from cache again\n self.assertEquals(t.a, 'new-a')\n _expect_log(t, None)\n\n # Delete, should be removed from cache, too\n del t.a\n _expect_log(t, 'del a')\n self.assertRaises(KeyError, lambda: t.a)\n self.assertRaises(KeyError, lambda: t['a'])\n _expect_log(t, 'get a')\n\n # Modify, do not cache on set\n t.b = 'new-b'\n _expect_log(t, 'set b')\n # Read, not from cache\n self.assertEquals(t.b, 'new-b')\n _expect_log(t, 'get b')\n # Read, from cache\n self.assertEquals(t.b, 'new-b')\n _expect_log(t, None)\n\n # Test failing setters\n self.assertRaises(KeyError, lambda: t.c)\n _expect_log(t, 'get c')\n self.assertRaises(CannotSet, lambda: setattr(t, 'c', 'nope'))\n _expect_log(t, 'set c')\n t['c'] = ('initial-c',)\n self.assertEquals(t.c, 'initial-c')\n _expect_log(t, 'get c')\n self.assertRaises(CannotSet, lambda: setattr(t, 'c', 'nope'))\n _expect_log(t, 'set c')\n self.assertEquals(t.c, 'initial-c')\n _expect_log(t, None)\n\n\n unittest.main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-13T00:33:59.383", "Id": "44214", "ParentId": "26836", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T09:44:26.980", "Id": "26836", "Score": "8", "Tags": [ "python", "lookup" ], "Title": "Python property() implementation that caches getter while still allowing a setter" }
26836
<p>I have this working code that selects which method to call based on values in the parameter:</p> <pre><code>@Override public Iterator&lt;DBObject&gt; __find(DBObject ref, DBObject fields, int numToSkip , int batchSize , int limit, int options){ Preconditions.checkNotNull(ref, "Reference object can't be null"); LOG.info("Reference object=" + ref); DBObject query = (DBObject) ref.get("$query"); DBObject orderby = (DBObject) ref.get("$orderby"); // Remove special fields dataCleansing(ref); if (query != null){ LOG.info("Query object=" + query); if (orderby != null){ LOG.info("Sort object=" + orderby); Iterator&lt;DBObject&gt; it = _store.getSortedObjectsLike(query, orderby); return it; } else { Iterator&lt;DBObject&gt; it = _store.getObjectsLike(query); return it; } } else { if (orderby != null){ LOG.info("Sort object=" + orderby); Iterator&lt;DBObject&gt; it = _store.getSortedObjects(orderby); return it; } else { // query and ordeby are both null Iterator&lt;DBObject&gt; it = _store.getObjects(); return it; } } } </code></pre> <p>I really think there's some way to better address this selection of functions than just plain if-else statement. </p> <p>As conditions might grow and more objects passed for condition checking. Is there an "elegant" way to deal with this kind of "choose which method to execute based on parameters values and existence" ? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T21:02:42.987", "Id": "41608", "Score": "0", "body": "The `it` variable you declare all along, in each branch, doesn't really have a use... What is more, there is no need to `else` if you `return`." } ]
[ { "body": "<p>One possibility is to create a method that accepts all possible parameters, and have that method gracefully handle <code>null</code> values, or use the <a href=\"http://en.wikipedia.org/wiki/Null_Object_pattern\" rel=\"nofollow\"><em>Null Object</em> pattern</a> for those parameters. <code>getSortedObjectsLike(query, orderby);</code> seems like a good candidate, if you could pass nulls for <code>query</code> and <code>orderby</code> or <code>new EmptyQuery()</code> and <code>new NoOrderBy()</code>.</p>\n\n<ul>\n<li>pro : no need for method selection, simply evaluate whether a parameter is available or not, and pass null or <em>Null Object</em> if unavailable.</li>\n<li>pro : simplified API</li>\n<li>con : adding parameters in the future will involve increasing the complexity of the one method that handles all parameters (can probably be mitigated with some refactoring)</li>\n<li>con : implementation of the method that handles all parameters may degrade into the kind of method selection we try to avoid here.</li>\n</ul>\n\n<hr>\n\n<p>Alternatively you could use introspection, and select a method based on the available parameters.</p>\n\n<ul>\n<li>pro : adding future parameters (if done judiciously) will not affect the method selection implementation</li>\n<li>con : every added parameter will double the number of methods needed on the API (for every existing one, we'll need one that also has the new parameter)</li>\n<li>con : harder to debug</li>\n<li>con : hides dependencies</li>\n<li>con : query and orderBy are currently the same type, introspection can't tell them apart</li>\n</ul>\n\n<hr>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T10:53:19.013", "Id": "41660", "Score": "0", "body": "I think there isn't much to discuss here. The complexity is on the wrong side of the ``getObjects`` call. Moving all this to a single method will make usage of this method much simpler everywhere else. What happens inside the method can more or less look like the above - a dispatch to different methods - given that is needed at all (i suspect that it isn't)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T11:09:05.280", "Id": "41661", "Score": "0", "body": "@Michael Zedeler I agree." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T08:02:16.570", "Id": "26869", "ParentId": "26837", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T09:49:26.770", "Id": "26837", "Score": "4", "Tags": [ "java" ], "Title": "Method Selection Engine" }
26837
<p>I was working on a sorting algorithm for my linked list implementation and wanted to get other people's input/comments/critique. What do you think of it in all aspects, including style?</p> <p>I was told that it is preferred to use a bool type for the <code>changeFlag</code> instead of using an int as it makes it more readable. Thoughts?</p> <pre><code>void LinkedList::sort() { if (head != 0) { Node* current = head; Node* prev = 0; Node* tempNode = 0; bool changeFlag = false; for (int i = 0; i &lt; length; i++) { while (current-&gt;next != 0) { tempNode = current-&gt;next; if (current-&gt;value &gt; tempNode-&gt;value) { changeFlag = true; current-&gt;next = tempNode-&gt;next; tempNode-&gt;next = current; if (prev != 0) prev-&gt;next = tempNode; prev = tempNode; if (head == current) head = tempNode; if (current-&gt;next == 0) end = current; } else { prev = current; current = current-&gt;next; } } if (changeFlag == false) break; else { prev = 0; current = head; changeFlag = false; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T20:51:06.310", "Id": "41640", "Score": "0", "body": "If you asked me, sorting a linked list is rather pointless. If you needed to sort a list, you wouldn't use a linked list. There are other list types better suited for sorting and a linked list isn't one of them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T02:11:52.627", "Id": "41648", "Score": "0", "body": "It's just to teach myself about data structures and how they work." } ]
[ { "body": "<p>Giant problem that I see: your for loop is completely redundant. You go through the entire list in the inner while loop and then just continue checking the condition N times before you finish the outer for loop.</p>\n\n<p>I think that you're taking an approach which is overly complicated for the given scenario. Because you're using a linked list specifically, I'd highly suggest using a merge sort, because you have the ability to easily separate the individual parts of the list. This would not only reduce the size of your code dramatically but it would also make it much more readable.</p>\n\n<p>For you specifically, I'd suggest commenting your code more. And I mean, commenting the <em>purpose</em> of code, not what it does (<code>// loop through list</code> is unhelpful). If you think that they're unnecessary, do them anyway and then strip them once you're satisfied with the algorithm. That way, while you're writing code, you'll be sure that you know what different parts do (like this redundant for loop).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T01:36:30.687", "Id": "41646", "Score": "1", "body": "I don't see how you think the for loop is redundant....???" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T04:55:23.473", "Id": "41651", "Score": "0", "body": "It's redundant because linked lists are traversed until NULL is encountered (you already have that in your while loop)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T10:50:48.583", "Id": "41659", "Score": "0", "body": "That should look a little better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T17:37:28.200", "Id": "41667", "Score": "0", "body": "A doubly nested loop is required for bubble sort. Each iteration of the inner loop moves one item to the top of the list. Thus you need to use the outer loop n times to bubble all the values into the correct order." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T17:53:24.853", "Id": "41669", "Score": "0", "body": "Oh yeah, I forgot about the bubble sort; I was thinking in general." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T23:54:31.290", "Id": "41692", "Score": "0", "body": "When I designed it I was thinking that worst case scenario was n^2, which is why the for loop iterated as many times as the length of the loop. I do appreciate your input though, it made me take another look at it and I realized that it was better to use a do...while loop, which in turn eliminated some of the code near the bottom of the for loop and makes it more readable!!!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T20:40:28.773", "Id": "26878", "ParentId": "26839", "Score": "2" } }, { "body": "<p>One of the problems of this code is that it implements a bubble sort, which is very inefficient ( O(n^2) running time) for large lists. As @AlexCharron suggests, use a merge sort, or alternatively, copy the list into a vector, sort that, and rebuild the list.</p>\n\n<p>Another problem is that your naming convention does not distinguish between locals (e.g. <code>prev</code>) and data members (e.g. <code>head</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T01:39:14.700", "Id": "41647", "Score": "0", "body": "What kind of naming scheme do you recommend?? I know the bubble sort isn't the most efficient, but I was doing this just to teach myself how data structures work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T15:01:25.983", "Id": "41663", "Score": "0", "body": "Three naming schemes I am familiar with are (1) suffix member variables with an underscore (`head_`); used at Google, for instance. (2) prefix member variables with `m_` (`m_Head`); also widely used, I believe. (3) prefix member variables with an f (`fHead`); used at Apple, for instance. Any of these is preferable over no differentiation at all, in my opinion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T17:33:53.327", "Id": "41666", "Score": "1", "body": "Bubble sort is also very good for short list. In the best case it is also O(n) (if the list is already sorted)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T17:53:54.757", "Id": "41670", "Score": "0", "body": "PS. Totally disagree with using prefix/suffix to distinguish members from local variables. If you need to do this then you have already made bad choices in the names of you members. To me adding the prefix/suffix is just a code smell that there are other fundamental problems. I do agree that you (the original poster) has chosen some bad names that makes it confusing. The best way is to choose variable names that make it more obvious what you are doing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T23:59:14.563", "Id": "41694", "Score": "0", "body": "Which variable names would you advocate changing Loki??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T00:26:54.097", "Id": "41695", "Score": "0", "body": "@LokiAstari can you give any example of a substantially sized C++ code base that does *not* distinguish local variables from members through some kind of naming convention? Your advice not to do that strikes me as rather bizarre." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T19:59:17.160", "Id": "41767", "Score": "0", "body": "@microtherion: Your advice was the standard about a decade ago. Nowadays not so much. I don't have any open source examples but all the company code I work with does not need it (mainly because we have good code review processes to start with). Requiring a prefix (to tell the variables apart) is a smell that there is something more bizarre wrong with your code. If you are just doing it for doing it sakes then your code could be fine, but then why apply such a bizarre rule in the first place." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T20:44:21.187", "Id": "41768", "Score": "0", "body": "`wc -l 'find . -name \"*.cpp\" -or -name \"*.h\"'` outputs `6264939 total`. Note Replaced back-quote with normal quote to make highlighting work in comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T21:27:29.893", "Id": "41771", "Score": "0", "body": "I’ll take your word that your company’s code base does not use prefixes/suffixes (and it would certainly qualify as substantial in my book), but can you expand on what practices you’re using *instead* to make it evident what names are data members, locals, or globals, respectively? “code review” is nice, but absent any standards in this area, what does the review flag? As an example, what names would you use for the 5 names in the above code?" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T00:21:45.170", "Id": "26882", "ParentId": "26839", "Score": "0" } }, { "body": "<p>What I would take away from this is how the standard library does this.</p>\n\n<p>It disassociates sorting algorithms from specific container types (by using iterators). Then you can write the sorting algorithm in a way that is independent of the actual container type.</p>\n\n<p>What I dislike about your code is that when you move elements you basically re-order the list (you actually move the nodes). This is a complex operation taking many checks. Personally I would leave the actual nodes where they are and move the values between nodes. std::swap() can be used for this.</p>\n\n<p>This:</p>\n\n<pre><code> current-&gt;next = tempNode-&gt;next;\n tempNode-&gt;next = current;\n if (prev != 0)\n prev-&gt;next = tempNode;\n prev = tempNode;\n if (head == current)\n head = tempNode;\n if (current-&gt;next == 0)\n end = current;\n</code></pre>\n\n<p>Can be replaced with:</p>\n\n<pre><code> swap(current-&gt;value, tempNode-&gt;value);\n</code></pre>\n\n<p>With C++ new move semantics this is now very efficient.</p>\n\n<blockquote>\n <p>EDIT: I was told that it is preferred to use a bool type for the changeFlag instead of using an int as it makes it more readable?? Thoughts?</p>\n</blockquote>\n\n<p>Yes. Use the correct type. <code>bool</code> is a truth value it imparts meaning to the person reading the code. Humans need that extra meaning to help them understand the code better.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T23:57:41.213", "Id": "41693", "Score": "0", "body": "Thank you very much Loki!!! Like you mentioned above, the STL does this for us. I was doing it just as a learning experience. I appreciate your input!!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-05T01:06:12.893", "Id": "41870", "Score": "0", "body": "@h4ck.b0x7: Sure. But as a learning exercise splitting the algorithm from the container would definitely be a worth trying." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T17:47:18.607", "Id": "26895", "ParentId": "26839", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T10:26:16.150", "Id": "26839", "Score": "5", "Tags": [ "c++", "sorting", "linked-list" ], "Title": "Linked List Sorting Algorithm" }
26839
<p>The general idea of this function is to load a different sound file depending on current time position of the video. I have the following information about audio files:</p> <pre><code>var samples: [ ['00:00:05', 'audio/1.mp3'], ['00:01:00', 'audio/2.mp3'] ] </code></pre> <p>The first element contains the end time for specific audio sample, and the second is the sample. I think we don't need the start time, because the following condition should return a good result:</p> <pre><code>if( video.currentTime &lt;= endTime ) { ... } </code></pre> <p>Anyway, here is the code of function I'm using to check which audio file to play (it's executed when the video is paused):</p> <pre><code>var APP.playAudio = function() { var pAudio = samples; // the array above for(var i = 0; i &lt; pAudio.length; i++ ) { if( video.currentTime &lt; hms_to_s(pAudio[i][0]) ) { pCurrentAudio = pAudio[i][1]; break; } } } </code></pre> <p>I'm looking for more tricky and clever way to achieve this. As you see, now we iterate over the <code>pAudio</code> array each time the video is paused.</p>
[]
[ { "body": "<p>You want to play a certain audio at a certain time? Well, you're in luck. I recently did this in a demo. It wasn't playing audio with video though. It was triggering animations at certain points of the audio, but it should be the same idea.</p>\n\n<p><code>&lt;audio&gt;</code> and <code>&lt;video&gt;</code> elements are <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement\" rel=\"nofollow\"><code>HTMLMediaElement</code></a>s and have <a href=\"https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Events/Media_events?redirectlocale=en-US&amp;redirectslug=DOM/Media_events\" rel=\"nofollow\">media events</a>.</p>\n\n<ul>\n<li><p>If you want to play your mapped audio in real time, there is the <code>timeupdate</code> event which is triggered when the current time of the element has changed.</p></li>\n<li><p>If you want to play it during pause, then there is the <code>paused</code> event.</p></li>\n</ul>\n\n<p>You can use these events to check the <code>currentTime</code> of your element, which in this case is your video. <code>currentTime</code> is in seconds. If you want to stick to your <code>hh:mm:ss</code> format, you'd need your own converter. </p>\n\n<p>Instead of urls, you should have preloaded audio elements there so that they will play instantly when we need them.</p>\n\n<p>Anyways, here's a sample structure with seconds and audio elements</p>\n\n<pre><code>var samples = [\n [5,HTMLAudioElement],\n [10,HTMLAudioElement],\n [15,HTMLAudioElement],\n ...\n];\n</code></pre>\n\n<p>Then, hook to the <code>timeupdate</code> event of the video, check the current time, and compare with the indicated item in the array. You can use a counter to indicate your current position.</p>\n\n<pre><code>var i = 0\n//get first audio as current audio and play\nvar currentAudio = samples[i][1].play();\n\nvideo.addEventListener('timeupdate',function(){\n\n //if video time is greater than current audio end time\n if(this.currentTime &gt; samples[i][0]){\n if(currentAudio) currentAudio.pause(); //pause existing audio (maybe do a \"seek to zero\" to reset)\n currentAudio = samples[++i][1]; //reference next audio as current\n currentAudio.play(); //play the current audio\n }\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T16:37:14.230", "Id": "26849", "ParentId": "26844", "Score": "3" } } ]
{ "AcceptedAnswerId": "26849", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T14:17:53.027", "Id": "26844", "Score": "4", "Tags": [ "javascript", "html5", "audio" ], "Title": "Playing different audio files based on video keyframe" }
26844
<p>I would like to see if the working code below can be written more elegantly. I am assuming there is a way to parse out the "r" and "h" to condense it down into a function. Any help is much appreciated for learning purposes. There are no parent/sibling relationships in the ID's.</p> <pre><code> $('#r1_1').hoverIntent(function(){ $('#h1_1').toggleClass('vis'); }); $('#r1_2').hoverIntent(function(){ $('#h1_2').toggleClass('vis'); }); $('#r1_3').hoverIntent(function(){ $('#h1_3').toggleClass('vis'); }); $('#r1_4').hoverIntent(function(){ $('#h1_4').toggleClass('vis'); }); $('#r1_5').hoverIntent(function(){ $('#h1_5').toggleClass('vis'); }); $('#r2_1').hoverIntent(function(){ $('#h2_1').toggleClass('vis'); }); $('#r2_2').hoverIntent(function(){ $('#h2_2').toggleClass('vis'); }); $('#r2_3').hoverIntent(function(){ $('#h2_3').toggleClass('vis'); }); $('#r2_4').hoverIntent(function(){ $('#h2_4').toggleClass('vis'); }); $('#r2_5').hoverIntent(function(){ $('#h2_5').toggleClass('vis'); }); $('#r3_1').hoverIntent(function(){ $('#h3_1').toggleClass('vis'); }); $('#r3_2').hoverIntent(function(){ $('#h3_2').toggleClass('vis'); }); $('#r3_3').hoverIntent(function(){ $('#h3_3').toggleClass('vis'); }); $('#r3_4').hoverIntent(function(){ $('#h3_4').toggleClass('vis'); }); </code></pre>
[]
[ { "body": "<p>A basic function for running it could be</p>\n\n<pre><code>function hi(n1, n2) {\n var r = '#r'+n1+'_'+n2;\n var h = '#h'+n1+'_'+n2;\n $(r).hoverIntent(function() {\n $(h).toggleClass('vis');\n });\n}\n</code></pre>\n\n<p>However, it's possible to trim this down more by creating an array, and storing both <code>r</code>, and <code>h</code> in it. The array would look something like this: <code>var arr = [\"#r\"+n1+\"_\"+n2, \"#h\"+n1+\"_\"+n2];</code>, and then instead of inserting <code>r</code> and <code>h</code> into the <code>hoverIntent</code> function, you would use <code>arr[0]</code> and <code>arr[1]</code>. If they are all meant to be run at once, you could run a nested <code>for</code> loop so that <code>r1_ - r3_</code> would be created, and then the secondary numbers would be populated.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T16:29:34.753", "Id": "41589", "Score": "0", "body": "Thank you Andrew - In the above basic function, how do I grab the unique values of n1 and n2?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T16:31:48.387", "Id": "41590", "Score": "0", "body": "@user2440204 n1 and n2 would be entered in as numbers. So for your first example, you would execute it as `hi(1, 1)`. If you need those numbers back, you could either add them as index two and three in the array, or you could return a different array with those two numbers in it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T16:49:10.183", "Id": "41593", "Score": "0", "body": "Thanks again. I am having difficulty coding what you are describing, so I guess this goes beyond my skill level right now. I will do some more studying and research." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T16:22:30.680", "Id": "26848", "ParentId": "26847", "Score": "1" } }, { "body": "<p>what about this? </p>\n\n<pre><code>$('.hover_intent').hoverIntent(function(){\n var id = $(this).attr( 'id' ); \n var selector = '#' + id.replace( 'r', 'h' );\n $( selector ).toggleClass('vis');\n});\n</code></pre>\n\n<p>The only inconvenients i see are : </p>\n\n<ul>\n<li>you need to add a <code>hover_intent</code> css class or your <code>rx_y</code> elements. This can be avoided with a regex selector like <code>$('[id^=r]')</code> (which means: <em>select all elements whose id starts with an 'r'</em>), but you should then use a more verbose id to avoid selecting everything that starts with an 'r'...</li>\n<li>selecting <code>$(this)</code> every time the event occurs can be bad performance-wise, especially if you have a lot of elements or if the event occurs a lot of times per second </li>\n</ul>\n\n<p>Another option is to use a data attribute on your element :</p>\n\n<pre><code>&lt;span class=\"hover_intent\" data-target=\"#h1_1\"&gt;Foo&lt;/a&gt;\n&lt;script type=\"text/javascript\"&gt;\n $('.hover_intent').hoverIntent( function(){\n $( $(this).data('target') ).toggleClass('vis') );\n });\n&lt;/script&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T16:50:17.330", "Id": "26851", "ParentId": "26847", "Score": "1" } }, { "body": "<p>Instead of using ids #r, let's include in the element the attribute data-something to differentiate the elements that must have the behavior setted by the function. Using a div, for instance:</p>\n\n<pre><code>&lt;div data-something=\"1_1\"&gt;&lt;/div&gt;\n&lt;div data-something=\"2_2\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>We won't need the ids with #r anymore. Considering that you already have the elements #h* we just need to put the id number inside data-something of the corresponding element, so that the function can use it:</p>\n\n<pre><code>$(\"div[data-something]\").hoverIntent(function() {\n var idNumber = $(this).data(\"something\");\n $('#h' + idNumber).toggleClass('vis');\n});\n</code></pre>\n\n<p>Now, you just need to use the data-something attribute.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T16:57:59.657", "Id": "41595", "Score": "0", "body": "ha ! i see we had the same idea at the same time :D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T14:37:27.143", "Id": "41620", "Score": "0", "body": "Thanks very much! Worked beautifully. And I learned a great deal from it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T16:54:45.613", "Id": "26852", "ParentId": "26847", "Score": "2" } } ]
{ "AcceptedAnswerId": "26852", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T15:43:03.933", "Id": "26847", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "JQuery hover with multiple ID's" }
26847
<p>I'm building a website that is used to search our system. The users can search on a lot of critera at once. As I try to do this though, I can't figure out how to simplify this horrible action.</p> <pre><code>public ActionResult Search(SearchViewModel model) { Expression&lt;Func&lt;Parcel, bool&gt;&gt; filterexpression = PredicateBuilder.True&lt;Parcel&gt;(); this.TryUpdateModel(model); IQueryable&lt;Parcel&gt; query = service.GetAllParcels().AsQueryable(); if (model == null) { model = new SearchViewModel(); } // TODO: add conditions to only include expressions that have values if (model.ParcelSearch.Strap != null) { filterexpression = filterexpression.And(service.StrapStartsWith(model.ParcelSearch.Strap.AsStrap())); } if (model.ParcelSearch.OwnerKeywords != null) { filterexpression = filterexpression.And(service.ContainsInOwnerName(model.ParcelSearch.OwnerKeywords)); } if (model.ParcelSearch.AddressKeywords != null) { filterexpression = filterexpression.And(service.ContainsInAddress(model.ParcelSearch.AddressKeywords)); } if (model.ParcelSearch.ZipCode != null) { filterexpression = filterexpression.And(service.LocatedWithinZipCode(model.ParcelSearch.ZipCode)); } if (model.ParcelSearch.Subdivision != null) { filterexpression = filterexpression.And(service.IsInSubdivision(model.ParcelSearch.Subdivision)); } // TODO: add boolean conditions. no need to check these for nulls ATM. filterexpression = filterexpression.Expand() .And(service.HasDock(model.PropertyFeatureSearch.Dock)) .And(service.HasPool(model.PropertyFeatureSearch.Pool)) .And(service.HasSeaWall(model.PropertyFeatureSearch.SeaWall)) .And(service.HasTennisCourt(model.PropertyFeatureSearch.Tennis)) .And(service.IsVacant(model.PropertyFeatureSearch.VacantLand)) .And(service.IsNew(model.PropertyFeatureSearch.StatusNew)) .Expand(); if (model.SalesSearch.SalesFrom != null &amp;&amp; model.SalesSearch.SalesTo != null) { filterexpression = filterexpression.And( service.SalesInRange(model.SalesSearch.SalesFrom.Value, model.SalesSearch.SalesTo.Value)); } if (model.SalesSearch.SaleAmountFrom != null &amp;&amp; model.SalesSearch.SaleAmountTo != null) { filterexpression = filterexpression.And( service.SalesAmountInRange(model.SalesSearch.SaleAmountFrom, model.SalesSearch.SaleAmountTo)) .Expand(); } if (model.SalesSearch.InstrumentNumber != null) { filterexpression = filterexpression.And(service.SalesWithInstrumentNumber(model.SalesSearch.InstrumentNumber)); } if (model.SalesSearch.GrantorSeller != null) { filterexpression = filterexpression.And(service.GrantorSellerContains(model.SalesSearch.GrantorSeller)); } if (model.ParcelSearch.UseCode != null) { filterexpression = filterexpression.And(service.UseCodeEquals(model.ParcelSearch.UseCode)); } // TODO:CREATE SEARCHING HERE var timer = new Stopwatch(); timer.Start(); query = query.Where(filterexpression.Expand()); this.TempData["filter"] = filterexpression; this.ViewData["count"] = query.Count(); IQueryable&lt;Parcel&gt; output; if (model.SortOption == "strap") { output = query.OrderBy(x =&gt; x.STRAP).Take(500); } else if (model.SortOption == "PropertyUse") { output = query.OrderBy(x =&gt; x.PROPERTY_USE).Take(500); } else { output = query.OrderByDescending(x =&gt; x.LastUpdated).Take(500); } int page = model.Page ?? 1; if ((int)this.ViewData["count"] &lt; (page + 1) * 10) { page = 1; } model.SearchResults = output.AsPagination(page, 10); timer.Stop(); Debug.Assert(timer.Elapsed.TotalSeconds.CompareTo(10) &lt; 0, "Query exceeded a reasonable amount of time"); Debug.Print(timer.Elapsed.TotalSeconds.ToString(CultureInfo.InvariantCulture)); ViewData["executionTime"] = timer.Elapsed.TotalSeconds.ToString(CultureInfo.InvariantCulture); if (model.UseAdvancedSearch) { return this.View("AdvancedSearch", model); } return this.View(model); } </code></pre> <h1>Update - What a difference so far.</h1> <pre><code> public ActionResult Search(SearchViewModel model) { if (model == null) { model = new SearchViewModel(); } this.TryUpdateModel(model); if (this.TryValidateModel(model)) { //model validated. Go ahead and apply filter. this.ApplyCriteriaFilter(model); //figure out the count } else { //model didn't validate so do something. } IQueryable&lt;Parcel&gt; query = service.GetAllParcels().AsQueryable().Where(this.filterexpression); // TODO:CREATE SEARCHING HERE var timer = Stopwatch.StartNew(); this.ViewData["count"] = query.Count(); query = this.Sort(query, model.SortOption); //refactor this guy int page = model.Page ?? 1; if ((int)this.ViewData["count"] &lt; (page + 1) * 10) { page = 1; } model.SearchResults = query.AsPagination(page, 10); timer.Stop(); Debug.Assert(timer.Elapsed.TotalSeconds &lt; 10, "Query exceeded a reasonable amount of time"); Debug.Print(timer.Elapsed.TotalSeconds.ToString(CultureInfo.InvariantCulture)); this.ViewData["executionTime"] = timer.Elapsed.TotalSeconds.ToString(CultureInfo.InvariantCulture); if (model.UseAdvancedSearch) { return this.View("AdvancedSearch", model); } return this.View(model); } </code></pre>
[]
[ { "body": "<p>I imagine you want to get rid of repetitive <code>if/And</code> blocks. To do that, you may start by generalizing the following pattern (note: I'm using <code>object</code> since you haven't specified the precise types you use; in your case, <code>object</code> will be replaced by something more specific).</p>\n\n<pre><code>var includeExpression = new Action&lt;Func&lt;bool&gt;, object&gt;(\n (predicate, obj) =&gt;\n {\n if (predicate)\n {\n filterexpression = filterexpression.And(obj);\n }\n });\n</code></pre>\n\n<p>This makes it possible to rewrite all those repetitive blocks in a more compact way:</p>\n\n<pre><code>includeExpression(\n model.ParcelSearch.Strap != null,\n service.StrapStartsWith(model.ParcelSearch.Strap.AsStrap()));\n</code></pre>\n\n<p>You can push it a bit more for the first five blocks, by creating an additional function, based on the first one:</p>\n\n<pre><code>var includeIfNotNull = new Action&lt;object, Func&lt;Service, ParcelSearch, object&gt;&gt;(\n (eval, transform) =&gt;\n {\n includeExpression(eval != null, transform(service, model.ParcelSearch)));\n });\n</code></pre>\n\n<p>Now, you can simply write:</p>\n\n<pre><code>includeIfNotNull(model.ParcelSearch.Strap, (s, p) =&gt; s.StrapStartsWith(p.Strap.AsStrap()));\n</code></pre>\n\n<p>given that this last optimization would be available only for the first five blocks.</p>\n\n<p>An additional rewrite would be to make an <code>IEnumerable</code> containing the predicates and the objects, and call <code>includeIfNotNull</code> inside the first <code>foreach</code> for the first five entries, then <code>includeExpression</code> inside the second <code>foreach</code> for the last five ones. However, I'm not convinced that it would improve readability.</p>\n\n<p>A few other suggestions:</p>\n\n<ul>\n<li><p>Putting the first five and the last five blocks in separate methods would make things clearer, IMO. This also applies to the block:</p>\n\n<pre><code>filterexpression =\n filterexpression.Expand()\n .And(service.HasDock(model.PropertyFeatureSearch.Dock))\n .And(service.HasPool(model.PropertyFeatureSearch.Pool))\n .And(service.HasSeaWall(model.PropertyFeatureSearch.SeaWall))\n .And(service.HasTennisCourt(model.PropertyFeatureSearch.Tennis))\n .And(service.IsVacant(model.PropertyFeatureSearch.VacantLand))\n .And(service.IsNew(model.PropertyFeatureSearch.StatusNew))\n .Expand();\n</code></pre></li>\n<li><p>The code:</p>\n\n<pre><code>var timer = new Stopwatch();\ntimer.Start();\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>var timer = Stopwatch.StartNew();\n</code></pre></li>\n<li><p>What about extracting:</p>\n\n<pre><code>IQueryable&lt;Parcel&gt; output;\n\nif (model.SortOption == \"strap\")\n{\n output = query.OrderBy(x =&gt; x.STRAP).Take(500);\n}\nelse if (model.SortOption == \"PropertyUse\")\n{\n output = query.OrderBy(x =&gt; x.PROPERTY_USE).Take(500);\n}\nelse\n{\n output = query.OrderByDescending(x =&gt; x.LastUpdated).Take(500);\n}\n</code></pre>\n\n<p>into a separate method which returns <code>IQueryable&lt;Parcel&gt;</code>?</p></li>\n<li><p><code>timer.Elapsed.TotalSeconds.CompareTo(10) &lt; 0</code> is totally weird and error prone. You should have used <code>timer.Elapsed.TotalSeconds &gt; 10</code> instead.</p></li>\n<li><p>Put the measurement of time into a method which takes an <code>Action</code> as a parameter, like:</p>\n\n<pre><code>private static long MeasureTime(Action action)\n{\n var timer = Stopwatch.StartNew();\n action();\n return timer.Milliseconds();\n}\n</code></pre>\n\n<p>so instead of having:</p>\n\n<pre><code>var timer = Stopwatch.StartNew();\nRun();\nSome();\nCode();\ntimer.Stop();\nLogElapsedTime(timer.ElapsedMilliseconds);\n</code></pre>\n\n<p>you can simply write:</p>\n\n<pre><code>var elapsedMilliseconds = MyClass.MeasureTime(\n () =&gt;\n {\n Run();\n Some();\n Code();\n });\n\nLogElapsedTime(elapsedMilliseconds);\n</code></pre>\n\n<p>or instead of:</p>\n\n<pre><code>var timer = Stopwatch.StartNew();\nRunSomeCode();\ntimer.Stop();\nLogElapsedTime(timer.ElapsedMilliseconds);\n</code></pre>\n\n<p>you can have:</p>\n\n<pre><code>var elapsedMilliseconds = MyClass.MeasureTime(RunSomeCode);\nLogElapsedTime(elapsedMilliseconds);\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T19:29:20.920", "Id": "41601", "Score": "0", "body": "This is turning out great so far. Should maybe these two Actions you define be moved out to my service layer?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T19:38:44.793", "Id": "41602", "Score": "0", "body": "Also can you elaborate on `Put the measurement of time into a method which takes an Action as a parameter` Merci Beaucoup" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T11:23:01.940", "Id": "41662", "Score": "0", "body": "@MVCylon: done. See the last edit." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T17:22:00.403", "Id": "26853", "ParentId": "26850", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T16:46:43.690", "Id": "26850", "Score": "4", "Tags": [ "c#", "mvc" ], "Title": "How can I refactor my Controller Action to not be so complex?" }
26850
<p>Can someone explain me how this code works or if it is possible to be written in another way? I tried it with just ArrayList but cannot figure it out.</p> <pre><code>public static Set&lt;Set&lt;Integer&gt;&gt; combinations(List&lt;Integer&gt; groupSize, int k) { Set&lt;Set&lt;Integer&gt;&gt; allCombos = new HashSet&lt;Set&lt;Integer&gt;&gt; (); // base cases for recursion if (k == 0) { // There is only one combination of size 0, the empty team. allCombos.add(new HashSet&lt;Integer&gt;()); return allCombos; } if (k &gt; groupSize.size()) { // There can be no teams with size larger than the group size, // so return allCombos without putting any teams in it. return allCombos; } // Create a copy of the group with one item removed. List&lt;Integer&gt; groupWithoutX = new ArrayList&lt;Integer&gt; (groupSize); Integer x = groupWithoutX.remove(groupWithoutX.size()-1); Set&lt;Set&lt;Integer&gt;&gt; combosWithoutX = combinations(groupWithoutX, k); Set&lt;Set&lt;Integer&gt;&gt; combosWithX = combinations(groupWithoutX, k-1); for (Set&lt;Integer&gt; combo : combosWithX) { combo.add(x); } allCombos.addAll(combosWithoutX); allCombos.addAll(combosWithX); return allCombos; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T17:46:59.223", "Id": "41597", "Score": "0", "body": "What is the showTeam() method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T17:50:18.320", "Id": "41598", "Score": "0", "body": "My mistake! its combinations() not showTeam()" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T20:50:19.957", "Id": "41605", "Score": "0", "body": "You say \"how this code works\" -- is this some code you have to reuse? If you can use some external code and want to rely on it, I'd suggest using Guava's `Collections2`" } ]
[ { "body": "<p>Basically the algorithm returns all subsets of <code>groupSize</code> (which should really be renamed to <code>group</code>), that have <code>k</code> elements.</p>\n\n<p>The method works recursively. To do so it needs two things : establish primitive cases that end the recursion, and a way of formulating the problem in terms of itself, yet closer to the primitive form.</p>\n\n<p>This algorithm has two primitive cases : </p>\n\n<ol>\n<li>k == 0 : there is only one set that has 0 elements : the empty set.</li>\n<li>k > size of the group : there are no subsets that have more elements than the original set</li>\n</ol>\n\n<p>So there are two ways we can get to a primitive case : formulating it in terms of smaller sets (smaller group), or in terms of smaller subsets (smaller k)</p>\n\n<p>The formulation in terms of itself for this algorithm is : given an element x from the group, its combinations are : <code>all subsets that contain x, and all subsets that do not contain x</code>.</p>\n\n<ul>\n<li><em>All subsets that do not contain x</em>, is really all subsets of <em>the group without x</em> of size k (moves closer to second primitive case)</li>\n<li><em>All subsets that contain x</em>, is all subsets of <em>the group without x</em> of size k-1 with x added to those subsets. (moves closer to both primitive cases)</li>\n</ul>\n\n<p>The algorithm takes the last element of the group as x (but could just as well take another) : <code>Integer x = groupWithoutX.remove(groupWithoutX.size()-1);</code></p>\n\n<p>An example will make this clearer :</p>\n\n<p>for <code>groupSize</code> = <code>[1, 2, 3, 4, 5]</code> and k = 3 the output would be </p>\n\n<p><code>[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [2, 3, 4], [2, 3, 5], [1, 4, 5], [2, 4, 5], [3, 4, 5]]</code></p>\n\n<p>Picking the last element x = 5</p>\n\n<p>this is</p>\n\n<ul>\n<li>all subsets of <code>[1, 2, 3, 4]</code> of size k = 3 : i.e. <code>[[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]</code></li>\n<li>and all subsets of <code>[1, 2, 3, 4]</code> of size k = 2 and 5 added i.e. <code>[[1, 2, 5], [1, 3, 5], [1, 4, 5], [2, 3, 5], [2, 4, 5], [3, 4, 5]]</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T07:14:36.603", "Id": "26867", "ParentId": "26854", "Score": "2" } }, { "body": "<p>In addition to bowmores explanation I did some refactoring:</p>\n\n<pre><code>public static Set&lt;Set&lt;Integer&gt;&gt; getCombinationsFor(List&lt;Integer&gt; group, int subsetSize) {\n Set&lt;Set&lt;Integer&gt;&gt; resultingCombinations = new HashSet&lt;Set&lt;Integer&gt;&gt; ();\n int totalSize=group.size();\n if (subsetSize == 0) {\n emptySet(resultingCombinations);\n } else if (subsetSize &lt;= totalSize) {\n List&lt;Integer&gt; remainingElements = new ArrayList&lt;Integer&gt; (group);\n Integer X = popLast(remainingElements);\n\n Set&lt;Set&lt;Integer&gt;&gt; combinationsExclusiveX = getCombinationsFor(remainingElements, subsetSize);\n Set&lt;Set&lt;Integer&gt;&gt; combinationsInclusiveX = getCombinationsFor(remainingElements, subsetSize-1);\n for (Set&lt;Integer&gt; combination : combinationsInclusiveX) {\n combination.add(X);\n }\n resultingCombinations.addAll(combinationsExclusiveX);\n resultingCombinations.addAll(combinationsInclusiveX);\n }\n return resultingCombinations;\n}\n\nprivate static void emptySet(Set&lt;Set&lt;Integer&gt;&gt; resultingCombinations) {\n resultingCombinations.add(new HashSet&lt;Integer&gt;());\n}\n\nprivate static Integer popLast(List&lt;Integer&gt; elementsExclusiveX) {\n return elementsExclusiveX.remove(elementsExclusiveX.size()-1);\n}\n</code></pre>\n\n<p>Edit: Made some minor changes for readability</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T12:23:26.593", "Id": "41614", "Score": "0", "body": "Is there a way it can be done without <Set> ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T12:51:19.050", "Id": "41615", "Score": "0", "body": "You could substitute Set<Set<Integer>> with List<List<Integer>> if you adjust the methods." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T13:01:21.783", "Id": "41617", "Score": "0", "body": "can you give me an example?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T13:16:39.970", "Id": "41619", "Score": "0", "body": "In addition to my previous comment add: \"as long as you guarantee, that every element in the list is unique(the behaviour of set does that). To experiment, i reccomend to open up your favourite IDE and make a search&replace for \"Set<Set<Integer>>\" with \"List<List<Integer>>\"" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T08:12:01.490", "Id": "26870", "ParentId": "26854", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T17:40:51.027", "Id": "26854", "Score": "0", "Tags": [ "java", "recursion" ], "Title": "Recursive method to return a set of all combinations" }
26854
<p>It's a (simple) guesser for game where you need to find words of a given length only using given letters. I'd like to know if there's a more pythonic way to do things here.</p> <pre><code>#!/usr/bin/env python3 import sys if len(sys.argv) &lt; 3: sys.exit("Usage: " + sys.argv[0] + " letters number_of_letters [dictionnaryfile]") letters = sys.argv[1].upper() wordsize = int(sys.argv[2]) dictionnary_name = "dict.txt" if len(sys.argv) &lt; 4 else sys.argv[3] try: wordlist = open(dictionnary_name).read().split('\n') except FileNotFoundError: sys.exit("Couldn't find dictionnary file \"" + dictionnary_name + "\"") good = [] for w in wordlist: if len(w) == wordsize: up = w.upper() ok = True for c in up: if not c in letters: ok = False break if ok: good.append(w) print("Found " + str(len(good)) + " results:") print(good) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-06T10:08:26.137", "Id": "41988", "Score": "1", "body": "checkout [argparse](http://docs.python.org/3.3/library/argparse.html). It's awesome! Also, it's worth avoiding making the wordlist upfront and instead iterating over the file object so the whole dictionary isn't read into memory, and is read from line by line instead." } ]
[ { "body": "<p>The following code shows I would have done what you asked in Python 2.7. Other readers will tell you the ways in which it is a) not Pythonic and b) wrong.</p>\n\n<ul>\n<li><p>Start with a module comment describing what the code is intended to do. (This is available to the code as <code>__doc__</code>.)</p></li>\n<li><p>Use the various Python string delimiters to avoid escaping.</p></li>\n<li><p>Name variables consistently.</p></li>\n<li><p>strip() text strings read from a text file.</p></li>\n<li><p>Make letters a set to reflect its usage.</p></li>\n<li><p>Create the list of matching words with a list comprehension.</p></li>\n</ul>\n\n<p>Here is the code.</p>\n\n<pre><code>\"\"\"\n Find all the words in a reference dictionary with a specified number of letters\n that contain all the letters in a specified list of letters.\n\n The number of letters and the list of letters must be specified on the command line.\n\n The reference dictionary may be specified on the command line. If is not then \n dict.txt is used.\n\n The matching of letters is case-insensitive. \n\"\"\"\nimport sys\n\nif len(sys.argv) &lt; 3:\n print &gt;&gt; sys.stderr, __doc__\n sys.exit('Usage: %s letters number_of_letters [dictionary_file]' % sys.argv[0])\n\nletters = set(sys.argv[1].upper())\nwordsize = int(sys.argv[2])\ndictname = 'dict.txt' if len(sys.argv) &lt;= 3 else sys.argv[3]\n\ntry:\n wordlist = [w.strip() for w in open(dictname).readlines()]\nexcept IOError:\n sys.exit('''Couldn't find dictionary file \"%s\"''' % dictname)\n\nmatches = [w for w in wordlist \n if len(w) == wordsize \n and all(c in letters for c in w.upper())]\n\nprint 'Found %d results:' % len(matches) \nprint matches\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T15:53:56.093", "Id": "41623", "Score": "0", "body": "BTW, any reason to remove the shebang?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T04:34:46.660", "Id": "41650", "Score": "0", "body": "I forgot to add it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T00:19:59.580", "Id": "26864", "ParentId": "26857", "Score": "8" } }, { "body": "<p>One thing others have missed is the style of opening files. Use the <code>with</code> statement to have it automatically closed once it's no longer needed.</p>\n\n<pre><code>try:\n with open(dictname) as f:\n wordlist = [w.strip() for w in f]\nexcept IOError as e:\n sys.exit('Error opening file \"{0}\", errno {1}'.format(e.filename, e.errno))\n</code></pre>\n\n<p>You can't assume it's because the file doesn't exist. Other errors result in an <code>IOError</code> as well. You'd need to check its <code>errno</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-09T09:37:43.380", "Id": "27187", "ParentId": "26857", "Score": "2" } } ]
{ "AcceptedAnswerId": "26864", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T20:54:36.020", "Id": "26857", "Score": "5", "Tags": [ "python", "python-3.x" ], "Title": "Finding words of a given length only using given letters" }
26857
<p>I am working on a project that involves XML parsing, and for the job I am using xml.dom.minidom. During development I identified several patterns of processing that I refactored into discrete methods. The code shown in the snippet below shows my definition of an <code>Article</code> class that is instantiated during initial processing and is later passed to other classes for interpretation and output.</p> <p>Because I wanted to consolidate my refactored methods into a single definition — and because I felt they were best thought of as extended minidom methods, I removed them from the Interpretation/Output classes and then monkey-patched them into the minidom module so that they would be available to any class operating on the Article's document.</p> <pre><code># -*- coding: utf-8 -*- import openaccess_epub.utils.element_methods as element_methods import openaccess_epub.utils as utils from openaccess_epub.jpts.jptsmetadata import JPTSMetaData20, JPTSMetaData23, JPTSMetaData30 import os.path import sys import shutil import xml.dom.minidom as minidom import logging log = logging.getLogger('Article') #Monkey patching in some extended methods for xml.dom.minidom classes minidom.Node.removeSelf = element_methods.removeSelf minidom.Node.replaceSelfWith = element_methods.replaceSelfWith minidom.Node.elevateNode = element_methods.elevateNode minidom.Element.getChildrenByTagName = element_methods.getChildrenByTagName minidom.Element.removeAllAttributes = element_methods.removeAllAttributes minidom.Element.getAllAttributes = element_methods.getAllAttributes minidom.Element.getOptionalChild = element_methods.getOptionalChild class Article(object): """ A journal article; the top-level element (document element) of the Journal Publishing DTD, which contains all the metadata and content for the article. 3.0 Tagset: http://dtd.nlm.nih.gov/publishing/tag-library/3.0/n-3q20.html 2.0 Tagset: http://dtd.nlm.nih.gov/publishing/tag-library/2.0/n-9kc0.html 2.3 Tagset: http://dtd.nlm.nih.gov/publishing/tag-library/2.3/n-zxc2.html """ def __init__(self, xml_file): """ The __init__() method has to do the following specific jobs. It must parse the article using xml.dom.minidom. It must check the parsed article to detect its DTD and version; it must also detect the publisher using self.identify_publisher(). It is responsible for using this information to create an instance of a metadata class such as found in jptsmeta.py to serve as the article's metadata attribute. """ log.info('Parsing file - {0}'.format(xml_file)) doc = minidom.parse(xml_file) #Here we check the doctype for the DTD under which the article was #published. This affects how we will parse metadata and content. dtds = {'-//NLM//DTD Journal Publishing DTD v2.0 20040830//EN': '2.0', '-//NLM//DTD Journal Publishing DTD v2.3 20070202//EN': '2.3', '-//NLM//DTD Journal Publishing DTD v3.0 20080202//EN': '3.0'} try: self.dtd = dtds[doc.doctype.publicId] dtdStatus = 'Article published with Journal Publishing DTD v{0}' log.debug(dtdStatus.format(self.dtd)) except KeyError: print('The article\'s DOCTYPE declares an unsupported Journal \ Publishing DTD: \n{0}'.format(doc.doctype.publicId)) sys.exit() #Access the root tag of the document name self.root_tag = doc.documentElement #Determine the publisher self.publisher = self.identify_publisher() log.info('Publisher - {0}'.format(self.publisher)) #Create instance of article metadata if self.dtd == '2.0': self.metadata = JPTSMetaData20(doc, self.publisher) elif self.dtd == '2.3': self.metadata = JPTSMetaData23(doc, self.publisher) elif self.dtd == '3.0': self.metadata = JPTSMetaData30(doc, self.publisher) #The &lt;article&gt; tag has a handful of potential attributes, we can check #to make sure the mandated ones are valid self.attrs = {'article-type': None, 'dtd-version': None, 'xml:lang': None, 'xmlns:mml': None, 'xmlns:xlink': None, 'xmlns:xsi': None} for attr in self.attrs: #getAttribute() returns an empty string if the attribute DNE self.attrs[attr] = self.root_tag.getAttribute(attr) self.validate_attributes() # Log errors for invalid attribute values try: self.body = self.root_tag.getElementsByTagName('body')[0] except IndexError: self.body = None def identify_publisher(self): """ This method determines the publisher of the document based on an an internal declaration. For both JP-DTDv2.0 and JP-DTDv2.3, there are two important signifiers of publisher, &lt;publisher&gt; under &lt;journal-meta&gt; and &lt;article-id pub-id-type="doi"&gt; under &lt;article-meta&gt;. """ log.info('Determining Publisher') pubs = {'Frontiers Research Foundation': 'Frontiers', 'Public Library of Science': 'PLoS'} dois = {'10.3389': 'Frontiers', '10.1371': 'PLoS'} if self.dtd in ['2.0', '2.3']: #The publisher node will be the primary mode of identification publisher = self.root_tag.getElementsByTagName('publisher') pname = False if publisher: log.debug('Located publisher element') pname = publisher[0].getElementsByTagName('publisher-name')[0] pname = pname.firstChild.data try: return pubs[pname] except KeyError: log.debug('Strange publisher name - {0}'.format(pname)) log.debug('Falling back to article-id DOI') pname = False if not pname: # If pname is undeclared, check article-id art_IDs = self.root_tag.getElementsByTagName('article-id') for aid in art_IDs: if aid.getAttribute('pub-id-type') == 'doi': idstring = aid.firstChild.data pub_doi = idstring.split('/')[0] try: return dois[pub_doi] except KeyError: print('Unable to identify publisher by DOI, aborting!') sys.exit() def validate_attributes(self): """ Most of the time, attributes are not required nor do they have fixed values. But in this case, there are some mandatory requirements. """ #I would love to check xml:lang against RFC 4646: # http://www.ietf.org/rfc/rfc4646.txt #I don't know a good tool for it though, so it gets a pass for now. mandates = [('xmlns:mml', 'http://www.w3.org/1998/Math/MathML'), ('xmlns:xlink', 'http://www.w3.org/1999/xlink'), ('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance')] attr_err = 'Article attribute {0} has improper value: {1}' for key, val in mandates: if self.attrs[key] and not self.attrs[key] == val: log.error(attr_err.format(key, self.attrs[key])) if self.attrs['article-type'] not in utils.suggested_article_types: art_type_err = 'article-type value is not a suggested value - {0}' log.warning(art_type_err.format(self.attrs['article-type'])) def get_DOI(self): """ A method for returning the DOI identifier of an article """ return self.metadata.article_id['doi'] </code></pre> <p>A lot of the code in this file is old and definitely should be revised. Though I welcome comment on anything, my primary question is specifically about whether or not monkey-patching is a good (or acceptable) solution. If not, what would be better instead? If it is okay, how could I improve my use?</p> <p>When I recently made the choice to use the monkey-patching solution, part of my justification was that I was not changing any of the native functions of the xml.dom.minidom module; all of these are <em>new</em> methods that do not change expected behavior that might cause confusion. Additionally this allowed me to use methods that fit minidom's "style" which I hoped would emphasize the analogous behavior through analogous idioms.</p> <p>For reference, the full codebase is <a href="https://github.com/SavinaRoja/OpenAccess_EPUB/tree/32ea9199e4a267872bf92393a317e421e7ac7b66" rel="nofollow">on GitHub</a>, and the element methods are <a href="https://github.com/SavinaRoja/OpenAccess_EPUB/blob/32ea9199e4a267872bf92393a317e421e7ac7b66/src/openaccess_epub/utils/element_methods.py" rel="nofollow">here</a>:</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T00:12:55.770", "Id": "41611", "Score": "2", "body": "Maybe you should use composition? OK, as a rule, I despise monkey patching, but composition is a good way to \"hide\" what is wrong with older/crappy implementations." } ]
[ { "body": "<p>The problem here is the minidom API is a well known API. Someone new to the code needs to know that you monkey patched it and why you did it. Otherwise they would be scouring the minidom docs looking for your methods. This is generally why monkey patching is a bad idea because it can be confusing to the next reader. Especially when the next reader is a person less experienced with the API or programming language.</p>\n\n<p>As @fge suggests, using composition in some way would be preferable here.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-24T23:40:46.660", "Id": "40010", "ParentId": "26859", "Score": "3" } }, { "body": "<p>I do not find the idea of parsing the file within the class initializer a good one. That place is for for initializing -instance- variables as the name suggests. I suggest you to delegate the processing (parsing) in separate functions. This is a note about the general design of your class <code>Article</code></p>\n\n<p>To instantiate the class, we need to pass an XML file as an argument. But within <code>__init__()</code> you make assumption it is a valid XML file. We can not trust an input. That is a security rule. However, in your case, the minimu you can do is to check for the validity of the input: what if the XML file is not well formed? What if the wrong path was given and simply does not exist? To remedy to these problems, you can improve your code concerning this point as follows:</p>\n\n<p>First, you need to import <a href=\"https://docs.python.org/3.6/library/pyexpat.html\" rel=\"nofollow noreferrer\"><em>xml.parsers.expat</em></a> with which you can raise an <a href=\"https://docs.python.org/3.6/library/pyexpat.html#expaterror-objects\" rel=\"nofollow noreferrer\"><code>ExpatError</code></a> exception in case your XML file is malformed. So in the import sections of your code, add this line:</p>\n\n<pre><code>from xml.parsers.expat import ExpatError\n</code></pre>\n\n<p>And wrap <code>doc = minidom.parse(xml_file)</code> like this:</p>\n\n<pre><code>try:\n self.doc = minidom.parse(xml_file)\nexcept ExpatError as err:\n print('Malformed XML file.')\n print('Exception: {}'.format(err.code))\n print('Line: {}'.format(err.lineno))\n print('Offset: {}.format(err.offset)')\n raise err\nexcept IOError as ioerr:\n print('Invalide path, can not read the file.')\n print(ioerr.strerror, ioerr.errno)\n raise ioerr\n</code></pre>\n\n<p>The second except above checks if the file exist within the provided path. Note also that you do not need to import a specific module to make use of <code>IOError</code> as it is a <a href=\"https://docs.python.org/3.6/library/exceptions.html\" rel=\"nofollow noreferrer\">built-in exception</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-25T07:11:00.540", "Id": "192886", "ParentId": "26859", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-31T21:10:10.193", "Id": "26859", "Score": "5", "Tags": [ "python", "xml", "python-3.x" ], "Title": "Using a monkey-patched XML parser to convert journal articles to ePub format" }
26859
<p>I have been doing some Code School classes on jQuery, and I needed a image slider for my site. Right now, there are only two responsive states, but that will most likely change (and/or become fluid later).</p> <p>I was just wondering if there are any best practices or general clean up I can do to the code. I'm still a newbie with jQuery, so any advice would be helpful.</p> <p>Plugins used: Fastclick and hammer.js</p> <pre><code>$(function() { FastClick.attach(document.body); var slide = $(".ImgSection li"); var ImgSec = $(".ImgSection").hammer(); var CrntPos = 0; var Width; var Time; var PlusPos; $(window).on("load resize", function(e) { Width = slide.outerWidth(true); }); ImgSec.on("dragleft dragright", "li", function(ev) { ev.gesture.preventDefault(); }); function changeImg (e){ CrntPos = $(this).index(); var ClkWth = Width * .1; var NewPos = (CrntPos * Width) - ClkWth; slide.css("transform", "translate3d(-"+ NewPos +"px,0,0)"); if (CrntPos === 1 ){ $("li:eq(0)").on("click", function() { slide.css("transform", "translate3d(0,0,0)"); }); } } slide.click(changeImg); ImgSec.on("swipe", "li", function(ev) { if(ev.gesture.direction == 'left'){ slide.eq(CrntPos + 1).trigger("click"); } if(ev.gesture.direction == 'right'){ slide.eq(CrntPos - 1).trigger("click"); } if($(this).is(':last-child') &amp;&amp; ev.gesture.direction == 'left'){ slide.eq(0).trigger("click"); } }); $(window).resize(function() { clearTimeout(Time); Time = setTimeout(Resize, 100); }); function Resize(){ if ($('img', slide).css('max-width') == '245px' ){ slide.eq(CrntPos).trigger('click'); } else { slide.eq(CrntPos).trigger('click'); } } }); </code></pre>
[]
[ { "body": "<ul>\n<li><p>For variable and function names, use <code>camelCase</code>. For constants, or at least variables that are used as constants, use <code>ALLCAPS_AND_UNDERSCORES</code>. For constructor functions, use <code>TitleCaps</code> (I forgot how they called this). This is a convention which is common among programming languages and you should follow this to avoid misunderstandings.</p></li>\n<li><p>Never forget semi-colons, even when JS inserts them for you at certain cases.</p></li>\n<li><p>As much as possible, use strict comparison (<code>===</code>,<code>!==</code> etc.)</p></li>\n<li><p>Use a tool to check for code quality. Most of the bad practices will be weeded-out by using such tools. You can use <a href=\"http://www.jshint.com/\" rel=\"nofollow\">JSHint</a> to check your syntax.</p></li>\n</ul>\n\n<p>As for code:</p>\n\n<pre><code>$(function () {\n\n //A handy tip in keeping things clean is that you can use comma-separated\n //variable declarations. It's best you use this style when declaring\n //variables without assigning anything.\n var width, time, plusPos;\n\n //As for variable declaration with assignments, it's best they are var'ed\n //individually. Commas tend to get messy when assignments are done.\n var slide = $(\".imgSection li\");\n var imgSec = $(\".imgSection\").hammer();\n var crntPos = 0;\n\n function changeImg(e) {\n\n crntPos = $(this).index();\n\n var clkWth = width * .1;\n var newPos = (crntPos * width) - clkWth;\n\n slide.css(\"transform\", \"translate3d(-\" + newPos + \"px,0,0)\");\n\n //I notice that changeImg is called every click of `slide`. This means\n //that if currentPos === 1, a handler gets attached? You might want to\n //review this one\n if(crntPos === 1) {\n $(\"li:eq(0)\").on(\"click\", function () {\n slide.css(\"transform\", \"translate3d(0,0,0)\");\n });\n }\n }\n\n //I found that your resize function does the same thing regardless of\n //the condition. We'll remove the condition instead.\n\n function resize() {\n slide.eq(crntPos).trigger('click');\n }\n\n //.on() accepts a map of events and handlers. You can use this style to\n //bind events on an object in one place neatly. You also avoid wrapping\n //the same object more than once with jQuery. In this case, it's avoiding\n //the call of $(window) more than once.\n $(window).on({\n 'load resize': function () {\n width = slide.outerWidth(true);\n },\n 'resize': function () {\n clearTimeout(time);\n time = setTimeout(resize, 100);\n }\n\n });\n\n imgSec.on({\n 'dragleft dragright': function (ev) {\n ev.gesture.preventDefault();\n },\n 'swipe': function (ev) {\n\n var index;\n\n //You can cache repeatedly accessed values\n var direction = ev.gesture.direction;\n\n //As you can see, the only difference the conditions do is determine the\n //value for .eq(). You can DRY the code by extracting the common calls.\n if(direction === 'left') {\n\n //taking advantage that the direction in this block is already left\n //we merge in the last child check\n if($(this).is(':last-child')) {\n index = 0;\n } else {\n index = crntPos + 1;\n }\n\n } else if(direction === 'right') {\n\n //Use an else to avoid further execution of the condition. That way,\n //when direction is already 'left', it won't check if it is 'right'.\n index = crntPos - 1;\n }\n\n //Our factored-out call\n slide.eq(index).trigger('click');\n\n }\n\n }, 'li');\n\n FastClick.attach(document.body);\n slide.click(changeImg);\n\n });\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T13:00:41.400", "Id": "41616", "Score": "1", "body": "@HaydenTarr I would add: Don't abbreviate everything. `current` is more readable than `crnt` (which I actually misread as \"ctrl\", when I first skimmed you code). Letters are cheap :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T19:31:19.230", "Id": "41638", "Score": "0", "body": "@Flambino ahh thats really good to know, for some reason thought it's the sames rules as css :) thanks man!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T03:34:36.217", "Id": "26866", "ParentId": "26863", "Score": "1" } } ]
{ "AcceptedAnswerId": "26866", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T00:15:13.937", "Id": "26863", "Score": "2", "Tags": [ "javascript", "jquery", "datetime", "image", "mobile" ], "Title": "Responsive image slider" }
26863
<p>I wrote a small script to analyse spam messages that are spam <em>false negative</em>; meaning that they are spam messages in nature but that happened to be in your <em>INBOX</em> folder because your spam filter failed to detect it correctly (I personally use SpamAssassin and unfortunately it rarely happens).</p> <p>The goal is to have a chance to analyse spam messages that are put in spam folder manually by running a script in cron jobs.</p> <p>Obviously, all spam messages will be analysed regardless of which email client you're using (<em>Thunderbird, Kaiten Mail or Roundcube</em>), because all you need is to have a message moved in spam folder.</p> <p>Example of my well working <em>PHP script</em>:</p> <pre><code>&lt;?php // Check if there is messages in SPAM folder that don't have [SPAM] lable (e.g.: manually moved from INBOX) exec("grep -L '\[SPAM\]' /home/domainexample.ru/Maildir/.Junk/cur/* 2&gt; /dev/null", $spam_messages); if (!empty($spam_messages)) { $sa_learn = '/usr/bin/sa-learn --spam'; foreach ($spam_messages as $spam_message) { //Learn a message that we believe is spam $sa_learn .= ' ' . $spam_message; $marked_as_spam = file_get_contents($spam_message); // Adding [SPAM] flag to message's subject of analyzed message $marked_as_spam = str_replace("Subject:", "Subject: [SPAM] ", $marked_as_spam); file_put_contents($spam_message, utf8_encode($marked_as_spam)); } // Logging the results $sa_learn .= ' &gt; ' . '/home/domainexample.ru/.spamassassin/logs/' . date('d.m.Y-G:i') . '_analyzer.log'; //Executing analyzer in background shell_exec("nohup $sa_learn 2&gt; /dev/null &amp; echo $!"); // Cleaning cached messages in Dovecot shell_exec("rm -f /var/lib/dovecot/index/domainexample.ru/.Junk/*"); } ?&gt; </code></pre> <p>I would like to have (in case there are) few ideas for improving this already working <strong>PHP</strong> script but most importantly, I would like to learn of how to write the same script using <strong>PERL</strong> or/and <strong>BASH</strong> scripting.</p> <p>Could you please suggest some ideas for improving current <em>PHP</em> script, along with providing pure and fully working examples of the same scenarios in <em>PERL</em> or/and <em>BASH</em>?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-07T06:52:32.823", "Id": "42094", "Score": "0", "body": "Interesting script, but it's a bit of a tall order to do all of these things. If you focus on either a single language (and show us the code if it's not PHP), you probably have a better chance at getting an answer. Judging by the use of `exec` and `shell_exec` it should be easy to convert this to a Bash script." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-08T06:57:36.237", "Id": "42170", "Score": "0", "body": "It wouldn't be that easy for me to do it, as I'm not familiar with Perl, for instance. If I do it, it will take much time for me and only few minutes for an expert in either Bash or Perl. I have just proposed to provide any example Bash `or/and` Perl." } ]
[ { "body": "<p>Here's an <em>untested</em> Bash version:</p>\n\n<pre><code>#!/usr/bin/env bash\nset -o errexit -o noclobber -o nounset\n\nwhile IFS= read -r -u 9 path\ndo\n /usr/bin/sa-learn --spam \"$path\" \\\n &gt; \"/home/domainexample.ru/.spamassassin/logs/$(date +%d.%m.%Y-%G:%S)_analyzer.log\" \\\n 2&gt;&amp;1 &amp;\n sed -i -e 's/^Subject:/Subject: [SPAM] /' \"$path\"\n rm \"$path\"\ndone 9&lt; &lt;(grep -FL '[SPAM]' /home/domainexample.ru/Maildir/.Junk/cur/* 2&gt; /dev/null)\n</code></pre>\n\n<p>Some changes from the original:</p>\n\n<ul>\n<li>Uses <code>grep</code>'s <code>-F</code> option to speed up search.</li>\n<li>Runs <code>sa-learn</code> repeatedly instead of once to avoid having to accumulate the data. Shouldn't slow down the execution since the processes are backgrounded.</li>\n<li>Deletes files as soon as they are processed, to avoid reprocessing if the previous run failed.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-11T07:44:37.693", "Id": "42309", "Score": "0", "body": "Based on the logic above, it's so different from PHP and I don't see how the `$path` is created / looped. Your example unfortunately is not working. I checked it on the test server and nothing is happening - logs are not created, messages are not processed, clean up is not deleting anything. What is wrong?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-12T08:16:31.900", "Id": "42399", "Score": "0", "body": "As logs are empty, I can't tell what is going on there. The script execution I just hanging.. Until you click `CTRL+C`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-12T08:30:26.590", "Id": "42404", "Score": "0", "body": "Yes. It print's out everything in console." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-12T08:36:51.427", "Id": "42407", "Score": "0", "body": "Yes, correct, logs are created every-time and it's just empty.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-12T08:37:22.960", "Id": "42409", "Score": "0", "body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/9208/discussion-between-l0b0-and-ilia-rostovtsev)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-12T15:33:20.033", "Id": "42437", "Score": "0", "body": "Why have you deleted all of your comments? You make me feel I'm talking to myself? :D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-14T07:01:02.190", "Id": "42588", "Score": "0", "body": "Any ideas why your script is not working (hanging) and why logs are empty but instead it's reported to the console? Should be easy to fix? ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-14T11:52:11.490", "Id": "42608", "Score": "0", "body": "You *are* expected to do some investigation yourself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-14T18:50:13.690", "Id": "42628", "Score": "0", "body": "Alright, will do that! My point was to get a working example just the same way I wrote it in PHP. I'm not very well familiar with BASH / Perl and it will take more time for me. Thanks anyway.." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-08T08:07:28.950", "Id": "27165", "ParentId": "26871", "Score": "2" } } ]
{ "AcceptedAnswerId": "27165", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T10:09:25.920", "Id": "26871", "Score": "1", "Tags": [ "php", "bash", "perl" ], "Title": "SpamAssassin spam analyzer script in PHP based on sa-learn command" }
26871
<p>I have two tables (<code>a</code> and <code>b</code>) which have both one <code>date</code> field of type <code>TIMESTAMP</code>. They represent two different type of actions (records): table <code>a</code>'s actions are $200 worth each, while table <code>b</code>'s ones worth $500. </p> <p>I want to calculate the total count of dollars worth of both tables actions limiting the maximum number or dollars per day to $10.000. Is there a more clean or efficient way to do this other than:</p> <pre><code>SELECT SUM(daily_sum_total) AS total FROM ( SELECT CASE WHEN SUM(daily_sum) &gt; 10000 THEN 10000 ELSE SUM(daily_sum) END AS daily_sum_total, day FROM ( SELECT COUNT(date) * 200 AS daily_sum, DATE(date) AS day FROM a GROUP BY day UNION ALL SELECT COUNT(date) * 500 AS daily_sum, DATE(date) AS day FROM b GROUP BY day ) AS daily_tmp_table GROUP BY day ) as total_tmp_table; </code></pre>
[]
[ { "body": "<p>You might try this:</p>\n\n<pre><code>select\n sum(amount) amount\nfrom(\n select\n least(sum(amount),10000) amount\n from (\n select date,\n 200 amount\n from a\n union all\n select date,\n 500 amount\n from b) list_of_all\n group by\n date(date)) list_by_day\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T16:13:12.780", "Id": "41624", "Score": "0", "body": "What's the difference between `date(date)` and `date_trunc('day', date)`? Also your current form does not sum all the returned results." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T16:53:33.800", "Id": "41625", "Score": "0", "body": "Never used Date actually -- I see it does a type casting. If you want a date data type I guess that either date() or cast() make sense. cast() is the ANSI version I think. I believe this does sum all the results as the sum runs against an inline view that projects all the rows of a & b." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T17:40:56.980", "Id": "41627", "Score": "0", "body": "\"I believe this does sum all the results as the sum runs against an inline view that projects all the rows of a & b\" - I've just run your query and all it does is returning a column of rows of the `amount`s grouped by date. You have to put run a `SELECT sum(amount) AS rep FROM x;` (where x is your current query) to get the total amount. Also when using a subquery in the `FROM` clause you should specify an alias." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T18:21:41.997", "Id": "41629", "Score": "0", "body": "Ah, when I changed the select to a Date() instead of a date_trunc() I forgot to change the group by ... perhaps that was it. Yes, I'll add the alias -- keep forgetting that PostgreSQL requires it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T18:26:58.613", "Id": "41630", "Score": "0", "body": "syntax error at or near \"day\", LINE 1: SELECT date(date) day. (you should always use `AS` when aliasing). The error is probably caused by the fact that `day` is also a function. Also even with that fix it is still showing only the rows column of all `amount`s, not the actual `sum()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T18:33:05.867", "Id": "41632", "Score": "0", "body": "Paste in the code your using, perhaps in the original question so you get it formatted. Aggregating on an inline view isn othing special, and isn't going to cause that sympton .. must be something else going on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T18:33:40.007", "Id": "41633", "Score": "0", "body": "Oh you're just looking for the total, not total broken out by day ... hang on ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T18:36:01.377", "Id": "41634", "Score": "0", "body": "Now the limit of `10.000` is applied globally, while in the original query it was applied *per day*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T18:36:50.317", "Id": "41635", "Score": "0", "body": "yeah ... noticed that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T18:38:54.797", "Id": "41637", "Score": "0", "body": "(PS: you can also remove `date(date) the_day,` from the first subquery)" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T16:08:05.297", "Id": "26875", "ParentId": "26872", "Score": "2" } } ]
{ "AcceptedAnswerId": "26875", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T12:40:19.777", "Id": "26872", "Score": "2", "Tags": [ "sql", "postgresql" ], "Title": "Summing different tables values limiting the results" }
26872
<p>This is a utility class I have in one of my projects and I seek feedback on it. I have read the <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Locale.html" rel="nofollow">javadoc for <code>Locale</code></a> quite a few times while developing this code. I think I have it right, but maybe there are holes in it...</p> <p>Reviews welcome; also, if there are parts of the code you don't understand due to lack of comments, I'd like to hear about that as well.</p> <p>Link to the original source: <a href="https://github.com/fge/msg-simple/blob/master/src/main/java/com/github/fge/msgsimple/locale/LocaleUtils.java" rel="nofollow">here</a>; test file for this class: <a href="https://github.com/fge/msg-simple/blob/master/src/test/java/com/github/fge/msgsimple/locale/LocaleUtilsTest.java" rel="nofollow">here (not pasted in this post)</a>.</p> <p>Note: this library is meant to work with Java 6+; I know of the <code>Locale.Builder</code> class, however this class only appeared in Java 7.</p> <pre><code>/** * Utility methods for {@link Locale} management * * &lt;p&gt;This class provides two methods:&lt;/p&gt; * * &lt;ul&gt; * &lt;li&gt;{@link #parseLocale(String)} parses a string and builds a {@link * Locale} object (strangely enough, there is no such method in the JDK!); * &lt;/li&gt; * &lt;li&gt;{@link #getApplicable(Locale)} returns an ordered list of locales * "applicable" to the given locale.&lt;/li&gt; * &lt;/ul&gt; * * &lt;p&gt;The {@link #getApplicable(Locale)} method emulates what the JDK's {@link * ResourceBundle} does when you look up a message in a locale; it returns an * ordered list from the most specific to the more general. For instance, given * the locale {@code "ja_JP_JP"}, it will generate the following list:&lt;/p&gt; * * &lt;ul&gt; * &lt;li&gt;{@code "ja_JP_JP"},&lt;/li&gt; * &lt;li&gt;{@code "ja_JP"},&lt;/li&gt; * &lt;li&gt;{@code "ja"},&lt;/li&gt; * &lt;li&gt;{@code ""} (the root locale, {@link Locale#ROOT}).&lt;/li&gt; * &lt;/ul&gt; */ public final class LocaleUtils { private static final Pattern UNDERSCORE = Pattern.compile("_"); private LocaleUtils() { } /** * Parse a string input as an argument and return a locale object * * &lt;p&gt;Three things to note:&lt;/p&gt; * * &lt;ul&gt; * &lt;li&gt;it is NOT checked whether the extracted language or country codes * are actually registered to the ISO;&lt;/li&gt; * &lt;li&gt;all input strings with more than two underscores are deemed * illegal;&lt;/li&gt; * &lt;li&gt;if the first component (the language) is empty, {@link * Locale#ROOT} is returned.&lt;/li&gt; * &lt;/ul&gt; * * @see Locale * * @param input the input string * @throws NullPointerException input is null * @throws IllegalArgumentException input is malformed (see above) * @return a {@link Locale} */ public static Locale parseLocale(final String input) { if (input == null) throw new NullPointerException("input cannot be null"); if (input.isEmpty()) return Locale.ROOT; /* * NOTE NOTE NOTE: in order for .split() to behave in a sane manner, we * MUST use the "multi-argument" version of .split() with a negative * argument. The no-argument version (this also stands for String's * .split()) will remove all empty strings from the end of the resulting * array up to the first non empty element. * * I don't know who designed this API, but he should either be given * the boot or killed[1]. * * [1] choose the better option; hint: choose option 2 */ final String[] elements = UNDERSCORE.split(input, -1); final int len = elements.length; if (len &gt; 3) throw new IllegalArgumentException("malformed input " + input); if (elements[0].isEmpty()) return Locale.ROOT; switch (len) { case 1: return new Locale(elements[0]); case 2: return new Locale(elements[0], elements[1]); case 3: return new Locale(elements[0], elements[1], elements[2]); default: throw new IllegalStateException("How did I get there??"); } } /** * Get a "decrementing" list of candidate locales for a given locale * * &lt;p&gt;The order of locale returned is from the more specific to the less * specific (the latter being {@link Locale#ROOT}).&lt;/p&gt; * * @param target the locale * @return the list of applicable locales */ public static Collection&lt;Locale&gt; getApplicable(final Locale target) { final String language = target.getLanguage(); final String country = target.getCountry(); final String variant = target.getVariant(); final List&lt;Locale&gt; ret = new ArrayList&lt;Locale&gt;(); ret.add(target); Locale locale; if (!variant.isEmpty()) { locale = new Locale(language, country); if (!locale.equals(Locale.ROOT)) ret.add(locale); } if (!country.isEmpty()) { locale = new Locale(language); if (!locale.equals(Locale.ROOT)) ret.add(locale); } if (!language.isEmpty()) ret.add(Locale.ROOT); return ret; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T18:22:52.687", "Id": "41678", "Score": "2", "body": "That's some neat code and good documentation, very nice job! The only thing I can see is your declaration of `len`, which you use only one time and happily not use it the next time, I'd suggest to drop that variable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T19:47:55.660", "Id": "41684", "Score": "0", "body": "Uhm, yup, well spotted..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T21:22:36.720", "Id": "41770", "Score": "0", "body": "OK, the code has changed a little since then, to account for the comment above; and I think I have detected a bug... However, I am working on another part of this project at the moment :p" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-04T14:28:35.820", "Id": "41813", "Score": "0", "body": "Actually, there was a bug with some inputs. But the bug is in `.split()`..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-05T10:01:29.397", "Id": "41894", "Score": "0", "body": "in parseLocale, checking for null is useless, the exception will happen when you do input.isEmpty()" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-05T10:04:26.807", "Id": "41895", "Score": "2", "body": "@grasGendarme yup, but the exception message in such a case is meaningless..." } ]
[ { "body": "<p>In general, your code is well structured, and well documented.</p>\n\n<p>As for the <code>-1</code> requirement for <code>split</code>, Java has done <em>the right thing</em> by keeping the behaviour consistent with the <a href=\"http://perldoc.perl.org/functions/split.html\" rel=\"nofollow\">Perl <em>RegEx library</em></a> .... so blame Perl (and perhaps Perl can blame someone else).</p>\n\n<p>My more significant issue is that, based on the fact that you have written this utility class, I expect that you are calling these methods 'often'. Since Local instances can be slow to create from scratch, I imagine that you have a performance problem too. Creating many <code>Locale</code> instances is not a great idea when they are thread-safe, and can be reused easily between threads/invocations.</p>\n\n<p>My recommendation to you would be to use a <code>java.util.concurrent.ConcurrentHashMap</code> to store the <code>Locale</code>s you create, and to do a lookup from the Map first, and only create the <code>Locale</code> if you need to.</p>\n\n<p>Something like:</p>\n\n<pre><code>// rename parseLocale(String input) and make it private.....\nprivate static final internalParseLocale(String ...) {\n}\n\nprivate static final ConcurrentHashMap&lt;String, Locale&gt; localemap = new ConcurrentHashMap&lt;&gt; ();\n\n// new public method\npublic static final Locale parseLocale(final String input) {\n final Locale gotit = localemap.get(input);\n if (gotit != null) {\n return gotit;\n }\n final Locale created = internalParseLocale(input);\n final Locale wasthere = localemap.putIfAbsent(input, created);\n if (wasthere != null) {\n // there was a race condition, and we lost!\n return wasthere;\n }\n return created;\n}\n</code></pre>\n\n<p>Then, in your <code>getApplicable()</code> method you should:</p>\n\n<ul>\n<li>avoid using <code>new Locale(...)</code> but instead use <code>parseLocale(.....)</code></li>\n<li>reuse the locales there too</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-08T13:20:48.033", "Id": "70732", "Score": "0", "body": "Well, it is not called that often, but thanks for the tips!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-21T13:49:21.313", "Id": "35833", "ParentId": "26877", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T19:06:41.840", "Id": "26877", "Score": "8", "Tags": [ "java", "parsing", "i18n" ], "Title": "Locale-related code -- are there corner cases I didn't see?" }
26877
<p>I wrote this program for sorting an array of type <code>String</code> alphabetical without using <code>compareTo()</code> method so I am saying that if you can find errors in my program please tell me I will try to fix it.</p> <pre><code>class some{ public static void main(String[] args) { String array[]={"names here"}; System.out.print("before:"); for (int i=0 ;i&lt;array.length;i++ ) System.out.print(array[i]+" "); array = SortA(array); System.out.println(); System.out.print("after:"); for (int i=0 ;i&lt;array.length;i++ ) System.out.print(array[i]+" "); }//end of main method public static int getSmallestRange(String[] array){ int range = array[0].length()-1; for (int i =0;i&lt;array.length ;i++ ) { if(range&gt;array[i].length()-1){ range = array[i].length()-1; } } return range ; } public static String[] SortA(String [] array){ String tmp=""; int index = 0 ; for (int i =0;i&lt;array.length ;i++ ) for (int j = i+1;j&lt;array.length ;j++ ) { if(array[i].charAt(index)&gt;array[j].charAt(index)){ tmp = array[i]; array[i] = array[j]; array[j] = tmp ; }//end of if }//end of loop index++; for (int x =0;x&lt;array.length-1 ;x++ ){ for (int y =x+1;y&lt;array.length ;y++ ) { if(array[x].charAt(0)==array[y].charAt(0)){ if(array[x].charAt(index)&gt;array[y].charAt(index)){ tmp = array[x]; array[x] = array[y]; array[y] = tmp ; } else if(array[x].charAt(index)==array[y].charAt(index)){ if(index&lt;getSmallestRange(array)) index++; } }//end of if }//end of loop } return array; }//end of method } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T06:50:42.133", "Id": "41654", "Score": "0", "body": "Currently it's incorrect, given an initial array of `{\"dds\", \"dda\"}`, it fails to sort them properly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T10:48:51.560", "Id": "41658", "Score": "2", "body": "First off, you have to properly format your code. The indentation is off and very confusing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T18:14:29.923", "Id": "41674", "Score": "0", "body": "@MichaelZedeler: I think checking and correcting usage of whitespace is appropriate for a code review. I mean that no properly formatted code in here is not a \"problem\", as we are here to point these things out. Just pointing that out because you said \"first off, you have to...\" which makes it sound like it is a criteria (which I disagree with)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T18:19:39.737", "Id": "41677", "Score": "1", "body": "In this context, I mean that formatting is first priority over everything else. Learning to program requires that you read and re-read your own code over and over again, so not formatting it right is really getting in the way of ever getting better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T19:59:22.057", "Id": "41685", "Score": "0", "body": "@MichaelZedeler: I completely agree with that!" } ]
[ { "body": "<p>First off, your use of whitespace is a mess, fix it. Press \"Format Code\" in your favorite IDE or do it manually.</p>\n\n<hr>\n\n<pre><code>class some{\n</code></pre>\n\n<ul>\n<li><a href=\"http://www.oracle.com/technetwork/java/codeconv-138413.html\" rel=\"nofollow\">The Java Naming Conventions</a> say that class names should be UpperCamelCase.</li>\n<li>Use a visibility modificator for clearness (<code>private</code>, <code>public</code>).</li>\n</ul>\n\n<hr>\n\n<pre><code>String array[]={\"names here\"};\n</code></pre>\n\n<p>Use descriptive variable names, like <code>sourceArray</code> or <code>unsortedArray</code>.</p>\n\n<hr>\n\n<pre><code>for (int i=0 ;i&lt;array.length;i++ )\n</code></pre>\n\n<ul>\n<li>Use appropriate variable names. This is a little bit unpopular with most people, but I prefer to use descriptive names even for such simple loops (<code>int idx</code>).</li>\n<li><p>As said before, your use pf whitespace is very confusing:</p>\n\n<pre><code>for (int idx = 0; idx &lt; array.length; idx++) {\n</code></pre></li>\n<li><p>Use appropriate loops, in this case a <code>for-each</code> loop:</p>\n\n<pre><code>for (String item : array) {\n</code></pre></li>\n</ul>\n\n<hr>\n\n<pre><code>String tmp=\"\";\nint index = 0 ;\n</code></pre>\n\n<p>Declaring variables once and reusing them through out whole function, especially larger functions, is bad. Declare variables where you need them and name them appropriately, like this:</p>\n\n<pre><code>String swapTemp = array[i];\narray[i] = array[j];\narray[j] = swapTemp;\n</code></pre>\n\n<hr>\n\n<pre><code> }//end of if\n }//end of loop\n</code></pre>\n\n<p>If code is correctly formatted, short and precise (only do one function per function), such comments are absolutely unnecessary.</p>\n\n<hr>\n\n<p>Consider <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html\" rel=\"nofollow\">using the Java Documentation feature</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T18:12:07.710", "Id": "26897", "ParentId": "26880", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-01T21:12:50.650", "Id": "26880", "Score": "2", "Tags": [ "java", "array", "sorting" ], "Title": "Sorting an array" }
26880
<p>I am trying to learn how to animate with tkinter. The code below is an example I was able to build. It creates a small 5x5 map of cubes, then one of them randomly moves around the screen (preferably on the map, but it can wander off).</p> <p>Is this a good way to do it? Is there a more pythonic, or more efficient way of doing it?</p> <pre><code>from tkinter import * from time import sleep from random import randrange class alien(object): def __init__(self): self.root = Tk() self.canvas = Canvas(self.root, width=400, height=400) self.canvas.pack() self.map = [[1, 0, 0, 1, 0], [0, 1, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 1, 0, 0], [1, 0, 0, 1, 0]] self.x = 0 self.y = 0 for row in range(len(self.map)): for column in range(len(self.map[row])): color = "green" if self.map[row][column] == 1: color = "black" #print(50 * row + 50, 50 * column + 50) self.canvas.create_rectangle(50 * row , 50 * column , 50 * row + 50, 50 * column + 50, outline=color, fill=color) self.creature = self.canvas.create_rectangle(50 * self.x, 50 * self.y, 50 * self.x + 50, 50 * self.y + 50, outline="red", fill="red") self.canvas.pack(fill=BOTH, expand=1) self.root.after(0, self.animation) self.root.mainloop() def animation(self): while True: i = randrange(1, 5) print(i) if i == 1: y = -1 elif i == 2: y = 1 elif i == 3: x = -1 elif i == 4: x = 1 sleep(0.025) print(self.x, self.y) self.canvas.move(self.creature, self.x, self.y) self.canvas.update() alien() </code></pre>
[]
[ { "body": "<p>Here is anoted version of your code</p>\n\n<pre><code>from tkinter import *\nfrom time import sleep\nfrom random import randrange\n\n# lowercase tkinter suggest you are using python3, in this case\n# inheriting (object) is not needed anymore to create newstyle\n# class\nclass alien(object):\n def __init__(self):\n self.root = Tk()\n self.canvas = Canvas(self.root, width=400, height=400)\n self.canvas.pack()\n self.map = [[1, 0, 0, 1, 0], [0, 1, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 1, 0, 0], [1, 0, 0, 1, 0]]\n self.x = 0\n self.y = 0\n for row in range(len(self.map)):\n for column in range(len(self.map[row])):\n color = \"green\"\n #since 0 evaluate to False, you can drop '== 1'\n if self.map[row][column] == 1:\n color = \"black\" \n self.canvas.create_rectangle(50 * row , 50 * column , 50 * row + 50, 50 * column + 50,\n outline=color, fill=color) \n self.creature = self.canvas.create_rectangle(50 * self.x, 50 * self.y, 50 * self.x + 50, 50 * self.y + 50,\n outline=\"red\", fill=\"red\")\n #this call overrides the previous 'canvas.pack'. Remove first.\n self.canvas.pack(fill=BOTH, expand=1) \n self.root.after(0, self.animation)\n self.root.mainloop()\n\n def animation(self):\n #see below for further explanations on animations.\n while True:\n i = randrange(1, 5)\n print(i)\n #note: randrange ouput from 1 to 5 (included)\n #thus i = 5 is not handled in your switch (might be on purpose)\n if i == 1:\n y = -1\n elif i == 2:\n y = 1\n elif i == 3:\n x = -1\n elif i == 4:\n x = 1\n # after you switch, either x or y (or both) are not\n # initialized\n sleep(0.025)\n # self.x and self.y are never updated\n print(self.x, self.y)\n # move is a relative command (expect delta x,delta y)\n # if self.x,self.y is your creature absolute position,\n # you might want to use 'coords' on (self.x, self.y) \n # or 'move' on (x,y)\n # in addition, your \"*50\" factor has disapeared.\n self.canvas.move(self.creature, self.x, self.y)\n # it is good practice to use 'update_idletasks' instead\n # of 'update' to avoid race conditions. By the way\n # the use of one of them is seldom required (see below)\n self.canvas.update()\nalien()\n</code></pre>\n\n<p>Regarding how you handle the animation, it could be profitable to run your simulation in the python mainloop. What you does now is to provide your own mainloop (<code>while True: [...] sleep(0.025) [...] canvas.update()</code>). This can work, but will fail as soon as you will want to add interactivity to your application (other widgets, or react to events on canvas). This will not work because the execution path is stuck in <code>alien.animation</code>. The solution there would be to rely on tkinter mainloop and to beg for <code>alien.animation</code> to be repeatedly called.</p>\n\n<pre><code>def animation(self):\n #while True: no longer needed\n i = randrange(1, 5)\n #[...]\n elif i == 4:\n x = 1\n #sleep(0.025) becomes\n self.root.after(25, animation)\n print(self.x, self.y)\n self.canvas.move(self.creature, x*50, y*50)\n #self.canvas.update() no longer needed\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T22:42:34.770", "Id": "41690", "Score": "0", "body": "why is update note needed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T05:04:40.713", "Id": "41705", "Score": "0", "body": "update is a way to ask tkinter to process pending events, by implicitly returning to the mainloop (with the after mechanism), you let tkinter process event freely (here the redraw is what you are interested in." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T14:05:32.880", "Id": "26893", "ParentId": "26885", "Score": "3" } }, { "body": "<ul>\n<li>Whenever you do <code>range(len(self.map))</code> in Python, you are most probably doing something wrong. The pythonic way to do this is to use <code>enumerate</code>.</li>\n</ul>\n\n<p>If you also use the ternary operator, remove the useless '== 1', store magic numbers in a unique place and factorize the mathematical expressions, you can transform this :</p>\n\n<pre><code> for row in range(len(self.map)):\n for column in range(len(self.map[row])):\n color = \"green\"\n if self.map[row][column] == 1:\n color = \"black\" \n #print(50 * row + 50, 50 * column + 50)\n self.canvas.create_rectangle(50 * row , 50 * column , 50 * row + 50, 50 * column + 50,\n outline=color, fill=color) \n self.creature = self.canvas.create_rectangle(50 * self.x, 50 * self.y, 50 * self.x + 50, 50 * self.y + 50,\n outline=\"red\", fill=\"red\")\n</code></pre>\n\n<p>Into this</p>\n\n<pre><code> r = 50\n for i,row in enumerate(self.map):\n for j,cell in enumerate(row)):\n color = \"black\" if cell else \"green\"\n self.canvas.create_rectangle(r*i, r*j , r*(i+1), r*(j+1),\n outline=color, fill=color)\n self.creature = self.canvas.create_rectangle(r*self.x, r*self.y, r*(self.x+1), r*(self.y+1),\n outline=\"red\", fill=\"red\")\n</code></pre>\n\n<ul>\n<li><p>Does <code>map</code> need to be an object member or could it be a variable local to <code>__init__</code> ?</p></li>\n<li><p>Is <code>animation()</code> working properly or should it update <code>self.x</code> and <code>self.y</code> ?</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T22:17:15.317", "Id": "41689", "Score": "0", "body": "What do you mean by your question about map? Is it does it need the self. designation? Then yes. Animation does work, it's messy but really it's a place holder." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T05:42:24.893", "Id": "41709", "Score": "0", "body": "If you are not using map outside the unit method, you could get rid of the self designation. As for animation, I guessed I misunderstood how it was supposed to work." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T21:14:11.730", "Id": "26899", "ParentId": "26885", "Score": "0" } } ]
{ "AcceptedAnswerId": "26893", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T04:47:23.233", "Id": "26885", "Score": "2", "Tags": [ "python", "optimization", "animation", "tkinter", "tk" ], "Title": "Animation with 5x5 map of cubes" }
26885
<p>I have the following code in Java:</p> <p><code>HangmanFunctions</code> class:</p> <pre><code>import java.util.ArrayList; import java.util.Random; public class HangmanFunctions { private static final String[] WORDS = {"jazz", "buzz", "hajj", "fuzz", "jinx", "jazzy", "fuzzy", "faffs", "fizzy", "jiffs", "jazzed", "buzzed", "jazzes", "faffed", "fizzed", "jazzing", "buzzing", "jazzier", "faffing", "fuzzing"}; private String word; private ArrayList&lt;Character&gt; hiddenWord = new ArrayList&lt;Character&gt;(); private ArrayList&lt;Character&gt; lettersGuessed = new ArrayList&lt;Character&gt;(); public HangmanFunctions() { setHiddenWord(); } public ArrayList&lt;Character&gt; getLettersGuessed() { return lettersGuessed; } private void setWord() { word = WORDS[new Random().nextInt(19)]; } public String getWord() { return word; } private void setHiddenWord() { setWord(); for (char letter: word.toCharArray()) { hiddenWord.add('-'); } } public ArrayList&lt;Character&gt; getHiddenWord() { return hiddenWord; } private ArrayList&lt;Integer&gt; getIndexesOf(char letter) { ArrayList&lt;Integer&gt; instances = new ArrayList&lt;Integer&gt;(); for (int i = word.indexOf(letter); i &gt;= 0; i = word.indexOf(letter, i + 1)) { instances.add(i); } return instances; } public void revealLetter(char letter) { for (int i: getIndexesOf(letter)) { hiddenWord.set(i, word.charAt(i)); } } public void addGuess(char letter) { lettersGuessed.add(letter); } private boolean isGuessed(char letter) { return lettersGuessed.indexOf(letter) != -1; } public Results getResult(char letter) { if (!isGuessed(letter)) { if (getIndexesOf(letter).size() &gt; 0) { return Results.CORRECT; } else { return Results.INCORRECT; } } else { return Results.ALREADY_GUESSED; } } } </code></pre> <p><code>HangmanPanel</code> class:</p> <pre><code>import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; public class HangmanPanel extends JPanel { private HangmanFunctions functions; private JLabel word; private JLabel lettersGuessed; private JTextField inputBox; private Font largeFont = new Font("sansserif", Font.PLAIN, 50); private int hangmanPos = 0; public HangmanPanel(HangmanFunctions functions) { this.functions = functions; setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.insets = new Insets(10, 10, 10, 350); word = new JLabel(toHiddenWord(functions.getHiddenWord())); word.setFont(largeFont); c.gridy = 0; add(word, c); lettersGuessed = new JLabel(getLettersGuessedString()); c.gridy = 1; add(lettersGuessed, c); inputBox = new JTextField(); inputBox.setPreferredSize(new Dimension(25, 25)); inputBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { newGuess(e.getActionCommand().charAt(0)); } }); c.gridy = 2; add(inputBox, c); } private String toHiddenWord(ArrayList&lt;Character&gt; word) { String hiddenWord = " "; for (int i = 0; i &lt; word.size(); i++) { hiddenWord += (word.get(i) + " "); } return hiddenWord; } private String getLettersGuessedString() { String lettersGuessedString = "Letters Guessed: "; for (char i: functions.getLettersGuessed()) { lettersGuessedString += (i + ", "); } return lettersGuessedString; } private void newGuess(char letter) { Results result = functions.getResult(letter); if (result == Results.CORRECT) { JOptionPane.showMessageDialog(null, "Correct.", "Hangman", JOptionPane.PLAIN_MESSAGE); functions.addGuess(letter); functions.revealLetter(letter); } else if (result == Results.INCORRECT) { JOptionPane.showMessageDialog(null, "Incorrect.", "Hangman", JOptionPane.PLAIN_MESSAGE); functions.addGuess(letter); hangmanPos++; repaint(); } else { JOptionPane.showMessageDialog(null, "Already Guessed.", "Hangman", JOptionPane.PLAIN_MESSAGE); } inputBox.setText(""); lettersGuessed.setText(getLettersGuessedString()); word.setText(toHiddenWord(functions.getHiddenWord())); if (functions.getHiddenWord().indexOf('-') == -1) { JOptionPane.showMessageDialog(null, "Congratulations, " + functions.getWord() + " was my word", "Hangman", JOptionPane.PLAIN_MESSAGE); } } @Override public void paintComponent(Graphics g) { g.drawLine(350, 0, 350, 500); switch (hangmanPos) { case 9: g.drawLine(500, 250, 525, 275); JOptionPane.showMessageDialog(null, "Oops! You've been hanged! My word was " + functions.getWord(), "Hangman", JOptionPane.PLAIN_MESSAGE); case 8: g.drawLine(500, 250, 475, 275); case 7: g.drawLine(500, 225, 525, 225); case 6: g.drawLine(500, 225, 475, 225); case 5: g.drawLine(500, 200, 500, 250); case 4: g.drawOval(475, 150, 50, 50); case 3: g.drawLine(500, 100, 500, 150); case 2: g.drawLine(600, 100, 500, 100); case 1: g.drawLine(600, 350, 600, 100); case 0: g.drawLine(450, 350, 600, 350); } } } </code></pre> <p><code>Results</code> enum:</p> <pre><code>public enum Results { CORRECT, INCORRECT, ALREADY_GUESSED } </code></pre> <p><code>Frame</code> class:</p> <pre><code>import javax.swing.JFrame; public class Frame extends JFrame { public Frame() { super("Hangman"); setSize(700, 500); setResizable(false); setVisible(true); add(new HangmanPanel(new HangmanFunctions())); } public static void main(String[] args) { new Frame(); } } </code></pre> <p>In theory, this code works, so I decided it was okay to post it here. However, when ran, it looks a bit like this:</p> <p><img src="https://i.stack.imgur.com/lsGMx.jpg" alt="Hangman in Java"></p> <p>So, I'm assuming there's a lot of bad practices used in my code. Can anyone identify them?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T01:31:35.247", "Id": "41696", "Score": "0", "body": "I started to work on the changes needed, but it's too much work. Basically, separate your one JPanel into two JPanels. One JPanel for the left side of your game, and another JPanel for the right side of your game. Your HangmanPanel is doing way too much work that should be a part of HangmanFunctions." } ]
[ { "body": "<h1>Overview</h1>\n\n<p>Separate the game's entry point, model, the view, and the controller into different classes:</p>\n\n<ul>\n<li>HangmanGame - The main entry point to the application.</li>\n<li>HangmanModel - Contains information about the word being guessed.</li>\n<li>HangmanView - Displays the results of the model.</li>\n<li>HangmanController - Updates the model based on events from the view.</li>\n</ul>\n\n<p>Identify the responsibilities and behaviours of the classes.</p>\n\n<h2>HangmanGame</h2>\n\n<p>Responsibilities:</p>\n\n<ul>\n<li>Creates instances of the required classes (see also <a href=\"http://www.springsource.org/\" rel=\"nofollow\">Spring</a>)</li>\n<li>Exits the application.</li>\n<li>Creates a new game.</li>\n</ul>\n\n<h2>HangmanModel</h2>\n\n<p>Responsibilities:</p>\n\n<ul>\n<li>Load words.</li>\n<li>Select a word to guess.</li>\n<li>Retrieves positions that a letter is found (or throws an exception).</li>\n<li>Tracks incorrect guesses.</li>\n</ul>\n\n<h2>HangmanView</h2>\n\n<p>Responsibilities:</p>\n\n<ul>\n<li>Creates a new UI for the view.</li>\n<li>Updates the drawing of the hangman.</li>\n<li>Updates the letters being displayed.</li>\n<li>Notifies listeners of guesses.</li>\n<li>Notifies listeners of when the user requests to quit.</li>\n<li>Animates the hanging.</li>\n</ul>\n\n<h2>HangmanController</h2>\n\n<p>Responsibilities:</p>\n\n<ul>\n<li>Listens for events from the view.</li>\n<li>Tells the view when the game is over.</li>\n<li>Tells the view when another guess is made.</li>\n<li>Tells the view where to put the letters.</li>\n</ul>\n\n<h1>Implementation</h1>\n\n<p>Once you've identified the classes, their responsibilities, and their collaborators, think about how you would implement the actions described above. For example:</p>\n\n<pre><code>public class HangmanModel {\n public void load( File dictionary ) { ... }\n public int[] guess( char ch ) { ... }\n public void badGuess() { ... }\n public void pickWord() { ... }\n}\n\npublic class HangmanGame {\n public void initialize() { ... }\n public void quit() { ... }\n public void newGame() { ... }\n}\n\npublic class HangmanView {\n public void initialize() { ... }\n public void drawHangman( HangmanStatus status ) { ... }\n public void drawWord( String word[] ) { ... }\n public void notifyGuess() { ... }\n public void notifyQuit() { ... }\n public void animateHanging() { ... }\n}\n</code></pre>\n\n<p>Once you are satisfied that you have thought about most of the possible actions that each class will need to make the game, then consider the attributes each class needs and how the implementation will work.</p>\n\n<h2>Procedural Programming vs. OOP</h2>\n\n<p>The <code>HangmanFunctions</code> class is not object-oriented. When writing object-oriented code try to think in terms of the objects in the system. For example, you could further split HangmanView into two classes: <code>HangmanUI</code> and <code>AnimatedHangman</code>. The <code>HangmanUI</code> would represent the user interface (ASCII text in DOS vs. Swing vs. AWT) wherein the user interacts with the game. The <code>AnimatedHangman</code> would abstract drawing and animating the hangman figure in the game.</p>\n\n<p>A set of functions is not an object-oriented class.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T04:13:40.143", "Id": "26907", "ParentId": "26898", "Score": "6" } } ]
{ "AcceptedAnswerId": "26907", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-02T19:06:36.110", "Id": "26898", "Score": "4", "Tags": [ "java", "game", "swing", "hangman" ], "Title": "Hangman in Java" }
26898
<p>I have a function in the C++ program, which does simple computations and writes result to two arrays - <code>result[53]</code> and <code>var1_new[53]</code>. It contains two code blocks:</p> <p>The first one -</p> <pre><code>double result[53]; result[0] = ((var1[13] * 1) + (var2[7] * 2)) / var3[0]; result[1] = ((var1[21] * 1) + (var2[7] * 2)) / var3[1]; result[2] = ((var1[12] * 2) + (var2[7] * 3)) / var3[2]; result[3] = ((var1[25] * 2) + (var2[7] * 3)) / var3[3]; //And so on, up to result[52] </code></pre> <p>And the second one -</p> <pre><code>double var1_new[53]; for (int x = 0; x &lt; 53; ++x) { var1_new[x] = var1[x]; } var1_new[13] += result[0]; var1_new[21] += result[1]; var1_new[12] += result[2]; var1_new[25] += result[3]; //And so on, up to var1_new[52] </code></pre> <p>The blocks above use <em>equal</em> array indexes <em>pattern</em> - <code>13, 21, 12, 15, etc</code>. The pattern is hardcoded.</p> <p>This code runs pretty fast, thus I don't want to increase performance, but I'm thinking about readability - the function that contain code blocks is very complex. How can I make it more readable? Is it even possible?</p>
[]
[ { "body": "<p>First, <strong>magic constants are bad</strong>, you should name them</p>\n\n<pre><code>int const N = 53;\ndouble result[N];\n</code></pre>\n\n<p>Second, <strong>magic patterns are even worse</strong>, you should also name them along with <strong>documentation comments</strong></p>\n\n<pre><code>// explain where the pattern comes from\nint const pattern[] = { 13, 21, 12, 25, /* 49 more constants */ };\n</code></pre>\n\n<p>Third, manually loop unrolling can sometimes help, but <strong>only after you benchmarked</strong></p>\n\n<pre><code>for (int i = 0; i &lt; N; ++i) {\n result[i] = ((var1[pattern[i]] * (i+1)) + (var2[7] * (i+2))) / var3[i];\n}\n</code></pre>\n\n<p>For your second part, rinse and repeat:</p>\n\n<pre><code>double var1_new[N];\n</code></pre>\n\n<p>Fourth, <strong>use the Standard Library for standardized algorithms</strong></p>\n\n<pre><code>#include &lt;algorithm&gt;\nstd::copy_n(var1, N, var1_new);\n</code></pre>\n\n<p>Again, rinse and repeat the loop unrolling</p>\n\n<pre><code>for (int i = 0; i &lt; N; ++i) {\n var1_new[pattern[i]] += result[i];\n}\n</code></pre>\n\n<p>Finally, you might want to give your variables <strong>meaningful names</strong>: <code>var1</code>, <code>var2</code>, <code>var3</code> do not explain <strong>their intended use</strong> very well. Think about what they mean in your application (it was unclear from the code fragment alone).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-05T09:32:45.930", "Id": "27029", "ParentId": "26909", "Score": "5" } } ]
{ "AcceptedAnswerId": "27029", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T07:39:11.133", "Id": "26909", "Score": "2", "Tags": [ "c++", "array" ], "Title": "Making complex array initializations more readable" }
26909
<p>How to optimize below code to reduce code with better performance? </p> <pre><code>import java.util.Scanner; public class ConsoleCalculatorImproved { static boolean ERROR = true; public static void main(String[] m) { String arg ; ConsoleCalculatorImproved cC = new ConsoleCalculatorImproved(); CalculatorMain cM = cC.new CalculatorMain(); float result; Scanner cInput = new Scanner(System.in); try { arg = m[0]; } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Enter Expression : "); arg = cInput.nextLine(); } result = cM.evaluateExpression(arg); if(ERROR == false) System.out.println(arg+" = "+result); } class CalculatorMain { String expression; StringBuilder numExtractor; float result,temp; int opCount; char operator,current; public CalculatorMain() { expression = new String(); numExtractor = new StringBuilder(); numExtractor.setLength(10); opCount = 0; result = temp = 0; operator = current = 0; } public boolean isDigit(char test) { if(test &gt;='0' &amp;&amp; test &lt;='9') return true; else return false; } public float evaluateExpression(String exp) { expression = exp.trim(); expression = "("+expression+")"; int i,sc=0; for(i=1;i&lt;expression.length();i++) { current = expression.charAt(i); if(i == 1) { if(isDigit(current)||current=='-') numExtractor.setCharAt( sc++ , current ); else if(current == '(') { if(expression.indexOf(')') != expression.lastIndexOf(')')) { CalculatorMain cm = new CalculatorMain(); String Temporary = expression.substring(2,expression.indexOf(')')); result = cm.evaluateExpression(Temporary); i = expression.indexOf(')'); StringBuilder t = new StringBuilder(expression); t.setCharAt(expression.indexOf(')'),'x'); expression = t.toString(); } else { System.out.println("ERROR : Pair of Brackets Expected"); } } else { System.out.println("ERROR : Invalid Expression !"); return result; } } else if( ( expression.charAt(i-1) != 'x' ) &amp;&amp; ( current == ')' )) { if(opCount == 0) { result = Float.parseFloat(numExtractor.toString()); break; } else { temp = Float.parseFloat(numExtractor.toString().trim()); switch(operator) { case'+': result+=temp;break; case'-': result-=temp;break; case'*': result*=temp;break; case'/': result/=temp;break; } break; } } else if( ( expression.charAt(i-1) == 'x' ) &amp;&amp; ( current == ')' )) { break; } else { if(isDigit(current) || (current == '.') ) { numExtractor.setCharAt( sc++ , current); } else if(current == '-' &amp;&amp; ( expression.charAt(i-1) == '+' || expression.charAt(i-1) == '-' || expression.charAt(i-1) == '*' || expression.charAt(i-1) == '/' )) { numExtractor.setCharAt( sc++ , current); } else { if((expression.charAt(i-1)!='x')&amp;&amp;(current == '+' || current == '-' || current == '*' || current == '/')) { if(opCount==0) { result = Float.parseFloat(numExtractor.toString().trim()); numExtractor = new StringBuilder(); numExtractor.setLength(10); sc = 0; opCount++; operator = current; } else { temp = Float.parseFloat(numExtractor.toString().trim()); numExtractor = new StringBuilder(); numExtractor.setLength(10); sc = 0; switch(operator) { case'+': result+=temp;break; case'-': result-=temp;break; case'*': result*=temp;break; case'/': result/=temp;break; } operator = current; temp = 0; opCount++; } } else if((expression.charAt(i-1)=='x')&amp;&amp;(current == '+' || current == '-' || current == '*' || current == '/')) { opCount++; operator = current; } else if(current == '(') { if( opCount !=0 &amp;&amp; (expression.indexOf(')') != expression.lastIndexOf(')'))) { CalculatorMain cm = new CalculatorMain(); String Temporary = expression.substring(i+1,expression.indexOf(')')); temp = cm.evaluateExpression(Temporary); i = expression.indexOf(')'); StringBuilder t = new StringBuilder(expression); t.setCharAt(expression.indexOf(')'),'x'); expression = t.toString(); switch(operator) { case'+': result+=temp;break; case'-': result-=temp;break; case'*': result*=temp;break; case'/': result/=temp;break; } } else if(opCount == 0) { System.out.println("ERROR : Missing Operator before Bracket"); return result; } else { System.out.println("ERROR : Pair of Brackets Expected"); } } else { System.out.println("Invalid Expression!"); return result; } } } } ERROR = false; return result; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T11:15:03.333", "Id": "41718", "Score": "1", "body": "Maybe you should tell us what this code does, how it works and why it works the way it works?" } ]
[ { "body": "<p>You need to compile and interpret a programming language, even though your language is rather simple expression language. Write <a href=\"http://en.wikipedia.org/wiki/Recursive_descent_parser\" rel=\"nofollow\">recursive descent parser</a> or use <a href=\"http://www.antlr.org/wiki/display/ANTLR3/Expression+evaluator\" rel=\"nofollow\">ANTLR</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T13:06:18.620", "Id": "26921", "ParentId": "26911", "Score": "1" } }, { "body": "<p>You should consider using <a href=\"https://github.com/sirthias/parboiled\" rel=\"nofollow\">Parboiled</a>. It allows you to write grammars entirely in Java.</p>\n\n<p>As a bonus, it has a calculator example, complete with parens etc.</p>\n\n<p>I know ANTLR is generally the name that comes first; but the fact that Parboiled does <em>not</em> require that you \"precompile\" your grammars is a HUGE bonus.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T19:28:21.727", "Id": "26949", "ParentId": "26911", "Score": "1" } }, { "body": "<p>You should read about <a href=\"http://en.wikipedia.org/wiki/Shunting-yard_algorithm\" rel=\"nofollow\">the Shunting-yard algorithm</a>. It can be used to parse mathematical expressions in the normal (infix) notation into postfix notation (or Reverse Polish Notation), which can then be evaluated easily (and efficiently).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-08T12:08:21.650", "Id": "27169", "ParentId": "26911", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T08:23:47.317", "Id": "26911", "Score": "2", "Tags": [ "java" ], "Title": "How to write this program efficiently and much shorter?" }
26911
<p>I wrote a web spider that I would like to download and parse pages concurrently. Here is what I am trying to achieve:</p> <ol> <li>instantiate a new instance of the class with the $startURL as the constructor</li> <li>spider $startURL with the public concurrentSpider() function</li> <li>foreach of the links found at that that URL, fork php, and in the child instantiate a new object for each of those links and spider it as well, concurrently.</li> </ol> <p>If the $startURL has 3 links, for example, I'm expecting for 3 processes to run simultaneously to retrieve the links from those pages. If each of those pages has 3 links, then I'm expecting 9 to then run simultaneously.</p> <p>Here is the code. There is only one public function, and the foreeach in the <code>public concurrentSpider($url)</code> function is where I am having problems, but I have included in entire class to be thorough.</p> <pre><code>class ConcurrentSpider { private $startURL; const DELAY = 1; const SLEEPTIME = 1; const ALLOW_OFFSITE = FALSE; private $maxChildren = 1; private $children = array(); function __construct($url) { // this is important if ALLOW_OFFSITE is FALSE // so that we have something to compare the url too. $this-&gt;startURL = $url; } public function concurrentSpider($url) { // STEP 1: // Download the $url $pageData = http_get($url, $ref = ''); if (!$this-&gt;checkIfSaved($url)) { $this-&gt;save_link_to_db($url, $pageData); } //print_r($pageData); sleep(self::SLEEPTIME); // STEP 2: // extract all links from this url's page data $linksOnThisPage = $this-&gt;harvest_links($url, $pageData); // STEP 3: // Check the links array from STEP 2 to see if the pages have // already been saved or is excluded because of any other // logic from the excluded_link() function $filteredLinks = $this-&gt;filterLinks($linksOnThisPage); //print_r($filteredLinks); // STEP 4: loop through each of the links and // repeat the process foreach ($filteredLinks as $filteredLink) { $pid = pcntl_fork(); switch ($pid) { case -1: print "Could not fork!\n"; exit(1); case 0: print "In child with PID: " . getmypid() . " processing $filteredLink \n"; //$this-&gt;concurrentSpider($filteredLink); // the above didn't work. let's try creating a new object // child unique variable based on $pid $var[$pid] = new ConcurrentSpider($this-&gt;startURL); $var[$pid]-&gt;concurrentSpider($filteredLink); sleep(2); exit(1); default: // print "$pid In the parent\n"; // Add an element to the children array $this-&gt;children[$pid] = $pid; // If the maximum number of children has been // achieved, wait until one or more return // before continuing. while (count($this-&gt;children) &gt;= $this-&gt;maxChildren) { $pid = pcntl_waitpid(0, $status); unset($this-&gt;children[$pid]); } } } } /** * extract URLs from a web page. * * @param type $pageData * @return type array $links on success, false on failure */ private function harvest_links($url, $pageData) { $link_array = array(); //get page base for $url $page_base = ResolveAddresses::get_base_page_address($url); $anchor_tags = parse_array($pageData['FILE'], '&lt;a', '&lt;/a&gt;', EXCL); //Put http attributes for each tag in array for ($xx = 0; $xx &lt; count($anchor_tags); $xx++) { $href = get_attribute($anchor_tags[$xx], "href"); $resolved_address = ResolveAddresses::resolve_address($href, $page_base); $link_array[] = $resolved_address; } return $link_array; } /** * Take an array of links and filter out * the ones that are not needed based on the * logic of the exclude_link() function. * * @param array $links * @return array */ private function filterLinks(array $links) { $filteredLinks = array(); foreach ($links as $link) { if (!$this-&gt;exclude_link($link, $filteredLinks)) { $filteredLinks[] = $link; } } print_r($filteredLinks); return $filteredLinks; } private function exclude_link($link, array $currentArray) { // TODO have this read from a file $exclusion_array = array(); $exclude = FALSE; if (in_array($link, $currentArray)) { $exclude = true; } // Exclude links that are Javascript commands if (stristr($link, "javascript")) { echo "Ignored JavaScript fuction: $link\n"; $exclude = true; } // Exclude links that contain # if (stristr($link, "#")) { echo "Ignored # in $link\n"; $exclude = true; } // Exclude links found in $exclusion_array for ($xx = 0; $xx &lt; count($exclusion_array); $xx++) { if (stristr($link, $exclusion_array[$xx])) { echo "Ignored excluded link: $link\n"; $exclude = true; } } // Exclude offsite links if requested if (self::ALLOW_OFFSITE === FALSE) { if ($this-&gt;get_domain($link) != $this-&gt;get_domain($this-&gt;startURL)) { //print get_domain($link) . " ". get_domain($SEED_URL)."\n"; echo "Ignored offsite link: $link\n"; $exclude = true; } } if ($exclude === FALSE) { // print "Added new link: $link \n"; } return $exclude; } /** * Compare against $startURL to make sure we are on same domain name. * @param type $url * @return type */ private function get_domain($url) { // Remove protocol from $url $url = str_replace("http://", "", $url); $url = str_replace("https://", "", $url); // Remove page and directory references if (stristr($url, "/")) $url = substr($url, 0, strpos($url, "/")); return $url; } private function checkIfSaved($url) { // Exclude redundant links // Check the database to see if the link was already saved. $sql = "select count(id) from url_data where url = '$url'"; $result = $conn-&gt;prepare($sql); $result-&gt;execute(); $number_of_rows = $result-&gt;fetchColumn(); if ($number_of_rows &gt; 0) { //print" Link: $link already exists in database\n"; return true; } return FALSE; } private function save_link_to_db($link, array $downloaded_data) { $sql = "insert into url_data values('', :raw_html, :stripped_html, :status, :error, :URL, 'N')"; $ps = $dbh-&gt;prepare($sql); // TODO test for success PDO execute statement $ps-&gt;execute(array(':raw_html' =&gt; preg_replace('/\s+/', ' ', strip_tags($downloaded_data['FILE'])), // serialize the entire array if we want all status data. for now, just // http return code is fine. //':status' =&gt; serialize($downloaded_data['STATUS']), ':status' =&gt; $downloaded_data['STATUS']['http_code'], ':error' =&gt; $downloaded_data['ERROR'], ':stripped_html' =&gt; preg_replace('/\s+/', ' ', strip_tags($downloaded_data['FILE'])), ':URL' =&gt; $link)); } } </code></pre> <p>Note the print statement in the child. This is a sample of that print out. $filteredLink is always the same link, which is element 0 of the filteredLinks array in the parent.</p> <pre><code>In child with PID: 4333 processing http://site.com/link.html In child with PID: 4334 processing http://site.com/link.html In child with PID: 4335 processing http://site.com/link.html </code></pre> <p>This seems to be an infinite loop.</p> <p>In the child, however, if I comment out the instantiation and use of the object, like this:</p> <pre><code>//$var[$pid] = new ConcurrentSpider($this-&gt;startURL); //$var[$pid]-&gt;concurrentSpider($filteredLink); </code></pre> <p>then the print statement prints correctly, and $filteredLink is link1.html, link2.html, link3.html, etc.</p> <p>What about my logic of trying to instantiate and use a new object in the child is causing it to loop indefinitely?</p>
[]
[ { "body": "<p>It look like the first link on every page of the site is the same (e.g. the link on a logo) and the children processes are simply printing this (correctly) so it looks like incorrect behavior, but isn't.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-04T14:48:09.880", "Id": "26985", "ParentId": "26913", "Score": "1" } } ]
{ "AcceptedAnswerId": "26985", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T09:54:10.260", "Id": "26913", "Score": "1", "Tags": [ "php", "multithreading", "concurrency" ], "Title": "Review of concurrent php logic for a web spider class" }
26913
<p>What is the best practice to output a list of prime numbers between two numbers? How can I achieve a better running time? This is a solution to a <a href="http://www.spoj.com/problems/PRIME1/" rel="nofollow">SPOJ problem</a> which is getting Time Limit Exceeded.</p> <pre><code>import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; class SPOJ2 { public static void main(String[] args) { try{ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int times = Integer.parseInt(reader.readLine().toString()); int temp=times-1; String[] input_string = new String[times]; int[] start_number = new int[times]; int[] end_number = new int[times]; int min_start_number=0, max_end_number=0; while(temp&gt;=0){ input_string[temp] = reader.readLine().toString(); --temp; } temp=times-1; while(temp&gt;=0){ String[] array_string = input_string[temp].split("\\s"); start_number[temp] = Integer.parseInt(array_string[0]); end_number[temp] = Integer.parseInt(array_string[1]); if(min_start_number == 0 || min_start_number &gt; start_number[temp]){ min_start_number = start_number[temp]; } if(max_end_number &lt; end_number[temp]){ max_end_number = end_number[temp]; } if(start_number[temp] &gt; end_number[temp]){ end_number[temp] = start_number[temp]+1; } --temp; } Prime prime_object = new Prime(); List&lt;Integer&gt; output_list = prime_object.primeBetween(min_start_number, max_end_number); temp = times-1; while(temp&gt;=0){ for(int count=0; count&lt;output_list.size(); count++){ if(output_list.get(count) &gt;= start_number[temp] &amp;&amp; output_list.get(count) &lt;= end_number[temp]){ System.out.println(output_list.get(count)); } } --temp; if(temp != times) System.out.println(""); } }catch(Exception e){ return; } } } class Prime { public List&lt;Integer&gt; primeBetween(int start_number, int end_number){ int last_check_number = (int)Math.sqrt(end_number); int start_check_number = (int)Math.sqrt(start_number); List&lt;Integer&gt; primes_list = new ArrayList&lt;Integer&gt;(); for(int count=2; count&lt;=end_number; count++){ primes_list.add(count); } for(int outer_i=0; (primes_list.get(outer_i)&lt;=start_check_number || (primes_list.get(outer_i)&gt;start_check_number &amp;&amp; primes_list.get(outer_i)&lt;last_check_number)); outer_i++){ for(int inner_i=outer_i; primes_list.get(inner_i)&lt;last_check_number; inner_i++){ int check_number = primes_list.get(inner_i); for(int temp=2; (temp*check_number)&lt;=end_number; temp++){ primes_list.remove(new Integer(temp*check_number)); } } } return primes_list; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T12:58:02.073", "Id": "41723", "Score": "3", "body": "The best practice is to take your problem and break it into many tiny steps. I can't guarantee it will run faster. I can guarantee it will be easier for mere mortals to understand." } ]
[ { "body": "<p>I followed my own advice, and broke the <a href=\"http://www.spoj.com/problems/PRIME1/\" rel=\"nofollow\">SPOJ problem</a> into many tiny steps.</p>\n\n<p>The first thing I did was create a class to hold the prime ranges that are given as input. The <code>PrimeRange</code> class is a basic getter/setter class for a range of numbers.</p>\n\n<pre><code>public class PrimeRange {\n\n private int minimum;\n private int maximum;\n\n public PrimeRange(int minimum, int maximum) {\n this.minimum = minimum;\n this.maximum = maximum;\n }\n\n public int getMinimum() {\n return minimum;\n }\n\n public int getMaximum() {\n return maximum;\n }\n\n @Override\n public String toString() {\n StringBuilder builder = new StringBuilder();\n builder.append(\"Prime range - minimum: \");\n builder.append(getMinimum());\n builder.append(\", maximum: \");\n builder.append(getMaximum());\n\n return builder.toString();\n }\n\n}\n</code></pre>\n\n<p>Next, I created a class that would give me all of the prime numbers from a minimum value to a maximum value.</p>\n\n<p>First, I calculated all of the prime numbers up to the square root of the maximum. Then, using those prime numbers, I calculated all of the prime numbers from the minimum to the maximum.</p>\n\n<p>This is the fastest algorithm I can think of for calculating large prime numbers.</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.List;\n\npublic class PrimeList {\n\n private List&lt;Integer&gt; primeFactors;\n private List&lt;Integer&gt; primeAnswers;\n\n private PrimeRange primeRange;\n\n public PrimeList(PrimeRange primeRange) {\n this.primeRange = primeRange;\n this.primeFactors = new ArrayList&lt;Integer&gt;();\n this.primeAnswers = new ArrayList&lt;Integer&gt;();\n calculateDivisorPrimes();\n calculateAnswerPrimes();\n }\n\n private void calculateDivisorPrimes() {\n primeFactors.add(2);\n primeFactors.add(3);\n primeFactors.add(5);\n\n int maxValue = primeRange.getMaximum();\n int maxSqrt = (int) Math.round(Math.pow((double) maxValue, 0.5D));\n\n for (int test = 7; test &lt;= maxSqrt; test += 2) {\n boolean testPassed = true;\n int sqrt = (int) Math.round(Math.pow((double) test, 0.5D));\n for (int divisor : primeFactors) {\n if (divisor &gt; sqrt) {\n break;\n }\n if (test % divisor == 0) {\n testPassed = false;\n break;\n }\n }\n if (testPassed) {\n primeFactors.add(test);\n }\n }\n }\n\n private void calculateAnswerPrimes() {\n int minValue = primeRange.getMinimum();\n int maxValue = primeRange.getMaximum();\n for (int test = minValue; test &lt;= maxValue; test++) {\n boolean testPassed = true;\n int sqrt = (int) Math.round(Math.pow((double) test, 0.5D));\n for (int divisor : primeFactors) {\n if (test == 1) {\n testPassed = false;\n break;\n }\n if (test == divisor) {\n break;\n }\n if (divisor &gt; sqrt) {\n break;\n }\n if (test % divisor == 0) {\n testPassed = false;\n break;\n }\n }\n if (testPassed) {\n primeAnswers.add(test);\n }\n }\n }\n\n public List&lt;Integer&gt; getPrimeAnswers() {\n return primeAnswers;\n }\n\n}\n</code></pre>\n\n<p>Now that we've taken these tiny steps, we can put them together to solve the problem.</p>\n\n<pre><code>import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class PrimeInput implements Runnable {\n\n private List&lt;PrimeRange&gt; primeRanges = new ArrayList&lt;PrimeRange&gt;();\n\n @Override\n public void run() {\n BufferedReader reader = new BufferedReader(new InputStreamReader(\n System.in));\n try {\n // First line contains count of subsequent lines\n String line = reader.readLine();\n int count = Integer.parseInt(line);\n\n // Read subsequent prime ranges\n for (int i = 0; i &lt; count; i++) {\n line = reader.readLine();\n PrimeRange primeRange = processLine(line);\n primeRanges.add(primeRange);\n }\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n try {\n if (reader != null) {\n reader.close();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n for (PrimeRange primeRange : primeRanges) {\n PrimeList primeList = new PrimeList(primeRange);\n for (Integer prime : primeList.getPrimeAnswers()) {\n System.out.println(prime);\n }\n System.out.println(\" \");\n }\n\n }\n\n private PrimeRange processLine(String line) {\n String[] range = line.split(\" \");\n int minimum = Integer.parseInt(range[0]);\n int maximum = Integer.parseInt(range[1]);\n return new PrimeRange(minimum, maximum);\n }\n\n public static void main(String[] args) {\n new PrimeInput().run();\n }\n}\n</code></pre>\n\n<p>I tested this Java application with large numbers, up to 1,000,000,000. The time was taken by the application writing numbers to <code>System.out</code>.</p>\n\n<p>I don't know if this code is fast enough for the SPOJ.</p>\n\n<p>I do know that this code is far easier to understand, because I broke the problem into tiny pieces and solved each tiny piece separately.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T14:17:42.713", "Id": "26930", "ParentId": "26916", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-03T11:32:10.303", "Id": "26916", "Score": "4", "Tags": [ "java", "programming-challenge", "primes", "time-limit-exceeded" ], "Title": "Outputting prime numbers between two numbers" }
26916