body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>Can someone please review this simple code for printing all paths in a matrix from bottom left to top right? If an element is 1, it is a "wall" and you cannot take it. </p> <p>Possible steps: up and right</p> <pre><code> // Prints possible paths from bottom left to top right public static void findPath(int n, int i , int j, int[][] mat,ArrayList&lt;Integer&gt; path) { if(i==0 &amp;&amp; j==n-1) { System.out.println(); for(Integer step: path) { System.out.print(","+step); } } if(isPossibleStep(i+1,j,n,mat)) { path.add(i+1); findPath(n,i+1, j,mat, path); } else if(isPossibleStep(i,j-1,n,mat)) { path.add(j-1); findPath(n,i, j-1,mat, path); } } // Tells if a given path is possible public static boolean isPossibleStep(int i, int j, int n,int[][] mat) { if(mat[i][j]==1) return false; if(i &lt; n &amp;&amp; j &gt; 0) return true; else return false; } </code></pre> <p>Also, how do I print just 1 possible path and then exit? It seems like a simple change but I am not able to think of a graceful way of doing it.</p>
[]
[ { "body": "<p>You can refactor the <code>findPath</code> logic somewhat and reduce the indent level while preserving the method's behavior:</p>\n\n<pre><code>// Prints possible paths from bottom left to top right\npublic static void findPath(int n, int i , int j, int[][] mat, ArrayList&lt;Integer&gt; path)\n{\n if(i == 0 &amp;&amp; j == n - 1)\n {\n System.out.println();\n for(Integer step: path)\n {\n System.out.print(\",\" + step);\n }\n }\n\n boolean rightStep = isPossibleStep(i + 1, j, n, mat); \n if(!isPossibleStep(i, j - 1, n, mat) &amp;&amp; !rightStep)\n return;\n\n path.add(rightStep ? ++i : --j);\n findPath(n, i, j, mat, path); \n}\n</code></pre>\n\n<p><code>isPossibleStep</code> can also be simplified by use of short-circuit logic. The following expresses the intent more directly with the benefit of being terse:</p>\n\n<pre><code>public static boolean isPossibleStep(int i, int j, int n, int[][] mat)\n{\n return mat[i][j] != 1 \n &amp;&amp; i &lt; n \n &amp;&amp; j &gt; 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T14:28:03.077", "Id": "4763", "Score": "0", "body": "Good notes, but the method `isPossibleStep` is still faulty, since the boundaries checks must be done *before* accessing the array. I've suggested a fix in my answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T08:22:48.363", "Id": "3159", "ParentId": "3156", "Score": "1" } }, { "body": "<p>I wonder what's the use of adding just <code>i+1</code> or <code>j-1</code> to the path. Shouldn't the path be composed of index pairs <code>(i,j)</code>?</p>\n\n<p>Building upon Victor's answer, here are some more optimizations:</p>\n\n<pre><code>public static void findPath(int n, int i, int j, int[][] mat, ArrayList&lt;Integer&gt; path) {\n if (i == 0 &amp;&amp; j == n-1) {\n System.out.println(path); // (1)\n }\n\n Integer step; // (2)\n if (isPossibleStep(i + 1, j, n, mat)) {\n step = ++i;\n } else if (isPossibleStep(i, j - 1, n, mat)) {\n step = --j;\n } else {\n return;\n }\n\n path.add(step);\n findPath(n, i, j, mat, path);\n}\n\npublic static boolean isPossibleStep(int i, int j, int n, int[][] mat) {\n return i &lt; n &amp;&amp; j &gt;= 0 // (3)\n &amp;&amp; mat[i][j] != 1;\n}\n</code></pre>\n\n<p>Notes:</p>\n\n<ol>\n<li><p>Instead of looping over the collection to print it, <code>ArrayList</code>'s <code>toString()</code> method can do that (with better performance). If you don't want to print the square brackets, just do a substring:</p>\n\n<pre><code>String pathStr = path.toString();\nSystem.out.println(pathStr.substring(1, pathStr.length()-1);\n</code></pre></li>\n<li><p>The code surrounding the temporary <code>step</code> variable can be simplified if you use index pairs to represent the path.</p></li>\n<li><p>The method <code>isPossibleStep</code> must check the indices <em>before</em> it tries to access the matrix. Otherwise you could end up with an <code>ArrayIndexOutOfBoundsException</code>. Also note that I'm checking for <code>j &gt;= 0</code>, because <code>0</code> is a valid index. (You should also check that <code>i &gt;= 0 &amp;&amp; j &lt; n</code> to be safe.)</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T10:00:44.843", "Id": "3162", "ParentId": "3156", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T03:54:51.573", "Id": "3156", "Score": "1", "Tags": [ "java", "algorithm", "matrix" ], "Title": "Matrix bottom left to top right" }
3156
<p>Can someone please review this code for me? I have not implemented all the methods for simplicity.</p> <pre><code>/** * Implements a blocking bounded queue from a given non-blocking unbounded queue implementation */ abstract class DerivedQueue&lt;E&gt; implements Queue&lt;E&gt; { DerivedQueue(Queue&lt;E&gt; queue, int size) { if(queue==null | size &lt;0) { throw new RuntimeException("Bad Input"); } fQueue = queue; fSize = size; } Queue&lt;E&gt; fQueue; int fSize; int fCnt; @Override public boolean addAll(Collection&lt;? extends E&gt; arg0) { return false; } @Override public boolean isEmpty() { return (fCnt==0); } public E remove() { if(fCnt==0) { try { wait(); } catch (InterruptedException e) { throw new RuntimeException("Waiting thread was interrupted during remove with msg:",e); } } E elem = fQueue.remove(); fCnt--; notifyAll(); return elem; } @Override public boolean add(E elem) { if(fCnt == fSize) { try { wait(); } catch (InterruptedException e) { throw new RuntimeException("Waiting thread was interrupted during remove with msg:",e); } } return fQueue.add(elem); } } </code></pre> <p>Open questions: </p> <ol> <li><p>Would calling <code>notifyAll()</code> lead to multiple waiting threads checking the <code>while()</code> condition at the same time, and hence there is a possibility that before the while gets satisfied, 2 threads are already out of it causing an outOfBound exception? Or does the methods need to be marked <code>synchronized</code> at all, and instead I can use a <code>synchronized</code> block for reading or writing part of the array while the checking of constrained and waiting can remain unsynchronized?</p></li> <li><p>Is there a way to notify precisely only the consumer threads (waiting in take) or only the producer (waiting input) threads in this example? <code>notifyAll</code> notifies all of them.</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T06:41:52.780", "Id": "4886", "Score": "0", "body": "Logical OR is done using a double-pipe `||`. A single pipe `|` is for bitwise OR." } ]
[ { "body": "<p>In my oppinion class variables should always be defined first - even before the constructor. Another issue: why are your variables prefixed with <code>f</code>? Rename to something less-confusing instead. Especially <code>fSize</code> and <code>fCnt</code> are quite close to each other. (Suggesting <code>maxSize</code> and <code>currentSize</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T05:39:18.580", "Id": "4831", "Score": "0", "body": "thnx I have made some echanges, I use f to denote Class fields and distinguish them from local/method level fields" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T08:20:18.543", "Id": "4836", "Score": "0", "body": "@p101 I use this. to use class fields ;) I know this is not required in java... but as you probably noticed - this doesn't increase readability." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T09:02:22.220", "Id": "3160", "ParentId": "3157", "Score": "2" } }, { "body": "<p>Your implementation is not threadsafe: Imagine the queue is empty, and several threads which want to remove an element are waiting. Then an element is added and <strong>all</strong> waiting threads are notified. Then they all try <strong>without further tests</strong> to remove an element, which will work only for the first thread, the next one will cause an underflow. Same scenario for several threads waiting to add.</p>\n\n<p>So either fix the problem or add a comment with a \"not threadsafe\" warning.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T06:25:17.690", "Id": "3215", "ParentId": "3157", "Score": "2" } }, { "body": "<p>This problem screams \"<a href=\"http://en.wikipedia.org/wiki/Semaphore_%28programming%29\"><b>semaphore</b></a>\".</p>\n\n<p>Have a semaphore whose count represents the number of slots available in the queue. Enqueuers decrement the semaphore. Dequeuers increment it. This effectively caps the amount of nodes in the queue to some maximum, namely the initial value of the semaphore.</p>\n\n<p>Likewise you can have a different semaphore represent the number of items currently enqueued. In this case dequeuers decrement it and enqueuers increment. For this one, the initial value is zero. This allows dequeuers to block until an item is available.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T06:42:20.750", "Id": "3216", "ParentId": "3157", "Score": "5" } }, { "body": "<p>I could see two more issue with the above code:</p>\n\n<ol>\n<li>These is missing increment to <code>fCurrrentCnt++</code> in the <code>add</code> method.</li>\n<li>This will result in deadlock, if try to call <code>remove</code> first and then <code>add</code>. Both will wait for each other.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T08:47:17.887", "Id": "3420", "ParentId": "3157", "Score": "1" } }, { "body": "<p>You don't need to implement this yourself. <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ArrayBlockingQueue.html\" rel=\"nofollow\"><code>ArrayBlockingQueue</code></a> already is in the JRE. You can use <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ArrayBlockingQueue.html#take%28%29\" rel=\"nofollow\"><code>ArrayBlockingQueue.take</code></a> instead of the <code>remove</code> method and <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ArrayBlockingQueue.html#put%28E%29\" rel=\"nofollow\"><code>ArrayBlockingQueue.put</code></a> instead of the <code>add</code> method.</p>\n\n<p>See also: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em></p>\n\n<p>Anyway, it does not seem completely thread-safe. The <code>fCurrrentCnt</code> field in the <code>isEmpty</code> method is read without any <code>synchronized</code> block.</p>\n\n<blockquote>\n <p>[...] synchronization has no effect unless both read and write operations are synchronized.</p>\n</blockquote>\n\n<p>From <em>Effective Java, 2nd Edition, Item 66: Synchronize access to shared mutable data</em>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-28T09:58:18.787", "Id": "18012", "ParentId": "3157", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T06:25:56.973", "Id": "3157", "Score": "2", "Tags": [ "java", "multithreading", "interview-questions", "queue" ], "Title": "Bounded blocking queue" }
3157
<p>I've written the following SQL to count the number of times the name 'Cthulhu' turns up for each tag on Stack Overflow (original <a href="http://data.stackexchange.com/stackoverflow/s/1527/cthulhu-fhtagn" rel="nofollow">here</a>):</p> <pre><code>select t.TagName, count (*) 'Tainted' from Posts p, Tags t, PostTags pt where p.Body like '%cthulhu%' and (pt.PostId = p.Id and t.Id = pt.TagId) group by t.TagName order by Tainted DESC, t.TagName ASC </code></pre> <p>It works, but I'm not used to cutting SQL manually; I'm more accustomed to using ORMs. I tried using <code>CONTAINS</code> instead of <code>LIKE</code>, but apparently <code>Body</code> isn't set up for full-text search.</p> <p>Could you please provide me some feedback - in particular, are there any best practices I'm missing, and whether there are standard formatting rules for SQL that would make it a bit easier on the eye?</p>
[]
[ { "body": "<pre><code>select t.TagName, count (*) 'Tainted'\n from Posts p\n inner join PostTags pt on (pt.PostId == p.Id)\n inner join Tags t on (t.Id == pt.TagId)\n where lower(p.Body) like '%cthulhu%'\n group by t.TagName\n order by Tainted desc, t.TagName asc\n</code></pre>\n\n<ul>\n<li>Notice the <code>lower</code> on the body, because <code>like</code> is (should?) be case sensitive.</li>\n<li>The joins are also easier to read IMHO than the conditions in the where clause.</li>\n<li>The formatting is based on right-aligning keywords and left-aligning clauses.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T15:13:57.640", "Id": "4770", "Score": "0", "body": "Like *is* case sensitive. Formatting suggestion...capitalize the SQL keywords? You have ASC and DESC caps, but otherwise all lower case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T07:20:48.827", "Id": "4834", "Score": "0", "body": "@Michael K.: Thanks for your notes. I said that `like` \"should\" be case sensitive just to be on the safe side (in case a DBMS such as SQL Server or MySQL has an option to make it insensitive). I didn't notice the casing of the words `ASC` and `DESC` when I copied them. I have corrected them; thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T07:21:14.193", "Id": "4835", "Score": "0", "body": "As for capitalization, I prefer to use small letters as long as I have syntax highlighting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T12:53:36.327", "Id": "4841", "Score": "1", "body": "@Hosam Consistency trumps preference for me. I care less about the style than whether it's applied universally :) Good point about other DBMS's." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T12:57:53.513", "Id": "4842", "Score": "0", "body": "@Michael K: Isn't it case-sensitive simply because the collation for `p.Body` is case-sensitive? Because this simple test shows that generally speaking, LIKE is *not* case-sensitive: `SELECT * FROM (SELECT 'A' UNION ALL SELECT 'sad' UNION ALL SELECT 'good-bye') x (f) WHERE f LIKE '%A%'`. This returns two rows on my computer (SQL Server 2008 R2) as well as in SE Data Explorer (don't know what server they use)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T13:07:17.013", "Id": "4843", "Score": "0", "body": "@Andriy: It sounds like it isn't case sensitive by default on SQL Server then. I know it is on DB2, and it looks like [Oracle has a setting](http://www.orafaq.com/node/91) for it. A quick search didn't reveal anything either way about MySQL." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T10:06:39.053", "Id": "3163", "ParentId": "3158", "Score": "2" } } ]
{ "AcceptedAnswerId": "3163", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T06:32:25.100", "Id": "3158", "Score": "5", "Tags": [ "sql", "stackexchange" ], "Title": "Finding the use of the word 'Cthulhu' in tags on Stack Overflow" }
3158
<p>I have a list of <code>checkboxes</code> styled using JQuery UI as buttons. Each have a <code>data-price</code> attributem containing a price in this format: <code>data-price="40.00"</code>, <code>data-price="25.00"</code> etc.</p> <p>When the user "checks" a box, I am adding it's <code>data-price</code> to the <code>totalPrice</code> var. Every time another box is clicked, it's own <code>data-price</code> is added to the total. If the user unchecks a boxm, that value is taken away. I have tried to prevent the value from going under 0.00 as well.</p> <p>I then output the <code>totalPrice</code> into a div - <code>totalBox</code>.</p> <pre><code>&lt;script type="text/javascript"&gt; totalPrice = 0.00; $(function() { var totalBox = $('#totalBox'); $( ".styled" ).button().bind('click', function() { var packagePrice = $(this).attr('data-price'); var cost = parseFloat(packagePrice); if(totalPrice&gt;=0.00) { if($(this).is(':checked')) { totalPrice += cost; } else { totalPrice -= cost; } } totalBox.html('&lt;span class="total"&gt;Total:&lt;/span&gt; &lt;span class="price"&gt;&amp;pound;' + totalPrice.toFixed(2) + '&lt;/span&gt;' ); }); }); &lt;/script&gt; </code></pre> <p>I imagine there are some optimisations here - any thoughts?</p>
[]
[ { "body": "<p>When working with prices, then in my opinion it's usually a good idea to avoid floating point numbers. Binary rounding errors can easily strike unexpectedly any time. </p>\n\n<p>Instead I'd suggest to work with integers (thus pennies) internally, and just add the decimal point for output.</p>\n\n<p>An other unrelated point: I would move the hard-coded HTML in the script to the HTML document and only write the price.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T12:47:23.757", "Id": "4840", "Score": "0", "body": "Good point about the integers, and I also agree with the HTML now that you mention it, thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T12:26:12.567", "Id": "3165", "ParentId": "3164", "Score": "2" } }, { "body": "<p>Few things:</p>\n\n<ol>\n<li><p>The <code>totalPrice</code> variable should be declared inside your <code>document.onready</code> callback (and remember about <code>var</code> keyword). You should avoid global variables declaration.</p></li>\n<li><p>You can prefix all variables which contain jquery object with <code>$</code> sign to make code more readable.</p></li>\n</ol>\n\n\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n\n $(function() {\n var totalPrice = 0.00;\n var $totalBox = $('#totalBox');\n\n $( \".styled\" ).button().bind('click', function() {\n var packagePrice = $(this).attr('data-price');\n var cost = parseFloat(packagePrice);\n\n if(totalPrice&gt;=0.00) {\n if($(this).is(':checked')) {\n totalPrice += cost;\n } else {\n totalPrice -= cost;\n }\n }\n\n $totalBox.html('&lt;span class=\"total\"&gt;Total:&lt;/span&gt;\n &lt;span class=\"price\"&gt;&amp;pound;' \n + totalPrice.toFixed(2) + '&lt;/span&gt;'\n );\n });\n });\n&lt;/script&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-11-24T21:44:26.600", "Id": "181259", "ParentId": "3164", "Score": "1" } } ]
{ "AcceptedAnswerId": "3165", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T11:24:58.170", "Id": "3164", "Score": "2", "Tags": [ "javascript", "jquery", "jquery-ui" ], "Title": "jQuery UI button and some calculations" }
3164
<p>I wrote the following code to insert records into a database. The user selects the rows from the <code>RadGrid</code> and the insert command is executed when that user clicks the button. I've been spending a lot of time trying to make this work (nothing currently happens when I click the button). However, I just realized my approach is probably very inefficient due to the fact that it will result in the application repeatedly opening and closing database connections. Even though I'm dealing with only a few hundred records I'd like to follow best practices as much as possible.</p> <p>How would you rewrite this code to be more efficient? My gut tells me it would be better to gather all of the new records and then deal with them as a collection.</p> <pre><code> protected void RadButton2_Click(object sender, EventArgs e) { foreach (GridDataItem item in RadGrid1.SelectedItems) { //GridDataItem item = (GridDataItem)RadGrid1.SelectedItems; int UserID = Convert.ToInt16(item["UserID"].Text); string Type = "D"; DateTime Date = DateTime.Now; string Description = "Monthly Storage Fee - Tag: " + item["PackageTag"].Text + Label3.Text; Int32 AmountDue = Convert.ToInt32(item["AmtDue"].Text); string connectionString = ConfigurationManager.ConnectionStrings["Foo"].ConnectionString; SqlConnection connection = new SqlConnection(connectionString); try { SqlCommand cmd = new SqlCommand("INSERT INTO Billing (UserID, Type, Date, Description, Amount) VALUES (@UserID, @Type, @Date, @Description, @AmountDue)", connection); cmd.Parameters.AddWithValue("@UserID", UserID); cmd.Parameters.AddWithValue("@Type", Type); cmd.Parameters.AddWithValue("@Date", Date); cmd.Parameters.AddWithValue("@Description", Description); cmd.Parameters.AddWithValue("@AmountDue", AmountDue); connection.Open(); cmd.ExecuteNonQuery(); } catch { Label4.Text = "uh oh"; } finally { connection.Close(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T13:47:42.707", "Id": "4758", "Score": "2", "body": "ADO.NET will actually not dispose or open/close the connection behind the scenes but decides whether to reuse an existing connection with enabled [Connection Pooling](http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx)(default). So yes, it's recommendet to open/close connections or use the [using-keyword](http://msdn.microsoft.com/en-us/library/yh598w02%28v=vs.80%29.aspx)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T14:22:32.957", "Id": "4762", "Score": "0", "body": "Are you by chance connecting to a SQL Server 2008 database? If so, you could work with the database developers to create a stored procedure that takes a table variable as an input parameter and inserts all the rows into the database at the same time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T14:39:01.903", "Id": "4765", "Score": "0", "body": "Yes I am actually. Interesting suggestion. I'm going to investigate that. For this project _I_ am the database developer too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T15:57:23.753", "Id": "4771", "Score": "0", "body": "Added some articles to get you started with TVP's as an answer." } ]
[ { "body": "<p>The insert block itself is alright: it safe and clean. And it avoids <a href=\"http://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow\">SQL Injection</a>.</p>\n\n<p>However, you should consider moving your persistent code away from the UI code. Try working in layers. There are some design patterns about the subject you should take a look.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T14:14:40.473", "Id": "4761", "Score": "0", "body": "Thanks. I plan to add layers for data access and business logic later. For the moment it's just simpler for me to work with fewer layers as I'm still learning." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T13:46:06.440", "Id": "3171", "ParentId": "3170", "Score": "0" } }, { "body": "<p>This is not best practice but simple logic.</p>\n\n<p>Why you have add inside the loop this (non change) parameters ?</p>\n\n<pre><code> string Type = \"D\";\n DateTime Date = DateTime.Now;\n string connectionString = \n ConfigurationManager.ConnectionStrings[\"Foo\"].ConnectionString;\n</code></pre>\n\n<p>Get them out of the loop.</p>\n\n<p>Second place the connection inside using, and totally outside the loop, why you need to open it and close it all the time.</p>\n\n<pre><code>protected void RadButton2_Click(object sender, EventArgs e)\n{\n //GridDataItem item = (GridDataItem)RadGrid1.SelectedItems; \n string Type = \"D\";\n DateTime Date = DateTime.Now;\n\n string connectionString = ConfigurationManager.ConnectionStrings[\"Foo\"].ConnectionString;\n SqlConnection connection = new SqlConnection(connectionString);\n\n using(SqlConnection connection = new SqlConnection(connectionString))\n {\n connection.Open();\n foreach (GridDataItem item in RadGrid1.SelectedItems)\n {\n try\n {\n string Description = \"Monthly Storage Fee - Tag: \" + item[\"PackageTag\"].Text + Label3.Text;\n Int32 AmountDue = Convert.ToInt32(item[\"AmtDue\"].Text);\n int UserID = Convert.ToInt16(item[\"UserID\"].Text);\n\n using (SqlCommand cmd = new SqlCommand(\"INSERT INTO Billing (UserID, Type, Date, Description, Amount) VALUES (@UserID, @Type, @Date, @Description, @AmountDue)\", connection))\n {\n cmd.Parameters.AddWithValue(\"@UserID\", UserID);\n cmd.Parameters.AddWithValue(\"@Type\", Type);\n cmd.Parameters.AddWithValue(\"@Date\", Date);\n cmd.Parameters.AddWithValue(\"@Description\", Description);\n cmd.Parameters.AddWithValue(\"@AmountDue\", AmountDue);\n\n cmd.ExecuteNonQuery();\n }\n }\n catch\n {\n Label4.Text = \"uh oh\";\n }\n } \n }\n}\n</code></pre>\n\n<p>Need some extra test for check if the connection is open or fail</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T14:41:48.610", "Id": "4767", "Score": "0", "body": "Aristos, can you spot anything I may have done wrong? When I run the app nothing actually inserts into the database. I'm not noticing any exceptions either. edit: I'm going with your recommended code by the way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T15:02:06.610", "Id": "4769", "Score": "0", "body": "@hughesdan I belive that fail in the date, you need to format it in the SQL way, or declare that is a date. As you add it now, its convert it to string, and probably fails to insert." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T16:45:13.433", "Id": "4774", "Score": "0", "body": "That's probably what it is. And come to thing of it I could also use SQL GetDate()." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-21T17:47:35.513", "Id": "165907", "Score": "1", "body": "`SqlCommand` also implements `IDisposable` and should be placed within a `using` block." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-22T08:31:58.970", "Id": "165994", "Score": "0", "body": "@JesseC.Slicer Yes you have right, if you like please update the code." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T13:47:47.980", "Id": "3172", "ParentId": "3170", "Score": "6" } }, { "body": "<p>I don't see anything particular that you've done wrong. Re: your question about opening and closing a connection multiple times, I think there is actually less overhead in doing this vs. leaving a connection open, as it does not fully allow the server to manage connection pooling.</p>\n\n<p>And re: trying to batch these into one update/insert statement, I think this is more trouble than its worth. I've done that in the past, but it ends up being very painful (typically have to implement a solution like XML), and it doesn't yield much benefits. And if you look at more modern solutions, like ORMs, this is exactly how they implement it.</p>\n\n<p>The only thing you may need to consider, is if all of these records need to be wrapped in a transaction (all records need to be updated/inserted, or all need to be rolled back). If so, then you would need to alter it for that. But if not, then what you have, to me, is perfectly acceptable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T13:55:11.323", "Id": "4760", "Score": "0", "body": "Each insert is independent (they're only related from a workflow standpoint), so probably not necessary to wrap them in a transaction. Thanks for sharing your experience trying to batch transactions in the past. Have you tried batching them into a Data Table? I don't even know if that would work. I'm just reading about it now." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T13:48:10.943", "Id": "3173", "ParentId": "3170", "Score": "0" } }, { "body": "<p>Something like this: you'll need only 1 connection in this case</p>\n\n<pre><code>protected void RadButton2_Click(object sender, EventArgs e)\n{\n string connectionString = ConfigurationManager.ConnectionStrings[\"Foo\"].ConnectionString;\n SqlConnection connection = new SqlConnection(connectionString);\n connection.Open();\ntry\n{\nforeach (GridDataItem item in RadGrid1.SelectedItems)\n{\n //GridDataItem item = (GridDataItem)RadGrid1.SelectedItems;\n int UserID = Convert.ToInt16(item[\"UserID\"].Text);\n string Type = \"D\";\n DateTime Date = DateTime.Now;\n string Description = \"Monthly Storage Fee - Tag: \" + item[\"PackageTag\"].Text + Label3.Text;\n Int32 AmountDue = Convert.ToInt32(item[\"AmtDue\"].Text);\n\n\n\n try\n {\n\n SqlCommand cmd = new SqlCommand(\"INSERT INTO Billing (UserID, Type, Date, Description, Amount) VALUES (@UserID, @Type, @Date, @Description, @AmountDue)\", connection);\n cmd.Parameters.AddWithValue(\"@UserID\", UserID);\n cmd.Parameters.AddWithValue(\"@Type\", Type);\n cmd.Parameters.AddWithValue(\"@Date\", Date);\n cmd.Parameters.AddWithValue(\"@Description\", Description);\n cmd.Parameters.AddWithValue(\"@AmountDue\", AmountDue);\n cmd.ExecuteNonQuery();\n }\n\n catch\n {\n Label4.Text = \"uh oh\";\n }\n\n finally\n {\n\n }\n}\n}\ncatch\n{\n\n}\nfinally\n{\n connection.Close();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T13:48:21.983", "Id": "3174", "ParentId": "3170", "Score": "1" } }, { "body": "<p>My take on it:</p>\n\n<pre><code>protected void RadButton2_Click(object sender, EventArgs e)\n{\n\nstring connectionString = ConfigurationManager.ConnectionStrings[\"Foo\"].ConnectionString;\nSqlConnection connection = new SqlConnection(connectionString);\nSqlCommand cmd = new SqlCommand(\"INSERT INTO Billing (UserID, Type, Date, Description, Amount) VALUES (@UserID, @Type, @Date, @Description, @AmountDue)\", connection);\n\n try\n {\n connection.Open();\n\n foreach (GridDataItem item in RadGrid1.SelectedItems)\n {\n GridDataItem item = (GridDataItem)RadGrid1.SelectedItems;\n int UserID = Convert.ToInt16(item[\"UserID\"].Text);\n string Type = \"D\";\n DateTime Date = DateTime.Now;\n string Description = \"Monthly Storage Fee - Tag: \" + item[\"PackageTag\"].Text + Label3.Text;\n Int32 AmountDue = Convert.ToInt32(item[\"AmtDue\"].Text);\n\n cmd.Parameters.Clear();\n cmd.Parameters.AddWithValue(\"@UserID\", UserID);\n cmd.Parameters.AddWithValue(\"@Type\", Type);\n cmd.Parameters.AddWithValue(\"@Date\", Date);\n cmd.Parameters.AddWithValue(\"@Description\", Description);\n cmd.Parameters.AddWithValue(\"@AmountDue\", AmountDue);\n\n cmd.ExecuteNonQuery();\n }\n }\n catch\n {\n Label4.Text = \"uh oh\";\n }\n\n finally\n {\n connection.Close();\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T13:52:33.600", "Id": "3175", "ParentId": "3170", "Score": "0" } }, { "body": "<p>ADO.NET will utilize Connection pooling if the connection string itself is identical each time, and will remove the overhead associated with the network.</p>\n\n<p>The advantages of opening/closing a connection during operations like this is that if your code will do time consuming stuff, then the connection will be available to other threads in the application, and lessen the number of simultaneous connection that you use. Of course, it all depends on design.</p>\n\n<p>You could either open close it before the loop, or do what you are doing. I would say that if your iterations are in the range of milliseconds, then open and close it once for the whole loop to minimize the slight overhead as well as object instantiation and memory usage. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T13:52:44.947", "Id": "3176", "ParentId": "3170", "Score": "1" } }, { "body": "<ol>\n<li>I don't think it is a good idea to have the database calling code in the UI page. See <a href=\"https://stackoverflow.com/questions/1035439/database-access-in-gui-thread-bad-isnt-it\">here</a></li>\n<li>Have you considered creating a data-layer using Entity Framework (or Linq2SQL). Then instead of writing all the queries manually, you can deal with the typed objects.</li>\n<li>While you should do what Aristos pointed out in any case (Even with EF, you should create the context at the level suggested by Aristos for the connection)</li>\n<li>After that perhaps you can use <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx\" rel=\"nofollow noreferrer\">System.Threading.Tasks</a> or a background worker to do the saving in a separate thread. </li>\n<li>I can see you are doing string concatenation with \"+\", consider using string.concat or string.format.</li>\n<li>Instead of using Convert.ToInt32(item[\"AmtDue\"].Text) consider using int.TryParse() pattern to convert text to int.</li>\n<li>Consider using FxCop to detect potential issues in the code.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T15:43:59.460", "Id": "3181", "ParentId": "3170", "Score": "1" } }, { "body": "<p>As long as you have access to SQL Server 2008, you can take advantage of TVP (Table Valued Parameters) which is a feature that was added to the 2008 version.</p>\n\n<p>Here are two articles that will help you get started. The first article has one key piece of information that's easy to miss when you're first getting started with TVP's. You not only have to define the table type, you have to grant execute rights to the new TVP type:</p>\n\n<ol>\n<li><a href=\"http://www.sqlteam.com/article/sql-server-2008-table-valued-parameters\" rel=\"nofollow\">http://www.sqlteam.com/article/sql-server-2008-table-valued-parameters</a></li>\n<li><a href=\"http://blog.sqlauthority.com/2008/08/31/sql-server-table-valued-parameters-in-sql-server-2008/\" rel=\"nofollow\">http://blog.sqlauthority.com/2008/08/31/sql-server-table-valued-parameters-in-sql-server-2008/</a></li>\n</ol>\n\n<p>Please note that while TVP's themselves are readonly, you can use them to directly insert into a table which will give you even greater protection from SQL injection and will reduce the number of round trips to and from the database in order to insert a small batch of records into your database.</p>\n\n<p>Hope this helps!</p>\n\n<p>Jeff</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T15:56:07.483", "Id": "3182", "ParentId": "3170", "Score": "2" } }, { "body": "<p>One other thing I noticed when looking at the other answers is that not only were you building the connection within the inner loop, you were building the query command multiple times as well.</p>\n\n<p>It's been a while since I've done much non-SQL coding, but I think what you're looking for should be more along the following lines. You shouldn't have to clear out your parameter list between calls. Also, if the UserID is the same on your form for each row, I would only do that conversion once as well.</p>\n\n<p>I've tried to extend the example Aristos provided by pulling even more out of the foreach loop and only creating the SqlCommand once to use between all of the calls.</p>\n\n<pre><code>protected void RadButton2_Click(object sender, EventArgs e)\n{\n try\n {\n string Type = \"D\";\n DateTime Date = DateTime.Now;\n\n string connectionString = ConfigurationManager.ConnectionStrings[\"Foo\"].ConnectionString;\n SqlConnection connection = new SqlConnection(connectionString);\n connection.Open();\n\n SqlCommand cmd = new SqlCommand(\"INSERT INTO Billing (UserID, Type, Date, Description, Amount) VALUES (@UserID, @Type, @Date, @Description, @AmountDue)\", connection);\n\n cmd.Parameters.Add(\"@UserID\", SqlDbType.Int);\n cmd.Parameters.Add(\"@Type\", SqlDbType.Int);\n cmd.Parameters.Add(\"@Date\", SqlDbType.Datetime);\n cmd.Parameters.Add(\"@Description\", SqlDbType.NChar, 80);\n cmd.Parameters.Add(\"@AmountDue\", SqlDbType.Money);\n\n cmd.Parameters(\"@Type\").Value = Type;\n cmd.Parameters(\"@Date\").Value = Date;\n\n foreach (GridDataItem item in RadGrid1.SelectedItems)\n {\n //GridDataItem item = (GridDataItem)RadGrid1.SelectedItems;\n int UserID = Convert.ToInt16(item[\"UserID\"].Text);\n string Description = \"Monthly Storage Fee - Tag: \" + item[\"PackageTag\"].Text + Label3.Text;\n Int32 AmountDue = Convert.ToInt32(item[\"AmtDue\"].Text);\n\n //Change only the parameters that are different between calls.\n cmd.Parameters.(\"@UserID\", UserID); \n cmd.Parameters(\"@Description\", Description);\n cmd.Parameters(\"@AmountDue\", AmountDue);\n\n cmd.ExecuteNonQuery();\n }\n }\n catch\n {\n Label4.Text = \"uh oh\";\n }\n finally\n {\n connection.Close();\n }\n}\n</code></pre>\n\n<p>I would still recommend utilizing Table Valued Parameters if possible, but this should be more efficient on your database if you weren't able to use TVP's.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T13:34:47.397", "Id": "4800", "Score": "0", "body": "That's a great point Jeff. No reason to loop through the parameters. I noticed you also added the SqlDbTypes, which I had omitted. Thanks. I'm going to experiment with a version of this page that uses TVP's. They look very promising." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T22:43:33.700", "Id": "3189", "ParentId": "3170", "Score": "1" } }, { "body": "<p>Best practices are based on years of use. One thing bugs my eyes though: The SQL is a one liner:</p>\n\n<pre><code>INSERT INTO Billing (UserID, Type, Date, Description, Amount) VALUES (@UserID, @Type, @Date, @Description, @AmountDue)\n</code></pre>\n\n<p>Very hard to comprehend when scripts grow and I normally format an insert this way (easy to insert and remove fields, and the params can be copied directly):</p>\n\n<pre><code>INSERT INTO Billing \n(UserID\n,Type\n,Date\n,Description\n,Amount)\nVALUES\n(@UserID\n,@Type\n,@Date\n,@Description\n,@AmountDue)\n</code></pre>\n\n<p>.. making it easy to modify. I have done this in Delphi where the query-class is a TStrings.</p>\n\n<p>I don't do want to do as below, as it is destined to fail when you forget a space.</p>\n\n<pre><code>\"INSERT INTO Billing \" +\n\"(UserID \"+\n\",Type \"+\n\",Date \"+\n\",Description \"+\n\",Amount) \"+\n\"VALUES \"+\n\"(@UserID \"+\n\",@Type \"+\n\",@Date \"+\n\",@Description \"+\n\",@AmountDue)\";\n</code></pre>\n\n<p>The solution, that looks a lot like Delphi, is this:</p>\n\n<pre><code>List&lt;string&gt; l = new List&lt;string&gt;();\nl.Add(\"INSERT INTO Billing\");\nl.Add(\"(UserID\");\nl.Add(\",Type\");\nl.Add(\",Date\");\nl.Add(\",Description\");\nl.Add(\",Amount)\");\nl.Add(\"VALUES\");\nl.Add(\"(@UserID\");\nl.Add(\",@Type\");\nl.Add(\",@Date\");\nl.Add(\",@Description\");\nl.Add(\",@AmountDue)\");\nstring line = string.Join(\"\\n\",l.ToArray());\n</code></pre>\n\n<p>Of course this will be wrapped in a generic SQL-class</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-21T14:21:49.070", "Id": "91410", "ParentId": "3170", "Score": "1" } } ]
{ "AcceptedAnswerId": "3172", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T13:40:48.650", "Id": "3170", "Score": "6", "Tags": [ "c#", "asp.net", "sql" ], "Title": "Inserting records into a database" }
3170
<p>I've created this (very) contrived example that demonstrates how we currently organize page specific JS in our app. Basically each page has a matching JS file that uses the <a href="http://ajaxian.com/archives/a-javascript-module-pattern" rel="nofollow">module pattern</a> to enclose page specific behaviors. Each module has an <code>init()</code> function that takes control IDs and wires up events, etc.</p> <p>This has worked fairely well for us, however now we are wanting to add unit tests. Since many of our modules store state in private variables our unit tests end up stomping all over each other.</p> <p>I think we need to stop using these singleton modules and instead use instances so that we can write better tests. What are some ways we could restructure this type of code so that it would be testable?</p> <p><a href="http://jsfiddle.net/joshuapoehls/z4P3R/5/" rel="nofollow">JS Fiddle here...</a></p> <h2>HTML</h2> <pre><code>&lt;div&gt; &lt;input type="file" /&gt;&lt;br/&gt; &lt;input type="file" /&gt;&lt;br/&gt; &lt;input type="file" /&gt; &lt;/div&gt; &lt;p&gt; &lt;br/&gt; &lt;input id="btnUpload" type="button" value="Upload Files" /&gt; or &lt;a href="#" id="btnClear"&gt;Clear files&lt;/a&gt; &lt;/p&gt; &lt;script&gt; MyPage.init({ clearLink: '#btnClear', uploadBtn: '#btnUpload', fileCtrls: "input[type='file']" }); &lt;/script&gt; </code></pre> <h2>JS</h2> <pre><code>MyPage = (function() { // private members var _files = []; var _initOptions; // public members return { init: function(options) { _initOptions = options; $(function() { // wire up the events $(options.clearLink).click(MyPage.clear); $(options.uploadBtn).click(MyPage.doUpload); $(options.fileCtrls).change(MyPage.addFile); }); }, addFile: function() { _files.push($(this).val()); }, doUpload: function() { alert('uploading ' + _files.length + ' files...'); }, clear: function() { _files = []; $(_initOptions.fileCtrls).val(''); } } })(); </code></pre>
[]
[ { "body": "<pre><code>MyPage = (function() {\n var Page = {\n addFile: function(e) {\n this._files.push($(e.target).val());\n },\n\n doUpload: function() {\n alert('uploading ' + this._files.length + ' files...');\n },\n\n clear: function() {\n this._files = [];\n $(this.options.fileCtrls).val('');\n }\n }\n\n // public members\n return {\n init: function(options) {\n var o = Object.create(Page, {\n options: { value: options },\n _files: { value: [] }\n });\n\n $(function() {\n // wire up the events\n options.clearLink.click($.proxy(o.clear, o));\n options.uploadBtn.click($.proxy(o.doUpload, o));\n options.fileCtrls.change($.proxy(o.addFile, o));\n });\n },\n\n\n }\n})();\n</code></pre>\n\n<p>Using <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/create\" rel=\"nofollow\"><code>Object.create</code></a></p>\n\n<p><a href=\"http://jsfiddle.net/xgc7z/\" rel=\"nofollow\">Live Example</a></p>\n\n<p><a href=\"https://github.com/kriskowal/es5-shim\" rel=\"nofollow\">ES5-shim</a> for browser support.</p>\n\n<p>As for testing use any old testing framework you like. Use <code>jQuery.sub()</code> to mock out jQuery</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T16:43:00.703", "Id": "4772", "Score": "0", "body": "How would you test this? Also, what if you needed to support a browser that doesn't support Object.create (like IE8)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T16:59:08.423", "Id": "4777", "Score": "0", "body": "@JamesEggers you can test using any old framework you want. I would use QUnit personally. Just create a dummy markup on your test page and create new page objects. I tend to have a generict `resetMarkup` function on my dummy pages for testing purposes." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T15:19:35.907", "Id": "3180", "ParentId": "3179", "Score": "1" } }, { "body": "<p>Here's my approach to your scenario. Still working through a few things; however, this should give you the general idea.</p>\n\n<ol>\n<li><p>A new DOM can be injected during\ntesting so that I don't need to rely\non the true form if I don't\nwant/need such.</p></li>\n<li><p>The DOM object in general could be\nabstracted out to it's own namespace\nfor selector reuse across pages.\n(I'm still toying with this idea).</p></li>\n<li><p>The approach adds an\nobject/namespace to the global\nscope.</p></li>\n</ol>\n\n<h2>Testing HTML</h2>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;script src=\"http://code.jquery.com/jquery-1.6.1.min.js\"&gt;&lt;/script&gt;\n &lt;script src=\"Script.js\"&gt;&lt;/script&gt;\n &lt;script&gt;\n var testDom = {\n uploadButton: $(\"&lt;input type='button'&gt;\")\n };\n $(function(){\n var page = new MyPage.Behaviors(testDom);\n page.init();\n\n testDom.uploadButton.trigger(\"click\");\n });\n &lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<h2>Example Script</h2>\n\n<pre><code>var MyPage = function($) {\n var _files\n , Dom = (function($){\n return {\n clearLink: $(\"#btnClear\")\n , uploadButton: $(\"#btnUpload\")\n , filesControl: $(\"input[type=file]\")\n };\n }($))\n\n , Behaviors = function(dom) { \n if (typeof dom === 'undefined'){\n dom = Dom;\n }\n\n function clear() {\n _files = [];\n dom.fileControl.val(\"\");\n }\n\n function doUpload(){\n alert('uploading ' + _files.length + ' files...');\n }\n\n function addFile(e){\n _files.push(e.target.value);\n }\n\n function bindElement ($element, trigger, callback){\n if (typeof $element !== 'undefined'){\n $element.bind(trigger, callback);\n }\n }\n\n function init() {\n _files = [];\n bindElement(dom.clearLink, \"click\", clear);\n bindElement(dom.uploadButton, \"click\", doUpload);\n bindElement(dom.fileControl, \"click\", addFile);\n }\n\n return {\n clear: clear\n , init: init\n , doUpload: doUpload\n , addFile: addFile\n };\n }\n\n return {\n Behaviors: Behaviors\n };\n}(jQuery);\n</code></pre>\n\n<p>On load, the Behaviors is initialized to my test DOM and then the uploadButton's click event is triggered to test the result. </p>\n\n<p>This works when tested in a browser but doesn't with <a href=\"http://jsfiddle.net/JamesEggers/XfHqa/\" rel=\"nofollow\">Fiddle</a> currently.</p>\n\n<p>I'm sure there's a better way; however, this would allow you to test your JavaScript in a more controlled method and also removes the reliance on actual markup if you are using something like JsTestDriver.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T16:57:56.897", "Id": "4776", "Score": "0", "body": "mocking the DOM like that seems like a horrible idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T17:28:23.427", "Id": "4778", "Score": "0", "body": "If you don't mock the DOM that way, then the only other alternative is to duplicate your page's markup for each feature/page. By abstracting out the DOM, you remove the need to actually have a test Html page." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T17:35:42.237", "Id": "4779", "Score": "0", "body": "@JamesEggers what's the difference between your `testDom` variable and test markup ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T17:50:22.650", "Id": "4780", "Score": "0", "body": "@Raynos Ultimately, it's the ancillary markup (i.e. Html tag, etc.). The other difference would be I could use JsTestDriver and keep all of my JavaScript and the tests in JavaScript and won't need to have separate Html file for the markup or to house JavaScript tests." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T17:52:36.847", "Id": "4781", "Score": "0", "body": "@Raynos Another advantage (in my opinion) of abstracting out the DOM selectors is that it becomes easier to reuse the same selector across pages. May not be a large gain when minified and combined, admittingly; however, may decrease the overall payload size." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T17:57:03.950", "Id": "4782", "Score": "0", "body": "@JamesEggers I can see the jstestdriver advantage barely but it's better to test in actual browsers or headless browsers (zombie/phantom) instead. I think it's over-engineered that way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T18:20:38.070", "Id": "4784", "Score": "0", "body": "@Raynos I agree and that's one of the things I like about JsTestDriver. It still executes the code in different bowsers just doesn't require a full markup test harness like qUnit." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T16:38:18.850", "Id": "3183", "ParentId": "3179", "Score": "1" } }, { "body": "<p>You have to design an application to be testable. Automated testing does not mean \"automatic\" testing. All we can do with a unit testing framework (like QUnit) is make assertions on what can be accessed by the framework.</p>\n\n<p>Any \"method\" you want to unit-test should be accessible outside of its closure or prototype object; (i.e.) it should be a property of the object, not a variable scoped within its function definition. After you call one of these methods in a unit test you can compare its return value or the application state against some expected value or condition. Again the application state you want to inspect has to be represented by public-scope properties too.</p>\n\n<p>The original script example relies heavily on UI event-driven behavior. You could the jQuery trigger function to emulate these events. Here's a refactored version of the app with a possible technique with a QUnit test suite included: (XML declaration and XHTML doctype omitted by the editor)</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n &lt;title&gt;Refactored App with QUnit Example&lt;/title&gt;\n &lt;link href=\"http://code.jquery.com/qunit/git/qunit.css\" media=\"screen\" type=\"text/css\" rel=\"stylesheet\" /&gt;\n&lt;/head&gt;\n&lt;body&gt;\n\n &lt;!-- original app markup --&gt;\n &lt;div&gt;\n &lt;input type=\"file\" /&gt;&lt;br/&gt;\n &lt;input type=\"file\" /&gt;&lt;br/&gt;\n &lt;input type=\"file\" /&gt;\n &lt;/div&gt;\n &lt;p&gt;\n &lt;br/&gt;\n &lt;input id=\"btnUpload\" type=\"button\" value=\"Upload Files\" /&gt;\n or &lt;a href=\"#\" id=\"btnClear\"&gt;Clear files&lt;/a&gt;\n &lt;/p&gt;\n\n &lt;!-- QUnit boilerplate: --&gt;\n &lt;h1 id=\"qunit-header\"&gt;Example QUnit Test Suite&lt;/h1&gt;\n &lt;h2 id=\"qunit-banner\"&gt;&lt;/h2&gt;\n &lt;div id=\"qunit-testrunner-toolbar\"&gt;&lt;/div&gt;\n &lt;h2 id=\"qunit-userAgent\"&gt;&lt;/h2&gt;\n &lt;ol id=\"qunit-tests\"&gt;&lt;/ol&gt;\n &lt;div id=\"qunit-fixture\"&gt;&lt;/div&gt;\n\n &lt;script type=\"text/javascript\" src=\"http://code.jquery.com/jquery-latest.js\"&gt;&lt;/script&gt;\n &lt;script type=\"text/javascript\" src=\"http://code.jquery.com/qunit/git/qunit.js\"&gt;&lt;/script&gt;\n &lt;script type=\"text/javascript\"&gt;\n\n // original app, refactored:\n\n var App = (function (jquery) {\n\n var $ = jquery,\n app = this;\n\n app.files = [];\n\n app.initOptions = null;\n\n app.addFile = function () {\n app.files.push($(this).val());\n };\n\n app.doUpload = function () {\n alert('uploading ' + app.files.length.toString() + ' files...');\n };\n\n app.clear = function () {\n app.files = [];\n app.initOptions.fileCtrls.val('');\n };\n\n app.init = function (options) {\n app.initOptions = options;\n\n // wire up the events\n options.clearLink.click(app.clear);\n options.uploadBtn.click(app.doUpload);\n options.fileCtrls.change(app.addFile);\n };\n\n return app;\n\n }($));\n\n $(document).ready(function () {\n var i;\n\n // initialization call on the app:\n\n App.init({\n clearLink: $('#btnClear'),\n uploadBtn: $('#btnUpload'),\n fileCtrls: $(\"input[type='file']\")\n });\n\n\n // QUnit test examples:\n\n test(\"Set File Input\", function () {\n for(i = 0; i &lt; App.initOptions.fileCtrls.length; i++) {\n App.initOptions.fileCtrls[i].value = 'C:/fakepath/document--add.png';\n $(App.initOptions.fileCtrls[i]).trigger('change');\n }\n equals(App.files.length, i, 'files array has ' + i.toString() + ' files');\n });\n\n test(\"Clear Files\", function () {\n $('#btnClear').trigger('click');\n ok((App.files.length == 0), 'files array is empty');\n for(i = 0; i &lt; App.initOptions.fileCtrls.length; i++)\n {\n equals(App.initOptions.fileCtrls[i].value, '', 'file input ' + i.toString() + \" value is empty\");\n }\n });\n });\n &lt;/script&gt;\n&lt;/body&gt;\n</code></pre>\n\n<p></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T13:05:21.680", "Id": "4797", "Score": "0", "body": "I'm not sure I understand how this refactored app is more testable than my initial version. In both cases the class is basically a singleton (so state is shared between tests unless the page is reset or we add a reset function to our app). This is the #1 problem I see with this codes 'testability'.You have made a few things additional things public in your version that were private in mine which could be nice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T15:01:09.290", "Id": "4805", "Score": "0", "body": "Just a small critique (or FYI if you were not aware of this). In your defined closure that builds the App object, you should be passing in jQuery instead of $ and then have the anonymous function parameter be your $. jQuery is the global object that jQuery creates. The $ is just an alias for that object and is also used in other frameworks. Passing in the jQuery object can isolate your snippet better." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T04:32:37.987", "Id": "3192", "ParentId": "3179", "Score": "0" } }, { "body": "<p>//original code:</p>\n\n<p>/*\nvar MyPage = function($) {\n var _files\n , Dom = (function($){\n return {\n clearLink: $(\"#btnClear\")\n , uploadButton: $(\"#btnUpload\")\n , filesControl: $(\"input[type=file]\")\n };\n }($))\n */\nThis part can get really messy if you are monkeying the DOM like that.. can cause severe troubles to your browser</p>\n\n<pre><code> //something like this will do the trick\n var the_Form= $('form:eq(0)'); //find our form\n\n var MyPage= jQuery(function($){\n var _files,\n Dom= (function($){\n return{\n //rediscover the elements, I would have done it with a class and checked on hasClass('class') for better testing from the frontend part\n clearLink: the_Form.find('a#btnClear'),\n uploadButton: the_Form.find('input[type=\"submit\"]#btnUpload'),\n filesControl: the_Form.find(\"input[type='file']\")\n</code></pre>\n\n<p>... continue with your program.. I believe that you need to have a method to destroy the element if you don't reload the page or want to do some real time interaction with AJAX perhaps for file uploading.. as there might be some of those objects existing afterwards..</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-25T20:51:38.473", "Id": "19003", "ParentId": "3179", "Score": "0" } } ]
{ "AcceptedAnswerId": "3183", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T15:03:31.853", "Id": "3179", "Score": "1", "Tags": [ "javascript", "unit-testing" ], "Title": "What is a better (more testable) way to structure this page-specific JS?" }
3179
<p>I've written the following C# code to insert rows (that a user enters from a web application) into a SQL database. How does this code look? Is there a better, more efficient way to accomplish the task?</p> <pre><code>public void UpdateDeviceStatus(string[] deviceId, byte[] status, string userId, string[] remarks, DateTime dateTurnin) { if (deviceId.Length != status.Length || status.Length != remarks.Length) throw new ArgumentOutOfRangeException("Invalid arguments passed to UpdateDeviceStatus: deviceId, status, and remarks must contain the same number of entries."); if (deviceId.Length == 0) throw new ArgumentOutOfRangeException("UpdateDeviceStatus expects to update status for at least one deviceId, but an empty array was passed in."); // Build the SQL statement StringBuilder sbSql = new StringBuilder(); sbSql.Append(@"INSERT INTO AT_Event_History(deviceId,parentCode,statusCode,remarks,userId,whenEntered) VALUES"); for (int i = 0; i &lt; deviceId.Length; i++) { string values = string.Format("({0},0,{1},{2},{3},{4}),", new string[] { "@deviceId" + i.ToString(), "@statusCode" + i.ToString(), "@remarks" + i.ToString(), "@userId", "@whenEntered" }); sbSql.Append(values); } string sql = sbSql.ToString(); sql = sql.TrimEnd(','); // remove the trailing comma ',' Database db = EnterpriseLibraryContainer.Current.GetInstance&lt;Database&gt;("AssetTrackConnection"); DbCommand command = db.GetSqlStringCommand(sql); command.CommandType = CommandType.Text; command.CommandText = sql; // Add in parameters db.AddInParameter(command, "@userId", DbType.AnsiString, userId); db.AddInParameter(command, "@whenEntered", DbType.Date, dateTurnin); for (int j = 0; j &lt; deviceId.Length; j++) { db.AddInParameter(command, "@deviceId" + j.ToString(), DbType.Guid, new Guid(deviceId[j])); db.AddInParameter(command, "@statusCode" + j.ToString(), DbType.Byte, status[j]); db.AddInParameter(command, "@remarks" + j.ToString(), DbType.AnsiString, remarks[j]); } // Execute the statement. db.ExecuteNonQuery(command); } </code></pre> <p>As you can see, I am looping to add db parameters to hold the value for each row. I think that there may be a better way to do this.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T13:45:46.297", "Id": "4801", "Score": "0", "body": "I just fixed my question. I'm sorry for the headaches caused by the ****ed part where I mixed up the question and the code sample." } ]
[ { "body": "<p>You are building a dynamic insert statement with parametrized values. This works and there's nothing wrong with this method. It may even be the best method for your circumstance. It works well when your table is \"small\". I have a rather large database which grows monotonically. We keep adding rows and never remove any. When your table grows beyond a certain point that is specific to your table design, inserts get very slow. At this point, you will want to consider using the <a href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx\">SqlBulkCopy</a> class. You insert the values into a DataTable and then do a bulk insert. This is much faster because it uses a SQL Server specific method of loading data faster. The <a href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx\">SqlBulkCopy</a> link has sample code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T13:49:51.707", "Id": "4802", "Score": "0", "body": "Thanks! I'm going to look into this `SqlBulkCopy` class and try it on some of my pages." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T23:02:33.563", "Id": "3190", "ParentId": "3184", "Score": "7" } }, { "body": "<p>In addition, starting with SQL 2008 stored procedures support <a href=\"http://www.codeproject.com/KB/cs/CSharpAndTableValueParams.aspx\" rel=\"nofollow\">Table-Valued Parameters</a>, which let you pass a multi-column, multi-row recordset as an argument to the stored proc.</p>\n\n<p>This can be useful in situations where (because of its limitations) BulkCopy is not a feasible solution. In particular, because it's \"one table at a time\".</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T22:39:31.260", "Id": "6929", "ParentId": "3184", "Score": "3" } } ]
{ "AcceptedAnswerId": "3190", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T16:49:49.450", "Id": "3184", "Score": "11", "Tags": [ "c#", ".net", "sql" ], "Title": "Insert multiple rows into a SQL table" }
3184
<p>I'm trying to implement the Strategy Pattern into my current code base. I would like to know if i'm going in the right direction on this?</p> <p><b>IOracleDB.cs:</b></p> <pre><code>/// &lt;summary&gt; /// Strategy /// &lt;/summary&gt; interface IOracleDB { DataSet DatabaseQuery(string query, OracleConnection oracleConnection); DataSet DatabaseQuery(string procedure, string parameters, OracleConnection oracleConnection); } </code></pre> <p><b>OracleDBContext.cs:</b></p> <pre><code>/// &lt;summary&gt; /// Context /// &lt;/summary&gt; class OracleDBContext { private readonly string _EmailConnectionString = ConfigurationManager .ConnectionStrings["EmailConnectionString"].ConnectionString; private readonly string _PhConnectionString = ConfigurationManager .ConnectionStrings["PhConnectionString"].ConnectionString; private readonly IOracleDB _oracleDB; private readonly OracleConnection _oracleConnection; public OracleDBContext(IOracleDB oracleDB, string table) { _oracleDB = oracleDB; switch (table.ToUpper()) { case "Email": _oracleConnection = new OracleConnection(_EmailConnectionString); return; case "Ph": _oracleConnection = new OracleConnection(_PhConnectionString); return; default: return; } } public void ConnectToDatabase() { _oracleConnection.Open(); } public void DisconnectFromDatabase() { _oracleConnection.Close(); _oracleConnection.Dispose(); } public string ConnectionStatus() { if (_oracleConnection != null) { return _oracleConnection.State.ToString(); } return "OracleConnection is null."; } public DataSet DatabaseQuery(string query) { return _oracleDB.DatabaseQuery(query, _oracleConnection); } public DataSet DatabaseQuery(string procedure, string parameters) { return _oracleDB.DatabaseQuery(procedure, parameters, _oracleConnection); } } </code></pre> <p><b>EmailTableClass.cs:</b></p> <pre><code>/// &lt;summary&gt; /// Concrete Strategy /// &lt;/summary&gt; class EmailTableClass : IOracleDB { public DataSet DatabaseQuery(string query, OracleConnection oracleConnection) { DataSet dataSet = new DataSet(); OracleCommand cmd = new OracleCommand(query); cmd.CommandType = CommandType.Text; cmd.Connection = oracleConnection; using (OracleDataAdapter dataAdapter = new OracleDataAdapter()) { dataAdapter.SelectCommand = cmd; dataAdapter.Fill(dataSet); } return dataSet; } public DataSet DatabaseQuery(string procedure, string parameters, OracleConnection oracleConnection) { throw new NotImplementedException(); } } </code></pre> <p><b>PhTableClass.cs:</b></p> <pre><code>/// &lt;summary&gt; /// Concrete Strategy /// &lt;/summary&gt; class PhTableClass : IOracleDB { public DataSet DatabaseQuery(string query, OracleConnection oracleConnection) { throw new NotImplementedException(); } public DataSet DatabaseQuery(string procedure, string parameters, OracleConnection oracleConnection) { DataSet dataSet = new DataSet(); OracleCommand cmd = new OracleCommand { CommandText = procedure, CommandType = CommandType.StoredProcedure, Connection = oracleConnection, }; OracleParameter oracleParameter = new OracleParameter { ParameterName = parameters }; using (OracleDataAdapter dataAdapter = new OracleDataAdapter()) { dataAdapter.SelectCommand = cmd; dataAdapter.Fill(dataSet); } return dataSet; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T20:28:50.483", "Id": "7140", "Score": "0", "body": "Thanks to everyone who responded to my question. I actually answered my own question a long time ago. I ended up rewriting everything and it all worked out in the end. Lol I don't know what I was thinking at the time. I blame it on lack of sleep." } ]
[ { "body": "<p>There are several issues that could be improved:</p>\n\n<ol>\n<li><p>First of all, having concrete classes which are all tied to a specific database (in this case Oracle), is usually completely opposite of what a Data Layer's responsibility should be. Consider changing the classes' names as follows:</p>\n\n<ul>\n<li><code>OracleConnection</code> --> <code>DbConnection</code></li>\n<li><code>OracleCommand</code> --> <code>DbCommand</code></li>\n<li><code>OracleParameter</code> --> <code>DbParameter</code>.</li>\n</ul>\n\n<p>To instantiate a new command, don't use a specific constructor, but rather use the <code>DbConnection.CreateCommand()</code> method (and, likewise, <code>DbCommand.CreateParameter()</code> to create its parameters). That means you only need to change the actual connection instance, if you decide to switch from Oracle to a different db provider one day.</p></li>\n<li><p>Next, <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow\">strategy pattern</a> is usually used to abstract a functionality which several different algorithms can execute, while exposing a single (common) interface. Creating a different strategy for different table queries is not appropriate, because the calling code already knows which table it is querying (there are no additional strategical choices your code can do).</p></li>\n<li><p>I am not sure if the <code>NotImplementedException</code>s are thrown deliberately, or you really haven't yet implemented those methods. If you are throwing to indicate that a certain implementation doesn't support that functionality, that is another alarm that these two implementations are not really different <strong>strategies</strong> for the <strong>same task</strong>.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T14:33:51.860", "Id": "3297", "ParentId": "3187", "Score": "4" } }, { "body": "<p>The design is wrong.<br>\nLet's say we have a class:</p>\n\n<pre><code> public class SomeClass\n {\n public void DoSomethingWithDb(OracleDBContext dbContext)\n {\n dbContext.ConnectToDatabase();\n var dataSet = dbContext.DatabaseQuery(\"some procedure\", \"some parameters\");\n dbContext.DisconnectFromDatabase();\n }\n }\n</code></pre>\n\n<p>What will we get when we use this class like this:</p>\n\n<pre><code> var dbContext = new OracleDBContext(new EmailTableClass(), \"Email\");\n var someClass = new SomeClass();\n someClass.DoSomethingWithDb(dbContext);\n</code></pre>\n\n<p>We'll get NotImplementedException.<br>\nBy the way, judging from the names of the classes, I can assume that we'll get an error if we write:</p>\n\n<pre><code>var dbContext = new OracleDBContext(new EmailTableClass(), \"Ph\");\n</code></pre>\n\n<p>I would:<br>\n1. Make EmailTableClass: OracleDBContext and PhTableClass: OracleDBContext<br>\n2. Remove method DatabaseQuery(string query, OracleConnection oracleConnection) from PhTableClass and method DatabaseQuery(string procedure, string parameters, OracleConnection oracleConnection) from EmailTableClass.<br>\n3. Move names of the tables to EmailTableClass and PhTableClass. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-05T12:56:51.953", "Id": "3893", "ParentId": "3187", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-28T19:12:23.093", "Id": "3187", "Score": "5", "Tags": [ "c#", ".net", "oracle" ], "Title": "Strategy Pattern for Oracle Database?" }
3187
<p>I have started learning HTML. Here is one of the very basic HTML pages I have written. I would appreciate advice about how to write code especially regarding indentation.</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt; &lt;head&gt; &lt;title&gt; Checking Different Headings | Isnt it fun?&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt; This is big&lt;/h1&gt; &lt;h2&gt; This is also good &lt;/h2&gt; &lt;h3&gt; This is also good &lt;/h3&gt; &lt;h4&gt; This is also good &lt;/h4&gt; &lt;h5&gt; This is also good &lt;/h5&gt; &lt;h6&gt; This is small &lt;/h6&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>I start my intention in head and body.</p>\n\n<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt; \n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\"&gt; \n&lt;head&gt;\n &lt;title&gt; Checking Different Headings | Isnt it fun?&lt;/title&gt;\n&lt;/head&gt;\n\n&lt;body&gt;\n &lt;h1&gt;This is big&lt;/h1&gt;\n &lt;h2&gt;This is also good&lt;/h2&gt;\n &lt;h3&gt;This is also good&lt;/h3&gt;\n &lt;h4&gt;This is also good &lt;/h4&gt;\n &lt;h5&gt;This is also good&lt;/h5&gt;\n &lt;h6&gt;This is small&lt;/h6&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>I also keep my tag tight–no spaces between text and tag.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T05:48:20.600", "Id": "4791", "Score": "0", "body": "Nice idea. Using some spaces would make it easy to read and understand the code. Isn't?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T06:52:53.100", "Id": "4793", "Score": "1", "body": "@fahad Inside your tags spaces don't really add any readability. Also it can have unusual side effects depending on how you've styled your page. It's cleaner to remove them where it isn't needed just like @natedavisolds. Around your tags is another thing all together and IMHO it is up to you how you indent your html." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T05:41:35.677", "Id": "3194", "ParentId": "3193", "Score": "5" } }, { "body": "<p>It looks like you have the right idea starting out. The previous answer gives good advice about indentation.</p>\n\n<p>However, it looks like you're using header tags to specify the size of your font. It is now generally considered good practice to use CSS to control the style of your HTML.</p>\n\n<p>Simple example:</p>\n\n<pre><code>&lt;html xmlns=\"http://www.w3.org/1999/xhtml\" &gt;\n&lt;head&gt;\n &lt;title&gt;Untitled Page&lt;/title&gt;\n &lt;style type='text/css'&gt;\n .pageTitle {\n font-size: x-large;\n font-weight: bolder;\n text-decoration: underline;\n } \n .sectionTitle {\n font-size: large; \n } \n .regular \n {\n font-size: medium;\n } \n &lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;h1 class='pageTitle'&gt;Page Title&lt;/h1&gt; \n &lt;h2 class='sectionTitle'&gt;Section Title&lt;/h2&gt; \n &lt;p class='regular'&gt;Lorem Ipsum Dolar Sit Amet!&lt;/p&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>See <a href=\"http://www.csszengarden.com/\" rel=\"nofollow\">http://www.csszengarden.com/</a> for good CSS examples.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T15:22:40.030", "Id": "4807", "Score": "0", "body": "Don't forget the DOCTYPE!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T15:38:12.337", "Id": "4808", "Score": "4", "body": "And one shouldn't use unnecessary classes. Style the elements first (`h1`, etc.) and use classes for exceptions not the regular styles." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T21:23:10.147", "Id": "4844", "Score": "1", "body": "Just a minor note to add. Inline CSS is ok, but you don't want to get carried away with it. When designing a page try to make things as modularized as possible; it makes for easy updating in the long run. So use external .css files to store all of your CSS goodness." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T14:06:59.430", "Id": "3199", "ParentId": "3193", "Score": "0" } }, { "body": "<p>You should consider following points: </p>\n\n<ul>\n<li><p>Consider if you really need/want to use XHTML. XHTML has many disadvantages and hardly any advantages. See, for example: <a href=\"http://www.webdevout.net/articles/beware-of-xhtml\">http://www.webdevout.net/articles/beware-of-xhtml</a></p>\n\n<p>Instead use either HTML 4.01, or possibly HTML 5 (it's no problem to \"upgrade\" from 4.01 to 5 later).</p></li>\n<li><p>Don't use the Transitional DOCTYPE. It's only for legacy webpages, that don't use CSS. All additional features of Transitional are covered by CSS.</p></li>\n<li><p>Your filler texts \"This is big\" and \"This is small\" suggest you my be misunderstanding the usage of <code>h1</code> to <code>h6</code> (and possibly HTML all together). <code>h1</code> to <code>h6</code> are <strong>not</strong> for changing font sizes, they are for marking-up headlines of different importance and \"depth\" in the document structure. HTML only determines how a text is structured, not how it looks like. To change the look of the text, use CSS.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T15:34:50.590", "Id": "3200", "ParentId": "3193", "Score": "5" } } ]
{ "AcceptedAnswerId": "3194", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T05:31:03.627", "Id": "3193", "Score": "4", "Tags": [ "beginner", "html" ], "Title": "Introductory HTML exercise" }
3193
<p>How would I make this code look less ugly?</p> <pre><code>// we are looping over an array of images // width is a parameter passed to the current function // // the resulting string looks like this: "30px 0" // (it's a tool that returns coordinates for a CSS sprite) // when iterating over the first item, we don't need // to add "-" and "px" to X coordinate result.push( ( i === 0 ? "0" : "-" + i * ( ( is2PixelRatio ? width / 2 : width ) + 10 ) + "px" ) + " 0" ); </code></pre>
[]
[ { "body": "<pre><code>// old\n\nvar result = [], width, is2PixelRatio;\nfor (var i = 0; i &lt; 10; i++) {\n width = i;\n result.push(\n ( i === 0 ? \"0\" : \"-\" + i * ( ( is2PixelRatio ? width / 2 : width ) + 10 ) + \"px\" ) + \" 0\"\n );\n}\nconsole.log(result);\n\n// new\n\nvar result2 = [\"0 0\"], width, is2PixelRatio = true;\nfor (var i = 1; i &lt; 10; i++) {\n width = i;\n result2.push(\"-\" + i*(width+10) + \"px 0\");\n}\nif (is2PixelRatio) {\n result2 = result2.map(function(val) {\n return val.replace(/[\\-]\\d+/, function(v) { \n return v / 2;\n });\n }); \n}\nconsole.log(result2);\n</code></pre>\n\n<p>Basically inject the default value into the array at the start. Then do that if is2PixelRatio logic at the end on the entire array.</p>\n\n<p><a href=\"http://jsfiddle.net/qDVAz/13/\" rel=\"nofollow\">Live example</a>.</p>\n\n<p>Uses <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/map\" rel=\"nofollow\"><code>Array.prototype.map</code></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T13:06:35.050", "Id": "4798", "Score": "0", "body": "while this is certainly prettier, and I love the idea of pre-populating array with \"0 0\" and removing that piece of logic from the loop, on iphone4 it will do 2 loops instead of one – and performance is really important in my case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T13:14:31.643", "Id": "4799", "Score": "0", "body": "@gryzzly sounds like a micro-optimisation. The algorithm is still O(n). Have you benchmarked and profiled the code? Have you identified this particular loop to be a real noticeable bottleneck? I'm a firm believer that you should only optimise algorithms to minimal O and should not care about O(n) vs O(2n) vs O(5n). Constants in the range of an order of magnitude are a different issue (i.e. O(20n) vs O(n) is significant)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-28T09:37:37.887", "Id": "6646", "Score": "0", "body": "Well, this may be true in general, but not in all cases, since not all methods are executed equally frequently. Difference between 10ms run and 20ms is most often negligible, except if you do happen to run that function 500 times ;)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T09:43:13.130", "Id": "3196", "ParentId": "3195", "Score": "2" } }, { "body": "<p>Minor upgrades, nice idea for the prepop result Raynos</p>\n\n<pre><code>result = [\"0 0\"]; // Outside of loop\n\n// ...\n\nif (is2PixelRatio) width /= 2; \nwidth += 10; // [Insert magik number explanation here]\n\nresult.push( -(i * width) + \"px 0\" ); // Negative numbers will convert to \"-30\"\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-28T04:45:49.490", "Id": "4442", "ParentId": "3195", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T09:27:53.670", "Id": "3195", "Score": "2", "Tags": [ "javascript" ], "Title": "JavaScript string manipulation with certain logic in it" }
3195
<blockquote> <p><strong><em>Follow-up to:</strong> <a href="https://codereview.stackexchange.com/questions/2650/waiting-for-a-lock-to-release-with-thread-sleep">Waiting for a lock to release with Thread.Sleep()?</a></em></p> </blockquote> <p>I've found the time I tried to rewrite my <code>WaitForLock</code>-Method to utilize the <a href="http://quartznet.sourceforge.net/" rel="nofollow noreferrer">Quartz.NET</a> Scheduler which I've been using for some months now for other stuff. It got a little bit more complicated but at least it now misses the dreaded <code>Thread.Sleep()</code> completely, which is a big improvement for me.</p> <p>Though, it might now be too complicated.</p> <pre><code>/// &lt;summary&gt;Waits for the lock to be released within the given timeout.&lt;/summary&gt; /// &lt;param name="lockName"&gt;The name of the lock.&lt;/param&gt; /// &lt;param name="timeout"&gt;The timeout in seconds.&lt;/param&gt; /// &lt;returns&gt;True if the Lock was released.&lt;/returns&gt; public bool WaitForLock(String lockName, Int32 timeout) { // IsLocked(String) does query the database for the status if(!locker.IsLocked(lockName)) return true; using(ManualResetEvent reset = new ManualResetEvent(False) { ScheduleLockWaiter(lockName, timeout, reset); reset.WaitOne(timeout * 1000); // WARNING: This overload is only available in: 4, 3.5 SP1, 3.0 SP2, 2.0 SP2 // I spend a half day trying to figure that out. } return !locker.IsLocked(lockName); } /// &lt;summary&gt;Create and schedule the job to wait for the lock.&lt;/summary&gt; /// &lt;param name="lockName"&gt;The name of the lock.&lt;/param&gt; /// &lt;param name="repeat"&gt;The times it shall repeat.&lt;/param&gt; /// &lt;param name="reset"&gt;The ManualResetEvent to report on.&lt;/param&gt; private void ScheduleLockWaiter(String lockName, Int32 repeat, ManualResetEvent reset) { // Utilizing Quartz.NET String name = "LockJob_" + lockName; Trigger trigger = TriggerUtils.MakeSecondlyTrigger("LockTrigger_" + lockName, 1, repeat - 1); JobDetail job = new JobDetail(name, _lockJobGroup, typeof(LockJob)); job.JobDataMap.Add("Locker", _locker); job.JobDataMap.Add("Reset", reset); job.JobDataMap.Add("LockName", lockName); if(_scheduler.GetJobDetail(name, _lockJobGroup) != null) _scheduler.UnscheduleJob(name, _lockJobGroup); _scheduler.ScheduleJob(job, trigger); } // Further down the road, our Job-Class public class LockJob : IJob { public void Execute(JobExecutionContext context) { ILocker locker = (ILocker)context.JobDetail.JobDataMap.Get("Locker"); ManualResetEvent reset = (ManualResetEvent)context.JobDetail.JobDataMap.Get("reset"); String lockName = (String)context.JobDetail.JobDataMap.Get("LockName"); if(!locker.IsLocked(lockName)) { context.Scheduler.UndscheduleJob(context.Trigger.Name, context.Trigger.Group); reset.Set(); } } } </code></pre> <p>I'm not quite sure if I have improved something, or created a beast which will devour me someday. Your thoughts on this?</p> <p><strong>Update:</strong> Since I still have the comment from <a href="https://codereview.stackexchange.com/users/1432/brian-reichle">Brian Reichle</a> in my ears, I've moved on to make the waiting and acquiring of the lock one atomic operation.</p> <p>Also the scheduled job has changed to directly acquire the Lock. Yes, I know that it tries to lock it twice on success (I just realized that, but did not see a way to change that).</p> <pre><code>/// &lt;summary&gt;Tries to acquire the Lock within the given timeout.&lt;/summary&gt; /// &lt;param name="lockName"&gt;The name of the lock.&lt;/param&gt; /// &lt;param name="timeout"&gt;The timeout in seconds.&lt;/param&gt; /// &lt;returns&gt;True if the Lock could be acquired.&lt;/returns&gt; public bool WaitForLock(String lockName, Int32 timeout) { // boolean ILocker.Lock(String lockName) // Returns true if it was able to engage the lock. if(locker.Lock(lockName)) return true; // Easy way out using(ManualResetEvent reset = new ManualResetEvent(False) { ScheduleLockWaiter(lockName, timeout, reset); reset.WaitOne(timeout * 1000, false); } return locker.Lock(lockName); } // Further down the road, our Job-Class public class LockJob : IJob { public void Execute(JobExecutionContext context) { ILocker locker = (ILocker)context.JobDetail.JobDataMap.Get("Locker"); ManualResetEvent reset = (ManualResetEvent)context.JobDetail.JobDataMap.Get("reset"); String lockName = (String)context.JobDetail.JobDataMap.Get("LockName"); if(locker.Lock(lockName)) { context.Scheduler.UndscheduleJob(context.Trigger.Name, context.Trigger.Group); reset.Set(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T19:53:23.717", "Id": "10818", "Score": "0", "body": "I don't see any benefits in using Quartz.Net vs polling it like you did in the first question. This is a far more complicated way of polling in 1s intervals. I am not sure how your `Locker` code looks like, but making `WaitForLock` a member of that class (`Locker`) would allow it to signal any blocked threads whenever a lock is released. This is probably what [Travis](http://codereview.stackexchange.com/a/2657/5368) had in mind: the purpose of `ManualResetEvent` is to provide synchronization without polling. You should post your code for the `Locker.Lock` method, it would be easier." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-16T01:44:28.187", "Id": "20358", "Score": "0", "body": "What version of .NET are you working with? I am asking because 4 provides some new [thread primitives](http://msdn.microsoft.com/en-us/library/dd460718) which may be of use." } ]
[ { "body": "<p>I read your original question and this one and don't see how using ManualResetEvent/Quartz adds anything valuable. As far as I understand the whole point of sleeping is just to avoid polling the DB too frequently.</p>\n\n<p>Here some pseudocode...</p>\n\n<pre><code>create table lock (name varchar(50) primary key)\n\n\nbool tryLockNonBlocking(name_to_lock) {\n try {\n insert into lock (name) values (:name_to_lock)\n commit\n return true\n } catch(UniqueConstraintViolation) {\n return false\n } \n}\n\nvoid releaseLock(name_to_release) {\n delete from lock where name = :name_to_release\n commit\n}\n\n\nfinal POLL_PERIOD = 100 // msecs\n\nbool tryLockWithTimeout(name_to_lock, timeoutSeconds) {\n waitTimeMS = timeoutSeconds * 1000\n while(true) {\n boolean gotLock = tryLockNonBlocking()\n if(gotLock)\n return true\n waitTime -= POLL_PERIOD\n if(waitTime &gt; 0) \n Sleep(POLL_PERIOD)\n else\n return false\n }\n}\n</code></pre>\n\n<p>Is that what you are trying to achieve?</p>\n\n<p>NB. This is just a very rough draft ... you might want to add some lock owner and check it in </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-01T19:32:30.753", "Id": "16083", "ParentId": "3197", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T10:33:13.163", "Id": "3197", "Score": "7", "Tags": [ "c#", "locking" ], "Title": "Waiting for a lock to release with ManualResetEvent and Quartz" }
3197
<p>I wrote this program to do a simple Caesar shift by a user inputted key, and then deshift. I'm really enjoying it, but I've run out of ideas on improvements! Can you think of anything?</p> <pre><code>def decrypt(): a=raw_input("Give me the word to decrypt:") number=input("What was it shifted by?") b=list(a) str(b) c=[ord(x)for x in(b)] d=[] for i in c: d.append(i-number) e=[chr(i) for i in (d)] e="".join(e) print "Decryption Successful, your word is",e,"!" def encrypt(): a=raw_input("Give me a word:") number=input("Give me a number:") b=list(a) str(b) c=[ord(x)for x in(b)] d=[] for i in c: d.append(i+number) e=[chr(i) for i in (d)] e="".join(e) print "Your Caesar shifted result (ascii code) is:",e,"!" print "Your key is", number, ",remember that!" def menu(): print "\n\n\nWelcome to the Caesar Shifter." print "What would you like to do?" print "Option 1:Encrypt Word" print "Option 2:Decrypt Word" print "If you would like to quit, press 0." choice=input("Pick your selection:") if choice==1: run=encrypt() run menu() elif choice==2: derun=decrypt() derun menu() elif choice==0: quit else: print"That is not a correct selection, please pick either 1, or 2." menu() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T18:23:02.880", "Id": "4810", "Score": "0", "body": "Agree with previous comment. One \"easy way\" to often improve code is to use more (smaller) functions that do less but do whatever they do really well -- it makes the program more modular, testable, and the function names (if chosen correctly) add self-documentation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T18:30:15.833", "Id": "4811", "Score": "0", "body": "So I should break up my functions more? So when say \"encrypt\" is run it calls 2 sub functions as opposed to just running that chunk of code?" } ]
[ { "body": "<p>This might not be quite what you've got in mind, but one big improvement you could make would be to use meaningful variable names and insert whitespace.</p>\n\n<pre><code>def decrypt():\n cyphertext = raw_input('Give me the word to decrypt:')\n shift = input('What was it shifted by?')\n\n cypher_chars = list(cyphertext)\n str(b) # this does nothing; you should remove it\n cypher_ords = [ord(x) for x in cypher_list]\n plaintext_ords = []\n for i in cypher_ords:\n plaintext_ords.append(i - shift)\n\n plaintext_chars = [chr(i) for i in plaintext_ords]\n plaintext = ''.join(plaintext_chars)\n print 'Decryption Successful, your word is', plaintext, '!'\n</code></pre>\n\n<p>Of course you could actually compress much of this into a one-liner. But for a new programmer, I'd suggest sticking with readable variable names that make it clear what's going on.</p>\n\n<p>Still, you could do that while compressing the code a bit:</p>\n\n<pre><code>def decrypt():\n cyphertext = raw_input('Give me the word to decrypt:')\n shift = input('What was it shifted by?')\n\n cypher_ords = [ord(x) for x in cyphertext]\n plaintext_ords = [o - shift for o in cypher_ords]\n plaintext_chars = [chr(i) for i in plaintext_ords]\n plaintext = ''.join(plaintext_chars)\n print 'Decryption Successful, your word is', plaintext, '!'\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T18:31:27.707", "Id": "4817", "Score": "0", "body": "Ok thanks, is it more a style system change so it's more interpretable?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T18:40:44.073", "Id": "4818", "Score": "0", "body": "@SecNewbie, yes, exactly. Using variable names like `a`, `b`, etc is ok if you're planning to throw those variables away immediately or on the next line. But it's much easier for others to read your code if you give descriptive names to variables that are used throughout the function. For that matter, it's much easier for _you_ to read your code, after setting it aside and returning to it after six months!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T18:28:21.117", "Id": "3203", "ParentId": "3201", "Score": "8" } }, { "body": "<p>I have to recommend against use of input. Input allows the user to enter arbitrary python expressions which is not what you want. Instead use <code>int(raw_input())</code> to get a number from the user.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T07:30:09.010", "Id": "3219", "ParentId": "3201", "Score": "1" } }, { "body": "<p>There are several improvements that you can make. As others have said, whitespace helps readability. Take a look at <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a>, the official Python style guide. This guide will help you style your code so that it looks and feels more Pythonic.</p>\n\n<p>One general note, the <code>input</code> function returns a <strong>string</strong>. So when you do arithmatic like:</p>\n\n<pre><code>&gt;&gt;&gt;should_be_a_num = input('Provide an integer')\n&gt;&gt;&gt;print(42 - should_be_a_num)\n</code></pre>\n\n<p>an error will be raised. Make sure you caste the input to an <code>int</code>.</p>\n\n<p>I also recommend a structure change. Let the <code>menu</code> function handle all user interaction (i.e printing to the screen and recieving input). </p>\n\n<h2>decrypt()</h2>\n\n<p>There are several improvements here. </p>\n\n<pre><code>b=list(a)\n</code></pre>\n\n<p>It seems you wanted to put the work into a list so it can be used in a list comprehension. However, this is not needed. The <code>string</code> type in Python is iterable, which means that it can used in a list comprehension:</p>\n\n<pre><code>list_of_characters = [char for char in 'hello world!']\n</code></pre>\n\n<p>Furthermore, you do not need the parens after <code>in</code> inside list comprehensions. The syntax in my above example works.</p>\n\n<pre><code>str(b)\n</code></pre>\n\n<p>This line does nothing to help decrypt the text.</p>\n\n<p>Also this can be done in 1 line. Return the decrypted value and just let the <code>menu</code> function handle all printing.</p>\n\n<pre><code>def decrypt(text, shift):\n return ''.join([chr(ord(char) - shift) for char in text])\n</code></pre>\n\n<h2>encrypt()</h2>\n\n<p>Many of the same sentiments apply here as they do in your <code>decrypt</code> function, so see that section for the details. Here is my encrypt function:</p>\n\n<pre><code>def encrypt(text, shift):\n return ''.join([chr(ord(char) + shift) for char in text])\n</code></pre>\n\n<h2>menu()</h2>\n\n<p>Instead of recursively calling itself, we can use a simple <code>while</code> loop. I also took the liberty of changing around your menu a tad so that the function could be streamlined.</p>\n\n<pre><code>def menu(): \n print \"\\n\\n\\nWelcome to the Caesar Shifter.\"\n\n # Set the beginning choice and store the function objects.\n choice = -1\n choices = {'1':encrypt, '2':decrypt}\n\n # Loop as long as the user doesn't choose `quit`.\n while choice != '3':\n print \"\\n\\nWhat would you like to do?\"\n print \"Option 1: Encrypt Word\"\n print \"Option 2: Decrypt Word\"\n print \"Option 3: Exit.\"\n\n choice = input(\"Pick your selection:\")\n\n # Try and get the function. If this errors its because the the choice\n # was not in our options. \n try:\n func = choices[choice]\n except KeyError:\n if choice != '3':\n print 'Incorrect selection. Please choose either 1, 2, or 3.'\n continue\n\n text = raw_input(\"Please give me a word:\")\n shift = input(\"Please provide a shift amount:\")\n func(text, int(shift))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-16T15:15:27.553", "Id": "87861", "Score": "0", "body": "+1 for being the only one to put `encrypt` and `decrypt` in functions on their own, not related to the input logic. You can do one step further by defining `decrypt` in terms of `encrypt`. Also, I reckon the modulo operator can be useful." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-16T13:38:13.557", "Id": "50913", "ParentId": "3201", "Score": "3" } } ]
{ "AcceptedAnswerId": "3203", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T18:14:34.163", "Id": "3201", "Score": "14", "Tags": [ "python", "caesar-cipher" ], "Title": "Simple Caesar shift and deshift" }
3201
<p>I am trying to <a href="http://www.htmliseasy.com/exercises/part06.html">learn by doing</a>. Here is the first problem that I have solved. I have actually not done it perfectly. The table header should cover both the text and the image but it is only above text. If you can help me out with the design I will be thankful.</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;Untitled Document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;table&gt; &lt;th &gt;&lt;h3&gt;Food you love to eat&lt;/h3&gt;&lt;/th&gt; &lt;tr&gt; &lt;td&gt;I love eating food . All types of food are good for health. I like fruits in them. Fruits are good for health.&lt;/td&gt; &lt;td width="170"&gt; &lt;img src ="http://www.htmliseasy.com/exercises/fruitbowl.gif" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>The HTML you submitted was invalid. I changed the following things so your html would be valid:</p>\n\n<ol>\n<li><p>Don't put <code>&lt;h3&gt;</code> tags inside a table. Header tags are used for headings only. Don't use headings to make text BIG or bold. Use CSS for positioning and font sizing.</p></li>\n<li><p>In a table, the <code>&lt;tr&gt;</code> tag is the first tag that should appear.</p></li>\n<li><p>In the <code>&lt;img&gt;</code> tag, the attribute <code>alt</code> is required. The <code>alt</code> attribute specifies alternate text for an image if the image cannot be displayed.</p></li>\n</ol>\n\n<p><strong>Your HTML validated:</strong></p>\n\n<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\"&gt;\n&lt;head&gt;\n&lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /&gt;\n&lt;title&gt;Untitled Document&lt;/title&gt;\n&lt;/head&gt;\n\n&lt;body&gt;\n &lt;h3&gt;Food you love to eat&lt;/h3&gt;\n&lt;table&gt;\n &lt;tr&gt; \n &lt;td&gt;I love eating food . All types of food are good for health. I like fruits in them. Fruits are good for health.&lt;/td&gt;\n &lt;td width=\"170\"&gt; &lt;img src =\"http://www.htmliseasy.com/exercises/fruitbowl.gif\" alt=\"Fruit Bowl\" /&gt; &lt;/td&gt;\n &lt;/tr&gt;\n&lt;/table&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T21:03:51.263", "Id": "4820", "Score": "2", "body": "Now that I think of it, I believe I know why you put the <h3> tags in the table. This is how you go about doing what you were wanting: `<td colspan=\"2\" align=\"center\"><font size=\"5\"><b><i>Food you love to eat</i></b></font></td>`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T22:09:36.910", "Id": "4821", "Score": "2", "body": "use td or th? th tag would be better for it I personally think" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T01:11:39.430", "Id": "4825", "Score": "2", "body": "If you would like to use <th> tags, there's no problem with that, just don't put header tags within them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T14:17:03.010", "Id": "4848", "Score": "0", "body": "@Eric: Yes, you got it right. I wanted to do the same as you mentioned. Thanks :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T18:28:52.313", "Id": "4860", "Score": "1", "body": "@Fahad: Cool, I'm glad thing's are working out for you. Good luck learning HTML. :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T20:55:59.657", "Id": "3205", "ParentId": "3204", "Score": "12" } }, { "body": "<p>This is a great start, but I would recommend finding resources that are more up to date. Nowadays tables are largely reserved for containing data, rather than structuring pages or most content.</p>\n\n<p>I highly suggest going to Youtube, and finding some starter videos containing HTML5. Table tutorials won't get you anywhere but 1996. Keep up the good work.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-08T05:37:10.253", "Id": "25026", "Score": "0", "body": "Thanks. By this time I am almost done with html and css. Now PHP, Python and .NET on the way :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-10T15:54:15.543", "Id": "25105", "Score": "0", "body": "Glad to hear. Sounds like you're moving along quickly!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-13T14:32:37.120", "Id": "71442", "Score": "2", "body": "where is the Review?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-13T14:45:22.963", "Id": "71444", "Score": "0", "body": "this does contain Data, this is actually a good use for a Table, especially if you want to add items dynamically." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-13T15:53:27.760", "Id": "71453", "Score": "0", "body": "Hi @danchet, good answer but could you add some more explanation on how to structuring the page without `<table>`? It's a very good advice better demonstrate your point." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-13T18:33:20.483", "Id": "71477", "Score": "1", "body": "This is such an over-discussed topic, I won't continue it here. Take a look at this thread. http://stackoverflow.com/questions/83073/why-not-use-tables-for-layout-in-html" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-07T20:47:31.387", "Id": "15422", "ParentId": "3204", "Score": "4" } }, { "body": "<p>Something that wasn't mentioned was the Use of the Table header tags</p>\n\n<p>If you want the Table headers it should look something like this</p>\n\n<pre><code>&lt;tr&gt;\n &lt;th colspan=\"2\"&gt;Food you love to eat&lt;/th&gt;\n&lt;/tr&gt;\n&lt;tr&gt; \n &lt;td&gt;\n I love eating food . All types of food are good for health. I like fruits in them. Fruits are good for health.\n &lt;/td&gt;\n &lt;td width=\"170\"&gt; \n &lt;img src =\"http://www.htmliseasy.com/exercises/fruitbowl.gif\" alt=\"Fruit Bowl\" /&gt; \n &lt;/td&gt;\n&lt;/tr&gt;\n</code></pre>\n\n<p>The Table headers need to be in a row. </p>\n\n<p>I added a <code>colspan</code> property because I don't see that you are going to need two separate table headers for each column. if you have more than 2 columns and you want the header to stretch across all of them then replace <code>\"2\"</code> with the appropriate number of columns. you can mix and match as well, creating a <code>th</code> that spans the last two and not the first one, or however you need it.</p>\n\n<hr>\n\n<h1>Just because snippets are cool</h1>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>table {\n border: 3px solid red;\n }\nth {\n border: 3px double green;\n }\ntd {\n border: 3px dashed blue;</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;table width=\"500px\"&gt;\n &lt;tr&gt;\n &lt;th colspan=\"2\"&gt;Food you love to eat&lt;/th&gt;\n &lt;/tr&gt;\n &lt;tr&gt; \n &lt;td&gt;\n I love eating food . All types of food are good for health. I like fruits in them. Fruits are good for health.\n &lt;/td&gt;\n &lt;td width=\"170\"&gt; \n &lt;img src =\"http://www.htmliseasy.com/exercises/fruitbowl.gif\" alt=\"Fruit Bowl\" /&gt; \n &lt;/td&gt;\n &lt;/tr&gt;\n&lt;/table</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>If you are listing multiple items that you \"love to eat\" then this would be a very good use of a table structure.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-13T14:49:24.103", "Id": "71446", "Score": "1", "body": "Actually, this is mentioned in a comment on Eric's answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-13T14:51:37.360", "Id": "71447", "Score": "0", "body": "@SimonAndréForsberg, not how to properly use `th` tags and that they are a special type of `td` tag that needs to be nested inside of a `tr`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-13T14:45:28.823", "Id": "41557", "ParentId": "3204", "Score": "10" } }, { "body": "<p>You could change your doctype to HTML5:</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n</code></pre>\n\n<p>You could also use a validator &mdash; <a href=\"http://validator.w3.org/\" rel=\"nofollow\">http://validator.w3.org/</a> , which will highlight any syntax problems such as missing alt attributes, missing tr element around a td element, etc.</p>\n\n<p>And since you have evolved since, you will find this resource useful: <a href=\"http://developers.whatwg.org/\" rel=\"nofollow\">http://developers.whatwg.org/</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-13T23:33:05.073", "Id": "41599", "ParentId": "3204", "Score": "3" } } ]
{ "AcceptedAnswerId": "3205", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T20:37:04.163", "Id": "3204", "Score": "12", "Tags": [ "beginner", "html" ], "Title": "Practicing HTML Tables" }
3204
<p>It's <a href="https://stackoverflow.com/q/6512914/497934">been pointed out</a> (see the first comment) that my makefile rebuilds <em>all</em> source files regardless of changes made.</p> <pre><code># Variables # TARGETS := libAurora.a libAurora.so # The names of targets that can be built. # This is used in the list of valid targets when no target is specified, and when building all targets. TARGET_DIRECTORY := ./Binaries # The place to put the finished binaries. CXX := g++ # The compiler to use to compile the source code into object files. CXXFLAGS := -I. -Wall -Wextra -fPIC -g -O4 # Options passed to the compiler when compiling source files into object files. AR := ar # The archiver to use to consolidate the object files into one library. ARFLAGS := -rcs # Options to be passed to the archiver. SOURCE_FILES := $(shell find Source -type f -name *.cpp) # Because it's inconvenient to maintain an up-to-date list of all the source files # that should be compiled, we just search for all .cpp files in the project OBJECT_FILES := $(SOURCE_FILES:.cpp=.o) .PHONY: Default # The default target, which doesn't actually do anything except give the user instructions, # can be called even if nothing needs to be updated. .INTERMEDIATE: %.o # Specifying the object files as intermediates deletes them automatically after the build process. # Rules # Default: @echo "Please specify a target, or use \"All\" to build all targets. Valid targets:" @echo "$(TARGETS)" All: $(TARGETS) lib%.a: $(OBJECT_FILES) $(AR) $(ARFLAGS) $(TARGET_DIRECTORY)/$@ $(OBJECT_FILES) lib%.so: $(OBJECT_FILES) $(AR) $(ARFLAGS) $(TARGET_DIRECTORY)/$@ $(OBJECT_FILES) </code></pre> <p>What can I do to improve it?</p>
[]
[ { "body": "<p>I think the suggestion in the link you mention is to not bother with making your object files \"intermediate\". I tend to agree.</p>\n\n<p>If <code>make</code> deletes the object files after the link step then it has to re-build them all at the next invocation of <code>make</code>. Without this, the next time you <code>make</code>, it can look at the dependencies of the object files (as specified by the makefile, the part after the <code>:</code>) and only rebuild them if the stated dependencies have a later timestamp.</p>\n\n<p>You might also want a <code>make clean</code> target to remove the objects via <code>rm</code>, so that you can delete them when you really want to. But the typical workflow for using <code>make</code> is to keep your object files around for extended periods and type <code>make</code> when you want to build what you've changed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T09:53:31.740", "Id": "3221", "ParentId": "3206", "Score": "3" } } ]
{ "AcceptedAnswerId": "3221", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T20:58:44.370", "Id": "3206", "Score": "3", "Tags": [ "makefile" ], "Title": "Optimizing a Makefile" }
3206
<p>Earlier this year, before I learnt about Code Review Stack Exchange, I gave <a href="https://stackoverflow.com/questions/5756147/basic-simple-asp-net-jquery-json-example/5756591#5756591">this answer</a> in response to a question about how to combine ASP.NET, jQuery, and JSON: </p> <p>I keep thinking that there must be a better way to handle the JSON than just using escaped string literals, but I'd like to know for sure.</p> <pre><code>urlToHandler = 'handler.ashx'; jsonData = '{ "dateStamp":"2010/01/01", "stringParam": "hello" }'; $.ajax({ url: urlToHandler, data: jsonData, dataType: 'json', type: 'POST', contentType: 'application/json', success: function(data) { setAutocompleteData(data.responseDateTime); }, error: function(data, status, jqXHR) { alert('There was an error.'); } }); // end $.ajax [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class handler : IHttpHandler , System.Web.SessionState.IReadOnlySessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json"; DateTime dateStamp = DateTime.Parse((string)Request.Form["dateStamp"]); string stringParam = (string)Request.Form["stringParam"]; // Your logic here string json = "{ \"responseDateTime\": \"hello hello there!\" }"; context.Response.Write(json); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T13:45:25.017", "Id": "4845", "Score": "0", "body": "Thanks for the answer. I was wondering, specifically, if there is a way to improve the client side scripting; a good way to format JSON client side. Supposing that the `dateStamp` and `stringParam` values were not hardcoded, but rather read from a web form, the only way I know to build the JSON is string concatenation, and that's no fun and ugly as sin!" } ]
[ { "body": "<p>You are correct. There is a better way. Starting in .NET 3.5, there is a <a href=\"http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx\">JavaScriptSerializer</a> class that can be used for simplifying JSON responses. It can be found in the <code>System.Web.Script.Serialization</code> namespace (<code>System.Web.Extensions</code> assembly)</p>\n\n<p>First, you'd need to make a model to represent your response:</p>\n\n<pre><code>public class SimpleResponse {\n public string responseDateTime { get; set; }\n\n public SimpleResponse() {\n responseDateTime = \"hello hello there!\";\n }\n}\n</code></pre>\n\n<p>...Then in your handler:</p>\n\n<pre><code> public void ProcessRequest(HttpContext context)\n {\n context.Response.ContentType = \"application/json\";\n var json = new JavaScriptSerializer();\n\n context.Response.Write(\n json.Serialize(new SimpleResponse())\n ); \n }\n</code></pre>\n\n<p>Here is the result:</p>\n\n<pre><code>{\"responseDateTime\":\"hello hello there!\"}\n</code></pre>\n\n<p>In an ASP.NET MVC application this is more trivial. Just return a JsonResult from your controller:</p>\n\n<pre><code>public JsonResult Index()\n{\n return Json(new SimpleResponse());\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T23:31:47.970", "Id": "35417", "Score": "0", "body": "I've learnt that some special steps need to be taken to deal with DateTime JSON serialization. I wrote about it on my personal web site: http://danielsadventure.info/DotNetDateTime/" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T06:01:52.670", "Id": "3214", "ParentId": "3208", "Score": "8" } } ]
{ "AcceptedAnswerId": "3214", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T22:29:25.740", "Id": "3208", "Score": "12", "Tags": [ "c#", "jquery", "asp.net", "ajax", "json" ], "Title": "Making a simple call to a server" }
3208
<p>Here is <a href="http://www.htmliseasy.com/exercises/part03.html" rel="nofollow">a problem</a> I solved. Please review this.</p> <pre><code>&lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;BLA| Welcome &lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1 align="center"&gt;Meet Jack&lt;/h1&gt; &lt;img src="http://www.htmliseasy.com/exercises/jack.gif" alt="Meet Jack"&gt; &lt;br/&gt; &lt;p&gt; He is Jack.He is an odd little boy that just got an empty box for his birthday. He may &lt;em&gt;look &lt;/em&gt; happy but is a &lt;em&gt;little &lt;/em&gt; disappointed. Now he will have to put a little things in the box.&lt;br/&gt; Jack would really like...&lt;br/&gt; &lt;ul&gt; &lt;li&gt;Roller blades&lt;/li&gt; &lt;li&gt;Magic tricks&lt;/li&gt; &lt;li&gt;Anything Pokemon&lt;/li&gt; &lt;li&gt;A motorized Lego set&lt;/li&gt; &lt;/ul&gt; &lt;br/&gt; You can get all this (and more) at an online toy store. Two very popular ones are &lt;a href="http://www.toysrus.com/"&gt;toysrus.com &lt;/a&gt;and &lt;a href="http://www.etoys.com/"&gt;eToys&lt;/a&gt;. &lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>Okay, I am not sure exactly in what limits your exercise is, but I'll answer to what I think is good web standard. (I've been a web developer for ~4 years)</p>\n\n<ol>\n<li>Don't use the align attribute. HTML is supposed to be a markup language. Use CSS to control the appearance of your html elements. In this case something like <code>h1 { text-align: center; }</code> should do just fine.</li>\n<li>Don't use the <code>&lt;br /&gt;</code> tags for other things than actual line-breaks (that is, to break text). I would remove all <code>&lt;br /&gt;</code> tags, since you don't need them in this exercise. Elements like ul, li and p are by default block elements, which flows vertically. If you need more space between elements, use margin/padding instead. However, img is not a block element by default, so you can either wrap it in a div or make it a block element using CSS like <code>img { display: block; }</code>.</li>\n<li>Do not put a ul inside a p tag. Close the p tag and then add another p tag after the ul instead.</li>\n<li>Fine detail: insert line breaks in text to increase readability. A typical practice is to keep lines less than 80 characters.</li>\n</ol>\n\n<p>Btw, you do know that there are <a href=\"http://validator.w3.org/\">validator tools for HTML</a>, right?</p>\n\n<p>EDIT: Full code, in a better way: (Note that I chose to preserve one br tag. Maybe it can be an exercise to figure out why)</p>\n\n<pre><code>&lt;!DOCTYPE HTML&gt;\n&lt;html&gt;\n &lt;head&gt;\n &lt;style&gt;\n h1 { text-align: center; }\n img { display: block; }\n &lt;/style&gt;\n &lt;title&gt;BLA| Welcome &lt;/title&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;h1&gt;Meet Jack&lt;/h1&gt;\n &lt;img src=\"http://www.htmliseasy.com/exercises/jack.gif\" alt=\"Meet Jack\" /&gt;\n &lt;p&gt;He is Jack. He is an odd little boy that just got an empty box for his\n birthday. He may &lt;em&gt;look&lt;/em&gt; happy but is a &lt;em&gt;little&lt;/em&gt;\n disappointed. Now he will have to put a little things in the box.&lt;br /&gt;\n Jack would really like...&lt;/p&gt;\n &lt;ul&gt;\n &lt;li&gt;Roller blades&lt;/li&gt;\n &lt;li&gt;Magic tricks&lt;/li&gt;\n &lt;li&gt;Anything Pokemon&lt;/li&gt;\n &lt;li&gt;A motorized Lego set&lt;/li&gt;\n &lt;/ul&gt;\n &lt;p&gt;You can get all this (and more) at an online toy store. Two very popular\n ones are &lt;a href=\"http://www.toysrus.com/\"&gt;toysrus.com&lt;/a&gt; and\n &lt;a href=\"http://www.etoys.com/\"&gt;eToys&lt;/a&gt;.&lt;/p&gt;\n\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T00:00:54.920", "Id": "4823", "Score": "0", "body": "@Betamos Thats an excellent and detailed answer! +2 if I could. The only thing I would add is a full CSS example as the OP doesn't have any. It would be good to show some example `<style>` tags or `<link> tag." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T00:45:40.490", "Id": "4824", "Score": "0", "body": "@Betamos: Thanks a lot for such a nice answer. I am trying to learn HTML from a long time but do not find good resources to learn.Sorry I don't know about the validator tool too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T01:49:24.697", "Id": "4826", "Score": "0", "body": "@James Thank you. I added the full rewrite with CSS code and some whitespace fixes as well. @fahad I see, maybe there are better learning resources out there? I don't know so much about it, but [you are not alone](http://stackoverflow.com/questions/4724327/references-to-learn-html-js-for-non-technical-person)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T01:54:16.037", "Id": "4827", "Score": "1", "body": "@fahad A good read would be the [HTML Dog](http://www.htmldog.com) site. It has references and articles at beginner,intermediate and advanced levels." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T14:14:16.850", "Id": "4846", "Score": "0", "body": "@Betamos: Because'<p>'tag is already followed by a line break?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T14:15:55.803", "Id": "4847", "Score": "0", "body": "@James:I like HTMLDOG. The problem I have with it is that it is using XHTML not HTML. I read here that XHTML is not considered very good to use." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T15:13:52.487", "Id": "4851", "Score": "1", "body": "@fahad: The syntax differences between HTML and XHTML are small. It's simple to convert between the two. The most important difference: \"Empty\" elements don't have a final `/`. XHTML: `<br/>`. HTML: `<br>`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T15:43:36.893", "Id": "4852", "Score": "1", "body": "@RoToRa In both XHTML and HTML5, `<tagname />` is allowed. I use them because they increase readability of the code and are more portable. @fahad The `br` tag is just there because it probably looks better with a new line there." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T23:41:34.993", "Id": "3211", "ParentId": "3209", "Score": "11" } } ]
{ "AcceptedAnswerId": "3211", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-29T22:36:45.937", "Id": "3209", "Score": "6", "Tags": [ "html", "html5" ], "Title": "HTML website practice exercise" }
3209
<p>How can I improve upon this integer class that I wrote? I am/will be using this for some calculation intensive crypto algorithms, mainly POLY1305AES. I might even write RSA using this. I know that there are more efficient algorithms for at least the algebraic operators, but I will rewrite those when I learn them.</p> <p>Right now, I am trying to find anything I might have missed while writing this.</p> <ol> <li>Should I change my container?</li> <li>Are can any of the algorithms be improved?</li> <li>Is something running too many times?</li> <li>Anything I should do dynamically?</li> </ol> <p>Note that this code might not run if your compiler is too strict, like <a href="http://ideone.com/GOtot" rel="nofollow">ideone.com</a>'s compiler (the errors are not caused by the lack of a <code>main()</code>; rather, it thinks some of the operators are ambiguous).</p> <p>There are a lot of operators and I'm still missing many of them.</p> <pre><code>/* integer.h An integer type that does not have bit size restrictions by Jason Lee @ calccrypto at yahoo dot com NOTE: whether or not negative numbers will be implemented is yet to be determined */ #ifndef INTEGER_H #define INTEGER_H #include &lt;cstdlib&gt; #include &lt;deque&gt; #include &lt;iostream&gt; #include &lt;stdint.h&gt; // Checks platform bitsize using stdint.h #ifndef BITS #define BITS 32 #if INTPTR_MAX == INT64_MAX #undef BITS #define BITS 64 #endif #endif // ////////////////////////////////////// class integer{ private: void clean(){ while ((value.begin() != value.end()) &amp; !value.front()) value.pop_front(); } integer twos_complement(){ return (~*this) + 1; } public: std::deque &lt;uint8_t&gt; value; // Constructors integer(){ value.clear(); } template &lt;typename T&gt; integer(T rhs){ *this = rhs; } integer(std::deque &lt;uint8_t&gt; val){ value = val; clean(); } integer(const integer &amp; rhs){ value = rhs.value; } // RHS input args only // Assignment Operator template &lt;typename T&gt; integer operator=(T rhs){ value.clear(); while (rhs &gt; 0){ value.push_front(rhs &amp; 255); rhs &gt;&gt;= 8; } return *this; } integer operator=(integer rhs){ value = rhs.value; return *this; } // Typecast Operators operator bool(){ return (bool) value.size(); } operator char(){ return (char) value.back(); } operator int(){ int out = 0, count = 0; std::deque &lt;uint8_t&gt;::iterator i = value.end(); while ((*this &gt; 0) &amp; (count &lt; (BITS &gt;&gt; 3))){ out += *(i++); count++; } return out; } operator uint8_t(){ return value.back(); } operator uint16_t(){ std::deque &lt;uint8_t&gt;::iterator i = value.end(); uint16_t out = value.back(); out += *--i; return out; } operator uint32_t(){ int out = 0, count = 0; std::deque &lt;uint8_t&gt;::iterator i = value.end(); while ((*this &gt; 0) &amp;&amp; (count &lt; 4)) out += *(i++); return out; } operator uint64_t(){ int out = 0, count = 0; std::deque &lt;uint8_t&gt;::iterator i = value.end(); while ((*this &gt; 0) &amp;&amp; (count &lt; 8)) out += *(i++); return out; } // Bitwise Operators template &lt;typename T&gt; integer operator&amp;(T rhs){ return *this &amp; integer(rhs); } integer operator&amp;(integer rhs){ std::deque &lt;uint8_t&gt; larger = value, smaller = rhs.value; if (value.size() &lt; rhs.value.size()) larger.swap(smaller); for(std::deque &lt;uint8_t&gt;::reverse_iterator i = smaller.rbegin(), j = larger.rbegin(); i != smaller.rend(); i++, j++) *i &amp;= *j; return integer(smaller); } template &lt;typename T&gt; integer operator|(T rhs){ return *this | integer(rhs); } integer operator|(integer rhs){ std::deque &lt;uint8_t&gt; larger = value, smaller = rhs.value; if (value.size() &lt; rhs.value.size()) larger.swap(smaller); while (smaller.size() &lt; larger.size()) smaller.push_front(0); for(std::deque &lt;uint8_t&gt;::reverse_iterator i = smaller.rbegin(), j = larger.rbegin(); i != smaller.rend(); i++, j++) *j |= *i; return integer(larger); } template &lt;typename T&gt; integer operator^(T rhs){ return *this ^ integer(rhs); } integer operator^(integer rhs){ std::deque &lt;uint8_t&gt; larger = value, smaller = rhs.value; if (value.size() &lt; rhs.value.size()) larger.swap(smaller); while (smaller.size() &lt; larger.size()) smaller.push_front(0); for(std::deque &lt;uint8_t&gt;::reverse_iterator i = smaller.rbegin(), j = larger.rbegin(); i != smaller.rend(); i++, j++) *j ^= *i; return integer(larger); } template &lt;typename T&gt; integer operator&amp;=(T rhs){ *this = *this &amp; rhs; return *this; } integer operator&amp;=(integer rhs){ *this = *this &amp; rhs; return *this; } template &lt;typename T&gt; integer operator|=(T rhs){ *this = *this | rhs; return *this; } integer operator|=(integer rhs){ *this = *this | rhs; return *this; } template &lt;typename T&gt; integer operator^=(T rhs){ *this = *this ^ rhs; return *this; } integer operator^=(const integer rhs){ *this = *this ^ rhs; return *this; } integer operator~(){ std::deque &lt;uint8_t&gt; out = value; std::deque &lt;uint8_t&gt;::reverse_iterator i = out.rbegin(), j = out.rend(); j--; for(i = i; i != j; i++) *i ^= 0xff; // get highest bit int8_t top = 8; while (!((1 &lt;&lt; top) &amp; *i)) top--; for(top = top; top &gt; -1; top--) *i ^= 1 &lt;&lt; top; return integer(out); } // Bit Shift Operators integer operator&lt;&lt;(unsigned int shift){ if (*this == 0) return *this; std::deque &lt;uint8_t&gt; out = value; for(unsigned int i = 0; i &lt; (shift &gt;&gt; 3); i++) out.push_back(0); shift &amp;= 7; if (shift){ out.push_front(0); std::deque &lt;uint8_t&gt;::iterator i = out.begin(), j = out.end(); i++; j--; for(; i != j; i++){ uint8_t temp = *i &gt;&gt; (8 - shift); --i; *i += temp; i++; *i = (uint8_t) (*i &lt;&lt; shift); } uint8_t temp = *i &gt;&gt; (8 - shift); i--; *i += temp; i++; *i &lt;&lt;= shift; } return integer(out); } integer operator&lt;&lt;(integer shift){ integer out = *this; for(integer i = 0; i &lt; (shift &gt;&gt; 3); i++) out &lt;&lt;= 8; for(integer i = 0; i &lt; (shift &amp; 7); i++) out &lt;&lt;= 1; return out; } integer operator&gt;&gt;(unsigned int shift){ if (shift &gt;= bits()) return integer(0); std::deque &lt;uint8_t&gt; out = value; for(unsigned int i = 0; i &lt; (shift &gt;&gt; 3); i++) out.pop_back(); shift &amp;= 7; if (shift){ std::deque &lt;uint8_t&gt;::reverse_iterator i = out.rbegin(), j = out.rend(); j--; for(; i != j; i++){ *i &gt;&gt;= shift; i++; uint8_t temp = *i &lt;&lt; (8 - shift); i--; *i += temp; } *j &gt;&gt;= shift; } return integer(out); } integer operator&gt;&gt;(integer shift){ integer out = *this; for(integer i = 0; i &lt; (shift &gt;&gt; 3); i++) out &gt;&gt;= 8; for(integer i = 0; i &lt; (shift &amp; 7); i++) out &gt;&gt;= 1; return out; } integer operator&lt;&lt;=(size_t shift){ *this = *this &lt;&lt; shift; return *this; } integer operator&gt;&gt;=(size_t shift){ *this = *this &gt;&gt; shift; return *this; } integer operator&lt;&lt;=(integer shift){ *this = *this &lt;&lt; shift; return *this; } integer operator&gt;&gt;=(integer shift){ *this = *this &gt;&gt; shift; return *this; } // Logical Operators bool operator!(){ return !(bool) *this; } template &lt;typename T&gt; bool operator&amp;&amp;(T rhs){ return (bool) (*this &amp;&amp; rhs); } template &lt;typename T&gt; bool operator&amp;&amp;(integer rhs){ return (bool) *this &amp;&amp; (bool) rhs; } template &lt;typename T&gt; bool operator||(T rhs){ return ((bool) *this) || rhs; } template &lt;typename T&gt; bool operator||(integer rhs){ return ((bool) *this) || (bool) rhs; } // Comparison Operators template &lt;typename T&gt; bool operator==(T rhs){ return (value == integer(rhs).value); } bool operator==(integer rhs){ return (value == rhs.value); } template &lt;typename T&gt; bool operator!=(T rhs){ return !(*this == rhs); } bool operator!=(integer rhs){ return !(*this == rhs); } template &lt;typename T&gt; bool operator&gt;(T rhs){ return (*this &gt; integer(rhs)); } bool operator&gt;(integer rhs){ if (bits() &gt; rhs.bits()) return true; if (bits() &lt; rhs.bits()) return false; if (value == rhs.value) return false; for(unsigned int i = 0; i &lt; value.size(); i++) if (value[i] != rhs.value[i]) return value[i] &gt; rhs.value[i]; return false; } template &lt;typename T&gt; bool operator&lt;(T rhs){ return (*this &lt; integer(rhs)); } bool operator&lt;(integer rhs){ if (bits() &lt; rhs.bits()) return true; if (bits() &gt; rhs.bits()) return false; if (value == rhs.value) return false; for(unsigned int i = 0; i &lt; value.size(); i++) if (value[i] != rhs.value[i]) return value[i] &lt; rhs.value[i]; return false; } template &lt;typename T&gt; bool operator&gt;=(T rhs){ return ((*this &gt; rhs) | (*this == rhs)); } bool operator&gt;=(integer rhs){ return ((*this &gt; rhs) | (*this == rhs)); } template &lt;typename T&gt; bool operator&lt;=(T rhs){ return ((*this &lt; rhs) | (*this == rhs)); } bool operator&lt;=(integer rhs){ return ((*this &lt; rhs) | (*this == rhs)); } // Arithmetic Operators template &lt;typename T&gt; integer operator+(T rhs){ return *this + integer(rhs); } integer operator+(integer rhs){ if (rhs == 0) return *this; if (*this == 0) return rhs; std::deque &lt;uint8_t&gt; top = value, bottom = rhs.value; if (value.size() &lt; rhs.value.size()) top.swap(bottom); top.push_front(0); while (bottom.size() + 1 &lt; top.size()) bottom.push_front(0); bool carry = false, next_carry; for(std::deque &lt;uint8_t&gt;::reverse_iterator i = top.rbegin(), j = bottom.rbegin(); j != bottom.rend(); i++, j++){ next_carry = ((*i + *j + carry) &gt; 255); *i += *j + carry; carry = next_carry; } if (carry) *top.begin() = 1; return integer(top); } template &lt;typename T&gt; integer operator+=(T rhs){ *this = *this + rhs; return *this; } integer operator+=(integer rhs){ *this = *this + rhs; return *this; } template &lt;typename T&gt; integer operator-(T rhs){ return *this - integer(rhs); } integer operator-(integer rhs){ if (rhs == 0) return *this; if (*this == rhs) return integer(0); if (rhs &gt; *this) exit(2);// to be worked on unsigned int old_b = rhs.bits(); rhs = rhs.twos_complement(); for(unsigned int i = old_b; i &lt; bits(); i++) rhs ^= integer(1) &lt;&lt; i; return (*this + rhs) &amp; (~(integer(1) &lt;&lt; bits())); // Flip bits to get max of 1 &lt;&lt; x } template &lt;typename T&gt; integer operator-=(T rhs){ *this = *this - rhs; return *this; } integer operator-=(integer rhs){ *this = *this - rhs; return *this; } template &lt;typename T&gt; integer operator*(T rhs){ return *this * integer(rhs); } integer operator*(integer rhs){ // long multiplication unsigned int zeros = 0; std::deque &lt;uint8_t&gt; row; std::deque &lt;std::deque &lt;uint8_t&gt; &gt; temp; integer out = 0; for(std::deque &lt;uint8_t&gt;::reverse_iterator i = value.rbegin(); i != value.rend(); i++){ row = std::deque &lt;uint8_t&gt;(zeros++, 0); // zeros on the right hand side uint8_t carry = 0; for(std::deque &lt;uint8_t&gt;::reverse_iterator j = rhs.value.rbegin(); j != rhs.value.rend(); j++){ uint16_t prod = (uint16_t(*i) * uint16_t(*j)) + carry;// multiply through row.push_front((uint8_t) prod); carry = prod &gt;&gt; 8; } if (carry != 0) row.push_front(carry); out += integer(row); } return out; } template &lt;typename T&gt; integer operator*=(T rhs){ *this = *this * integer(rhs); return *this; } integer operator*=(integer rhs){ *this = *this * rhs; return *this; } template &lt;typename T&gt; integer operator/(T rhs){ return *this / integer(rhs); } integer operator/(integer rhs){ if (rhs == 0){ std::cout &lt;&lt; "Error: division or modulus by zero" &lt;&lt; std::endl; exit(1); } if (rhs == 1) return *this; if (*this == rhs) return integer(1); if ((*this == 0) | (*this &lt; rhs)) return integer(0); // Checks for divisors that are powers of two uint16_t s = 0; integer copyd(rhs); while ((copyd &amp; 1) == 0){ copyd &gt;&gt;= 1; s++; } if (copyd == 1) return *this &gt;&gt; s; //////////////////////////////////////////////// integer copyn(*this), quotient = 0; while (copyn &gt;= rhs){ copyd = rhs; integer temp(1); while ((copyn &gt;&gt; 1) &gt; copyd){ copyd &lt;&lt;= 1; temp &lt;&lt;= 1; } copyn -= copyd; quotient += temp; } return quotient; } template &lt;typename T&gt; integer operator/=(T rhs){ *this = *this / integer(rhs); return *this; } integer operator/=(integer rhs){ *this = *this / rhs; return *this; } template &lt;typename T&gt; integer operator%(T rhs){ return *this - (integer(rhs) * (*this / integer(rhs))); } integer operator%(integer rhs){ *this = *this - (*this / rhs) * rhs; return *this; } template &lt;typename T&gt; integer operator%=(T rhs){ *this = *this % integer(rhs); return *this; } integer operator%=(integer rhs){ *this = *this % rhs; return *this; } // Increment Operator integer operator++(){ *this += 1; return *this; } integer operator++(int){ integer temp(*this); ++*this; return temp; } // Decrement Operator integer operator--(){ *this -= 1; return *this; } integer operator--(int){ integer temp(*this); --*this; return temp; } // get private value unsigned int bits(){ if (value.empty()) return 0; unsigned int out = value.size() &lt;&lt; 3; uint8_t top = 128; while (!(value.front() &amp; top)){ out--; top &gt;&gt;= 1; } return out; } std::deque &lt;uint8_t&gt; data(){ return value; } }; // lhs type T as first arguemnt // Bitwise Operators template &lt;typename T&gt; T operator&amp;(T lhs, integer rhs){ return (T) (rhs &amp; lhs); } template &lt;typename T&gt; T operator|(T lhs, integer rhs){ return (T) (rhs | lhs); } template &lt;typename T&gt; T operator^(T lhs, integer rhs){ return (T) (lhs * rhs); } template &lt;typename T&gt; T operator&amp;=(T &amp; lhs, integer rhs){ lhs = (T) (integer(lhs) &amp; rhs); return lhs; } template &lt;typename T&gt; T operator|=(T &amp; lhs, integer rhs){ lhs = (T) (integer(lhs) | rhs); return lhs; } template &lt;typename T&gt; T operator^=(T &amp; lhs, integer rhs){ lhs = (T) (integer(lhs) ^ rhs); return lhs; } // Comparison Operators template &lt;typename T&gt; bool operator==(T lhs, integer rhs){ return (rhs == lhs); } template &lt;typename T&gt; bool operator!=(T lhs, integer rhs){ return (rhs != lhs); } template &lt;typename T&gt; bool operator&gt;(T lhs, integer rhs){ return (rhs &lt; lhs); } template &lt;typename T&gt; bool operator&lt;(T lhs, integer rhs){ return (rhs &gt; lhs); } template &lt;typename T&gt; bool operator&gt;=(T lhs, integer rhs){ return (rhs &lt;= lhs); } template &lt;typename T&gt; bool operator&lt;=(T lhs, integer rhs){ return (rhs &gt;= lhs); } // Arithmetic Operators template &lt;typename T&gt; T operator+(T lhs, integer rhs){ return (T) (rhs + lhs); } template &lt;typename T&gt; T &amp; operator+=(T &amp; lhs, integer rhs){ lhs = lhs + rhs; return lhs; } template &lt;typename T&gt; T operator-(T lhs, integer rhs){ return (T) (integer(rhs) - lhs); } template &lt;typename T&gt; T &amp; operator-=(T &amp; lhs, integer rhs){ lhs = lhs - rhs; return lhs; } template &lt;typename T&gt; T operator*(T lhs, integer rhs){ return (T) (rhs * lhs); } template &lt;typename T&gt; T &amp; operator*=(T &amp; lhs, integer rhs){ lhs = (T) (rhs * lhs); return lhs; } template &lt;typename T&gt; T operator/(T lhs, integer rhs){ return (T) (integer(lhs) / rhs); } template &lt;typename T&gt; T &amp; operator/=(T &amp; lhs, integer rhs){ lhs = lhs / rhs; return lhs; } template &lt;typename T&gt; T operator%(T lhs, integer rhs){ return (T) (integer(lhs) % rhs); } template &lt;typename T&gt; T &amp; operator%=(T &amp; lhs, integer rhs){ lhs = lhs % rhs; return lhs; } // IO Operator std::ostream &amp; operator&lt;&lt;(std::ostream &amp; stream, integer rhs){ std::string out = ""; if (rhs == 0) out = "0"; else { int div = 10; if (stream.flags() &amp; stream.oct) div = 8; if (stream.flags() &amp; stream.dec) div = 10; if (stream.flags() &amp; stream.hex) div = 16; while (rhs &gt; 0){ out = "0123456789abcdef"[(rhs % div).data().back()] + out; rhs /= div; } } stream &lt;&lt; out; return stream; } #endif // INTEGER_H </code></pre>
[]
[ { "body": "<p>For here:</p>\n\n<pre><code>while ((value.begin() != value.end()) &amp; !value.front())\n</code></pre>\n\n<p>You should use logical <code>&amp;&amp;</code> instead of <code>&amp;</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T03:34:14.143", "Id": "3234", "ParentId": "3212", "Score": "7" } }, { "body": "<pre><code>#define BITS 32\n#if INTPTR_MAX == INT64_MAX\n #undef BITS\n #define BITS 64\n#endif\n</code></pre>\n\n<p><code>#define</code> it, and optionally <code>#undef</code>ing it is ugly. Use an <code>else</code> block with parallel <code>#define</code>s instead.</p>\n\n<pre><code> integer(){\n value.clear();\n }\n</code></pre>\n\n<p><code>value</code> will be empty when the object is constructed, so there is no need to clear it.</p>\n\n<pre><code> operator char(){\n return (char) value.back();\n }\n</code></pre>\n\n<p>Converting to a <code>char</code> by ignoring everything but one element strikes me as ill-advised.</p>\n\n<pre><code> operator uint64_t(){\n int out = 0, count = 0;\n std::deque &lt;uint8_t&gt;::iterator i = value.end();\n while ((*this &gt; 0) &amp;&amp; (count &lt; 8))\n out += *(i++);\n return out;\n }\n</code></pre>\n\n<p>Do you really need to convert to so many different integer types? You should probably assert/throw an error if the value cannot be stored in the output format type. </p>\n\n<pre><code> integer operator|(integer rhs){\n std::deque &lt;uint8_t&gt; larger = value, smaller = rhs.value;\n</code></pre>\n\n<p>You make unnecessary copies of the data here.</p>\n\n<pre><code> if (value.size() &lt; rhs.value.size())\n larger.swap(smaller);\n while (smaller.size() &lt; larger.size())\n smaller.push_front(0);\n for(std::deque &lt;uint8_t&gt;::reverse_iterator i = smaller.rbegin(), j = larger.rbegin(); i != smaller.rend(); i++, j++)\n</code></pre>\n\n<p>Why are you using a reverse iterator?</p>\n\n<pre><code> *j |= *i;\n return integer(larger);\n }\n</code></pre>\n\n<p>The <code>&amp;</code> operator is very similar; they should be refactored to eliminate duplicate code.</p>\n\n<pre><code> integer operator~(){\n std::deque &lt;uint8_t&gt; out = value;\n std::deque &lt;uint8_t&gt;::reverse_iterator i = out.rbegin(), j = out.rend();\n j--;\n</code></pre>\n\n<p><code>i</code> and <code>j</code> are not very helpful names.</p>\n\n<pre><code> for(i = i; i != j; i++)\n *i ^= 0xff;\n // get highest bit\n int8_t top = 8;\n while (!((1 &lt;&lt; top) &amp; *i))\n top--;\n for(top = top; top &gt; -1; top--)\n *i ^= 1 &lt;&lt; top;\n return integer(out);\n }\n</code></pre>\n\n<p>Can't you just apply <code>~</code> to all of the elements? At any rate, some comments as to why you are doing what you are doing here would be useful.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T14:27:54.900", "Id": "4872", "Score": "0", "body": "i changed the reverse iterators for `|` and `^`, but i think it works better for `&`, since any bits over the smaller number will become 0. and how do i reduce the copying? i want to operate on one set of the data, without knowing which one the `value`, and which is `rhs.value` without changing `value`. also, i think that `operator char` is the same as the standard integer to char cast, so what do you think i should change it to? return a string?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T08:47:03.603", "Id": "3237", "ParentId": "3212", "Score": "10" } }, { "body": "<ul>\n<li><p>You should also be using <code>&lt;cstdint&gt;</code> instead of <code>&lt;stdint.h&gt;</code>. Stick to just the C++ equivalent libraries that are all incorporated in the <code>std</code> namespace.</p></li>\n<li><p>The class name <code>integer</code> should be capitalized to <code>Integer</code>. In general, class names, being the name of a <em>type</em>, should be named differently from functions and objects.</p></li>\n<li><p>For error outputs, use <a href=\"http://en.cppreference.com/w/cpp/io/cerr\" rel=\"nofollow\"><code>std::cerr</code></a> instead of <code>std::cout</code>.</p>\n\n<p>You <em>can</em> also give a comment at the top, stating that <code>&lt;iostream&gt;</code> is included only for this purpose, considering that this class doesn't primarily deal with I/O operations.</p></li>\n<li><p>With so many overloaded operators, it may be beneficial to move the class implementation to a separate .cpp file. The templated functions would best stay in the header file, but they can also be moved outside of the class declaration and placed after it. That way, it would be easier to see the actual declarations in case just those need to be maintained.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-26T19:56:46.027", "Id": "63987", "ParentId": "3212", "Score": "5" } } ]
{ "AcceptedAnswerId": "3237", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T02:20:44.760", "Id": "3212", "Score": "7", "Tags": [ "c++", "bitwise", "integer" ], "Title": "Custom integer class for calculating crypto algorithms" }
3212
<p>I have an OpenClose class which just represents the hours of operation of a business by the opening and closing time. It takes the opening and closing times as arguments to its constructor, and each is a datetime object.</p> <p>The data is coming from an external source in a string, formatted like "HH:MM (AM|PM)-HH:MM (AM|PM)"</p> <p>I have the following function to turn this into an OpenClose object:</p> <pre><code>def __get_times(self, hours): return OpenClose(*map(lambda x: datetime.strptime(x, "%I:%M %p"), hours.split("-"))) </code></pre> <p>What do you think of this? Is it too much for one line? Too confusing? Should I split it up into multiple lines?</p> <p>It sort of bugged me when doing it with multiple lines, but I can certainly see how this would be more readable, despite my hatred of explicitly doing the datetime calculation twice:</p> <pre><code>format = "%I:%M %p" open_time, close_time = hours.split("-") open_time = datetime.strptime(format) close_time = datetime.strptime(format) return OpenClose(open_time, close_time) </code></pre> <p>An alternative would be to use a combination of these approaches:</p> <pre><code>format = "%I:%M %p" hours = hours.split("-") open_time, close_time = map(lambda x: datetime.strptime(x, format), hours) return OpenClose(open_time, close_time) </code></pre> <p>Which of these is best?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T16:06:39.140", "Id": "5095", "Score": "0", "body": "Please define \"best\" so that we know what's important to you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T05:41:46.930", "Id": "5110", "Score": "0", "body": "@S.Lott I'm asking what should be important to me. To what degree does readability trump brevity? At what point does expressiveness taper off into unmaintainability?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T10:23:43.113", "Id": "5114", "Score": "0", "body": "\"I'm asking what should be important to me.\" That's silly. What's important to you is to write code that gets me a new Bentley Continental. Brevity is awful -- no one wins at code golf. However, you have other people on a team, you have existing coding styles, you have hundreds of considerations we can never know anything about. Performance. Existing Code Base Compatibility. Reusability. Design Patterns in common use in your organization. It is your obligation to define best. We can only provide random advice. \"No One Wins at Code Golf\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T10:33:17.693", "Id": "5115", "Score": "0", "body": "@S.Lott sure brevity _can be_ awful, but that's the exception, not the rule -- otherwise, why have we spent decades attempting to do more things with less code? I see your point about there maybe being existing standards that I didn't disclose, but isn't that always the case? This is a code review site and I was asking whether I was trying to put too much on one line. In my last comment I was pointing out that I was aware of a line between expressiveness and code golf, and with this question I was merely asking if I had crossed it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T10:35:49.420", "Id": "5116", "Score": "0", "body": "\"why have we spent decades attempting to do more things with less code?\". I don't know. Why? It is universally awful. It is a maintenance burden, and maintenance is the bulk of the cost of ownership of software. \"No One Wins at Code Golf\" Only you can define \"best\". You actually need to actually think about what is best in your environment, culture and organization and actually share that every time you use the word \"best\" in an open forum like this. Sadly, we don't know you. For code review purposes, however, \"No One Wins at Code Golf\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T10:52:29.470", "Id": "5117", "Score": "0", "body": "@S.Lott. I disagree. Brevity in a language means you have to learn the abstractions once, rather than taking a long time to write anything again and again. I maintain that this is a trivial question that didn't warrant a clarification of \"in your opinion, am I cramming too much in one line?\" It doesn't seem worthwhile to keep arguing the subject though, I was just asking for thoughts about my code, and yours is as helpful as Lennart's was." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T10:54:55.490", "Id": "5118", "Score": "0", "body": "If you value brevity so much. Why ask the question here? You seem to have already made up your mind that brevity has value. After 30 years, I can safely say that brevity is nothing but cost. Your experience, obviously, is different and you have someone been blessed with work environments free of confusing, obscure, costly code. I've had the burden of replacing code golf programs, so perhaps that colors my opinions. Cheers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T11:01:50.290", "Id": "5119", "Score": "0", "body": "@S.Lott I didn't mean to offend, I just meant that brevity _as a whole_ isn't bad (in the context of abstraction in modern languages, since you said it was \"universally bad\" I thought you were expanding the context to that level), whereas (from what I understand) you're referring to the narrower context of code golf only. I happily concede to your opinion about that, especially considering that the code-golfiness of my work is what I was looking for opinions of." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T11:24:17.883", "Id": "5121", "Score": "0", "body": "Brevity is bad. The value proposition is short for the sake of being short. Abstraction, summarization and conceptual chunking aren't brevity. The value proposition is to present a tidy concept that's removes \"needless\" details. The question (as with \"best\") is which details are truly needless." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-25T00:51:06.800", "Id": "14808", "Score": "0", "body": "In the future, you could always go with this: write equivalent code (and I stress *equivalent*), and comment out the version(s) you don't care for at the moment. Go with the one that uses the least resources, and trust that the next person is capable of commenting out your approach, and subbing in one that makes more sense to them." } ]
[ { "body": "<p>Yes, too much for one line, yes, too confusing. Making a map an lambda for two values like that is silly, unless you are trying to win an obfuscation contest.</p>\n\n<p>So, the middle version is best.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T17:28:17.180", "Id": "4855", "Score": "1", "body": "I'd have to agree too. In most cases when I see someone chime in with a \"one liner\" answer to some problem, I think of all the times I've had to deal with someone's \"cute\" solution years later and dreamed about punching them for it..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T06:46:41.010", "Id": "3217", "ParentId": "3213", "Score": "6" } }, { "body": "<p>\"No One Wins at Code Golf\". One liners are simply a mistake waiting to happen. They don't create any value because they can be obscure. They're remarkably hard to maintain.</p>\n\n<p>Sometimes, a one-liner (i.e., a simple list comprehension) is very clear and makes sense.</p>\n\n<p>In this case, </p>\n\n<pre><code>open_time = datetime.strptime(open_time,format)\nclose_time = datetime.strptime(close_time,format)\n</code></pre>\n\n<p>Are not redundant enough to care about.</p>\n\n<p>This has a fundamental error. </p>\n\n<pre><code>OpenClose(*map(lambda x: datetime.strptime(x, \"%I:%M %p\"), hours.split(\"-\")))\n</code></pre>\n\n<p>The above has the error of hard-coding the format string into the statement.\nThe format string is the most likely thing to change and should be in a configuration object of some kind so that it can be found and changed easily. If not in a configuration object, then a class-level attribute. Or a module-level global.</p>\n\n<p>The next most common mutation is to go from what you have (which doesn't handle the ValueError) to this.</p>\n\n<pre><code>try: \n open_time= datetime.strptime(open_time,format)\nexcept ValueError, e:\n log.error( \"Open time in %s is invalid: %s\", hours, open_time )\n return\ntry:\n close_time = datetime.strptime(close_time,format)\nexcept ValueError, e:\n log.error( \"Close time in %s is invalid: %s, hours, close_time\n return\n</code></pre>\n\n<p>This is no better.</p>\n\n<pre><code>OpenClose( *map(lambda x: datetime.strptime(x, format), hours.split(\"-\")) )\n</code></pre>\n\n<p>Nor is this.</p>\n\n<pre><code>OpenClose( *[datetime.strptime(x, format) for x in hours.split(\"-\")] )\n</code></pre>\n\n<p>Is shorter, but no better.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T11:07:35.620", "Id": "5120", "Score": "0", "body": "Happily, I do handle the exception up the call chain a few levels. You're right about the hard-coded string, I'll change that. It's true that since there'll only ever be two items using `map` is silly, although I confess I didn't think of your list comprehension example... tempting but I'll have to save it for a more fitting opportunity :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T10:42:26.950", "Id": "3408", "ParentId": "3213", "Score": "5" } }, { "body": "<p>One guideline of clean code: don't return expressions, only return variables (or constants or objects). Applying just that guideline dictates splitting into 2 lines.</p>\n\n<p>The question to ask for any implementation is:</p>\n\n<ul>\n<li><p>Does it improve performance, if so, how? See <a href=\"http://wiki.python.org/moin/PythonSpeed/PerformanceTips\" rel=\"nofollow\">http://wiki.python.org/moin/PythonSpeed/PerformanceTips</a></p></li>\n<li><p>The current code does not yield a performance improvement from putting everything on one line..</p></li>\n<li><p>So it can be optimized for better readability.. (results in fewer bugs)</p></li>\n<li><p>And it can be optimized for better maintainability.. (results in fewer bugs)</p>\n\n<ul>\n<li><p>return() with a simple argument is easy to read for program flow (any odd side effects are easy to see) = better readability</p></li>\n<li><p>Adding code prior to the return() (for example exception handling or new return values) can be done by creating logical expressions or adding new side effects = better maintainability</p>\n\n<ul>\n<li>Typically the person maintaining the code (adding a new return value) may not be as familiar with the algorithm or original implementation, so there is higher likelihood of bugs being introduced..</li>\n</ul></li>\n</ul></li>\n</ul>\n\n<p>See also :</p>\n\n<blockquote>\n <p>Python Patterns - An Optimization Anecdote\n <a href=\"http://www.python.org/doc/essays/list2str.html\" rel=\"nofollow\">http://www.python.org/doc/essays/list2str.html</a></p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-23T23:48:10.180", "Id": "5439", "Score": "0", "body": "Why? Why shouldn't you return expressions? I prefer returning an expression to assigning into a variable and returning that on the next line." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T20:05:32.760", "Id": "3568", "ParentId": "3213", "Score": "2" } }, { "body": "<p>I'll go against the trend and say that it's ok, but cramped. There's a chunk of code that you don't want to repeat, and I agree with the sentiment. But since that chunk of code is a semantic unit, it should get more visibility. Give it a name, for documentation.</p>\n\n<pre><code>def __get_times(hours):\n def parse_time(s): return datetime.strptime(s, \"%I:%M %p\")\n return OpenClose(*map(parse_time, hours.split(\"-\")))\n</code></pre>\n\n<p>There's still a bit of a smell in that <code>OpenClose</code> expects exactly two arguments, but <code>split</code> could in principle produce any number. Furthermore, <code>strptime</code> itself could fail if the string was improperly formatted. When you get around to implementing clean error reporting, you'll need to report an error before calling <code>OpenClose</code>; it'll be easier if you get the parsing out of the way first.</p>\n\n<pre><code>def __get_times(hours):\n def parse_time(s): return datetime.strptime(s, \"%I:%M %p\")\n opening, closing = map(parse_time, hours.split(\"-\"))\n return OpenClose(opening, closing)\n</code></pre>\n\n<p>To distinguish between a wrong number of components and badly formatted times, it may be nicer to extract the times before checking the number:</p>\n\n<pre><code>def __get_times(hours):\n def parse_time(s): return datetime.strptime(s, \"%I:%M %p\")\n times = map(parse_time, hours.split(\"-\"))\n if len(times) &lt;&gt; 2: raise …\n return OpenClose(*times)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T21:54:43.120", "Id": "3632", "ParentId": "3213", "Score": "1" } }, { "body": "<p>Explicitly calling map with a lambda isn't usually necessary; using a list comprehension is usually more natural/Pythonic. Therefore you'd have this (which is very similar to your third iteration):</p>\n\n<pre><code>def __get_times(self, hours):\n open_time, close_time = [datetime.strptime(s, \"%I:%M %p\") for s in hours.split(\"-\")]\n return OpenClose(open_time, close_time)\n</code></pre>\n\n<hr>\n\n<p>I didn't use the asterisk because it obfuscates for the reader what the expected call to the <code>OpenClose</code> constructor is.</p>\n\n<hr>\n\n<p>In two of your examples, you've reused a variable to hold different value types. While perfectly legal, I think this reduces readability:</p>\n\n<pre><code>open_time, close_time = hours.split(\"-\")\nopen_time = datetime.strptime(format)\nclose_time = datetime.strptime(format)\n</code></pre>\n\n<p>and then</p>\n\n<pre><code>hours = hours.split(\"-\")\n</code></pre>\n\n<p>I'm interested in what variables are declared and what they are meant to store. So if asked, what does <code>hours</code> mean, instead of a simple answer you have to say: first it holds a string, then later it holds a two-element list of strings. Similarly, first <code>open_time</code> holds a string, then later it holds a datetime instance.</p>\n\n<hr>\n\n<p>On the subject of brevity, I never think of brevity as a first-class virtue, but it definitely plays into readability. I'd rather read something short than something long, but making something <em>too</em> short can of course detract from readability.</p>\n\n<hr>\n\n<p>But here's where things get dicey. I think we're maybe focusing on the wrong question. One line or five, I think there's something wrong with your program.</p>\n\n<p>Some class has a private method called <code>__get_times</code> which takes one string argument, doesn't rely on current state, and returns an <code>OpenClose</code> instance. At a minimum, we shouldn't call it <code>__get_times</code> because that name implies that we'll get a return of multiple time values, but that's not what we get at all.</p>\n\n<p>But why does the <code>OpenClose</code> class exist at all? It's just a pair of values; I can't imagine any legitimate behaviors/methods that should be owned by it. If brevity/readability is your goal, then it would certainly be enhanced by getting rid of near-useless classes. Yes, sometimes bundling values together into a structure can reduce mental overhead, but in this case it doesn't seem worth it. Whoever owns an <code>OpenClose</code> instance should probably just own an <code>open</code> and a <code>close</code> value, neither of which should be a new custom type.</p>\n\n<p>And for that matter, whoever owns <code>__get_times</code> with a single string argument, why do they need a 1 or 2 line method which should probably only be called once?</p>\n\n<p>Then there's the part (and I can't stress this enough) where it doesn't rely on any internal state. At best, this whole thing should be a free-standing function which takes one string argument and returns a pair of time instances (NOT datetimes; you're talking about time of day). It's also more easy to test, tweak, and verify this way.</p>\n\n<pre><code>def parse_open_close_times(range_string, format=\"%I:%M %p\"):\n \"\"\"Returns a pair of time-of-day instances based on RANGE_STRING.\"\"\"\n return [datetime.strptime(s.strip(), format).time() for s in range_string.split(\"-\")]\n</code></pre>\n\n<p>In short, brevity/readability is better addressed by not proliferating questionable classes than by playing code golf with methods with odd signatures.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-30T20:12:20.103", "Id": "148586", "ParentId": "3213", "Score": "0" } } ]
{ "AcceptedAnswerId": "3217", "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T04:25:13.827", "Id": "3213", "Score": "5", "Tags": [ "python", "datetime", "comparative-review", "interval" ], "Title": "Representing the opening and closing time for a business" }
3213
<p>I'm building a web application and is trying to make my code reusable. I've decided to create components that can be used outside this project.</p> <p>Now I'm trying to create a simple DI container, one class, and I would like some help checking it out. I'm thinking to do something like this:</p> <pre><code>class Container { protected static $_services = array(); protected static $_shared = array(); /** * Create and store a new service in the container. * * @param string $service Service identifier name. * @param mixed $params Service parameters, array or a Closure object. * @return object Ramverk\Framework\Container. */ public function add($service, $params) { if (!is_object($params) &amp;&amp; !is_array($params)) { throw new Exception("Service params must be a Closure object or an array."); } static::$_services[$service] = $params; return $this; } /** * Get a shared service object, will return the same object each time. * * @param string $service Name of the shared service to get. * @return object Shared service object. */ public function get($service) { if (!array_key_exists($service, static::$_shared)) { static::$_shared[$service] = $this-&gt;getNew($service); } return static::$_shared[$service]; } /** * Get a new instance of an existing service. * * @param string $service Name of the service to create. * @return object Create service object. */ public function getNew($service) { // Make sure service has been added if (!array_key_exists($service, static::$_services)) { throw new Exception("Service '$service' not found"); } // get container service $container = static::$_services[$service]; // If service is wrapped in a Closure we invoke it if (is_object($container)) { return $container(); } // Make sure we have a class to work with if (!isset($container['class'])) { throw new Exception("A class must be set in $service service"); } // Get service key and remove key $class = $container['class']; unset($container['class']); // Check if this service uses adapters if (array_key_exists('adapter', $container)) { $config = (array) $container['adapter']; if (!isset($config['class'])) { throw new Exception("An adapter class must be set in $service service"); } // Grab adapter name and remove unwanted the keys $adapter = $config['class']; unset($config['class'], $container['adapter']); // Create the instance and return it return new $class(new $adapter($config)); } // Create class instance and pass parameters to constructor return new $class($container); } } </code></pre> <p>Adding a new service must contain a name (id) and either a Closure object or an array. The following will create and return the same thing:</p> <pre><code>$container = new Container(); $container-&gt;add('session', function() { $config = array( 'name' =&gt; 'my_session', 'expires' =&gt; '4 hours', ); $storage = new Session\Adapter\Native($config); return new Session($storage); }); // - Equals to: $container-&gt;add('session', array( 'class' =&gt; 'Session', 'adapter' =&gt; array( 'class' =&gt; 'Session\Adapter\Native', 'name' =&gt; 'my_session', 'expires' =&gt; '4 hours', ), )); // Now I get the shared object with: $session = $container-&gt;get('session'); // Or create a new instance $session = $container-&gt;getNew('session'); </code></pre> <p>Am I doing it right?</p>
[]
[ { "body": "<p>You should read the following series of articles: <a href=\"http://fabien.potencier.org/article/11/what-is-dependency-injection\" rel=\"nofollow\">http://fabien.potencier.org/article/11/what-is-dependency-injection</a></p>\n\n<p>Additionally, the resulting component (PHP 5.2+) is there: <a href=\"http://components.symfony-project.org/dependency-injection/\" rel=\"nofollow\">http://components.symfony-project.org/dependency-injection/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T17:02:24.693", "Id": "29641", "Score": "0", "body": "The dependecy injection container from symfony is PHP 5.3+" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T09:16:00.067", "Id": "3220", "ParentId": "3218", "Score": "1" } }, { "body": "<p>I think that pimple ( <a href=\"http://pimple-project.org/\" rel=\"nofollow\">http://pimple-project.org/</a> ) is the version used in symfony 2. \nmight be worth checking out.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T20:39:21.210", "Id": "7911", "Score": "1", "body": "Nope, it's not used in Symfony2. It is used in Silex. And I agree with you, it's definitely a simple and good existing solution for the problem the OP is trying to solve." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-08T15:15:10.487", "Id": "3968", "ParentId": "3218", "Score": "3" } }, { "body": "<p>Why are you defining the properties as static? I would absolutely not do that. It means two instantiations of the Container will have the same services.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T20:38:18.590", "Id": "5238", "ParentId": "3218", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T07:01:14.280", "Id": "3218", "Score": "5", "Tags": [ "php", "design-patterns" ], "Title": "Simple DI container" }
3218
<p>For every word there are 2^n different ways of writing the word if you take into account upper/lower case letters. Eg for "word" we can write;</p> <ul> <li>word</li> <li>Word</li> <li>wOrd</li> <li>WOrd</li> <li>woRd</li> <li>WoRd</li> <li>etc</li> </ul> <p>I've written this code to calculate all the combinations. Is there any way I can improve the performance? Profiling tells me that this method takes 99.9% of the execution time of my program (which measures password strength).</p> <pre><code>String word = "word"; int combinations = 1 &lt;&lt; word.length(); for (int i=0; i&lt;combinations; i++) { StringBuilder buf = new StringBuilder(word); for (int j=0; j&lt;word.length(); j++) { if ((i &amp; 1&lt;&lt;j) != 0) { String s = word.substring(j, j+1).toUpperCase(); buf.replace(j, j+1, s); } } System.out.println(buf); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T11:04:52.783", "Id": "4837", "Score": "1", "body": "Why would you want to *know* all possible combinations if all you want to know is the strength of the password?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T12:23:42.087", "Id": "4839", "Score": "1", "body": "This is a brute strength algorithm. If it seems slow, it's because your algorithm is O(2^n) where n is the length of the word you're trying. There's a good reason why it's slow and it's the same reason passwords aren't easily crackable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T13:33:41.620", "Id": "5171", "Score": "0", "body": "Why do you have to calculate all combinations to measure password strength? I absolutely see no benefit. I'm sure there are much faster algorithms for measuring password strength." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T12:40:37.577", "Id": "76920", "Score": "0", "body": "For measuring such things, you generally need to count the combinations, not 'have' all of them.\n\nYou already know that it's 2^n, you just need to find out the n - i.e., count how many of the symbols are case-sensitive (letters), and then calculate the 2^n formula." } ]
[ { "body": "<pre><code>public static void comb(String word) {\n int combinations = 1 &lt;&lt; word.length();\n char[][] chars = { word.toLowerCase().toCharArray(),\n word.toUpperCase().toCharArray() };\n char[] result = new char[word.length()]; \n\n for (int i = 0; i &lt; combinations; i++) {\n for (int j = 0; j &lt; word.length(); j++) {\n result[j] = chars[(i &gt;&gt; j) &amp; 1][j];\n }\n System.out.println(new String(result));\n }\n}\n</code></pre>\n\n<p><strong>[Edit]</strong></p>\n\n<p>I did some profiling, and my version seems slightly better, and the following version is even a little bit faster:</p>\n\n<pre><code>public static void comb(String word) {\n word = word.toLowerCase(); \n int combinations = 1 &lt;&lt; word.length();\n for (int i = 0; i &lt; combinations; i++) {\n char[] result = word.toCharArray();\n for (int j = 0; j &lt; word.length(); j++) {\n if (((i &gt;&gt; j) &amp; 1) == 1 ) {\n result[j] = Character.toUpperCase(word.charAt(j));\n } \n }\n System.out.println(new String(result));\n }\n} \n</code></pre>\n\n<p>However, all versions so far are in the same ballpark and won't change something substantial, because <code>System.out.println</code> dominates the performance.</p>\n\n<p><strong>[Edit 2]</strong></p>\n\n<p>The algorithm really doesn't matter much, the <code>System.out.println</code> impact is too heavy. Collection everything in a <code>StringBuilder</code> and calling <code>System.out.println</code> doesn't help either. However, quite surprisingly my profiler tells me that this simple recursive version performs best:</p>\n\n<pre><code>public static void comb4(String word) {\n comb4(word,new char[word.length()],0);\n} \n\nprivate static void comb4(String word, char[] accu, int index) {\n if(index == word.length()) {\n System.out.println(accu);\n } else {\n char ch = word.charAt(index);\n accu[index] = Character.toLowerCase(ch);\n comb4(word, accu , index+1);\n accu[index] = Character.toUpperCase(ch);\n comb4(word, accu, index+1);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T14:24:00.430", "Id": "4849", "Score": "1", "body": "Can we agree that `just posting code` without explanations is bad practice?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T14:40:33.757", "Id": "4850", "Score": "0", "body": "The snippet is short, the changes are obvious, the general functioning is the same. 'nuff said." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T15:45:39.297", "Id": "4853", "Score": "0", "body": "nice idea, but this implementation doubles my execution time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T16:48:41.847", "Id": "4854", "Score": "0", "body": "Landei's solution is faster for me (I admit: a single run with `wordingitalldaylong`, redirected to stdout 0.96s Landei-, 2.05s QWerky-code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T22:07:20.423", "Id": "4864", "Score": "0", "body": "Hmmm, then I'd guess that for short words the overhead for calling toLowerCase and toUpperCase is too big, while for longer words the tighter loop wins. Probably a version without the Array `chars`, but using `Character.toUpper` and `Character.toLower` on `word.charAt(j)` would be better. Obviously some profiling could be helpful." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T13:18:49.507", "Id": "3225", "ParentId": "3222", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T10:37:28.190", "Id": "3222", "Score": "2", "Tags": [ "java", "optimization" ], "Title": "Finding all upper/lower case combinations of a word" }
3222
<p>I have searched for method to find and replace strings sequence in binary files without any luck. The main requirement was that method should not load all file in memory but rather use chunks. I am new in c# and code may look not "polished" but it works fine. Maybe someone will have ideas how this code could be improved or does it have any flaws? p.s. Thanks goes to <a href="https://stackoverflow.com/questions/6525660/replace-sequence-of-bytes-in-binary-file">Jon Skeet</a> for idea. </p> <pre><code>public static void ReplaceTextInFile(string inFile, string find, string replace) { if (find.Length!=replace.Length) throw new ArgumentException("The lenght of find and replace strings must match!"); const int chunkPrefix = 1024*10; var findBytes = GetBytes(find); var replaceBytes = GetBytes(replace); long chunkSize = findBytes.Length * chunkPrefix; var f = new FileInfo(inFile); if (f.Length &lt; chunkSize) chunkSize = f.Length; var readBuffer = new byte[chunkSize]; using (Stream stream = File.Open(inFile, FileMode.Open)) { int bytesRead; while ((bytesRead=stream.Read(readBuffer, 0, readBuffer.Length)) != 0) { var replacePositions = new List&lt;int&gt;(); var matches = SearchBytePattern(findBytes, readBuffer, ref replacePositions); if (matches != 0) foreach (var replacePosition in replacePositions) { var originalPosition = stream.Position; stream.Position = originalPosition - bytesRead + replacePosition; stream.Write(replaceBytes, 0, replaceBytes.Length); stream.Position = originalPosition; } if (stream.Length == stream.Position) break; var moveBackByHalf = stream.Position - (bytesRead / 2); stream.Position = moveBackByHalf; } } } static public int SearchBytePattern(byte[] pattern, byte[] bytes, ref List&lt;int&gt; position) { int matches = 0; for (int i = 0; i &lt; bytes.Length; i++) { if (pattern[0] == bytes[i] &amp;&amp; bytes.Length - i &gt;= pattern.Length) { bool ismatch = true; for (int j = 1; j &lt; pattern.Length &amp;&amp; ismatch == true; j++) { if (bytes[i + j] != pattern[j]) ismatch = false; } if (ismatch) { position.Add(i); matches++; i += pattern.Length - 1; } } } return matches; } public static byte[] GetBytes(string text) { return Encoding.UTF8.GetBytes(text); } </code></pre> <p>usage</p> <pre><code> ReplaceTextInFile(@"MyFile.bin", "Text to replace", "New Text! Test!"); </code></pre>
[]
[ { "body": "<p>One thing I noted is that your <code>SearchBytePattern</code> function returns an int that is always equal to the number of elements in the <code>position</code> list. You can either make the return void, or make the function return a new list, since the two are superfluous.</p>\n\n<p>Also, comments help.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T14:49:38.920", "Id": "3227", "ParentId": "3226", "Score": "0" } }, { "body": "<p>A few issues with the code:</p>\n\n<ul>\n<li>You're comparing the <em>string</em> length for both, but then replacing the <em>bytes</em>. In UTF-8 encoding, as you're using, it's possible that the two will be different: if find = \"aeiou\" and replace = \"áéíóú\" you'll have findBytes.Length == 5, and replaceBytes.Length == 10</li>\n<li>You don't need to pass the position parameter by reference to <code>SearchBytePattern</code>, since you're not changing the reference, only calling methods on it.</li>\n<li>On <code>SearchBytePattern</code>, you don't need the outermost loop to go all the way to <code>bytes.Length</code>, it only needs to go to <code>bytes.Length - pattern.Length + 1</code> (and that would simplify the inner \"if\"</li>\n<li>stream.Read doesn't necessarily return the count of bytes you asked for - it can return less than that. Your code should be ready to handle that situation.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T17:57:05.310", "Id": "4900", "Score": "0", "body": "+1 This will only work for plain ASCII strings (but since there is a requirement that find/replace length are equal, I believe this is a pretty specific application which could be limited to ASCII). Also, as you said, the last block will create problems if the previous one had a match near the end because OP doesn't check the actual bytes read." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T16:15:40.637", "Id": "3271", "ParentId": "3226", "Score": "4" } }, { "body": "<p>Performance wise, you might want to check <a href=\"https://en.wikipedia.org/wiki/Boyer-Moore_string_search_algorithm\" rel=\"nofollow noreferrer\">Boyer-Moore's algorithm</a> (Googling found <a href=\"https://www.codeproject.com/Articles/12781/Boyer-Moore-and-related-exact-string-matching-algo\" rel=\"nofollow noreferrer\">this article</a> on CodeProject, and <a href=\"http://www.blackbeltcoder.com/Articles/algorithms/fast-text-search-with-boyer-moore\" rel=\"nofollow noreferrer\">this article</a> somewhere else). The algorithm is very efficient because it preprocesses your input string to know <strong>where to jump when there is a mismatch</strong>.</p>\n\n<p>For example, if you are looking for the string <code>\"Text to replace\"</code> (15 chars), you should first check the 15-th character in your input stream. If it is a <code>'z'</code>, then obviously you can immediately jump 15 characters ahead, because there is no such character in your search string. On the other hand, if it's an <code>'r'</code>, then it might be the starting letter of the word <code>replace</code>, and the algorithm will jump 6 characters to try to align the matching string with the input stream. This is far more efficient than moving the pointer by only a single position in each iteration. </p>\n\n<p>Next, your buffer size of <code>10*1024*find.Length</code> doesn't make sense. What is the purpose of this multiplication compared to a fixed buffer size (larger than <code>find</code>, of course)? And, more importantly, why do you keep going back by <strong>half this length</strong> every time, when you have already checked this data and should only backup for <code>find.Length-1</code> (in case the match is at the very end of your buffer)? What you are doing right now would only make sense if your buffer is exactly twice the length of <code>find</code> (which is what Jon probably meant in his answer).</p>\n\n<p>Apart from that, <a href=\"https://codereview.stackexchange.com/questions/3265/replace-sequence-of-strings-in-binary-file/3271#3271\">carlosfigueira</a>s answer covers the errors in your code (<code>SearchBytePattern</code> should have a parameter indicating the number of bytes actually read from the stream), and the problems dealing with Unicode (if you haven't read it already, check Jon Skeet's <a href=\"https://web.archive.org/web/20091105021417/http://msmvps.com/blogs/jon_skeet/archive/2009/11/02/omg-ponies-aka-humanity-epic-fail.aspx\" rel=\"nofollow noreferrer\">OMG Ponies</a>, the part about Unicode).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T08:21:57.933", "Id": "4919", "Score": "0", "body": "I use \"going back by half\" method to not miss Search String. As you already correctly pointed Search String can be separated by chunks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-07-03T18:38:24.057", "Id": "3272", "ParentId": "3226", "Score": "3" } }, { "body": "<p>You could remove the first if statement in SearchBytePattern by changing the condition in the outer for loop and the start of the inner for loop like so:</p>\n\n<pre><code>for (int i = 0; i &lt; bytes.Length - pattern.Length; i++)\n{\n bool ismatch = true;\n for (int j = 0; j &lt; pattern.Length &amp;&amp; ismatch == true; j++)\n</code></pre>\n\n<p>further, you can break the inner loop, when a difference is found:</p>\n\n<pre><code>if (bytes[i + j] != pattern[j])\n{\n ismatch = false;\n break;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T16:24:49.040", "Id": "3746", "ParentId": "3226", "Score": "2" } }, { "body": "<p>So a few immediate things I see are, the hardcoded encoding, if you aren't going to identify the encoding of the file to search automatically, then make it a parameter the user specifies. You really can't do this accurately without certainty of the correct encoding to use. For more information on this and why check out:\n<a href=\"http://www.joelonsoftware.com/articles/Unicode.html\" rel=\"nofollow\">http://www.joelonsoftware.com/articles/Unicode.html</a></p>\n\n<p>Also, the chunk prefix is better off either handed in by the user, or being based off a: memory constraints you are aware of for the activity of this process, or b: the size of the file, as the chunk size will cause wildly different read-through performance based on the size of the file, i.e.</p>\n\n<p>2gb file at 20mb a chunk will be processed much quicker than at 256b a chunk. A 400k file would be completely acceptable at 256b a chunk.</p>\n\n<p>Know the memory limitations, concurrency expectations (so you aren't creating too many IO waits), and time expectations of the user to decide the chunk size, otherwise leave it up to users as a parameter.</p>\n\n<p>Next, the name <code>SearchBytePattern</code> gives absolutely no illustration to the user what it's going to do, (I'm still not sure what it does having read it..) maybe it is returning the position of the beginning index of the BytePattern? Maybe it's returning by parameter the actual string in it's location? Give it a very clear unambiguous name (even if it's long), same goes for the parameters, a \"position\" is an integer, a list of int's might be positions? Or something else, and it's uncelar what they're positions for..</p>\n\n<p>Disambiguate your parameters and method names.</p>\n\n<p>Next, get rid of SearchBytePattern altogether anyway, instead of downconverting your searchpattern to bytes, use the correct encoding with a StreamReader and a StreamWriter which sends to a seperate file. then you just need to (forgive minor mistakes, winging it..):</p>\n\n<pre><code>char[] charsReadFromFile = new char[chunkSize];\n\ndo\n{\n int numberOfCharsReadFromFile = streamReaderOnGivenFile.Read(charsReadFromFile, 0, chunkSize);\n string stringReadFromFile = new String(charsReadFromFile).Trim(charsReadFromFile.Skip(numberOfCharsReadFromFile).ToArray());\n streamWriterOnNewFile.Write(stringReadFromFile.Replace(searchPattern, stringToReplacePatternWith));\n} while(numberOfCharsReadFromFile &gt; 0)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T23:33:28.577", "Id": "3749", "ParentId": "3226", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T14:42:08.453", "Id": "3226", "Score": "3", "Tags": [ "c#", "strings", "file" ], "Title": "Replace sequence of strings in binary file" }
3226
<p>I wonder if there is any way to write the followig in a few lines instead of using all cases. Both <code>CategoryType</code> and <code>AnimalSpecies</code> are <code>Enum</code>s.</p> <pre><code>private AnimalSpecies GetAnimalSpeciesBasedOnCategoryType(CategoryType categoryType) { switch (categoryType) { case CategoryType.Reptile : return AnimalSpecies.Reptile; case CategoryType.Bird: return AnimalSpecies.Bird; case CategoryType.Mammal: return AnimalSpecies.Mammal; case CategoryType.Insect: return AnimalSpecies.Insect; case CategoryType.Marine: return AnimalSpecies.Marine; default: MessageBox.Show("Category doesn't exist.Something wrong in programming code"); return AnimalSpecies.Marine; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T17:34:47.750", "Id": "4856", "Score": "0", "body": "Dictionary data structure?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T17:51:52.010", "Id": "4857", "Score": "1", "body": "This is probably better asked on stack" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T17:56:16.953", "Id": "4858", "Score": "5", "body": "If not having a corresponding category is a programming error, then the two Enums are effectively identical, and there is no sense in having them. Why do you need two different Enum types? Are you trying to store information in the type of an attribute? that would better be done in its value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T01:26:04.720", "Id": "4867", "Score": "3", "body": "Your `default` case should throw an exception." } ]
[ { "body": "<p>How about (untested not near a computer at the moment)</p>\n\n<pre><code> return (AnimalSpecies )Enum.Parse(typeof(AnimalSpecies ), categoryType.ToString());\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T17:57:09.443", "Id": "4859", "Score": "0", "body": "This looks correct, assuming the names of both enums always exactly match." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T15:31:37.923", "Id": "4951", "Score": "0", "body": "@Anders - .NET 4 introduced `Enum.TryParse()`. You could use that and then throw the same exception as shown in the `default` case in your question." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T17:47:14.633", "Id": "3230", "ParentId": "3229", "Score": "4" } } ]
{ "AcceptedAnswerId": "3230", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T17:32:27.037", "Id": "3229", "Score": "3", "Tags": [ "c#" ], "Title": "Return specific variable of Enum, determined by variable with the same name of another Enum?" }
3229
<p>I'm using an ObservableCollection in a WPF app. The source of the data doesn't provide changes. It provides snapshots instead. The method I wrote to update the ObservableCollection works but it seems inelegant. Is there a better way to do this?</p> <pre><code> public static void UpdateMarketOrderList( ObservableCollection&lt;MarketOrder&gt; oldList, List&lt;MarketOrder&gt; newList) { int oi = 0; // old list iterator int ni = 0; // new list iterator while (ni &lt; newList.Count) { if (oi == oldList.Count) { oldList.Insert(oi, newList[ni]); } else if (oldList[oi].Price == newList[ni].Price) { if (oldList[oi].Quantity != newList[ni].Quantity) { oldList[oi].Quantity = newList[ni].Quantity; } ++oi; ++ni; } else if (oldList[oi].Price &lt; newList[ni].Price) { oldList.RemoveAt(oi); } else if (oldList[oi].Price &gt; newList[ni].Price) { oldList.Insert(oi, newList[ni]); } } while (oldList.Count &gt; ni) { oldList.RemoveAt(ni); } } </code></pre> <p>If it matters, the definition MarketOrder can be considered to be this:</p> <pre><code>public class MarketOrder { public decimal Price { get; set; } public decimal Quantity { get; set; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T19:33:53.413", "Id": "4862", "Score": "0", "body": "Is it assumed that lists are sorted by `Price` and there are no duplicates per Price?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T19:50:41.333", "Id": "4863", "Score": "0", "body": "Snowbear: Yes. I do an .OrderBy(x => x.Price).ToList() before calling. I should probably do that in the method itself." } ]
[ { "body": "<p>After studying your code snippet for a bit here's what I came up with. </p>\n\n<p>I wouldn't call them iterators. They're really acting more as indexing operators that doubles as a loop counter. Furthermore, they're always incremented in sync and they have the exact same initial value.</p>\n\n<pre><code>int oi = 0; // old list iterator\nint ni = 0; // new list iterator\n</code></pre>\n\n<p>So I would replace with simply:</p>\n\n<pre><code>int i = 0;\n</code></pre>\n\n<p>The second loop for trimming the extra elements:</p>\n\n<pre><code>while (oldList.Count &gt; ni)\n{\n oldList.RemoveAt(ni);\n}\n</code></pre>\n\n<p>The post-condition for <code>i</code> after the first loop has to be equal to <code>newList.Count</code> otherwise we would still be looping the first while. Thusly, changing the condition to this is clearer:</p>\n\n<pre><code>while (oldList.Count &gt; newList.Count)\n</code></pre>\n\n<hr>\n\n<p>After tracing your <code>UpdateMarketOrderList</code> method, the discernible end effect, from what I can tell, just seems to be a replacement of the oldList with the newList. If that's really the desired end consequence of running this function, why not simplify it, succinctly to this instead?</p>\n\n<pre><code>public static void UpdateMarketOrderList( ObservableCollection&lt;MarketOrder&gt; oldList, \n List&lt;MarketOrder&gt; newList )\n{\n oldList.Clear();\n\n for(int i = 0; i &lt; newList.Count; ++i)\n {\n oldList.Add(newList[i]);\n }\n}\n</code></pre>\n\n<p>Then again you didn't specify in your question what the pre/post-conditions are for <code>UpdateMarketOrderList</code>, which is something that <em>does</em> matter.</p>\n\n<hr>\n\n<p>After reading OP's comment that fired change events are important, I would refactor the main loop like this:</p>\n\n<pre><code> while (i &lt; newList.Count)\n {\n if (i == oldList.Count ||\n oldList[i].Price &gt; newList[i].Price)\n {\n oldList.Insert(i, newList[ni]); \n }\n else if (oldList[i].Price &lt; newList[i].Price)\n {\n oldList.RemoveAt(i);\n continue;\n }\n else if (oldList[i].Quantity != newList[i].Quantity) \n // &amp;&amp; oldList[i].Price == newList[i].Price\n {\n Debug.Assert(oldList[i].Price == newList[i].Price);\n oldList[i].Quantity = newList[i].Quantity;\n }\n\n ++i;\n }\n</code></pre>\n\n<p>With this refactor you decrease the indent level and tighten the loop a bit while preserving existing behavior. The key thing to realize is that <code>RemoveAt</code> doesn't <em>increment</em> the loop counter. Your previous code did that in a slightly less direct manner.</p>\n\n<p>My gut feeling is that this could be refactored further still but without a good idea of the expected side-effects and other requirements for this method, it will be difficult to refactor this safely.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-02T08:44:48.660", "Id": "4884", "Score": "0", "body": "Clearing and then adding elements isn't acceptable because the change information is lost. Notice that it is an ObservableCollection and changes fire events. That said, the first half of your answer is gold. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T01:38:25.900", "Id": "5141", "Score": "0", "body": "@Jere I remember reading about the fire events in msdn but didn't realize at the time it was important for your scenario. I've edited my answer with more info." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T22:23:38.510", "Id": "3256", "ParentId": "3231", "Score": "3" } } ]
{ "AcceptedAnswerId": "3256", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-30T18:28:48.907", "Id": "3231", "Score": "4", "Tags": [ "c#" ], "Title": "Keeping an observable collection up to date" }
3231
<p>This code kinda hurts my feelings -- everything else in my code is done in neat one-liners, exploiting algorithms and, sometimes <code>boost::bind</code>, except for this piece. To say nothing about awkward <code>if(b!=a)</code>.</p> <p>Is there a better way to do the task?</p> <pre><code>#include &lt;iostream&gt; #include &lt;list&gt; using namespace std; int main() { int arr[] = {1,2,3,4,5,6}; list&lt;int&gt; lst(arr,arr+sizeof(arr)/sizeof(int)); for(list&lt;int&gt;::iterator a = lst.begin(); a != lst.end();a++) { for(list&lt;int&gt;::iterator b = a; b != lst.end(); b++) if(b != a) cout &lt;&lt; " ("&lt;&lt;*a&lt;&lt;","&lt;&lt;*b&lt;&lt;")"; cout &lt;&lt; "\n"; } return 0; } </code></pre>
[]
[ { "body": "<p>Also not really pretty, but perhaps a start</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n#include &lt;list&gt;\nusing namespace std;\n\nint main()\n{\n list&lt;int&gt; lst = {1,2,3,4,5,6};\n\n auto a = lst.cbegin();\n int first = *a;\n auto output_pairs = [&amp;first](const int second){ cout &lt;&lt; \" (\"&lt;&lt;first&lt;&lt;','&lt;&lt;second&lt;&lt;')'; };\n while(++a != lst.cend())\n {\n for_each(a, lst.cend(), output_pairs);\n cout &lt;&lt; '\\n';\n first = *a;\n }\n cout &lt;&lt; flush;\n}\n</code></pre>\n\n<p>It's C++0x because I was too lazy to write a functor for that lambda and I don't know the Boost.Lambda syntax off the top of my head.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T23:42:44.887", "Id": "3257", "ParentId": "3243", "Score": "2" } }, { "body": "<p>(Let's start over.)</p>\n\n<p>It generally looks good. You have to have two loops because you want pairs, one way or another. But if you want all off-diagonal pairs, i.e. if you mean \"unequal index\" rather than \"unequal value\", you don't need the conditional:</p>\n\n<pre><code> for (list&lt;int&gt;::const_iterator a = lst.begin(), b, end = lst.end(); a != end; )\n {\n for (b = ++a; b != end; ++b) cout &lt;&lt; \" (\" &lt;&lt; *a &lt;&lt; \", \" &lt;&lt; *b &lt;&lt; \")\";\n cout &lt;&lt; \"\\n\";\n }\n</code></pre>\n\n<p>If you mean pairs of unequal <em>values</em>, you could start like this:</p>\n\n<pre><code> for (list&lt;int&gt;::const_iterator a = lst.begin(), b, end = lst.end(); a != end; )\n {\n for (b = ++a; b != end; ++b) if (*b != *a) cout &lt;&lt; \" (\" &lt;&lt; *a &lt;&lt; \", \" &lt;&lt; *b &lt;&lt; \")\";\n cout &lt;&lt; \"\\n\";\n }\n</code></pre>\n\n<p>However, this still produces redundant output, since you don't track repeated values in the outer loop (which should be \"for all <em>unique</em> <code>a</code> in the list). In that case it might be nicer to use a set of pairs container perhaps, with a suitable predicate.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-02T11:16:05.783", "Id": "3260", "ParentId": "3243", "Score": "2" } } ]
{ "AcceptedAnswerId": "3260", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T12:57:53.863", "Id": "3243", "Score": "3", "Tags": [ "c++", "iterator", "iteration" ], "Title": "Iterating over unequal unordered pairs in one collection" }
3243
<p>I have the following code, but it's too slow. How can I make it faster?</p> <pre><code>&lt;?php class Ngram { const SAMPLE_DIRECTORY = "samples/"; const GENERATED_DIRECTORY = "languages/"; const SOURCE_EXTENSION = ".txt"; const GENERATED_EXTENSION = ".lng"; const N_GRAM_MIN_LENGTH = "1"; const N_GRAM_MAX_LENGTH = "6"; public function __construct() { mb_internal_encoding( 'UTF-8' ); $this-&gt;generateNGram(); } private function getFilePath() { $files = array(); $excludes = array('.', '..'); $path = rtrim(self::SAMPLE_DIRECTORY, DIRECTORY_SEPARATOR . '/'); $files = scandir($path); $files = array_diff($files, $excludes); foreach ($files as $file) { if (is_dir($path . DIRECTORY_SEPARATOR . $file)) fetchdir($path . DIRECTORY_SEPARATOR . $file, $callback); else if (!preg_match('/^.*\\' . self::SOURCE_EXTENSION . '$/', $file)) continue; else $filesPath[] = $path . DIRECTORY_SEPARATOR . $file; } unset($file); return $filesPath; } protected function removeUniCharCategories($string){ //Replace punctuation(' " # % &amp; ! . : , ? ¿) become space " " //Example : 'You&amp;me', become 'You Me'. $string = preg_replace( "/\p{Po}/u", " ", $string ); //-------------------------------------------------- $string = preg_replace( "/[^\p{Ll}|\p{Lm}|\p{Lo}|\p{Lt}|\p{Lu}|\p{Zs}]/u", "", $string ); $string = trim($string); $string = mb_strtolower($string,'UTF-8'); return $string; } private function generateNGram() { $files = $this-&gt;getFilePath(); foreach($files as $file) { $file_content = file_get_contents($file, FILE_TEXT); $file_content = $this-&gt;removeUniCharCategories($file_content); $words = explode(" ", $file_content); $tokens = array(); foreach ($words as $word) { $word = "_" . $word . "_"; $length = mb_strlen($word, 'UTF-8'); for ($i = self::N_GRAM_MIN_LENGTH, $min = min(self::N_GRAM_MAX_LENGTH, $length); $i &lt;= $min; $i++) { for ($j = 0, $li = $length - $i; $j &lt;= $li; $j++) { $token = mb_substr($word, $j, $i, 'UTF-8'); if (trim($token, "_")) { $tokens[] = $token; } } } } unset($word); $tokens = array_count_values($tokens); arsort($tokens); $ngrams = array_slice(array_keys($tokens), 0); file_put_contents(self::GENERATED_DIRECTORY . str_replace(self::SOURCE_EXTENSION, self::GENERATED_EXTENSION, basename($file)), implode(PHP_EOL, $ngrams)); } unset($file); } } $ii = new Ngram(); ?&gt; </code></pre>
[]
[ { "body": "<p>This code seems to be very good as far as performance is concerned. I cannot see any way to improve it.</p>\n\n<p>I used xdebug and cachegrind to see that my test samples were bound by the performance of the loop that creates the tokens. I investigated switching the $i and $j loops around, but the performance was no better.</p>\n\n<p>I cannot see any way to improve the code, so I would look at a faster CPU or a compiled language like C. There are also large improvements in performance with PHP 5.4, so moving to that might be a very good option.</p>\n\n<h2>Response to Other Answer</h2>\n\n<p>We now have two answers both claiming different bottlenecks. This makes things interesting! I'll list the evidence that makes me believe it is a CPU bottleneck. The first evidence I'll investigate will be the profiling information. The second will be a simple proof of removing the I/O and observing the runtimes. Skip to the second in the \"Removed I/O\" section if you just want the quick answer.</p>\n\n<h2>Profiling</h2>\n\n<p>The tools I am using are <a href=\"http://xdebug.org/\" rel=\"nofollow noreferrer\">xdebug</a> and <a href=\"http://kcachegrind.sourceforge.net/html/Home.html\" rel=\"nofollow noreferrer\">kcachegrind</a>.</p>\n\n<p>First I created four some sample files. My first 3 files were lorem ipsum type texts in Greek, Chinese and Latin. My fourth was the concatenation of these three files and is shown below:</p>\n\n<pre><code>遺健問使物済表績象全問前禎。画更予服的負要前行年語断。肉購会際以面長力攻以野所。治条育録療常強門守更校尊無場審言団。早患社支科視徐取告性表変全意主場。度坂信神暮明死載高深典導昇話。無稿乳横面祝揚倉厘積卒食当正使。食考割闘出護空樫京速地間作夜半文性新局。前馬報惑般供筋子真車東生然歌論略形。政図警情調並浜校素先間後善経完。\n\nLorem ipsum dolor sit amet, eu ius nisl impedit. Tritani denique ut nam, brute aliquid iudicabit eos ei. Ad vix hinc numquam, unum utamur vix cu. Natum ubique vocibus ei duo.\n\nQuo te eius propriae voluptatibus, id nostro forensibus signiferumque est, graecis senserit gloriatur per et. Eu munere facete scripserit vel, cu vim laudem noster. His cu dictas prodesset, aliquando constituto reprimique sed ex. Mazim decore imperdiet ut vel. Scripta delicatissimi an pro, quo ex porro nominati.\n\nΔε τις έργων κανείς γραμμή, κι χρόνου φακέλους γειτονιάς ήδη. Σε πακέτων επενδυτής λες, που κρατήσουν επεξεργασία δε, μια ακούσει ξεχειλίζει παρατηρούμενη τα. Νέων πετάνε συνηθίζουν δε για', στη να σωστά ευκολότερο βαθμολόγησε. Απλό τέτοιο διοίκηση στα μη, δε νέο τότε περιβάλλον, οι δώσε απαρατήρητο των.\n\nΒαθμολόγησε επιδιόρθωση επιχειρηματίες αν ματ, σου δεδομένη αγοράζοντας δωροδοκηθούν με, τα ένα αναφορά βουτήξουν. Αν καρέκλα υποψήφιο εξαρτάται όσο, και δε τεράστιο προκύπτουν σημαντικός, αν ναι καθώς διορθώσει. Υόρκη ιδιαίτερα τη άρα, τα λοιπόν παράγοντες μας. Πόρτες γραμμές σκεφτείς λες με. Σου βγήκε αρχεία δε. Και εφαμοργής κακόκεφος δε.\n</code></pre>\n\n<p>I then ran the code, with a small modification to help benchmarking:</p>\n\n<pre><code>$startTime = microtime(true);\n\nfor ($i = 1; $i &lt;= 10; $i++)\n{\n $ii = new Ngram();\n}\n\n$finishTime = microtime(true);\necho 'Took: ' . ($finishTime - $startTime) . 'seconds';\n</code></pre>\n\n<p>It took about 0.61 seconds without xdebug enabled and 29.1 seconds with it. Note how much slower it is with xdebug (it takes a lot of time to keep track of the execution for profiling)! I then observed the xdebug information using kcachegrind:</p>\n\n<p><img src=\"https://i.stack.imgur.com/3Gkjc.png\" alt=\"kcachegrind table\"></p>\n\n<p>You can see that the time listed against <code>file_put_contents</code> (which is highlighted in the image is very small. Of the 29.1 seconds it only spends .01 seconds writing the files (4 of them). This was on my SSD with an ext4 filesystem. You can see that there are 40 calls to <code>file_put_contents</code> 4 files, 10 times each. Actually, more time is spent by <code>getFilePath</code> which has more costly file stat operations.</p>\n\n<p>The more interesting part is how the 29 seconds gets spent in <code>generateNGram</code>. I have a picture of what I believe to be the \"hot\" part of the code:</p>\n\n<p><img src=\"https://i.stack.imgur.com/3QFdu.png\" alt=\"kcachegrind hot\"></p>\n\n<p>We get into 4 levels of looping here where there are 121280 calls to the inner loop functions. There are no times listed for the for loop structures or the addition to the tokens array (<code>$tokens[] = $token;</code>). I don't exactly know where the 29 seconds got used, but I am assuming that it was within these loops.</p>\n\n<h2>Removed I/O</h2>\n\n<p>The simple way of determining whether this is I/O bound is to remove the I/O. I commented out the <code>file_put_contents</code> line and ran the benchmark again. I found that there was no difference in time with 0.63 seconds without xdebug and 29.2 seconds with it (compared to 0.61 and 29.1). It was actually slower (due to timing fluctuations), but this just shows the negligible influence of the I/O.</p>\n\n<h2>Summary</h2>\n\n<p>I still believe this is a CPU bottleneck and maintain my recommendation for a faster CPU, PHP 5.4 or a compiled language. The other answer raises good points in the \"Optimization, what for?\" section.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T11:28:48.157", "Id": "18178", "Score": "0", "body": "ngrams are generated with *big* corpora. It could be CPU-bound indeed, but this provides little evidence since you can't be I/O-bound with just a few words to read. (oh, and I upvoted.) If it's not IO-bound, then there's a lot of room for optimization. It's easy to imagine a \"char-based\" parser whith very little CPU overhead (and will avoid costly explode, strlen and so on)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T11:48:22.407", "Id": "18179", "Score": "0", "body": "+1 to your answer too, I guess it would be interesting to have files of the order 1TB to make this a more realistic test. I'll leave it as unresolved, but my leaning is towards CPU-bound." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T12:32:27.953", "Id": "18186", "Score": "0", "body": "After some testing with bigger corpora (gutenberg books), it's defintely CPU-bound. What do your languages/*.lng files look like? It's complete gibberish here. If it was normal word n-grams then I could have written a better implementation based on a queue of length N_GRAM_MAX_LENGTH. But I have no idea what he's doing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T13:14:57.993", "Id": "18190", "Score": "0", "body": "It seems that it is unique segments, I'm seeing output in the file including whether they are from the \\_start or end\\_ of a word (note the underscores). I'm not really sure what it is for or if that was the intention." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-31T06:39:25.253", "Id": "10522", "ParentId": "3244", "Score": "6" } }, { "body": "<p>After some testing, it's CPU-bound. I also hit PHP maximum allowed memory size when working with larger files: it eats more than 3G of memory when loading a 4M file. Try reducing the memory usage. :)</p>\n\n<p>I'm leaving my answer below since Paul answered to it.</p>\n\n<h2>I/O bottleneck</h2>\n\n<p>It's quite obvious that you're going to create a <em>lot</em> of data. The <a href=\"http://books.google.com/ngrams/datasets\" rel=\"nofollow\">Google Ngram corpus</a>, for example, uses 1To of disk space. You probably have less data, but you're still going to generate a lot of bytes, which suggests that your program is not CPU-bound, but IO-bound. This also means that using a faster CPU or another language wouldn't help at all.</p>\n\n<h2>A lower bound</h2>\n\n<p>Let's try to work out a lower bound to see what improvements can be made. Since you can't go any faster than a program simply writing the ngrams without any calculation, you should try copying your ngrams data to another folder to see how long it would take. Using \"cp\" would be dangerous, since there may be crazy optimizations like copy-on-write on your specific filesystem.</p>\n\n<pre><code>time cat ngrams/* &gt; all_my_ngrams\ntime cat corpus/* &gt; all_my_corpus\n</code></pre>\n\n<p>You can then compare this to the time it takes for your program to complete, and see where you're losing your time. Another option is to use microtime to benchmark the time you take to actually do computations, and the time to <code>file_get_contents</code> and <code>file_put_contents</code>.</p>\n\n<h2>Optimization, what for?</h2>\n\n<p>Since it's probably a one-off script, why do you want to make it fast? Once you have your ngrams, you can reuse them and forget about this script. Is there a good reason to improve this script? If the problem is more specific than \"takes too long\", than we can help: too much RAM? takes months? Specific strategies can help for specific problems.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-01T04:49:33.247", "Id": "18238", "Score": "0", "body": "That is a very good point. This will probably be memory bound! Keeping a count of the tokens within the inner for loop rather than just adding them would help with this." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-30T09:03:48.697", "Id": "11324", "ParentId": "3244", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T14:21:08.343", "Id": "3244", "Score": "6", "Tags": [ "performance", "regex", "php5", "natural-language-processing", "unicode" ], "Title": "N-gram generation" }
3244
<p>I am always tired of the very verbose syntax in Java for creating small maps. <a href="http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList%28T...%29" rel="nofollow"><code>Arrays.asList(T... a)</code></a> is very convenient, and therefore I want something similar for a map.</p> <pre><code>public class MapUtils { public static &lt;K, V&gt; MapBuilder&lt;K, V&gt; asMap(K key, V value) { return new MapBuilder&lt;K, V&gt;().entry(key, value); } public static class MapBuilder&lt;K, V&gt; extends HashMap&lt;K, V&gt; { public MapBuilder&lt;K, V&gt; entry(K key, V value) { this.put(key, value); return this; } } } /* Example of how to use asMap */ public class Example { public void example() { Map&lt;String, String&gt; map = MapUtil.asMap("key", "value").entry("key2", "value2"); } } /* Example of how the one way to create an inline Map in Java */ public class Before { public void before() { Map&lt;String, String&gt; map = new HashMap&lt;String, String&gt;() {{ put("key", value"); put("key2", value2"); }}; } } </code></pre> <p>Any inputs on how to improve this implementation of <code>MapUtils</code>? Do you consider the <code>asMap</code> function a good idea, or am I too lazy to write some extra characters?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T21:33:38.000", "Id": "4878", "Score": "0", "body": "Looks nice to me. But Landeis solution seems reasonable. :)" } ]
[ { "body": "<p>google-collections has all about it, e.g. <a href=\"http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/ImmutableMap.html#of%28K,%20V,%20K,%20V%29\" rel=\"nofollow\">ImmutableMap.of()</a>.\nMoreover they teach using right data structure, like <strong>true</strong> immutable collections, ordered lists etc. I really enjoyed it.</p>\n\n<hr>\n\n<p>Google Collections is now part of Google Guava, and it includes <a href=\"http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/ImmutableMap.Builder.html\" rel=\"nofollow\">ImmutableMap.Builder</a>. With this you can do:</p>\n\n<pre><code> static final ImmutableMap&lt;String, Integer&gt; WORD_TO_INT =\n new ImmutableMap.Builder&lt;String, Integer&gt;()\n .put(\"one\", 1)\n .put(\"two\", 2)\n .put(\"three\", 3)\n .build();\n</code></pre>\n\n<p>You can call the <code>put(K, V)</code> method as many times as you like. Builders are great for this kind of situation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T12:30:50.120", "Id": "4926", "Score": "0", "body": "Nice tip with google-collections. But it only supports up to five entries." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-06T11:26:31.017", "Id": "4967", "Score": "0", "body": "I have edited this answer with an example of using ImmutableMap.Builder, which gets around the 5 entries limit. I'm waiting for it to be peer reviewed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T18:05:20.133", "Id": "3249", "ParentId": "3245", "Score": "5" } }, { "body": "<p>In my opinion <code>MapBuilder</code> should <em>contain</em> a <code>Map</code>, not extend one. Another possible design would be to use a single call with varargs:</p>\n\n<pre><code>public class MapUtil {\n public static &lt;K,V&gt; Map&lt;K,V&gt; asMap(Map.Entry&lt;K,V&gt;... entries) {\n Map&lt;K,V&gt; map = new HashMap&lt;K,V&gt;();\n for(Map.Entry&lt;K,V&gt; entry : entries) {\n map.put(entry.getKey(), entry.getValue());\n }\n return map;\n }\n\n public static &lt;K,V&gt; Map.Entry&lt;K,V&gt; e(final K k, final V v) {\n return new Map.Entry&lt;K, V&gt;() {\n public K getKey() {\n return k;\n }\n public V getValue() {\n return v;\n }\n public V setValue(V value) {\n throw new UnsupportedOperationException(\"Not supported\");\n }\n };\n }\n} \n\nimport static very.useful.MapUtil.*;\n... \nMap&lt;String, Integer&gt; map = asMap(e(\"x\",1),e(\"y\",2),e(\"z\",3));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T21:35:11.867", "Id": "4879", "Score": "1", "body": "Well, well, but `e`? Just `e`? A bit aggressive and cryptic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T08:33:59.437", "Id": "4887", "Score": "0", "body": "I used `e` for \"entry\", but of course this is a matter of taste. The best thing would be an operator as in Scala (here `->`), but the only symbolic things we have for Java names are `$` and `_`. Hmmm, maybe we should use `$$` for pairs, that would make at least a little bit sense." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T14:36:34.633", "Id": "4897", "Score": "3", "body": "Well, or maybe `entry` for entry? :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T18:07:37.530", "Id": "4901", "Score": "1", "body": "@user unknown: IMHO that would be too long." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T12:29:12.650", "Id": "4925", "Score": "0", "body": "I don't like the `e`-function either, but I guess it is a necessary evil." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T19:33:25.527", "Id": "3250", "ParentId": "3245", "Score": "8" } }, { "body": "<p>I like Landei version, but I have also an untyped version of asMap like asMap(key,value,key,value,...). It is not typed Map, but in many cases, it fits the bill pretty well.</p>\n\n<p>So</p>\n\n<pre><code>Map quickMap = asMap(\"prop1\",\"val1\",\"prop2\",12,\"prop3\");\n</code></pre>\n\n<p>In this case \"prop3\" will have a value null. </p>\n\n<p>Implementation: </p>\n\n<pre><code>static final public Map&lt;String, Object&gt; asMap(Object... objs) {\n HashMap&lt;String, Object&gt; m = new HashMap&lt;String, Object&gt;();\n\n for (int i = 0; i &lt; objs.length; i += 2) {\n String key = objs[i].toString();\n if (i + 1 &lt; objs.length) {\n Object value = objs[i + 1];\n m.put(key, value);\n } else {\n m.put(key, null);\n }\n }\n return m;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-16T10:16:38.417", "Id": "191774", "Score": "0", "body": "I wouldn't recommend this. Only the last value can contain null this way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-17T01:16:27.517", "Id": "191958", "Score": "0", "body": "@yuri I am not sure, because a asMap(\"prop1\",null,\"prop2\",12,\"prop3\"); should work, no?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-18T05:29:08.160", "Id": "192163", "Score": "0", "body": "sure, but it is inconsistent, which means that if you get an odd list of objects, chances are the programmer made a mistake. So I would at least implement a check on `%2==0` for the argument list. And you always return something of type `Map<String, Object>`, maybe make a templated version?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T04:48:05.837", "Id": "45463", "ParentId": "3245", "Score": "1" } } ]
{ "AcceptedAnswerId": "3250", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T14:27:49.660", "Id": "3245", "Score": "11", "Tags": [ "java" ], "Title": "asMap-implementation for Java (based on Arrays.asList)" }
3245
<p>We have some required services down temporarily when our server start. So we need some reconnection logic for them until they are finally up. There is a requirement to have also syncronious way for that. Here is my generic implementation for that via a single background thread:</p> <pre><code>public class RunUntilSuccess { private static final Logger log = LoggerFactory.getLogger(RunUntilSuccess.class); private final String processName; private final Task task; private final int maxAttempts; private final int interval; private final TimeUnit unit; private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); private AtomicInteger count = new AtomicInteger(0); public RunUntilSuccess(String processName, Callable&lt;Boolean&gt; task, int interval, TimeUnit unit) { this(processName, task, interval, unit, -1); } public RunUntilSuccess(String processName, Callable&lt;Boolean&gt; callable, int interval, TimeUnit unit, int maxAttempts) { if (callable == null) { throw new IllegalArgumentException("Callable cannot be null"); } this.processName = processName; this.task = new Task(callable); this.interval = Math.max(0, interval); if (unit == null) { throw new IllegalArgumentException("Unit cannot be null"); } this.unit = unit; this.maxAttempts = (maxAttempts &gt; 0) ? maxAttempts : -1; start(); } private void start() { log.debug("Starting task execution. " + toString()); executor.scheduleWithFixedDelay(task, 0, interval, unit); } /** * Wait until success */ public void await() throws InterruptedException { while (!executor.awaitTermination(interval, unit)) { } } public boolean await(long timeout, TimeUnit unit) throws InterruptedException { return executor.awaitTermination(timeout, unit); } private boolean isAttemptsLimitReached(int attempt){ return (maxAttempts &gt; 0) &amp;&amp; (attempt &gt;= maxAttempts); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(RunUntilSuccess.class.getSimpleName()); sb.append("{processName='").append(processName).append('\''); sb.append(", interval=").append(interval); sb.append(", unit=").append(unit); sb.append(", maxAttempts=").append(maxAttempts); sb.append('}'); return sb.toString(); } private class Task implements Runnable { private final Callable&lt;Boolean&gt; task; public Task(Callable&lt;Boolean&gt; task) { this.task = task; } @Override public void run() { if (isAttemptsLimitReached(count.getAndIncrement())) { log.debug("Task execution finished unsuccessfully after " + count + " attempts."); executor.shutdown(); } else { log.debug("Attempt #" + count); try { if (Boolean.TRUE.equals(task.call())) { log.debug("Attempt #" + count + " was successful. Task execution finished."); executor.shutdown(); } else { throw new FalseExecution(); } } catch (Exception e) { log.error("Attempt #" + count + " failed due to:", e); } } } } public static class FalseExecution extends RuntimeException { } </code></pre> <p>usage:</p> <pre><code>Callable&lt;Boolean&gt; connector = new Callable&lt;Boolean&gt;() { @Override public Boolean call() throws Exception { // connect to ... return true; } }; RunUntilSuccess initializer = new RunUntilSuccess("name", connector, reconnectTimeoutSeconds, TimeUnit.SECONDS); // initializer.await() after it for sync way </code></pre> <p>Is it a common task and how generic this code? Thanks!</p>
[]
[ { "body": "<p>When you submit a task to an Executor you get back a Future, which feels like the appropriate API here since you want to block in one thread on a delayed computation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T19:48:53.133", "Id": "3286", "ParentId": "3246", "Score": "1" } }, { "body": "<p>Your use of <code>executor.awaitTermination()</code> seems odd to me. I would instead have used a CountdownLatch to trigger success in a blocked thread. But I also agree with @Craig P. Motlin that a Future makes sense.</p>\n\n<p>Besides that specific comment, you might consider some asynchronous notification technique for the dependency to declare that it's alive. That might be overkill for your scenario, but it's worked for me. Jini service registry, JMS messages, Hazelcast, plain UDP multicast, etc.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-28T02:47:09.103", "Id": "7201", "ParentId": "3246", "Score": "2" } }, { "body": "<p>design you callable something like below - and you can use Futures.get() to get the result back.</p>\n\n<pre><code>public Boolean call() {\n\n boolean flag = false;\n while(!(isAttemptsLimitReached(count.getAndIncrement()) || flag)){\n\n try{\n\n //try connection (with timeout)\n\n }catch(Exception e){\n // show exception \n }\n\n //continue loop\n }\n\n return flag;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-28T12:17:31.223", "Id": "11261", "Score": "0", "body": "might be a good idea to decide on how to spell `boolean` (capital B or not?) and then stick with it for consistency." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-28T12:53:47.653", "Id": "11265", "Score": "0", "body": "@codesparkle this is a pointer code and not \"code to be copied\" !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-28T14:34:16.303", "Id": "11273", "Score": "0", "body": "it was just a suggestion to improve readability..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-28T18:41:10.960", "Id": "11307", "Score": "0", "body": "@Nrj, thanks, seems for clear code with Future" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-28T10:23:09.600", "Id": "7212", "ParentId": "3246", "Score": "1" } } ]
{ "AcceptedAnswerId": "7212", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T14:57:54.470", "Id": "3246", "Score": "3", "Tags": [ "java", "multithreading" ], "Title": "connect in a background until success" }
3246
<p>I've been using this variation of the Repository pattern for over a year now:</p> <pre><code> public interface IReadOnlyRepository&lt;T, in TId&gt; where T : AbstractEntity&lt;TId&gt; { T Get( TId id ); IEnumerable&lt;T&gt; GetAll(); } /// &lt;summary&gt; /// Defines a generic repository interface for /// classes solely in charge of getting and processing data from a data source /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt; /// &lt;typeparam name="TId"&gt;The type of the id.&lt;/typeparam&gt; public interface IRepository&lt;T, in TId&gt; : IReadOnlyRepository&lt;T, TId&gt; where T : AbstractEntity&lt;TId&gt; { /// &lt;summary&gt; /// Determines whether the specified entity has duplicates. /// &lt;/summary&gt; /// &lt;param name="entity"&gt;The entity.&lt;/param&gt; /// &lt;returns&gt; /// &lt;c&gt;true&lt;/c&gt; if the specified entity has duplicates; otherwise, &lt;c&gt;false&lt;/c&gt;. /// &lt;/returns&gt; bool HasDuplicates(T entity); /// &lt;summary&gt; /// Inserts the specified entity. /// &lt;/summary&gt; /// &lt;param name="entity"&gt;The entity.&lt;/param&gt; void Save( T entity ); /// &lt;summary&gt; /// Inserts the entity or updates it if it already exists. /// &lt;/summary&gt; /// &lt;param name="entity"&gt;The entity.&lt;/param&gt; T SaveOrUpdate( T entity ); /// &lt;summary&gt; /// Updates the specified entity. /// &lt;/summary&gt; /// &lt;param name="entity"&gt;The entity.&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; T Update(T entity); /// &lt;summary&gt; /// Deletes the specified entity from the data source. /// &lt;/summary&gt; /// &lt;param name="entity"&gt;The entity.&lt;/param&gt; void Delete(T entity); /// &lt;summary&gt; /// Deletes the entity with the specified id. /// &lt;/summary&gt; /// &lt;param name="id"&gt;The id.&lt;/param&gt; void Delete(TId id); } </code></pre> <p>but recently, after rereading some books on Design Patterns, I've had this seemingly amazing idea to apply some patterns to my repositories.</p> <pre><code>public interface IRepository&lt;T, in TId&gt; : IReadOnlyRepository&lt;T, TId&gt; where T : AbstractEntity&lt;TId&gt; { void Execute(IRepositoryCommand command); void Execute(IBatchRepositoryCommand command); } public interface IRepositoryCommand&lt;T&gt; { void Execute(T entity); } public interface IBatchRepositoryCommand&lt;T&gt; { void Execute(IEnumerable&lt;T&gt; entities); } public SaveCommand&lt;T&gt; : IRepositoryCommand&lt;T&gt; { public void Execute(T entity) { // Logic for saving goes here } } public BatchSaveCommand&lt;T&gt; : IRepositoryCommand&lt;T&gt; { public void Execute(IEnumerable&lt;T&gt; entities) { // Logic for batch saves go here } } </code></pre> <p>which would then be called like this:</p> <pre><code>_myRepository.Execute(new SaveCommand()); </code></pre> <p>My reasoning is that placing logic for the common data access operations (e.g. saving, deleting) gets to be so repetitive that right now I'm relying on a T4 template to recreate those everytime I have a new entity enter the playing field. This way I just define the most commonly used Data Access operations and then have any of my callers <code>execute</code> whatever action they need to execute.</p> <p>Can you critique my work? I do have the tendency to overthink and overengineer things.</p>
[]
[ { "body": "<p>I think it be useful to introduce explicit units of work that can be used in areas where needed such as Save(). I'd also suggest a generic Query() interface that will take a lambda to improve flexibility in retrieval. You might also consider asynchronous scenarios.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-02T07:31:12.140", "Id": "4883", "Score": "0", "body": "I excluded details on Unit of Work, but the presumption is that every Command implementation will have a reference to it. A generic query interface huh? I can't picture it atm. How would I go about implementing it? I've encountered a LOT of variations of queries and I couldn't find a good place to introduce this level of flexibility." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T21:02:24.743", "Id": "4904", "Score": "0", "body": "Having a generic Query interface makes sense if there is a proper `IQueryable` implementation which would understand the \"lambda\" (an expression tree, actually) and create the db queries accordingly. In other words, there should be Linq-to-Sql, Linq-to-NHibernate or something similar under the hood. Basically, your repo interface has a `Query` method which (if you are using NHibernate) calls `Session.Linq<T>()` and returns an `IQueryable`. This keeps the repo interface simple (because you can do complex queries), but it's hard to implement if your repo only uses ADO.NET underneath." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T03:18:28.437", "Id": "4918", "Score": "0", "body": "I use QueryOver and sadly, it doesn't return IQueryables. I'm still trying to think of a way to get around that limitation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T10:17:14.023", "Id": "4920", "Score": "1", "body": "@John: that would basically be NHibernate's custom way of adding query support without actually implementing `IQueryable`. In other words, you may expose it, but be prepared to use NHibernate-specific constructs in your business layer. The query object pattern itself is tempting to use because it lets you write queries in the business layer, but there are IMHO more cases where strongly typed generic repo interfaces are a better solution (check [this link](http://stackoverflow.com/questions/1666477/ddd-repositories-pattern-with-nhibernate/1666712#1666712))." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T10:24:19.973", "Id": "4921", "Score": "1", "body": "@John: `IQueryable` or `QueryOver` seem like a silver bullet at first, but eventually you may need to do some \"hand-made\" queries yourself (for performance or other reasons), and then it will turn out that being too generic is not such a good thing after all. I am mostly writing this because I started with Linq-to-NHibernate which was implemented rather poorly in NH2.0, and some of more complex queries could not be resolved, which made me realize that query object pattern relies on a contract which cannot easily be abstracted (I don't like the idea of having to implement `IQueryable` myself)." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T20:51:49.377", "Id": "3251", "ParentId": "3247", "Score": "0" } }, { "body": "<p>Although the command pattern you brought in makes it easy to create a 'flexible' Execute method. I wonder if it is really transparant to the ones who read your code.</p>\n\n<p>Perhaps you can combine your two ideas, by implementing a certain ReadOnlyRepository using the command objects. So that the user of your interace keeps using:</p>\n\n<pre><code>repository-&gt;Update(SomeEntity);\n</code></pre>\n\n<p>While the repository implementation does:</p>\n\n<pre><code>repository.Execute(new UpdateCommand());\n</code></pre>\n\n<p>Consider, if you had to make a change to your later interface. Where would you need to update that in your code? In my suggestion it simply requires you to change it at one place. (since all the other code still uses the 'old' interface).</p>\n\n<p>I hope my post makes sense :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T06:26:51.053", "Id": "3263", "ParentId": "3247", "Score": "1" } }, { "body": "<p>Most of my saving and deleting etc are all handled in a base repository class, so I don't really repeat anything.</p>\n\n<p>so for a lot of things you only really need....</p>\n\n<p>IBlahRepository inherits IRepository</p>\n\n<p>ConcreteBlahRepository inherits IBlahRepository and Repository</p>\n\n<p>which is all generic on an Entity</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T02:30:44.097", "Id": "3280", "ParentId": "3247", "Score": "0" } } ]
{ "AcceptedAnswerId": "3263", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T15:29:08.620", "Id": "3247", "Score": "2", "Tags": [ "c#", "design-patterns" ], "Title": "Variations of the Repository Pattern" }
3247
<p>For my project, I needed a way to instantiate different object types during runtime using "string names", for this I designed a generic factory that is created for each object hierarchy type (currently there are two different hierarchies that need the factory).</p> <p>We want the factory to be simple to use and simple to register new types, for this, the factory relies on two classes types.</p> <p>The first one, is the object creator, that each new class that needs to register on the factory instantiates, this is constructed as shown below:</p> <pre><code>template &lt;typename T, typename Y&gt; class ObjectCreatorBase_c: public ObjectCreatorAutoUnlinkHook_t { public: typedef T ObjectType_t; typedef Y ObjectCreatorProc_t; public: ObjectCreatorBase_c(const String_c &amp;name, ObjectCreatorProc_t proc): strName(name), pfnCreateProc(proc) { if(proc == NULL) { std::stringstream stream; stream &lt;&lt; "creator proc cant be null, entity " &lt;&lt; name; PH_RAISE(INVALID_PARAMETER_EXCEPTION, "[ObjectCreatorBase_c::ObjectCreatorBase_c]", stream.str()); } } T Create(const String_c &amp;name) const { return pfnCreateProc(name); } inline const String_c &amp;GetName() const { return strName; } inline bool operator&lt;(const ObjectCreatorBase_c &amp;rhs) const { return strName.compare(rhs.strName) &lt; 0; } private: String_c strName; protected: ObjectCreatorProc_t pfnCreateProc; }; </code></pre> <p>This base class is created because there are two types (right now) of creation function, one with a single parameter for the constructor and another with two. Each type is specialized as shown below:</p> <pre><code>template &lt;typename T&gt; class ObjectCreator_c: public ObjectCreatorBase_c&lt;T, T(*)(const String_c &amp;)&gt; { public: typedef ObjectCreatorBase_c&lt;T, ObjectCreatorProc_t&gt; BaseType_t; public: ObjectCreator_c(const String_c &amp;name, ObjectCreatorProc_t proc): BaseType_t(name, proc) { GenericFactory_c&lt;ObjectCreator_c&lt;T&gt; &gt;::GetInstance().Register(*this); } }; template &lt;typename T, typename Y&gt; class ObjectCreator1_c: public ObjectCreatorBase_c&lt;T, T(*)(const String_c &amp;, Y )&gt; { public: ObjectCreator1_c(const String_c &amp;name, T(*proc)(const String_c &amp;, Y ) ): ObjectCreatorBase_c(name, proc) { GenericFactory1_c&lt;ObjectCreator1_c, Y &gt;::GetInstance().Register(*this); } T Create(const String_c &amp;name, Y param) const { return pfnCreateProc(name, param); } }; </code></pre> <p>The first creator just has a default string parameter that is common for all classes and the second one has an extra template parameter that can be customized.</p> <p>Finally the factory is defined as show below:</p> <pre><code>template &lt;typename T&gt; class GenericFactory_c: boost::noncopyable { public: typedef typename T::ObjectType_t ObjectType_t; static GenericFactory_c &amp;GetInstance() { static GenericFactory_c&lt;T&gt; clInstance_gl; return clInstance_gl; } ObjectType_t Create(const String_c &amp;className, const String_c &amp;name) const { return this-&gt;GetObjectCreator(className).Create(name); } protected: GenericFactory_c() { } friend T; void Register(T &amp;creator) { setObjectCreators.insert(creator); } const T &amp;GetObjectCreator(const String_c &amp;className) const { typename ObjectCreatorSet_t::const_iterator it = setObjectCreators.find(className, ObjectCreatorComp_s&lt;T&gt;()); if(it == setObjectCreators.end()) PH_RAISE(OBJECT_NOT_FOUND_EXCEPTION, "[EntityFactory_c::Create]", className); return *it; } protected: typedef boost::intrusive::set&lt;T, boost::intrusive::constant_time_size&lt;false&gt; &gt; ObjectCreatorSet_t; ObjectCreatorSet_t setObjectCreators; }; </code></pre> <p>Also, there is a specialization of the factory for the object with an extra parameter:</p> <pre><code>template &lt;typename T, typename Y&gt; class GenericFactory1_c: public GenericFactory_c&lt;T&gt; { public: static GenericFactory1_c &amp;GetInstance() { static GenericFactory1_c clInstance_gl; return clInstance_gl; } ObjectType_t Create(const String_c &amp;className, const String_c &amp;name, Y param) const { return this-&gt;GetObjectCreator(className).Create(name, param); } }; </code></pre> <p>By the last, I have created this "comparable" object for searching the set of creators:</p> <pre><code> template&lt;typename T&gt; struct ObjectCreatorComp_s { bool operator()(const String_c &amp;name, const T &amp;res) const { return name.compare(res.GetName()) &lt; 0; } bool operator()(const T &amp;res, const String_c &amp;name) const { return res.GetName().compare(name) &lt; 0; } }; </code></pre> <p>To help understand the code above, below I show how it is being used. For example, for defining a new type to be used with the factory, we use:</p> <pre><code>typedef GenericFactory&lt;ObjectCreator_c&lt;MyObject*&gt; &gt; MyObjectFactory_t; </code></pre> <p>Define a object creator for a concrete type:</p> <pre><code>static ObjectCreator&lt;MyObject*&gt; MyConcreteObject_CreatorObject("MyConcreteObject", MyConcreateObject::Create); </code></pre> <p>Where we assume that "MyConcreteObject" has a static method called "Create" that returns a new instance of the type.</p> <p>Note also that the creator instance will auto-register itself on the appropriate factory.</p> <p>For creating an object instance, we could use:</p> <pre><code>MyObject *obj = MyObjectFactory_t::GetInstance().Create("MyConcreteObject", "objectName"); </code></pre> <p>Any thoughts or suggestion about the design or simple ways to do it are welcome!</p> <p>Thank you</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T22:26:11.663", "Id": "4908", "Score": "0", "body": "Are all your objects default-constructible?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T22:33:45.170", "Id": "4909", "Score": "0", "body": "No, they all need at least one parameter on the constructor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T22:53:26.897", "Id": "4910", "Score": "0", "body": "I admittedly cannot claim to understand much of this design pattern, but I'm just thinking, if I want to register a class `Foo` whose only constructor takes two mandatory arguments, `Foo(char, double)`, how would I `Create` an instance of this class?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T12:40:54.207", "Id": "4927", "Score": "0", "body": "The design assume that each object type has a static Create member function defined in its class. For registering it, you must create a static creator object, like the code sample: static ObjectCreator<MyObject*> MyConcreteObject_CreatorObject(\"MyConcreteObject\", MyConcreateObject::Create);" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T12:48:01.953", "Id": "4928", "Score": "3", "body": "And does the object's `Create` method take an arbitrary number of arguments, or just one or none? Hmm.. to be honest, I can't really see through this vast amount of indirection and tell whether it makes sense. If you're set on this design, I can't say anything meaningful. If you're willing to consider alternatives, though, perhaps we could start higher up and think it over again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T13:08:57.540", "Id": "4929", "Score": "0", "body": "The objects take a fixed number of arguments. For example, for a factory of type \"X\", all objects should take the same arguments, for example, one string and a int. The problem is: I need to create objects by type defined using a string, something like: Create(\"typeABC\", \"param1\", param2); Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T14:01:09.143", "Id": "4930", "Score": "0", "body": "Hm, just thinking... if you want an abstract factory that returns a pointer to a new object like `Factory::make(\"MyObject\")`, then the return type of that function cannot vary depending on the runtime-provided argument. So returning a `MyObject*` seems out of the question -- at best one can return a `void*` and cast that. But that means that you'd know the type already at compile time. So why use a string-based type registry in the first place?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T14:59:27.383", "Id": "4931", "Score": "0", "body": "good point, but to simplify this all objects from a factory<X> should share a common interface or common base class, in this case type X, the diferent object types will derive from X. Something like: Factory<Fruit> factory; factory.Create(\"apple\");" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T15:02:03.053", "Id": "4932", "Score": "0", "body": "@bcsanches let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/714/discussion-between-kerrek-sb-and-bcsanches)" } ]
[ { "body": "<p>Here are two things that you could do to generalise the Factory pattern and decouple the parameter problem. Either or both would make your life easier.</p>\n\n<ol>\n<li>You could consider using the concept of <code>boost::any</code> to allow an arbitrary number arguments of any type in your constructor list.</li>\n<li>Write in the concept of the Null type (an empty class) to represent the case where the parametrised type Y is empty.</li>\n<li>Traits classes allow object hierarchies to do behaviour selection based on type.</li>\n</ol>\n\n<p>Your Generic Factory is a creation behaviour that depends on type. A traits class for each of your creatable object types that is able to allow both the construction and interpretation of the array of any type that the factory interface understands will allow you to decouple the Factory from the Type and the Type should always have both a default constructor and possibly custom constructor(s) that the traits class knows how to use.</p>\n\n<p>PS: I am not a fan of this class type naming style <code>ObjectType_t</code>. The type name is a double tautology.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T07:17:58.920", "Id": "7056", "Score": "1", "body": "+1 for the hatred of hungarian notation... You can buy these things called \"IDEs\" now that will automatically tell you what type a variable is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T16:32:28.423", "Id": "7065", "Score": "0", "body": "yes, IDE can tell the type for you, but you have to keep selecting or putting the cursor in everything that you want to know the type. Your eyes are faster than your hands :)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T16:33:04.273", "Id": "7066", "Score": "0", "body": "I liked the idea of boost::any, I will try it when I have time. Thanks" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T06:27:15.787", "Id": "4721", "ParentId": "3248", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T16:12:06.417", "Id": "3248", "Score": "9", "Tags": [ "c++", "design-patterns", "template" ], "Title": "Generic C++ Factory" }
3248
<p>I've only been writing php for a couple of months, and I've never really had anyone to look at any code I have written. I've written this class, that returns an email address from a database, based on a set schedule. I feel like a lot of the time, I'm doing things the long way, or just the wrong way. So I would really appreciate it if someone could review this class, and make any suggestions at all, as far as coding style, optimization, etc..</p> <p>Let me explain how it works - a quick overview.This email script is called by procmail, and the email address it returns gets forwarded by procmail. The database it connects to has 4 tables(right now).</p> <pre><code>The schedule table has 4 columns, and time in/out are military time. date | tc_name | time_in | time_out The Tour Consultant table has columns: tc_name | friendly_name | email The counters table holds the counters for the currently active Tour Consultants: tc_name | count The lastactivehash table is one field only, and just holds a string of the last tour consultants that were active. Each time this string changes the counters table is flushed, and reinitialized with the current active Tour Consultants. </code></pre> <p>How this is supposed to work: Should divy up emails evenly between current active Tour Consultants. If no one is active, it should look ahead to tomorrow, if it is evening, or the same day if it is morning, and process everyone that is working that day.</p> <p>I tried to name the functions in a way that would explain what they are doing. This is a pretty simple class, but if I should comment it out, let me know.</p> <p>Note: get_manual_override is not implemented.</p> <pre><code>&lt;?php class schedule { private $tomorrow; private $today; private $timenow; private $dblink; private $active_day; private $active_time; private $counters; public $final_email; function __construct() { $this-&gt;dblink = new mysqli('127.0.0.1', '####', '####', '####'); date_default_timezone_set('America/Anchorage'); $this-&gt;today = date('Y-m-d'); $this-&gt;tomorrow = date('Y-m-d', mktime(0, 0, 0, date("m") , date("d")+1, date("Y"))); //military time $this-&gt;timenow = date('Hi'); //This is to be implemented as of yet if ($address = $this-&gt;get_manual_override){ //email it die(); } else{ //Query the db for everyone that has today's date set if ($this-&gt;get_active_full_day($this-&gt;today)){ //Filter these results based on who is active at the current time. $this-&gt;get_active_time(); } //Fallback, try to get tomorrow. else{ if($this-&gt;get_active_full_day($this-&gt;tomorrow)){ $this-&gt;process_whole_day(); $this-&gt;filter_active(); } //Ultimate Fallback, set a default array of emails here (TODO) else{ echo 'didnt find anything'; } } } } //Query the db for people who are active today private function get_active_full_day($date) { $query = "SELECT * FROM schedule LEFT OUTER JOIN tour_consultants ON tour_consultants.tc_name = schedule.tc_name WHERE `date` = '$date'"; $result = $this-&gt;dblink-&gt;query($query) ; if((isset($result-&gt;num_rows)) &amp;&amp; ($result-&gt;num_rows != '')) { $itr = 0; //Store the results into an associative array. while ($row = $result-&gt;fetch_assoc()) { $this-&gt;active_day[$itr]['time_in'] = $row['time_in']; $this-&gt;active_day[$itr]['time_out'] = $row['time_out']; $this-&gt;active_day[$itr]['tc_name'] = $row['tc_name']; $this-&gt;active_day[$itr]['email'] = $row['email']; $itr++; } return true; } else{ return false; } } //This will only run if Today's date is set up in the database. private function get_active_time() { //Loop through the array of active today, and look for people who are currently working. //If they are active, add them to the activetime array. foreach($this-&gt;active_day as $record =&gt; $ar) { if($this-&gt;is_between($this-&gt;timenow, $ar['time_in'], $ar['time_out'])) $this-&gt;active_time[] = $ar; } //If it didn't find anybody currently active. if(!isset($this-&gt;active_time)){ $times_out = array(); $times_in = array(); //Make an array of everybody working today's times in and times out. $itr = 0; foreach($this-&gt;active_day as $record =&gt; $ar) { $times_in[$itr] = $ar['time_in']; $times_out[$itr] = $ar['time_out']; $itr++; } //If the time now is less than the minimum of the times in, then it is morning, and process everyone working //Today if($this-&gt;timenow &lt; min($times_in)) { if($this-&gt;process_whole_day()){ $this-&gt;filter_active(); return true; } else{ return false; } //If the time now is later than the max of times out, get everyone working tomorrow, and process them. } elseif($this-&gt;timenow &gt; max($times_out)) { if($this-&gt;get_active_full_day($this-&gt;tomorrow)){ if($this-&gt;process_whole_day()){ $this-&gt;filter_active(); return true; } else{ return false; } } else{ return false; } } else { //THis else happens if we are probably between shifts... //Process the whole current day here. $this-&gt;process_whole_day(); $this-&gt;filter_active(); } } //This else is what happens when it does find people working at the current time. else{ $this-&gt;filter_active(); return true; } } private function filter_active() { if(!isset($this-&gt;active_time)){ return false; } else{ /* Get a list of the names of people that were active last time an email was sent. If the list has changed, reset the email counters, if it hasn't changed, get the current counters. */ if($lastactive = $this-&gt;get_last_active()){ $curractive = ''; foreach($this-&gt;active_time as $arr) { $curractive .= $arr['tc_name']; } if($lastactive != $curractive) { $this-&gt;reset_counters(); } else{ $this-&gt;counters = $this-&gt;get_counters(); } } //Error getting last hash, so reset counters to be safe. else{ $this-&gt;reset_counters(); } /* Add the counters array to the active time array. */ $min = min($this-&gt;counters); foreach($this-&gt;active_time as $id =&gt; $arr) { if(isset($this-&gt;counters[$arr['tc_name']])){ $this-&gt;active_time[$id]['sent'] = $this-&gt;counters[$arr['tc_name']]; } else{ $this-&gt;active_time[$id]['sent'] = 0; $min = 0; } } /* Find the people who have been emailed the least */ foreach($this-&gt;active_time as $id =&gt; $arr) { if($arr['sent'] == $min){ $leastsent[$id] = $arr; } } /* If more than one person has the same minimum counter, pick a random one of them. */ if(count($leastsent) &gt; 1){ $final = array_rand($leastsent, 1); $final = $leastsent[$final]; } else{ $final = $leastsent['0']; } if(isset($final)) { $newcounter = $final['sent']; /* Increment the counter, and store it in the database, then set the lastactive names in the database. ($this-&gt;activetime) */ $newcounter++; $this-&gt;set_counter($final['tc_name'], $newcounter); $this-&gt;set_last_active(); $this-&gt;final_email = $final['email']; } } } /* Get the list of people who were last active */ private function get_last_active() { $query = "SELECT hash FROM lastactivehash WHERE `id` = '0' LIMIT 1"; if($result = $this-&gt;dblink-&gt;query($query)) { while ($row = $result-&gt;fetch_assoc()) { $oldhash = $row['hash']; } return $oldhash; } else{ return false; } } /* Set the list of people who were active this time around */ private function set_last_active() { $names = ''; foreach($this-&gt;active_time as $arr) { $names .= $arr['tc_name']; } $query = "UPDATE lastactivehash SET `hash`='$names' WHERE `id`='0'"; $result = $this-&gt;dblink-&gt;query($query); if($this-&gt;dblink-&gt;affected_rows != 1) return false; else return true; } /* Get the list of email counters */ private function get_counters() { $query = "SELECT * FROM counters"; if($result = $this-&gt;dblink-&gt;query($query)) { while ($row = $result-&gt;fetch_assoc()) { $counters[$row['tc_name']] = $row['count']; } return $counters; } else{ return 0; } } /* Set a single email counter */ private function set_counter($name, $count) { if($name == '' || $count == ''){ return false; } else{ $query = "UPDATE counters SET `count`='$count' WHERE `tc_name`='$name'"; $this-&gt;dblink-&gt;query($query); if($this-&gt;dblink-&gt;affected_rows != 1) return false; else return true; } } /* Reset email counters, set everybody with an active time to 0 */ private function reset_counters() { $truncate = "TRUNCATE TABLE counters"; $this-&gt;dblink-&gt;query($truncate); foreach($this-&gt;active_time as $arr){ $name = $arr['tc_name']; $query = "INSERT INTO counters (tc_name, count) VALUES ('$name', '0')"; $this-&gt;dblink-&gt;query($query); if($this-&gt;dblink-&gt;affected_rows != 1) $bad = 1; $this-&gt;counters[$arr['tc_name']] = '0'; } if ($bad = 1) return false; else return true; } /* Simple utility function check if one value is between two others. */ private function is_between($value, $min, $max){ if (($value &gt;= $min) &amp;&amp; ($value &lt;= $max)) return true; else return false; } /* Helper function - Set the array of active_day, to currently active, active_time */ private function process_whole_day(){ if((isset($this-&gt;active_day)) &amp;&amp; (!isset($this-&gt;active_time))){ $this-&gt;active_time = $this-&gt;active_day; return true; } else{ return false; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T17:11:33.387", "Id": "4985", "Score": "0", "body": "Ok, I went through and commented out the whole mess. Will someone give me some suggestions please?" } ]
[ { "body": "<p>I'd consider:</p>\n\n<ul>\n<li>breaking it into smaller object (e.g. extract counters)</li>\n<li>do not hardcode the <code>dblink</code> connection + settings (e.g. pass the object in the constructor)</li>\n<li>use phpdoc comments</li>\n<li>correct formatting</li>\n</ul>\n\n<p>Try to write unit test for this class, you'll spot all the drawbacks quickly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T06:54:24.893", "Id": "3743", "ParentId": "3252", "Score": "4" } } ]
{ "AcceptedAnswerId": "3743", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T21:16:38.260", "Id": "3252", "Score": "2", "Tags": [ "php", "mysql" ], "Title": "PHP email selector class" }
3252
<p>I'm working on a project for an image recognition software. The software takes an image and returns a set of labels (a label is just a string of text) which describe the contents of that image. Each returned label is also associated with a confidence value which quantifies how certain the algorithm of its label assignment.</p> <p>A key component of the project is a library of training data. Training data is built by taking labeled images (images with descriptive strings of text already associated with them), passing the images through a bunch of tests called heuristics, and saving the set of values returned from those heuristics along side the associated label. The heuristic values generated from unlabeled images are compared to the library of heuristic return values and labels stored in the training data library to determine what labels should be associated with the unlabeled image. </p> <p>Please critique the design and quality of the following code:</p> <pre><code>/// &lt;summary&gt;Training data is a set of heuristics return values associated with their corresponding input label. /// Traning data is used to take an unlabeled set of heuristic return values and to compare those return values /// to labeled sets of heuristic return value and use that comparison to determine the most appropriate label to /// associate.&lt;/summary&gt; public class TrainingData { /// &lt;summary&gt;Key is the label associated with the value which is a set of heuristic return values&lt;/summary&gt; private Dictionary&lt;string, List&lt;HeuristicReturnValues&gt;&gt; library = new Dictionary&lt;string, List&lt;HeuristicReturnValues&gt;&gt;(); public void AddHeuristics(HeuristicReturnValues returnValuesToAdd) { if (returnValuesToAdd.Label == null) { throw new NullReferenceException( "Trying to add an unlabeled set of heuristic return values to the traning data library"); } if(library.ContainsKey(returnValuesToAdd.Label)){ //Add the heuristic return values to the list associated with the corresponding label in the library List&lt;HeuristicReturnValues&gt; listOfHeuristics = library[returnValuesToAdd.Label]; listOfHeuristics.Add(returnValuesToAdd); library[returnValuesToAdd.Label] = listOfHeuristics; } else { //Create a new label entry in the library library.Add(returnValuesToAdd.Label, new List&lt;HeuristicReturnValues&gt;(){returnValuesToAdd}); } } /// &lt;summary&gt;Take an unlabeled HeursiticReturnVaules object and compare it to each key value pair in the /// library and return the best match as a LookupResult&lt;/summary&gt; public List&lt;LookupResult&gt; PerformLookUp(HeuristicReturnValues unlabeledReturnValues) { if (unlabeledReturnValues.Label != null) throw new Exception("This guy is supposed to be unlabeled!"); List&lt;LookupResult&gt; comparisonValues = new List&lt;LookupResult&gt;(); foreach (var labeledReturnValues in library) { comparisonValues.Add(labeledReturnValues.Value.Compare(unlabeledReturnValues)); } return comparisonValues.OrderBy(i =&gt; i.ConfidenceValue).ToList(); } } /// &lt;summary&gt;Contains the label to be associated with the unlabeled HeuristicReturnValues and a confidence value /// which reflects the algorithm's confidence in making that assignment.&lt;/summary&gt; public class LookupResult { public LookupResult(string lbl, double confidence) { this.Label = lbl; this.ConfidenceValue = confidence; } public string Label { get; set; } public double ConfidenceValue { get; set; } } public static class LibraryExtensionMethods { public static LookupResult Compare(this List&lt;HeuristicReturnValues&gt; labeledSet, HeuristicReturnValues unlabledHeuristic) { //Implement a comparison between labeled and unlabeled heuristic return values throw new NotImplementedException(); } } </code></pre>
[]
[ { "body": "<p>for starters, if you are going to be linqy, you can be totally linqy</p>\n\n<pre><code>public List&lt;LookupResult&gt; PerformLookUp(HeuristicReturnValues unlabeledReturnValues)\n{\nif (unlabeledReturnValues.Label != null) \n throw new Exception(\"This guy is supposed to be unlabeled!\");\n\nreturn library.Select(labeled =&gt; labeled.Value.Compare(unlabeledReturnValues))\n .OrderBy(i =&gt; i.ConfidenceValue).ToList();\n }\n }\n</code></pre>\n\n<p>use 'var' a bit more to make things less wordy.</p>\n\n<p>In fact, if you have resharper, it will help you clean up a lot of this code</p>\n\n<p>rename 'PerformLookup' to be what your comment says it is.. FindBestMatch or something similar</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T02:10:28.927", "Id": "3279", "ParentId": "3254", "Score": "1" } } ]
{ "AcceptedAnswerId": "3279", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T21:30:36.017", "Id": "3254", "Score": "1", "Tags": [ "c#", "library" ], "Title": "Critique the design and quality of this TrainingData class used in my image recognition software" }
3254
<p>Assuming I have 5 arrays, all just indexed arrays, and I would like to combine them, this is the best way I can figure, has anyone found a more efficient solution?</p> <pre><code>function mymap_arrays() { $args = func_get_args(); $key = array_shift($args); return array_combine($key, $args); } $keys = array('u1', 'u2', 'u3'); $names = array('Bob', 'Fred', 'Joe'); $emails = array('bob@mail.com', 'fred@mail.com', 'joe@mail.com'); $ids = array(1, 2, 3); $u_keys = array_fill( 0, count($names), array('name', 'email', 'id') ); $users = array_combine($keys, array_map('mymap_arrays', $u_keys, $names, $emails, $ids) ); </code></pre> <p>This returns:</p> <pre><code>Array ( [u1] =&gt; Array ( [name] =&gt; Bob [email] =&gt; bob@mail.com [id] =&gt; 1 ) [u2] =&gt; Array ( [name] =&gt; Fred [email] =&gt; fred@mail.com [id] =&gt; 2 ) [u3] =&gt; Array ( [name] =&gt; Joe [email] =&gt; joe@mail.com [id] =&gt; 3 ) ) </code></pre> <p>EDIT: After a lot of benchmarking, this is the fastest solution I've come up with</p> <pre><code>function test_my_new() { $args = func_get_args(); $keys = array_shift($args); $vkeys = array_shift($args); $results = array(); foreach($args as $key =&gt; $array) { $vkey = array_shift($vkeys); foreach($array as $akey =&gt; $val) { $result[ $keys[$akey] ][$vkey] = $val; } } return $result; } $keys = array('u1', 'u2', 'u3'); $names = array('Bob', 'Fred', 'Joe'); $emails = array('bob@mail.com', 'fred@mail.com', 'joe@mail.com'); $ids = array(1,2,3); $vkeys = array('name', 'email', 'id'); test_my_new($keys, $vkeys, $names, $emails, $ids); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T23:16:12.070", "Id": "4881", "Score": "4", "body": "Do you have to use arrays? I think using classes to group related data (and behavior) would be a lot nicer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T22:04:02.563", "Id": "5104", "Score": "0", "body": "Why would you even receive the data as such?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T19:54:41.300", "Id": "5130", "Score": "0", "body": "sorry for the delay, @c_maker & @phant0m this data is part of an api, I have no control over the format of the data, it actually comes in as delimited strings that I explode into arrays, I edited my question with my latest attempt" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-09T13:51:03.623", "Id": "10347", "Score": "0", "body": "I have to agree with @c_maker. I would really look at taking the input from the api and feeding it in to classes. At the end of the day, do you really need this code to perform the faster, or to be more easily read and maintained?" } ]
[ { "body": "<p>I would suggest the following:</p>\n\n<pre><code>function combine_keys_with_arrays($keys, $arrays) {\n $results = array();\n\n foreach ($arrays as $subKey =&gt; $arr)\n {\n foreach ($keys as $index =&gt; $key)\n {\n $results[$key][$subKey] = $arr[$index]; \n }\n }\n\n return $results;\n}\n\n$keys = array('u1', 'u2', 'u3');\n$names = array('Bob', 'Fred', 'Joe');\n$emails = array('bob@mail.com', 'fred@mail.com', 'joe@mail.com');\n$ids = array(1,2,3);\n\ncombine_keys_with_arrays($keys, array('name' =&gt; $names,\n 'email' =&gt; $emails,\n 'id' =&gt; $ids));\n</code></pre>\n\n<p>The second parameter to the function can be built as you need it. It avoids array shifting and variable arguments, but I think it should be pretty fast.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-09T09:52:26.807", "Id": "6637", "ParentId": "3255", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-01T22:03:50.947", "Id": "3255", "Score": "6", "Tags": [ "php", "array" ], "Title": "Combining 3 or more arrays in php" }
3255
<p>The source code, or rather the concept I'd like to get reviewed is what now allows me to do the following during reflection:</p> <pre><code>object validator; // An object known to implement IValidation&lt;T&gt; object toValidate; // The object which can be validated by using the validator. // Assume validator is IValidation&lt;string&gt; and toValidate string. IValidation&lt;object&gt; validation = Proxy.CreateGenericInterfaceWrapper&lt;IValidation&lt;object&gt;&gt;( validator ); validation.IsValid( toValidate ); // This works! No need to know about the type. // Assuming the validator validates strings, this will throw an InvalidCastException. //validation.IsValid( 10 ); </code></pre> <p>I no longer need to know about concrete types during reflection where <strong>I know types will match</strong>. It looks kind of like covariance but the result only works because types are guaranteed to match. This allows me to support any type, since no manual type checks need to be done to cast to the correct interface type.</p> <p>The <code>CreateGenericInterfaceWrapper</code> method uses <a href="http://www.codeproject.com/KB/dotnet/runsharp.aspx" rel="nofollow">RunSharp</a> to emit the code. This source code, and an extended explanation <a href="http://whathecode.wordpress.com/2011/07/02/casting-to-less-generic-types/" rel="nofollow">can be found on my blog</a>.</p> <p>My main concerns are:</p> <ul> <li>Did anybody encounter such a use case before, and found a better way to solve it?</li> <li>Did I write something which I could just have found in an existing library?</li> </ul> <hr> <p>To further clarify why I wrote this solution, I copied the example from my blog of the code I would have to write to be able to use the <code>IsValid</code> method during reflection.</p> <pre><code>object validator; // An object known to implement IValidation&lt;T&gt; object toValidate; // The object which can be validated by using the validator. // 'validator' can be any type validator which can validate 'toValidate'. if ( validator is IValidation&lt;string&gt; ) { IValidation&lt;string&gt; validation = (IValidation&lt;string&gt;)validator; validation.IsValid( (string)toValidate ); } else if ( validator is IValidation&lt;int&gt; ) { IValidation&lt;int&gt; validation = (IValidation&lt;int&gt;)validator; validation.IsValid( (int)toValidate ); } else if ... // and so on to support any possible type ... </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T19:23:31.103", "Id": "4903", "Score": "1", "body": "Having check the articles on your blog, I still haven't found the actual (concrete) use cases (which you said exist). Could you elaborate a bit more on that? I don't see the point where you would switch to having an `object` as the type of your class instance (there are usually ways which keep the type safety around). Obviously, once you've lost the type information, generics are pretty useless, but the point is to keep this information around, not to break type safety in order to get back this information after it has been lost." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T22:02:59.967", "Id": "4905", "Score": "0", "body": "@Groo: I updated my question in an attempt to clarify the problem. Actually the posted code is a concrete example which I use in my library. The problem lies in the fact that `validator` can be a validator for any type. An attribute applied to a property defines a certain validator. A factory class extracts this validator from the class and uses it. In my concrete scenario this is a dependency property factory which greatly simplifies creating and maintaining DPs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T22:03:08.173", "Id": "4906", "Score": "0", "body": "In [this unit test](https://github.com/Whathecode/Framework-Class-Library-Extension/blob/master/Whathecode.PresentationFramework.Aspects.Tests/Windows/DependencyPropertyFactory/Attributes/ValidatorsTest.cs) you can see a use case of the attributes. Compare it to [normal dependency property usage](http://msdn.microsoft.com/en-us/library/ms745795.aspx). My factory approach has less duplication and doesn't rely on string literals." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T08:30:22.813", "Id": "4948", "Score": "2", "body": "Ok, you could have just used a non-generic interface (e.g. `IValidation.Valid(object)`), although each concrete implementation would have to cast the `object` to the appropriate type (which is what the wrapper does right now for you). Your approach nevertheless gives stronger type safety while implementing individual validators." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T09:50:15.363", "Id": "4949", "Score": "0", "body": "@Groo: Yup! Nice insight, didn't look at it that way before. I love generics. ;p" } ]
[ { "body": "<p>I recently faced a similar problem, but took a duck-typing approach instead, which works providing the type assumptions hold. For your case, this is what I would have written:</p>\n\n<pre><code>var validatorType = validator.GetType();\nvalidatorType.GetMethod(\"IsValid\").Invoke(validator, toValidate);\n</code></pre>\n\n<p>If there are overloads of <code>IsValid</code>, you'll need to specify the one with the right argument type in the call to <code>GetMethod</code>, but you can find that from <code>toValidate.GetType()</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T13:55:47.620", "Id": "4894", "Score": "1", "body": "Thanks for the answer, but I believe it's a less optimal solution. 1. `Invoke` is really slow. To this extent I [previously posted](http://codereview.stackexchange.com/questions/1070/generic-advanced-delegate-createdelegate-using-expression-trees/1646#1646) how I create delegates from `MethodInfo` which are a lot faster than using `Invoke`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T13:57:09.457", "Id": "4895", "Score": "1", "body": "2. You rely on string literals to find the methods, you'll have to manually find every method in the interface. My solution uses the interface itself to find the methods, so you can change the interface without having to rewrite other code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T14:06:12.263", "Id": "4896", "Score": "1", "body": "3. Type safety is already broken, so the following isn't that much of an advantage. Still, you can choose to use any less generic type parameters, not only `object`. E.g. `IValidation<IValidatable>`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T00:11:49.207", "Id": "4915", "Score": "0", "body": "All fair points, but are you sure that using Invoke is slower than using Reflection.Emit? I presume that CreateGenericInterfaceWrapper is caching the work it does. In my case these choices were reasonable given the context." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T00:31:28.343", "Id": "4916", "Score": "0", "body": "I'm pretty sure Reflection.Emit is slower, since it compiles classes at runtime. The thing is you only need to compile once, and then you'll have the same speed as an ordinary compiled class. Thus the only added overhead is an extra method call and the casts to the correct types. [Jon's results](http://msmvps.com/blogs/jon_skeet/archive/2008/08/09/making-reflection-fly-and-exploring-delegates.aspx) say `Invoke` is 600 times as slow. Of course, if you don't need the speed, don't worry about it. ;p" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T00:22:57.447", "Id": "4943", "Score": "0", "body": "Thanks for the link. Jon's results show that invoke costs 100 ticks on his machine. I imagine you'd have to do a lot of invokes on a very quick running method to detect any difference in your application. In Jon's case, that's exactly what happened. In my case, my invoked methods are calling a database, so the overhead is a drop in the ocean." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-02T01:56:13.270", "Id": "6779", "Score": "0", "body": "Imagining the implications of @Steven's solution performing in a heavy load situation, it would out-perform any method using `Invoke()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T04:13:29.477", "Id": "7227", "Score": "0", "body": "IAbstract, adding 100 ticks to a method that takes 1,000,000 ticks is nothing, regardless of how you slice it. Similarly, adding 100 ticks to a method that takes 100 ticks that you only call once or a handful of times is also just noise in the equation. To make dynamic compilation worthwhile, you need a quick running method that you call very frequently." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T04:29:36.697", "Id": "3262", "ParentId": "3258", "Score": "1" } }, { "body": "<blockquote>\n <p>Did anybody encounter such a use case before, and found a better way to solve it?</p>\n</blockquote>\n\n<p>There's the <code>IEnumerable</code> pattern:</p>\n\n<pre><code>public interface IValidation\n{\n bool IsValid(object obj);\n}\n\npublic interface IValidation&lt;T&gt; : IValidation\n{\n bool IsValid(T t);\n}\n\npublic abstract class BaseValidation&lt;T&gt; : IValidation&lt;T&gt;\n{\n public bool IsValid(object obj)\n {\n return IsValid((T)obj);\n }\n\n public abstract bool IsValid(T t);\n}\n</code></pre>\n\n<p>Whether it's better or not is debatable, but it should at least be familiar to anyone who has to maintain your code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-02T19:58:26.417", "Id": "4551", "ParentId": "3258", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-02T00:58:29.050", "Id": "3258", "Score": "5", "Tags": [ "c#", "proxy", "reflection" ], "Title": "Casting to less generic types" }
3258
<p>I have a live chat database and I am trying to get an idea of how many concurrent chats staff are taking. I'm not sure of the best way to report it so I have decided to get a list of chats for a given period then for each one display a count of chats that overlapped that one in some way.</p> <p>I am querying 2 tables across a join but this is just to get the Operators name. The fields that have the relevant dates are:</p> <pre><code>DateTime? ChatRequests.Answered DateTime? ChatRequests.Closed </code></pre> <p>I think I have everything covered. I just want to see if anyone can tell me if I'm missing anything, or if there is a better approach to it.</p> <pre><code>ChatRequests .Where (cr =&gt; (cr.Created.AddHours (10).Date == DateTime.Now.AddDays (-1).Date)) .Where (cr =&gt; cr.OperatorID.HasValue) .Join ( Operators, chat =&gt; chat.OperatorID.Value, op =&gt; op.ID, (chat, op) =&gt; new { chat = chat, op = op } ) .Select ( g =&gt; new { Operator = g.op.FullName, Answered = g.chat.Answered.Value.AddHours (10), Closed = g.chat.Closed.Value.AddHours (10), Duration = (Decimal)((g.chat.Closed.Value - g.chat.Answered.Value).TotalMinutes), Company = g.chat.AccountName, Contact = g.chat.ContactName, OtherChatsInSamePeriod = ChatRequests .Where (cr =&gt; (cr.OperatorID == g.chat.OperatorID)) .Where (cr =&gt; (cr.ID != g.chat.ID)) .Where ( cr =&gt; (cr.Answered.Value &gt;= g.chat.Answered.Value &amp;&amp; cr.Answered.Value &lt;= g.chat.Closed.Value) || (cr.Closed.Value &gt;= g.chat.Answered.Value &amp;&amp; cr.Closed.Value &lt;= g.chat.Closed.Value) || (cr.Answered.Value &lt; g.chat.Answered.Value &amp;&amp; cr.Closed.Value &gt; g.chat.Closed.Value) ) .Count () } ) </code></pre>
[]
[ { "body": "<p>A faster version of your final where clause is:</p>\n\n<pre><code>cr.Answered.Value &lt;= g.chat.Closed.Value &amp;&amp; cr.Closed.Value &gt;= g.chat.Answered.Value\n</code></pre>\n\n<p>If you do not want to count end points as overlapping (e.g. a call ending exactly at 9:59 and a call beginning exactly at 9:59 do not overlap) then use:</p>\n\n<pre><code>cr.Answered.Value &lt; g.chat.Closed.Value &amp;&amp; cr.Closed.Value &gt; g.chat.Answered.Value\n</code></pre>\n\n<p>You can also remove the <code>.Where (cr =&gt; (cr.ID != g.chat.ID))</code> condition and subtract 1 from the total count since it should be guaranteed that there is only one call taking place by the same operator during the same time period in question.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-06T08:02:27.097", "Id": "3304", "ParentId": "3259", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-02T02:26:24.103", "Id": "3259", "Score": "5", "Tags": [ "c#", "linq", "chat" ], "Title": "Getting items with overlapping DateTime using Linq" }
3259
<p>I have built a website using HTML and CSS. Actually I wanted to learn by implementing real world examples. I have built a site like Google. The search box does not work(I actually did not wanted to go further in the form action part and also did not wanted to use any search engine) and I have <strong>not</strong> copied anything from their site. Its just an effort to learn HTML and CSS. Please have a look and review it.</p> <p><strong>CODE:</strong></p> <pre><code>&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=utf-8"&gt; &lt;title&gt;MyGoogle&lt;/title&gt; &lt;style type="text/css"&gt; #header { width:100%; height:20px; } #header hr { border: none; border-bottom: 2px solid #06f; } .menu ul { text-decoration:none; margin:0; padding:0; } .menu li { display:inline; } #footer { } #logo { padding-top:150px; padding-left:50px; height:500; width: 100%; } .menu { width:100%; background-color:#FFF; } #searchbuttons { padding-left:80px; } #searchbox { padding-left:0px; padding-top:20px; } #container { padding-left:450px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="header"&gt; &lt;div class="menu"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="http://www.google.com.pk/webhp?hl=en&amp;tab=iw"&gt;Web&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://www.google.com.pk/imghp?hl=en&amp;tab=wi"&gt;Images&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://news.google.com.pk/nwshp?hl=en&amp;tab=in"&gt;News&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://translate.google.com.pk/?hl=en&amp;tab=nT"&gt;Translate&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://books.google.com.pk/bkshp?hl=en&amp;tab=Tp"&gt;Books&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://scholar.google.com.pk/schhp?hl=en&amp;tab=ps"&gt;Scholar&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="https://mail.google.com/mail/?hl=en&amp;shva=1"&gt;Gmail&lt;/a&gt;&lt;/li&gt; &lt;!--Was unable to add a drop down menu for more --&gt; &lt;/ul&gt; &lt;/div&gt;&lt;!-- Menu division ends--&gt; &lt;hr/&gt; &lt;!--This does not display--&gt; &lt;/div&gt;&lt;!--Header Division ends--&gt; &lt;div id="container"&gt; &lt;div id="logo"&gt;&lt;img src="http://dvice.com/pics/google_dilemma.jpg" width="300" height="114" &gt;&lt;/div&gt;&lt;!--Logo division ends--&gt; &lt;!--was having a problem when adding --&gt; &lt;form action="http://www.datafeedfile.com/examples/javascript_search.php" method="get"&gt; &lt;div id="searchbox"&gt; &lt;input type="text" title="Search Text" accesskey="s" alt="Search Text" size="60px" maxlength="80" value="" /&gt; &lt;/div&gt; &lt;!--Search Box Devision ends--&gt; &lt;div id= "searchbuttons"&gt; &lt;input type="submit" value="Google Search"/&gt; &lt;input type="submit" value=" I'm Feeling Lucky"&gt; &lt;/div&gt; &lt;!--Search Button division ends--&gt; &lt;/form&gt; &lt;/div&gt; &lt;!--container ends--&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>One reason the <code>&lt;hr/&gt;</code> tag does not display is because the hr element is known to render differently depending on your browser. Try using Firefox, it usually is the best at rendering all sorts of tags. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T15:30:40.627", "Id": "4898", "Score": "0", "body": "Thanks. Yes I was having problem with hr tag." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T13:45:06.503", "Id": "3268", "ParentId": "3261", "Score": "1" } }, { "body": "<p>Just a few quick things I see to help improve your code:</p>\n\n<ol>\n<li>I would start using the HTML5 Doctype, unless you have a specific reason not to. <code>&lt;!doctype html&gt;</code></li>\n<li><p>Instead of having an <code>&lt;hr&gt;</code> tag why not just put a border-bottom:2px solid #06f; on your #header div. And then add like a padding-bottom:5px;</p></li>\n<li><p>Instead of having</p>\n\n<pre><code> &lt;div class=\"menu\"&gt;\n &lt;ul&gt;\n &lt;li&gt;&lt;a href=\"\"&gt;Link&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"\"&gt;Another Link&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p>Why not just do this:</p>\n\n<pre><code>&lt;ul class=\"menu\"&gt;\n &lt;li&gt;&lt;a href=\"\"&gt;Link&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"\"&gt;Another Link&lt;/a&gt;&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>And just change your CSS accordingly:</p>\n\n<pre><code> .menu { text-decoration:none; margin:0; padding:0; }\n .menu li { display:inline; }\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T15:31:56.150", "Id": "4899", "Score": "0", "body": "Thanks alot. Very nice suggestions. I would look forward and try to follow your suggestions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T22:24:40.480", "Id": "4907", "Score": "0", "body": "Shouldn't doctype be uppercase?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T19:08:46.153", "Id": "8239", "Score": "1", "body": "@Akito while the w3c specifies that doctypes need to exactly match the html version they reflect in a case sensitive matter, browsers actually parse them in a case-insensitive manner. As a reference you can find [all doctypes you might want here](http://www.w3.org/QA/2002/04/valid-dtd-list.html)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T14:38:51.450", "Id": "3270", "ParentId": "3261", "Score": "3" } } ]
{ "AcceptedAnswerId": "3270", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-02T16:03:18.547", "Id": "3261", "Score": "1", "Tags": [ "html", "css" ], "Title": "Please have a look at my HTML" }
3261
<p>I just watched a Khan Academy <a href="http://www.khanacademy.org/video/insertion-sort-algorithm?playlist=Computer%20Science" rel="nofollow">video</a> on Insertion Sort and I've tried to write an implementation in Python. Please suggest corrections or improvements on this program:</p> <pre><code>unsorted_list=[45,99,1,-22,7,3,294,10,36] def insertion_sort(unsorted): for i in range(1,len(unsorted)): for j in range(i): if unsorted[i]&lt;unsorted[j]: temp = unsorted[j] unsorted[j]=unsorted[i] unsorted[i]=temp return unsorted print insertion_sort(unsorted_list) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T12:15:18.220", "Id": "4893", "Score": "1", "body": "This acts more like [bubble sort](http://en.wikipedia.org/wiki/Bubble_sort) in that it swaps more elements than necessary. The inner loop should not put the sorted sublist out of order. You need to run the inner loop in reverse and move the *ith* element toward the front of the sorted list--swapping each time with the next element closer to the front--until it finds its spot." } ]
[ { "body": "<p>And swapping in Python can be performed less verbose way:</p>\n\n<pre><code>unsorted[i], unsorted[j] = unsorted[j], unsorted[i]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T14:31:08.910", "Id": "3269", "ParentId": "3264", "Score": "5" } }, { "body": "<p>I wouldn't call your implementation insertion sort as it's sorting in place using swaps, which as David pointed out makes it look more like a bubble sort. An insertion sort sorts by building up a new list and inserting items into the proper place. A very crude first pass at an insertion sort might look like:</p>\n\n<pre><code>def insertion_sort(unsorted_list):\n result = []\n for n in unsorted_list:\n inserted = False\n for i in range(len(result)):\n if n &lt; result[i]:\n result.insert(i, n)\n inserted = True\n break\n if not inserted:\n result.append(n)\n return result\n</code></pre>\n\n<p>This could be greatly improved for larger data sets by making the inner search take advantage of the fact that <code>s</code> is sorted and doing a binary search for the insertion point. Of course, this being Python, the whole mess could be optimized to <code>sorted(unsorted_list)</code>. ;)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T21:44:33.260", "Id": "3300", "ParentId": "3264", "Score": "6" } }, { "body": "<p>The name <code>unsorted</code> for a list which eventually becomes sorted is terrible.</p>\n\n<p>Call it <code>the_list</code> or something else. But don't give it a name which -- at the end of the <code>insertion_sort</code> function will be untrue. Give it a name which will always be true.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T16:05:48.207", "Id": "3397", "ParentId": "3264", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T07:57:02.547", "Id": "3264", "Score": "6", "Tags": [ "python", "sorting", "insertion-sort" ], "Title": "Khan inspired Insertion Sort" }
3264
<p>I have a little project going on and so far I'm not really having any problems. But since I haven't internalized all of Python's core features yet, I'm pretty sure my code offers pretty many subjects to optimize.</p> <p>Please point out anything that could be done better. For example, I'm feeling uncomfortable with the method <code>updateMousePosition</code> as it seems kind of ugly to me.</p> <pre><code>#!/usr/bin/python import sys from PySide import QtCore, QtGui from PySide.QtGui import QWidget, QApplication, QPixmap, QLabel from UI_TextureViewer import Ui_UI_TextureViewer from ExtendedLabel import ExtendedLabel class TextureViewer(QWidget, Ui_UI_TextureViewer): """ A widget that displays a single texture. The textures resides in a ExtendedLabel (which enables connecting to a mouseMovedSignal) which is put inside a QScrollArea to enable arbitrary zooming. The widget also shows the u and v coordinates based on the position of the mouse.""" def __init__(self, filename, parent=None): """ Default ctor. Connects all buttons, loads the texture from file and sets up a default zoom value of 1.0""" super(TextureViewer, self).__init__(parent) self.setupUi(self) self.filename = filename self.buttonZoomIn.clicked.connect(self.zoomIn) self.buttonZoomOut.clicked.connect(self.zoomOut) self.buttonResetZoom.clicked.connect(self.resetZoom) self.u = 0 self.v = 0 self.labelFilename.setText(filename) self.zoomValue = 1.0 self.loadImage() def loadImage(self): """ Loads the image stored in self.filename and sets up the labels showing information about the original (umzoomed) image. """ self.image = QPixmap() self.image.load(self.filename) imgs = [str(self.image.size().width()), str(self.image.size().height())] self.labelSize.setText("x".join(imgs)) self.zoom(self.zoomValue) def zoom(self, factor): """ Zooms the texture by the given factor. Zooming is achieved by creating a scaled copy of the original image and showing it by setting setPixmap of an ExtendedLabel. """ imageLabel = ExtendedLabel() imageLabel.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop) imageLabel.mouseMovedSignal.connect(self.updateMousePosition) ow, oh = [self.image.size().width(), self.image.size().height()] sw, sh = [ow * factor, oh * factor] zoomedImage = self.image.scaled(sw, sh) imageLabel.setPixmap(zoomedImage) self.scrollArea.setWidget(imageLabel) self.updateZoomLabel() def updateZoomLabel(self): """ Updates the label that shows the current zoom value. """ f = self.zoomValue * 100.0 self.labelZoom.setText("{0:.0f}%".format(f)) def zoomIn(self): """ Zooms in 25% on the image. """ self.zoomValue += 0.25 self.zoom(self.zoomValue) def zoomOut(self): """ Zooms out 25% of the image. If the zoom value is less than 25%, then the step size is decreased to 5%. Total zoom level is clamped to 5%. """ if self.zoomValue &lt;= 0.25: v = 0.05 else: v = 0.25 if self.zoomValue - v &gt; 0.05: self.zoomValue -= v self.zoom(self.zoomValue) def resetZoom(self): """ Resets the zoom factor to 1.0. """ self.zoomValue = 1.0 self.zoom(self.zoomValue) def updateMousePosition(self, event): """ Slot that is called by the mouseMovedSignal of the ExtendedLabel which shows the image. Computes the u and v coordinates of the current mouse position and updates the labels showing the coordinates. """ absx, absy = [event.x(), event.y()] sx, sy = [self.image.width() * self.zoomValue, self.image.height() * self.zoomValue] self.u = float(absx) / float(sx) self.v = float(absy) / float(sy) if self.u &gt; 1.0: self.u = 1.0 if self.v &gt; 1.0: self.v = 1.0 self.labelU.setText("{0:.4f}".format(self.u)) self.labelV.setText("{0:.4f}".format(self.v)) if __name__ == '__main__': app = QApplication(sys.argv) frame = TextureViewer("../../media/textures/DarkGrass.png") frame.show() app.exec_() </code></pre>
[]
[ { "body": "<p>A few things I can see that will clean up the code a tad are:</p>\n\n<pre><code>def updateMousePosition(self, event):\n \"\"\" Slot that is called by the mouseMovedSignal of the ExtendedLabel\n which shows the image.\n Computes the u and v coordinates of the current mouse position and\n updates the labels showing the coordinates. \"\"\"\n sx = self.image.width() * self.zoomValue\n sy = self.image.height() * self.zoomValue\n self.u = min(float(event.x()) / float(sx), 1.0)\n self.v = min(float(event.y()) / float(sy), 1.0)\n self.labelU.setText(\"{0:.4f}\".format(self.u))\n self.labelV.setText(\"{0:.4f}\".format(self.v))\n</code></pre>\n\n<p>absx and absy are used once, so I don't see a point in assigning them to temp vars. I'd put sx/sy on separate lines. (As an aside, your use of square brackets is pretty spurious as \"x,y = 1,2\" has the same net effect as \"x,y = [1,2]\" without the creation of a temp list.) Your if's are basically capping self.u and self.v at 1.0. Also are you actually using the self.v and self.u anywhere else or are they just locals to get the values for the setText() calls? If so, they could just be local variables like f in updateZoomLabel().</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T21:17:37.620", "Id": "3299", "ParentId": "3267", "Score": "2" } } ]
{ "AcceptedAnswerId": "3299", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T12:04:34.450", "Id": "3267", "Score": "3", "Tags": [ "python", "performance", "image" ], "Title": "Texture viewer widget" }
3267
<p>I have created a data structure to handle some audio data I am generating (simple sine wave right now). It had some errors in it due to some misunderstanding of my ancient C knowledge that has been fixed by my cousin. I am wondering if there may yet still be more issues.</p> <p>I have considered turning this into a C++ class, but because I don't have enough experience with C++ I would likely turn it into a huge memory leak waiting to happen. This is really being used with Objective C on the iPad - but nothing prevents this from being used elsewhere.</p> <p>All of the functions are publicly accessible, and should be fairly obvious how they should be used. But essentially you alloc the structure, push and pop (which make it sound like a stack but it very much is not), and finally release the structure. You will notice it is in a C Object Oriented Design - I did that intentionally to make things easier to remember. </p> <p>I did not use a circular buffer because I hadn't reached the ballmer peak yet when I was writing this and I couldn't quite get the right form. The queue basically works on the principle that you append on the end, and take data off the top - and the stuff left is moved up to the top.</p> <p>I was looking to use some vector acceleration functions from this at some point. It presently is being used in threaded code behind locks with NSCondition. </p> <p>To see how this is being used now, the structure is used in <a href="https://github.com/iaefai/Tapping/blob/master/MikeOscarNovemberEchoYankee/Tone.m" rel="nofollow">this .m file</a> and is part of <a href="https://github.com/iaefai/Tapping/tree/master/MikeOscarNovemberEchoYankee" rel="nofollow">this project</a>.</p> <pre><code>// from the header file - just converted to a typedef, untested... typedef struct { float *buffer; float *end; size_t max_length; } FIFO; #include "FIFO.h" FIFO *FIFO_alloc(size_t length) { FIFO *restrict ptr = NULL; ptr = (FIFO*)calloc(1, sizeof(FIFO)); if (ptr == NULL) { return NULL; } ptr-&gt;buffer = (float*)calloc(length, sizeof(float)); if (ptr-&gt;buffer == NULL) { free(ptr); return NULL; } ptr-&gt;end = ptr-&gt;buffer; ptr-&gt;max_length = length; return ptr; } void FIFO_release(FIFO *fifo) { if (fifo) { free(fifo-&gt;buffer); free(fifo); } } bool FIFO_push(FIFO *restrict fifo, const float *restrict data, size_t count) { if (!fifo || !data || count == 0) return false; // test for the length available if (fifo-&gt;max_length - (int)(fifo-&gt;end - fifo-&gt;buffer) &lt; count) { return false; } memcpy(fifo-&gt;end, data, count*sizeof(float)); fifo-&gt;end += count; return true; } bool FIFO_pop(FIFO *restrict fifo, float *restrict data, size_t count) { if (!fifo || !data) return false; if (count == 0 || FIFO_size(fifo) &lt; count) return false; // move count items from the buffer memcpy(data, fifo-&gt;buffer, count*sizeof(float)); // move empty space back to the beginning memmove(fifo-&gt;buffer, fifo-&gt;buffer + count, (fifo-&gt;end - fifo-&gt;buffer - count) * sizeof(float)); // reposition end pointer fifo-&gt;end -= count; return true; } size_t FIFO_size(const FIFO *fifo) { if (fifo) { return (size_t)(fifo-&gt;end - fifo-&gt;buffer); } return 0; } size_t FIFO_maxsize(const FIFO *fifo) { if (fifo) { return fifo-&gt;max_length; } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T12:39:29.503", "Id": "62831", "Score": "1", "body": "Just a comment about malloc/calloc: in C you shouldn't cast the result. (While in C++, you would have to cast it.) http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc" } ]
[ { "body": "<p>Looks pretty good....</p>\n\n<p>there's a few style things I'd change</p>\n\n<pre><code>if (fifo-&gt;max_length - (int)(fifo-&gt;end - fifo-&gt;buffer) &lt; count) {\n</code></pre>\n\n<p>I'd bracket things here for clarity.</p>\n\n<p>potentially I'd also extract fifo->end - fifo->buffer into a separate function as you use it multiple times</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T00:41:56.827", "Id": "4917", "Score": "0", "body": "actually, you already have extracted it.....ok, I'd then use it in the code :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T00:39:52.710", "Id": "3276", "ParentId": "3273", "Score": "1" } }, { "body": "<p>Here's a few suggestions in addition to what Keith mentions.</p>\n\n<p>I would try to avoid the memory copy and move operations. You mention a circular buffer, which is one way of doing it, another would be to have the fifo hold discrete buffers and pop each buffer from the front in it's entirety. Avoiding the copy and move operations should speed up the code significantly, which I assume is of concern when processing audio data :)</p>\n\n<p>Also, I would drop the typedef, just use <code>struct fifo</code> instead. This makes it easier to convert this into a full ADT (Abstract Data Type) later, and just forward declare the struct to users while keeping the actual struct private.</p>\n\n<p>As a final note, are you absolutely sure that the <code>restrict</code> keyword is the proper thing to use here?</p>\n\n<p><strong>Edit:</strong>\nHere's one naive way of getting rid of the memove operation:</p>\n\n<pre><code>typedef struct {\n float *buffer;\n float *start;\n float *end;\n size_t max_length;\n} FIFO;\n\n\nbool FIFO_pop(FIFO *restrict fifo, float *restrict data, size_t count) {\n if (!fifo || !data) return false;\n if (count == 0 || FIFO_available(fifo) &lt; count) return false;\n\n // move count items from the buffer\n memcpy(data, fifo-&gt;start, count*sizeof(float));\n fifo-&gt;start += count;\n\n return true;\n}\n</code></pre>\n\n<p>This will only work if you know the max sized buffer that you need, but it should give you an idea.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T10:40:55.353", "Id": "4922", "Score": "0", "body": "The memory copy/move operations are used to copy the data into the awaiting buffer given by the audio system callback. I am not sure there is a way to avoid that - I was under the impression that memory copy was fairly fast. The audio system comes in with a request for so many samples (n floats) and it might vary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T10:58:22.283", "Id": "4923", "Score": "0", "body": "You may not be able to avoid the copies to the destination buffer, that depends on the implementation of the media library you're using. The moves, however should be fairly trivial to remove." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T21:06:30.827", "Id": "4939", "Score": "0", "body": "I am not sure how one would go about removing the moves. The moves are to move it back to the head of the buffer, and it is done with a move because it is potentially overlapping." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T02:52:31.903", "Id": "4945", "Score": "0", "body": "not sure what your point is on the typedef? you can forward declare a typedef and struct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T08:24:43.223", "Id": "4947", "Score": "0", "body": "@iaefai see edited answer for a suggestion.\n@Keith Nicholas forward declaring anonymous typedefed structs cause all kinds of problems with type redefinition errors etc. They can be overcome, but by dropping the typedef altogether they just disappear." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T09:30:09.380", "Id": "3283", "ParentId": "3273", "Score": "3" } } ]
{ "AcceptedAnswerId": "3283", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T19:50:20.503", "Id": "3273", "Score": "4", "Tags": [ "c", "objective-c", "queue", "audio" ], "Title": "FIFO queue for audio data" }
3273
<p>I've been focusing on my PHP skills lately but have been shifting to JavaScript. I'm familiar with the bare-bone basics of jQuery. I'm not as familiar with JavaScript as I'd like to be. I'm a solo-developer so I'd just like somebody to take a look at this and point out any mistakes or things I could be doing better.</p> <p><strong>What the code does</strong></p> <p>Creates an arbitrary number of <code>&lt;script&gt;</code> elements, assigns a <code>type</code> and <code>src</code> attribute to each one and then inserts that <code>&lt;script&gt;</code> element before the <code>&lt;/body&gt;</code>.</p> <p><strong>The code</strong></p> <p>See Better Code below!</p> <pre><code>function async_init() { var element, type, src; var parent = document.getElementsByTagName('body'); var cdn = new Array; cdn[0] = 'http://code.jquery.com/jquery-1.6.2.js'; cdn[1] = 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.js'; for (var i in cdn) { element = document.createElement('script'); type = document.createAttribute('type'); src = document.createAttribute('src'); type.nodeValue = 'text/javascript'; src.nodeValue = cdn[i]; element.setAttributeNode(type); element.setAttributeNode(src); document.body.insertBefore(element, parent); } } &lt;body onload="async_init()"&gt; </code></pre> <p>Right now the code is working, which is great. But my questions:</p> <ol> <li>Is this the "best" way to do this? I define best as <strong>optimum user experience</strong> and <strong>efficient code</strong>.</li> <li>Are there any obvious "noobie" flaws in my JavaScript? </li> <li>Is there anyway I could get the <code>onload</code> attribute out of the <code>body</code>?</li> </ol> <p>I used <a href="https://developer.mozilla.org/en/JavaScript">Mozilla Developer Network</a> as my JavaScript reference. If there are any other references that are <strong>accurate, documented &amp; useful</strong> I would love to have more information.</p> <p>Thanks for checking the code out and your feedback, even if its pointing out how my code sucks!</p> <p><strong>Better code after critique</strong></p> <pre><code>function async_init() { var element; var cdn = new Array; cdn[0] = 'http://code.jquery.com/jquery-1.6.2.js'; cdn[1] = 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.js'; for (var i in cdn) { element = document.createElement('script'); element.setAttribute('type', 'text/javascript'); element.setAttribute('src', cdn[i]); document.body.appendChild(element); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T23:26:19.467", "Id": "4911", "Score": "1", "body": "I believe no harm would be done were you to call [`setAttribute`](https://developer.mozilla.org/En/SetAttribute) directly on `element` rather than creating explicit attribute nodes. It'd make the code ever so much less bulky." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T23:34:01.947", "Id": "4912", "Score": "0", "body": "@Kerrek Thanks for the tip. I thought that was a little too much code for an attribute. Making some changes..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T23:37:19.410", "Id": "4913", "Score": "0", "body": "Oh, no `onload`, please. Always use [`addEventListener`](https://developer.mozilla.org/en/DOM/element.addEventListener) -- though you can only call that once the DOM has been created, so slingshoot it through an initialization function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T00:07:30.610", "Id": "4914", "Score": "0", "body": "@KerrekSB, there's nothing wrong with the use of the `onload` attribute via the body. It's actually far more stable than `addEventListener`, which falls flat in IE < 8." } ]
[ { "body": "<p>You've erred many times in the above code. However, that means you get to learn a lot about how to properly interact with the DOM. In many instances, there are built-ins that quickly and efficiently get the job done.</p>\n\n<p>First off, you're incorrectly accessing the body. <a href=\"http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-56360201\" rel=\"nofollow\" title=\"HTMLDocument.body\"><code>document.body</code></a> is a well-supported reference to the body that's been around since at least DOM Level 1.</p>\n\n<p>Secondly, you're taking the hard route towards creating an array. In his book, \"<a href=\"http://books.google.ca/books?id=PXa2bby0oQ0C&amp;printsec=frontcover&amp;dq=javascript%20the%20good%20parts&amp;hl=en&amp;ei=igIRTrHZGoi2sAOH2vGeDg&amp;sa=X&amp;oi=book_result&amp;ct=result&amp;resnum=1&amp;ved=0CCkQ6AEwAA#v=onepage&amp;q&amp;f=false\" rel=\"nofollow\" title=\"JavaScript: The Good Parts\">JavaScript: The Good Parts</a>\", <a href=\"http://en.wikipedia.org/wiki/Douglas_Crockford\" rel=\"nofollow\" title=\"Douglas Crockford\">Douglas Crockford</a> insists on using literals instead of constructors. In this case, an array literal is <code>[]</code>. This is an easier way of calling <code>new Array()</code>.</p>\n\n<p>Thirdly, you're incorrectly iterating over the <code>cdn</code> array with a <code>for...in</code> loop instead of a <code>for</code> loop. A <code>for...in</code> loop is meant for objects as it iterates over the properties of an object. Not only is it slower than a normal <code>for</code> loop, but it also is very susceptible to prototype modification. For example, try running this code with a build of MooTools (jsFiddle has one enabled by default):</p>\n\n<pre><code>for(var key in [])\n{\n console.log(key); \n}\n</code></pre>\n\n<p>You'll get a ton of hits because MooTools modifies the <code>Array</code> prototype. You'd have to do a <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/hasOwnProperty\" rel=\"nofollow\" title=\"hasOwnProperty\"><code>hasOwnProperty</code></a> check for each property just to avoid those pitfalls. Avoid <code>for...in</code> on anything but objects.</p>\n\n<p>Next, declaring the <code>i</code> variable inside of the <code>for...in</code> loop gives the illusion of block scope. This isn't the case, since <code>i</code> is available anywhere in the function after it's been defined. Only functions have scope in JavaScript. Here are Crockford's thoughts via \"...The Good Parts\" (page 102): </p>\n\n<blockquote>\n <p>In most languages, it is generally best to declare variables at the first site of use. That turns out to be a bad practice in JavaScript because it does not have block scope. It is better to declare all variables at the top of each function.</p>\n</blockquote>\n\n<p>Finally, setting the attributes for each script tag isn't necessary. Since you're already interacting with the DOM, setting their cousin, the DOM property is a better idea. The DOM provides shortcuts to node properties and is more stable than setting attributes. get/set/removeAttribute all have the unfortunate shortcoming of being very weird in various Internet Explorer builds. They're best avoided unless completely necessary.</p>\n\n<p>Fixed + optimized:</p>\n\n<pre><code>function async_init() {\n var element;\n var parent = document.body;\n var cdn = [\"http://code.jquery.com/jquery-1.6.2.js\", \"https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.js\"];\n var i = 0, file;\n for (i;i&lt;cdn.length;i++) {\n file = cdn[i];\n element = document.createElement(\"script\");\n element.type = \"text/javascript\";\n element.src = file;\n parent.appendChild(element);\n //free file's value\n file = null;\n }\n /*\n * Cleanup at end of function, which isn't necessary unless lots of memory is being \n * used up.\n * No point nulling a Number, however. In some ECMAScript implementations\n * (ActionScript 3), this throws a warning.\n */\n //empty array\n cdn.splice(0, cdn.length);\n //clear variable values\n element = null;\n parent = null;\n cdn = null;\n}\n</code></pre>\n\n<p>Also note that since you're adding these scripts asynchronously, there's no stable way to detect when the file has loaded, short of a script loader or a timer (my opinion is neither are stable). </p>\n\n<p>An alternative is to use <code>document.write</code> to append these scripts synchonously. However, you'll have to use a DOMString and escape the forward slash in the script's end tag. This will append it to the end of the body tag. </p>\n\n<p>Example: <code>document.write(\"&lt;script type=\\\"text/javascript\\\" src=\\\"\\\"&gt;&lt;\\/script&gt;\");</code></p>\n\n<p>Note that the backslash character (<code>\\</code>) escapes characters in JavaScript. I've used it to escape the double quotes for each attribute along with the forward slash in the end tag.</p>\n\n<p>If you have any more questions regarding JavaScript or the DOM, feel free to ask in the comments.</p>\n\n<p>-Matt</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T00:06:43.667", "Id": "3275", "ParentId": "3274", "Score": "5" } } ]
{ "AcceptedAnswerId": "3275", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-03T23:00:59.230", "Id": "3274", "Score": "6", "Tags": [ "javascript" ], "Title": "JavaScript dynamic <script> creation" }
3274
<p>So this isn't EXACTLY my code but it is close enough to show what I have. Also the naming is only for this site so if its not really clear forgive me. Its much clearer in the actual code.</p> <pre><code>class Member(models.Model): team = models.IntegerField(default=0) match = models.ForeignKey(Match, null=True, blank=True) def engage(self, match_instance, team_number): self.match = match_instance self.team = team_number self.save() class NPCGeneric(models.Model): speed = models.IntegerField(default=1) difficulty = models.IntegerField(default=0) class NPCInstance(Member): generic = models.ForiegnKey(NPCGeneric); status = models.CharField(max_length=50) def engage(self, match_instance, team_number): new_instance = NPCInstance(generic=self) new_instance.save() return new_instance.engage(match_instance, team_number) class Player(Member): name = models.CharField(max_length=100) class Match(models.Model): event_members = [] def __init__(self, *args, **kwargs): retval = super(Match, self).__init__(*args, **kwargs) if(args[0] and hasattr(args[0], '__iter__')): teams = args[0] args = args[1:] self.__init_new__(teams) elif(self.id): self.__init_existing__() return retval def __init_new__(self, teams): new_teams = [] for team in teams: new_team = [] new_teams.append(new_team) team_number = new_teams.index(new_team) for event_member in team: team_member = event_member .engage(self, team_number) team_member .save() new_team.append(team_member) self.event_members = new_teams def __init_existing__(self): new_teams = [] def add_list(list, member, team): while(list.__len__() &lt; (team + 1)): list.append([]) list[team].append(member) for event_member in self.member_set.all(): try: member = event_member.npcinstance except: member = event_member.player add_list(new_teams, member, member.team) self.event_members= new_teams </code></pre> <p>So this is where I start thinking that there has to be a better cleaner way. Unfortunately my brain just keeps getting stuck on what I already have. </p> <p>I'd love to know if anyone can suggest a cleaner/Pythonic way for holding the Members in the Match class. specifically:</p> <ul> <li>The initialising just seems very odd and clumsy. I'm afraid I will introduce errors this way.</li> <li>a better way of representing teams other than a list of lists <code>event_members</code></li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-06T16:05:41.200", "Id": "4969", "Score": "0", "body": "Can you clarify what are you trying to achieve? Such an unusual `Match` initialization *might* be \"odd and clumsy\", but without knowing the intent of the code it's hard to tell if it is so and whether there are alternatives. It would be also useful if you comment the code for clarification (especially the \"odd\" places)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-09T01:10:01.290", "Id": "5020", "Score": "0", "body": "@Anton I django they have this `member_set` but i can't really access it per team. and if a team gets knocked out of the match then there might be a team missing (e.g. teams 1, 2, 4 and 5) might be still in the match but not team 3). The Intent of the code is to hold `Members` grouped by team in an object called `Match`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-09T01:34:54.123", "Id": "5021", "Score": "0", "body": "I still don't get it... You *can* access members per team through `member_set`: `member_set.filter(team=<some_team_number>)`. Also, why not add members to matches via `Team` objects? You'll be able to access members on a match like that: `team_set.get(number=<some_team_number>).member_set`. And if team gets knocked out, you can just set a flag on `Team` object (or clear its `ForeignKey`, which will remove it from match's `team_set`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-09T01:43:56.300", "Id": "5022", "Score": "0", "body": "I had thought about `Team` objects but I was hoping not to get too complex. i can't access the filtering in the templates either." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-09T02:10:03.973", "Id": "5023", "Score": "0", "body": "I think it's time to move discussion to answer thread. Too long for a comment..." } ]
[ { "body": "<p>Sorry, it just seems to me that issues lie outside of the piece of code that you're suggesting to review. The code itself is more or less fine, but some assumptions behind it seem not right.</p>\n\n<blockquote>\n <p>I had thought about Team objects but I was hoping not to get too complex. i can't access the filtering in the templates either.</p>\n</blockquote>\n\n<p>Well, you still have teams anyway, you're just passing them around \"implicitly\", by their numbers. IMO it actually makes it more complex, and is less \"pythonic\" (remember, <a href=\"http://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow\">explicit is better than implicit</a>).</p>\n\n<p>And, although I don't know the exact requirements, but maybe what you're trying to do in templates could be achieved another way?</p>\n\n<p>Update in response to comment:</p>\n\n<blockquote>\n <p>Also I want to point out that the code works. It just doesn't \"mesh\" in my head well.</p>\n</blockquote>\n\n<p>The code may work, but it looks very… unconventional. And in Python conventions mean a lot. And in Django they mean even more: it's a framework, and, as any other framework, it has lots of design decisions already made for you. It allows you to focus on your data structures and your business logic, but it does that by taking from you some freedom.</p>\n\n<p>So when you're starting to write such complex initialization methods, then probably something is going wrong. I'd say this, and \"implicit\" teams, are cases when you're beginning to \"fight the framework\". It's usually the losing battle. The conventional way is to just have a Team class. It will also make code more maintainable, which is very important. (What if the requirements change and you'll need to store more information about the team, not only its number?)</p>\n\n<blockquote>\n <p>i am also trying to keep the number of different objects in the DB to a minimum but its not THAT important</p>\n</blockquote>\n\n<p>Seems like <a href=\"http://c2.com/cgi/wiki?PrematureOptimization\" rel=\"nofollow\">premature optimization</a>. I doubt that could be a performance bottleneck. Although it depends on your requirements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T23:35:17.467", "Id": "5054", "Score": "0", "body": "No I don't need to worry about the team on the template. That's just another piece of data. It means I then have to access the members by `match > teams > members` instead of just `match > members`. I do like the link for explicit/implicit. That hadn't occured to me. Also I want to point out that the code works. It just doesn't \"mesh\" in my head well. I thought i should add i am also trying to keep the number of different objects in the DB to a minimum but its not THAT important" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T02:30:07.520", "Id": "5075", "Score": "0", "body": "I've updated the answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T03:54:20.177", "Id": "5076", "Score": "0", "body": "Thats a great Answer! It wasn't a performance issue so much as an I'm-not-really-a-db-person issue. Thanks for the response and effort!." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T04:37:08.497", "Id": "5077", "Score": "1", "body": "You're welcome! I'm not a DB person either—but Django's ORM abstraction advocates thinking about information in terms of objects / classes instead of tables, so I'm trying to follow that approach where possible and not to worry about how many tables I'll end up with. And I should say that having a good number of tables never caused problems with maintenance for me so far." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-09T02:10:05.630", "Id": "3358", "ParentId": "3278", "Score": "4" } } ]
{ "AcceptedAnswerId": "3358", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T01:59:17.650", "Id": "3278", "Score": "2", "Tags": [ "python", "django" ], "Title": "Django Team Sport class" }
3278
<p>In a web game there is a ranking of the top points games played of the month:</p> <pre><code>// QUERY SELECT * FROM game WHERE date &gt;= date_sub(CURDATE(),INTERVAL 1 MONTH) ORDER BY points DESC limit 0, 20 </code></pre> <p>But, in that case one player can be the top 1,2,3... so I have changed the query to add a distinct, and then only appears one game for player (the game with max points):</p> <pre><code>// Query that filters player names SELECT g.* FROM game g INNER JOIN ( SELECT playerName, MAX(points) AS MaxPoints FROM game GROUP BY playerName ) groupGame ON g.playerName = groupGame.playerName AND g.points = groupGame.MaxPoints WHERE date &gt;= date_sub(CURDATE(),INTERVAL 1 MONTH) ORDER BY points DESC limit 0, 20 </code></pre> <p>The query works OK but the second query is much slower than the first. Is there any way to optimize it?</p>
[]
[ { "body": "<p>You will have to test performance, but a <code>GROUP BY</code> should help:</p>\n\n<pre><code>SELECT playerName, MAX(points) AS points /*[, other columns]*/\nFROM game\nWHERE date &gt;= date_sub(CURDATE(),INTERVAL 1 MONTH)\nGROUP BY playerName /*[, other columns]*/\nORDER BY points DESC\nLIMIT 0, 20\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T08:59:29.103", "Id": "3282", "ParentId": "3281", "Score": "3" } } ]
{ "AcceptedAnswerId": "3282", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T07:30:54.657", "Id": "3281", "Score": "2", "Tags": [ "mysql", "sql" ], "Title": "Query of top players of the month" }
3281
<p>As you can see, the following is pretty ugly and seems to be unnecessarily long. Is there a shorter/neater way to do this?</p> <pre><code>function addNewRow(body, id){ var myRow = document.createElement("tr"); myRow.id = id+''; var c1 = document.createElement("td"); var c2 = document.createElement("td"); var c3 = document.createElement("td"); var c4 = document.createElement("td"); var d = document.createElement("div"); myRow.appendChild(c1); myRow.appendChild(c2); myRow.appendChild(c3); myRow.appendChild(c4); myRow.appendChild(d); var i1 = document.createElement("input"); var i2 = document.createElement("input"); var i3 = document.createElement("input"); var i4 = document.createElement("input"); i1.type = 'text'; i1.id = 'drwID_' + id; i1.name = 'drwID_' + id; i1.disabled = !editing; i2.type = 'text'; i2.id = 'pos_' + id; i2.name = 'pos_' + id; i2.disabled = !editing; i3.type = 'text'; i3.id = 'stm_' + id; i3.name = 'stm_' + id; i3.disabled = !editing; i4.type = 'text'; i4.id = 'note_' + id; i4.name = 'note_' + id; i4.disabled = !editing; c1.appendChild(i1); c2.appendChild(i2); c3.appendChild(i3); c4.appendChild(i4); body.appendChild(myRow); } </code></pre>
[]
[ { "body": "<p>You need to use loops. Really, that's about it - all of the element creation and appending can be done in a loop, while the prefix for each of the element's <code>name</code> and <code>id</code> be stored in an array.</p>\n\n<pre><code>function addNewRow(body, id) {\n var myRow = document.createElement(\"tr\"),\n d = document.createElement(\"div\"),\n inputPrefix = ['drwID_', 'pos_', 'stm_', 'note_'];\n\n myRow.id = id + '';\n\n for(var i = 0; i &lt; inputPrefix.length; i++){\n var td = document.createElement('td'),\n input = document.createElement('input');\n\n input.type = 'text';\n input.id = inputPrefix[i] + id;\n input.name = inputPrefix[i] + id;\n input.disabled = !editing;\n\n td.appendChild(input);\n myRow.appendChild(td);\n }\n\n myRow.appendChild(d);\n body.appendChild(myRow);\n}\n</code></pre>\n\n<p>You are generating invalid HTML here though - <code>tr</code>s cannot contain <code>div</code> elements. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T11:34:43.107", "Id": "4924", "Score": "0", "body": "Thanks!\n\nI didn't think of storing the prefixes in an array, that's why i couldn't figure out a way to loop it. You're right about the div too, that thing isn't supposed to be there..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T11:17:24.793", "Id": "3285", "ParentId": "3284", "Score": "2" } } ]
{ "AcceptedAnswerId": "3285", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T10:44:52.423", "Id": "3284", "Score": "3", "Tags": [ "javascript", "html" ], "Title": "Generating table rows for a form using js" }
3284
<p>I'm creating a JavaScript/WebGL based game and would like you all to take a look at the current entity component system which I created for it. I've used it once before on another project, and while I was very happy with the results, there were parts of it I did not feel 100% good about. </p> <p>In particular, sometimes a component needs to call the <code>attachedEntities</code> version of a function it has overridden. For example <code>handleInput</code> might call the <code>attachedEntities</code> <code>handleInput</code> functions and then with the new <code>movementVector</code> multiply them by negative 1 so now all input while this component is active is reversed.</p> <p>When I intercept the properties, I currently wrap intercepted function calls into a closure (see <code>basecomponent.intercept()</code>) so that the <code>this</code> object can refer to the component itself. Without that the <code>this</code> object was still being referred to as the <code>attachedEntity</code> (from within the components version of that function), so to get the components properties I had to run a query.</p> <p>Things I've used as reference:</p> <ul> <li><a href="http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/" rel="nofollow noreferrer">http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/</a></li> <li><a href="http://gameprogrammingpatterns.com/component.html" rel="nofollow noreferrer">http://gameprogrammingpatterns.com/component.html</a></li> <li><a href="http://blog.bengarney.com/2010/06/12/composition-vs-inheritance/" rel="nofollow noreferrer">http://blog.bengarney.com/2010/06/12/composition-vs-inheritance/</a></li> </ul> <p>Full source code can be found <a href="https://github.com/onedayitwillmake/ChuClone" rel="nofollow noreferrer">here</a>.</p> <p><strong>Base Component</strong> </p> <pre><code>(function() { ChuClone.namespace("ChuClone.components"); ChuClone.components.BaseComponent = function() { this.interceptedProperties = {}; return this; }; ChuClone.components.BaseComponent.prototype = { /** * Array of properties intercepted, this is used when detaching the component * @type {Array} */ interceptedProperties : null, /** * @type {ChuClone.GameEntity} */ attachedEntity : null, /** * @type {Number} */ detachTimeout : 0, /** * Unique name for this component * @type {String} */ displayName : "BaseComponent", /** * If a component can stack, then it doesn't matter if it's already attached. * If it cannot stack, it is not applied if it's currently active. * For example, you can not be frozen after being frozen. * However you can be sped up multiple times. * @type {Boolean} */ canStack : false, /** * Attach the component to the host object * @param {ChuClone.GameEntity} anEntity */ attach: function(anEntity) { this.attachedEntity = anEntity; }, /** * Execute the component * For example if you needed to cause an animation to start when a character is 'unfrozen', this is when you would do it */ execute: function() { }, /** * Detaches a component from an 'attachedEntity' and restores the properties */ detach: function() { clearTimeout(this.detachTimeout); this.restore(); this.interceptedProperties = null; this.attachedEntity = null; }, /** * Detach after N milliseconds, for example freeze component might call this to unfreeze * @param {Number} aDelay */ detachAfterDelay: function(aDelay) { var that = this; this.detachTimeout = setTimeout(function() { that.attachedEntity.removeComponentWithName(that.displayName); }, aDelay); }, /** * Intercept properties from the entity we are attached to. * For example, if we intercept handleInput, then our own 'handleInput' function gets called. * We can reset all the properties by calling, this.restore(); * @param {Array} arrayOfProperties */ intercept: function(arrayOfProperties) { var len = arrayOfProperties.length; var that = this; while (len--) { var aKey = arrayOfProperties[len]; this.interceptedProperties[aKey] = this.attachedEntity[aKey]; // Wrap function calls in closure so that the 'this' object refers to the component, if not just overwrite if(this.attachedEntity[aKey] instanceof Function) { this.attachedEntity[aKey] = function(){ that[aKey].apply(that, arguments); } } else { this.attachedEntity[aKey] = this[aKey]; } } }, /** * Restores poperties that were intercepted that were intercepted. * Be sure to call this when removing the component! */ restore: function() { for (var key in this.interceptedProperties) { if (this.interceptedProperties.hasOwnProperty(key)) { this.attachedEntity[key] = this.interceptedProperties[key]; } } } } })(); </code></pre> <p><strong>JumpComponent</strong></p> <pre><code> (function(){ ChuClone.namespace("ChuClone.components"); ChuClone.components.JumpPadComponent = function() { ChuClone.components.JumpPadComponent.superclass.constructor.call(this); console.log(this) }; ChuClone.components.JumpPadComponent.prototype = { displayName : "JumpPadComponent", // Unique string name for this Trait _textureSource : "assets/images/game/jumppad.png", _restitution : 2, _previousMaterial : null, _previousRestitution : 0, /** * @inheritDoc */ attach: function(anEntity) { ChuClone.components.JumpPadComponent.superclass.attach.call(this, anEntity); var view = anEntity.getView(); var body = anEntity.getBody(); // Swap materials this._previousMaterial = view.materials[0]; view.materials[0] = new THREE.MeshLambertMaterial( { color: 0xFFFFFF, shading: THREE.SmoothShading, map : THREE.ImageUtils.loadTexture( this._textureSource ) }); view.materials[0] = new THREE.MeshBasicMaterial( { color: 0x608090, opacity: 0.5, wireframe: true } ); // Swap restitution this.swapRestitution( body ); // Listen for body change this.intercept(['setBody', 'height']); }, /** * Sets the restitution level of the provided body's fixtures to make it a jumppad * @param {Box2D.Dynamics.b2Body} aBody */ swapRestitution: function( aBody ) { var node = aBody.GetFixtureList(); while(node) { var fixture = node; node = fixture.GetNext(); this._previousRestitution = fixture.GetRestitution(); fixture.SetRestitution( this._restitution ); } }, /** * Set the body * @param {Box2D.Dynamics.b2Body} aBody */ setBody: function( aBody ) { this.interceptedProperties.setBody.call(this.attachedEntity, aBody ); if(aBody) // Sometimes setBody is called with null this.swapRestitution( aBody ) }, /** * Restore material and restitution */ detach: function() { this.attachedEntity.getView().materials[0] = this._previousMaterial; var node = this.attachedEntity.getBody().GetFixtureList(); while(node) { var fixture = node; node = fixture.GetNext(); fixture.SetRestitution(this._previousRestitution); } ChuClone.components.JumpPadComponent.superclass.detach.call(this); } }; ChuClone.extend( ChuClone.components.JumpPadComponent, ChuClone.components.BaseComponent ); })(); </code></pre> <p><strong>Entity support for components</strong> </p> <pre><code> /** * Adds and attaches a component, to this entity * @param {ChuClone.components.BaseComponent} aComponent * @return {ChuClone.components.BaseComponent} */ addComponent: function(aComponent) { // Check if we already have this component, if we do - make sure the component allows stacking var existingVersionOfComponent = this.getComponentWithName(aComponent.displayName); if (existingVersionOfComponent &amp;&amp; !existingVersionOfComponent.canStack) { return false; } // Remove existing version if (existingVersionOfComponent) { this.removeComponentWithName(aComponent.displayName); } this.components.push(aComponent); aComponent.attach(this); return aComponent; }, /** * Convenience method that calls ChuClone.GameEntity.addComponent then calls execute on the newly created component * @param {ChuClone.components.BaseComponent} aComponent * @return {ChuClone.components.BaseComponent} */ addComponentAndExecute: function(aComponent) { var wasAdded = this.addComponent(aComponent); if (wasAdded) { aComponent.execute(); return aComponent; } return null; }, /** * Returns a component with a matching .displayName property * @param aComponentName */ getComponentWithName: function(aComponentName) { var len = this.components.length; var component = null; for (var i = 0; i &lt; len; ++i) { if (this.components[i].displayName === aComponentName) { component = this.components[i]; break; } } return component; }, /** * Removes a component with a matching .displayName property * @param {String} aComponentName */ removeComponentWithName: function(aComponentName) { var len = this.components.length; var removedComponents = []; for (var i = 0; i &lt; len; ++i) { if (this.components[i].displayName === aComponentName) { removedComponents.push(this.components.splice(i, 1)); break; } } // Detach removed components if (removedComponents) { i = removedComponents.length; while (i--) { removedComponents[i].detach(); } } }, /** * Removes all components contained in this entity */ removeAllComponents: function() { var i = this.components.length; while (i--) { this.components[i].detach(); } this.components = []; } </code></pre> <p><strong>Usage</strong></p> <pre><code>var jumpPadComponent = new ChuClone.components.JumpPadComponent(); entity.addComponentAndExecute( jumpPadComponent ); //... Some time later entity.removeComponentWithName( ChuClone.components.JumpPadComponent.prototype.displayName ); </code></pre> <p>I'm curious about others' thoughts on this implementation of such a component-based system for a JavaScript game. </p> <p><code>JumpPadComponent</code> attached to a couple of standard entities:</p> <p><img src="https://i.stack.imgur.com/wx0k5.jpg" alt="JumpPad component toggle"></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T20:35:29.327", "Id": "4936", "Score": "2", "body": "\"i did not feel 100% about. <code dump>\" Would you like to give a high level overview of which parts might need addressing" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T20:46:06.663", "Id": "4937", "Score": "2", "body": "A rough review of the code makes me think it's far too verbose and over-engineered. KISS." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T21:13:47.967", "Id": "4940", "Score": "0", "body": "Well that isn't much help, in fact you had already posted that before I finished posting the entire code dump - specifically the management of components within the entity. Which was one of the more important parts ot it." } ]
[ { "body": "<p>Your code requires a ton of domain knowledge to properly review. I went to your Github repository to try and be more familiar with what you have.</p>\n\n<p><strong>Entity support for components</strong></p>\n\n<p>You asked specifically for this one, and I did find some things to ponder upon.</p>\n\n<p><strong><code>addComponent</code></strong></p>\n\n<ul>\n<li><p><code>existingVersionOfComponent</code> -> a better name could be <code>existingInstanceofComponent</code> or even simpler <code>instance</code>, as there is no versioning.</p></li>\n<li><p><code>// Remove existing version</code>, for me it is confusing that the component can <code>stack</code>, but you still only allow 1 instance of it. Maybe you should find a better name/descriptor than <code>stack</code>.</p></li>\n</ul>\n\n<p><strong><code>addComponentAndExecute</code></strong></p>\n\n<ul>\n<li>You return <code>null</code> here , not bad in itself, except that you return <code>false</code> in <code>addComponent</code>. You might want to consider reviewing your code and standardizing on <code>false</code> or <code>null</code>.</li>\n</ul>\n\n<p><strong><code>removeComponentWithName</code></strong></p>\n\n<ul>\n<li><p>This code confuses me. It seems built with multiple instances of the same component in mind, but then it <code>breaks</code> out the <code>for</code> loop. It seems you could write this code with 1 loop.</p></li>\n<li><p>You can merge the 2 loops here in to 1 loop:</p>\n\n<pre><code>removeComponentWithName: function(aComponentName) {\n var len = this.components.length;\n var removedComponents = [];\n for (var i = 0; i &lt; len; ++i) {\n if (this.components[i].displayName === aComponentName) {\n removedComponents.push(this.components.splice(i, 1));\n break;\n }\n }\n\n // Detach removed components\n if (removedComponents) {\n i = removedComponents.length;\n while (i--) {\n removedComponents[i].detach();\n }\n }\n},\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>removeComponentWithName: function(componentName) {\n var len = this.components.length,\n removedComponent;\n for (var i = 0; i &lt; len; ++i) {\n if (this.components[i].displayName === componentName) {\n removedComponent = this.components.splice(i, 1).pop();\n removedComponent.detach();\n break;\n }\n }\n},\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T01:27:19.330", "Id": "67626", "Score": "1", "body": "Great feedback. The get component with name, uses the string, displayName property of a component - because it looks for instances of that type, instead of a specific component." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T02:05:46.403", "Id": "67632", "Score": "0", "body": "Right, it can be called by other components with no specific instance in mind. For example a slowdown component, will just get a component called 'speedup' by name and disable it. Not sure what your question is then, obviously" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T13:09:28.937", "Id": "67703", "Score": "0", "body": "Removed that part." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-27T21:56:24.013", "Id": "40208", "ParentId": "3287", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T20:08:27.150", "Id": "3287", "Score": "11", "Tags": [ "javascript", "design-patterns", "game", "entity-component-system" ], "Title": "Component-based system for JavaScript game" }
3287
<p>Is there any way to refactor this?</p> <pre><code>public IEnumerable&lt;Option&gt; Options { get { { List&lt;Option&gt; ListOption = new List&lt;Option&gt;(); if (!String.IsNullOrEmpty(Option1)) { ListOption.Add(new Option() {Name=Option1 }); } if (!String.IsNullOrEmpty(Option2)) { ListOption.Add(new Option() { Name = Option2 }); } if (!String.IsNullOrEmpty(Option3)) { ListOption.Add(new Option() { Name = Option3 }); } if (!String.IsNullOrEmpty(Option4)) { ListOption.Add(new Option() { Name = Option4 }); } return ListOption; } } } public class Option { public string Name { get; set; } } </code></pre>
[]
[ { "body": "<p>This is a bit neater:</p>\n\n<pre><code>List&lt;Option&gt; ListOption = new List&lt;Option&gt; { };\nAction&lt;string&gt; add = x =&gt; { if (!String.IsNullOrEmpty(x)) ListOption.Add(new Option { Name = x }); }\nadd(Option1);\nadd(Option2);\nadd(Option3);\nadd(Option4);\nreturn ListOption;\n</code></pre>\n\n<p>This is perhaps even better:</p>\n\n<pre><code>return (new string[] {Option1, Option2, Option3, Option4})\n .Where(x =&gt; !String.IsNullOrEmpty(x))\n .Select(x =&gt; new Option { Name = x })\n .ToList();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-11T17:35:19.360", "Id": "425293", "Score": "0", "body": "I personally find this hard to read and pretty long winded. I think a simple loop as per @Grant Thomas answer below might be more appropriate here." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T04:48:39.157", "Id": "3291", "ParentId": "3290", "Score": "34" } }, { "body": "<p>Just to be kind of outrageous, here's a version using a standard looping mechanism:</p>\n\n<pre><code>static List&lt;Option&gt; GetNonNullOptions(params string[] options)\n{\n var results = new List&lt;Option&gt;();\n if (options != null)\n {\n foreach (var option in options)\n {\n if (option != null)\n {\n results.Add(new Option { Name = option });\n }\n }\n }\n return results;\n}\n</code></pre>\n\n<p>Leaving you to do something like this:</p>\n\n<pre><code>var nonNullOptions = GetNonNullOptions(Option1, Option2, Option3, Option4);\n</code></pre>\n\n<p>Notice that I only check for null value items, as an empty string and a null value are two different things.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-11T17:33:12.810", "Id": "425292", "Score": "0", "body": "YES these days actually writing a foreach in C# is rightfully frowned upon and should clearly NEVER be done (it's not like looping is a core language construct for a reason). We should all use linq for absolutely everything, all the time ;) haha +1" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T12:43:11.383", "Id": "3292", "ParentId": "3290", "Score": "8" } }, { "body": "<p>This is a good opportunity to use the <code>yield</code> operator:</p>\n\n<pre><code>public IEnumerable&lt;Option&gt; Options\n{\n get\n {\n if (!string.IsNullOrEmpty(Option1)) yield return new Option{Name=Option1};\n if (!string.IsNullOrEmpty(Option2)) yield return new Option{Name=Option2};\n if (!string.IsNullOrEmpty(Option3)) yield return new Option{Name=Option3};\n if (!string.IsNullOrEmpty(Option4)) yield return new Option{Name=Option4};\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T21:09:18.860", "Id": "3298", "ParentId": "3290", "Score": "11" } } ]
{ "AcceptedAnswerId": "3291", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T04:35:04.967", "Id": "3290", "Score": "15", "Tags": [ "c#", "null" ], "Title": "Checking for Null before adding into List" }
3290
<p>I started to play around with Hibernate since yesterday and came up with the following example of one-to-many relationship example, but I am not sure if I am doing right and I have no one around me knowing Hibernate. Please take a quick look at it, then maybe point out anything wrong.</p> <p>My goal is to use a one-to-many relationship with annotations to perform basic Insert and Update.</p> <p>The Entity classes are from <a href="http://www.vaannila.com/hibernate/hibernate-example/hibernate-mapping-one-to-many-using-annotations-1.html" rel="nofollow">here</a>.</p> <p><strong>Student</strong></p> <pre><code>@Entity @Table(name = "STUDENT") public class Student { private long studentId; private String studentName; private Set&lt;Phone&gt; studentPhoneNumbers = new HashSet&lt;Phone&gt;(0); public Student() { } public Student(String studentName, Set&lt;Phone&gt; studentPhoneNumbers) { this.studentName = studentName; this.studentPhoneNumbers = studentPhoneNumbers; } @Id @GeneratedValue @Column(name = "STUDENT_ID") public long getStudentId() { return this.studentId; } public void setStudentId(long studentId) { this.studentId = studentId; } @Column(name = "STUDENT_NAME", nullable = false, length = 100) public String getStudentName() { return this.studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } @OneToMany(cascade = CascadeType.ALL) @JoinTable(name = "STUDENT_PHONE", joinColumns = { @JoinColumn(name = "STUDENT_ID") }, inverseJoinColumns = { @JoinColumn(name = "PHONE_ID") }) public Set&lt;Phone&gt; getStudentPhoneNumbers() { return this.studentPhoneNumbers; } public void setStudentPhoneNumbers(Set&lt;Phone&gt; studentPhoneNumbers) { this.studentPhoneNumbers = studentPhoneNumbers; } //I added in this method for updating public void addPhone(Phone phone) { this.studentPhoneNumbers.add(phone); } } </code></pre> <p><strong>Phone</strong></p> <pre><code>@Entity @Table(name = "PHONE") public class Phone { private long phoneId; private String phoneType; private String phoneNumber; public Phone() { } public Phone(String phoneType, String phoneNumber) { this.phoneType = phoneType; this.phoneNumber = phoneNumber; } @Id @GeneratedValue @Column(name = "PHONE_ID") public long getPhoneId() { return this.phoneId; } public void setPhoneId(long phoneId) { this.phoneId = phoneId; } @Column(name = "PHONE_TYPE", nullable = false, length=10) public String getPhoneType() { return this.phoneType; } public void setPhoneType(String phoneType) { this.phoneType = phoneType; } @Column(name = "PHONE_NUMBER", nullable = false, length=15) public String getPhoneNumber() { return this.phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } } </code></pre> <p><strong><code>CreateMain</code>: create the entry in <code>STUDENT</code>, <code>STUDENT_PHONE</code> and <code>PHONE</code> tables</strong></p> <pre><code>public class CreateMain { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); Set&lt;Phone&gt; phoneNumbers = new HashSet&lt;Phone&gt;(); phoneNumbers.add(new Phone("house", "32354353")); phoneNumbers.add(new Phone("mobile", "9889343423")); Student student = new Student("Eswar", phoneNumbers); session.save(student); transaction.commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { session.close(); } } } </code></pre> <p><strong><code>UpdateMain</code>: Insert a new PHONE entry for the entry created in <code>CreateMain</code></strong></p> <pre><code>public class UpdateMain { public static void main(String[] args) { String testupd = "Eswar"; Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); Query queryResult = session.createQuery("from Student"); List allStudents = queryResult.list(); for (int i = 0; i &lt; allStudents.size(); i++) { Student student = (Student) allStudents.get(i); if(student.getStudentName().compareTo(testupd)==0) { student.addPhone(new Phone("test","12345678")); session.update(student); } } session.getTransaction().commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { session.close(); } } } </code></pre> <p><strong><code>DeleteMain</code>: delete the entry</strong></p> <pre><code>public class UpdateMain { public static void main(String[] args) { String testupd = "Eswar"; Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); Query queryResult = session.createQuery("from Student"); List allStudents = queryResult.list(); for (int i = 0; i &lt; allStudents.size(); i++) { Student student = (Student) allStudents.get(i); if(student.getStudentName().compareTo(testupd)==0) { student.addPhone(new Phone("test","12345678")); session.update(student); } } session.getTransaction().commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { session.close(); } } } </code></pre>
[]
[ { "body": "<p>Just 3 little remarks because it really looks good already.</p>\n\n<ul>\n<li><p>You want the setters of the id's to be private. They are generated\nvalues by Hibernate and other classes shouldn't mess with them.</p></li>\n<li><p>Also for the default constructors of <code>Student</code> and <code>Phone</code>, Hibernate\nneeds only default package visibility. So best to remove the public\naccess modifiers in your default constructors.</p></li>\n<li><p>I would also create a <code>StudentDao</code> class instead of the 3 *Main classes. And if you like, you can use Spring Transaction annotations to reduce the transaction boilerplate code.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-29T07:27:15.173", "Id": "36334", "ParentId": "3293", "Score": "4" } }, { "body": "<p>How well does your code work? I haven't tested it, but I see some things that may cause the program to behave strangely. Overall, it's still OK though.</p>\n\n<ul>\n<li>Consider placing the annotations (<code>@Column</code>, <code>@Id</code>, ...) on the fields rather than the accessors. I know the debate is still open, but I think the improved readability of your class (column definitions are a lot closer to each other) more than compensate any downside it could have (except if you <em>need</em> it of course).</li>\n<li>From a purely relational point of view, you're missing a column in your \"Phone\" entity. You need both a <code>technical id</code> (primary key) and the <code>ID</code> of the student whom it belongs to. Currently, you're using the \"phoneId\" column as a foreign key (<code>inverseJoinColumns = phone_id</code>) and a primary key (with a generated value at that!) I don't see how it can work well. This is your biggest problem currently.</li>\n<li>Unless your use case requires the opposite, you should create the \"Many\" entity and set its \"One\" entity. In your case, create a phone, set its student and save it. You can't do that currently because you don't have a \"Student\" attribute in the \"Phone\" entity. You should add it. The reason for that is that every time you want to ass a phone to a student, you need the entire collection (so you can add something to it). Hibernate will fetch it from the database, which can be slow if your collection is big, even though you don't actually need the collection. In some cases (if you're using the entity outside a transaction and the collection is lazily loaded) it could even fail!</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-07T08:00:56.617", "Id": "106810", "ParentId": "3293", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T13:43:03.407", "Id": "3293", "Score": "5", "Tags": [ "java", "hibernate" ], "Title": "Hibernate @OneToMany relationship" }
3293
<p>I'm currently trying to prove a data structure which I've created to speed up lookups for integral keys. The specific case I have in mind has the following usage case:</p> <ol> <li>At start is populated with n number of items (where n can be from 1 to thousands), and the specific key is actually an <code>unsigned int</code>.</li> <li>The critical path in the code requires a lookup based on this key.</li> </ol> <p>I've tried the following:</p> <ol> <li>sorted <code>vector</code> with binary search</li> <li><code>std::map</code></li> <li><code>boost::unordered_map</code></li> </ol> <p>And now this tree. I've found through profiling that the following holds</p> <ol> <li>If every item looked up exists, then <code>unordered_set</code> is quicker than <code>std::map</code> which is quicker than sorted vector</li> <li>If the number of successful lookups for the search set is low, then <code>std::map</code> is quicker than <code>unordered_set</code> (I guess the hash overhead is higher for failure case)</li> </ol> <p>With this tree, I've found that it's quicker in all cases, but what I would like is some critique on the approach - are there any further optimisations that I am missing for example, and here is the tree:</p> <pre><code>/** Copyright: Nim 2011 */ template &lt;typename KeyType, typename ValueType&gt; class tree { public: typedef ValueType value_type; typedef ValueType&amp; reference; typedef ValueType const&amp; const_reference; typedef KeyType key_type; typedef ValueType* iterator; typedef ValueType const* const_iterator; private: static const size_t MAX_SIZE = 256; typedef unsigned char index_type; struct node { node() : _cKey(), _cValue(), _vNodes() {} ~node() { cleanup(); } void add(key_type index, key_type key, const_reference value) { if (!index) { _cKey = key; _cValue.reset(new value_type(value)); return; } // get the lsb index_type lsb = index &amp; 0xff; if (!_vNodes) { _vNodes = new node*[MAX_SIZE](); _vNodes[lsb] = new node(); } else if (!_vNodes[lsb]) _vNodes[lsb] = new node(); _vNodes[lsb]-&gt;add(index &gt;&gt; 8, key, value); } iterator find(key_type index, key_type key) { if (_cKey == key) return _cValue.get(); if (_vNodes) { // get the lsb index_type lsb = index &amp; 0xff; if (_vNodes[lsb]) return _vNodes[lsb]-&gt;find(index &gt;&gt; 8, key); } return 0; } const_iterator find(key_type index, key_type key) const { if (_cKey == key) return _cValue.get(); if (_vNodes) { // get the lsb index_type lsb = index &amp; 0xff; if (_vNodes[lsb]) return _vNodes[lsb]-&gt;find(index &gt;&gt; 8, key); } return 0; } void optimize() { if (_vNodes) { // first see how many nodes we have size_t count = 0; for(size_t i = 0; i &lt; MAX_SIZE; ++i) count += (_vNodes[i] != 0); switch(count) { case 0: return; // nothing to optimize case 1: pullup(); break;// we could pull up default: { // means we have more than one node at this level, so optimize each for(size_t i = 0; i &lt; MAX_SIZE; ++i) if (_vNodes[i]) _vNodes[i]-&gt;optimize(); } } } } void pullup() { // try to pullup a leaf node for(size_t i = 0; i &lt; MAX_SIZE; ++i) if (_vNodes[i]) { // if we manage to pullup, then cleanup the nodeset at this level if (_vNodes[i]-&gt;pullup(_cKey, _cValue)) cleanup(); break; } } bool pullup(key_type&amp; key, boost::shared_ptr&lt;value_type&gt;&amp; value) { if (!_vNodes) { // this is a leaf node - key = _cKey; value = _cValue; return true; } // cannot pull up at this level // see whether we can pull up from levels below size_t count = 0; for(size_t i = 0; i &lt; MAX_SIZE; ++i) count += (_vNodes[i] != 0); switch(count) { case 0: { // this is a leaf node - key = _cKey; value = _cValue; return true; } case 1: { for(size_t i = 0; i &lt; MAX_SIZE; ++i) if (_vNodes[i]) // if we manage to pullup, then cleanup the nodeset at this level return _vNodes[i]-&gt;pullup(key, value); break; } default: { // means we have more than one node at this level so cannot pullup } } return false; } void print(size_t index, std::ostream&amp; str) { str &lt;&lt; "&lt;node i='" &lt;&lt; index &lt;&lt; '\''; if (_cValue) str &lt;&lt; " key='" &lt;&lt; _cKey &lt;&lt; "' value='" &lt;&lt; *_cValue &lt;&lt; "'"; str &lt;&lt; '&gt;' &lt;&lt; std::endl; if (_vNodes != 0) for(size_t i = 0; i &lt; MAX_SIZE; ++i) if (_vNodes[i]) _vNodes[i]-&gt;print(i, str); str &lt;&lt; "&lt;/node&gt;"; } void cleanup() { if (_vNodes) { for(size_t i = 0; i &lt; MAX_SIZE; ++i) if (_vNodes[i]) delete _vNodes[i]; delete[] _vNodes; _vNodes = 0; } } key_type _cKey; boost::shared_ptr&lt;value_type&gt; _cValue; node** _vNodes; }; public: tree() : _vNodes() {} ~tree() { if (_vNodes != 0) { for(size_t i = 0; i &lt; MAX_SIZE; ++i) if (_vNodes[i]) delete _vNodes[i]; delete[] _vNodes; _vNodes = 0; } } iterator end() { return 0; } const_iterator end() const { return 0; } void add(key_type key, const_reference value) { // get the lsb unsigned char lsb = key &amp; 0xff; if (!_vNodes) { _vNodes = new node*[MAX_SIZE](); _vNodes[lsb] = new node(); } else if (!_vNodes[lsb]) _vNodes[lsb] = new node(); _vNodes[lsb]-&gt;add(key &gt;&gt; 8, key, value); } iterator find(key_type key) { if (_vNodes) { // get the lsb index_type lsb = key &amp; 0xff; if (_vNodes[lsb]) return _vNodes[lsb]-&gt;find(key &gt;&gt; 8, key); } return 0; } const_iterator find(key_type key) const { if (_vNodes) { // get the lsb index_type lsb = key &amp; 0xff; if (_vNodes[lsb]) return _vNodes[lsb]-&gt;find(key &gt;&gt; 8, key); } return 0; } void optimize() { if (_vNodes ) // optmize each root node for(size_t i = 0; i &lt; MAX_SIZE; ++i) if (_vNodes[i]) _vNodes[i]-&gt;optimize(); } friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; str, tree const&amp; t) { str &lt;&lt; "&lt;?xml version='1.0'?&gt;" &lt;&lt; std::endl; if (!t._vNodes) return str &lt;&lt; "&lt;tree/&gt;" &lt;&lt; std::endl; str &lt;&lt; "&lt;tree&gt; " &lt;&lt; std::endl; for(size_t i = 0; i &lt; MAX_SIZE; ++i) if (t._vNodes[i]) t._vNodes[i]-&gt;print(i, str); return str &lt;&lt; "&lt;/tree&gt; " &lt;&lt; std::endl; } private: node** _vNodes; }; </code></pre> <p>Some salient points:</p> <ol> <li>I don't need the container to be iterable - all I want is the fastest possible lookups</li> <li>I don't care about insertion performance as it's a start up cost</li> <li>I've added an <code>optimize</code> method to "prune" the tree and this works nicely, however the performance difference between a pruned and a normal tree is negligible.</li> <li>Yes, I've considered <code>boost::scoped_array</code>.</li> <li>I am considering using a <code>std::vector&lt;node*&gt;</code> rather than <code>node**</code>, I find the pointer syntax strangely appealing.</li> </ol>
[]
[ { "body": "<p>Just a few points (caveat: I'm not a C++ expert).</p>\n\n<ol>\n<li><p>Comparing structured (i.e., non-scalar) keys is often the most expensive part of doing a search; it is usually worth searching first on an integer hash of the key. This way you only need to do integer comparisons for the most part.</p></li>\n<li><p>I am AMAZINGLY surprised that binary search on a sorted array doesn't beat the pants off everything else. Binary search is vastly simpler than anything else and has optimal pruning. I seriously suspect your results here are to do with issue (1) above.</p></li>\n<li><p>You don't say how much your results differed in your experiments. If the differences are small, it probably isn't worth rolling your own code.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T09:36:02.523", "Id": "4979", "Score": "0", "body": "Thanks for your comments, 1) yes, which is why unordered_map (which uses a hashing) suffers, hashing is actually more expensive than four right shifts (which is worst case with the above tree). 2) Well, a binary search on a sorted array is really no different to a search on a binary tree (which is what map uses) - and hence there is virtually no difference between the two. 3) Real numbers are irrelevant (i.e. platform specific), but the percentages are significant, the tree above can be more than three times quicker than any of the other approaches - I wouldn't have bothered otherwise." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T03:16:21.710", "Id": "4988", "Score": "0", "body": "Hi Nim, I'd expect binary search to be faster because it has half the number of memory accesses (each binary tree node requires one access for the key and one access for the child pointer). Is it possible that sorted vector is not inlining your comparison function?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T08:43:16.763", "Id": "4993", "Score": "0", "body": "I don't have a specific comparison function, I've implemented the `operator<` for the simple structure which I store in the vector, and this structure has the integer key, which looks like `lhs.id < rhs.id` - I didn't check the assembler, but I'd be mightily surprised if it didn't inline the above. I'm using a very small number of elements for testing (64 to be precise) and I'd be surprised if the entire structure was not in the cache (in all the four tests)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T08:52:44.380", "Id": "4994", "Score": "0", "body": "...and increasing the number of test items increases the the time taken (unsurprisingly - logarithmically!) With 200 items, the \"optimized\" tree maintains the best speed - the difference between that and `unordered_map` (which remains the same - as expected) is still three times - the unoptimized tree is half the time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-09T00:01:37.043", "Id": "5019", "Score": "0", "body": "Hang on, I've just looked at your code - you've implemented a 256-way tree! Of course that will be faster, but at much greater memory cost. Inserting 256 items with keys 256i for i in 0..255 will occupy enough space for 64K items." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-09T11:52:16.580", "Id": "5027", "Score": "0", "body": "It's a little bigger than that! ;) The nodes are created only as necessary and the optimization cleans up lots of redundant nodes. The resulting three is actually quite efficient (interms of memory) whilst being very fast for lookups (iteration via visitors is no slouch either)." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-06T23:17:26.833", "Id": "3317", "ParentId": "3294", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T13:45:04.533", "Id": "3294", "Score": "6", "Tags": [ "c++", "algorithm", "tree", "lookup" ], "Title": "Tree/array mashup" }
3294
<p>I've written a python module that randomly generates a list of ideas that can be used as the premises for furthur research. For instance, it would be useful in situations where a new thesis topic is required, either for a masters or a doctorate program. Or if someone is just simply bored with their lives and wants some brainstorming ideas about the kind of project that they would like to be involved in, this python module can be used.</p> <p>The output is a list of random ideas or technologies. It is up to the user as to how they interpret the output. Each idea in the list can be assessed individually, or the ideas can be combined in ways never thought off before to create something new.</p> <p>I would like some input on how else I can improve the project or what other features I may add. The project is hosted on github. The name of the project is <a href="https://github.com/kissandra79/Ranto" rel="nofollow">ranto</a> for lack of a better name.</p> <p>For the impatient, here is the code from the sole python file in the project...</p> <pre><code>import random import sys def topics(f): f = open(f, 'r') wordlist = [] for i in f: wordlist.append(i.strip()) return wordlist def mainp(): wordlist = topics('../data/' + sys.argv[1]) while True: print random.sample(wordlist, int(sys.argv[2])) if raw_input() == '': continue else: break mainp() </code></pre> <p>If you want to test it out, you need to download one of the data files from the github repo linked earlier.</p> <p>Any feedback would be appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-06T16:21:17.783", "Id": "4971", "Score": "1", "body": "Even for such simple program there's a thing you could do: replace each <tab> with four spaces (it isn't obvious here, but it is on the GitHub); this is a PEP recommendation. On a slightly unrelated note (since this is Code Review, not Feature Review), it would be cool if Ranto could get data for topics from other sources—for example, Wikipedia." } ]
[ { "body": "<p>I can't tell from your question whether you are wanting ideas to improve this python code or the project itself. Your code above works and is readable, so take the following re-spelling of it as minor nitpicks.</p>\n\n<pre><code>def topics(f):\n for i in open(f): # inline the call to open(), and drop the implicit 'r'.\n yield i.strip() # \"yield\" turns this into a generator function that will only\n # read as many lines of the file as are requested.\n\ndef mainp(): # consider renaming to something more descriptive (generate_topics?)\n wordlist = topics('../data/' + sys.argv[1])\n response = True # Or any \"truthy\" value that drops us into the while loop one time.\n while response:\n print random.sample(wordlist, int(sys.argv[2]))\n response = raw_input()\n\nif __name__ == \"__main__\": # Putting in this if guard allows you to import your \n mainp() # functions above from anywhere else you might want them.\n</code></pre>\n\n<p>You may want to peruse the <a href=\"http://docs.python.org/howto/functional.html#generators\" rel=\"nofollow\">HOWTO for generator functions</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T14:51:40.767", "Id": "5091", "Score": "0", "body": "-1: \"and drop the implicit 'r'.\" Never works out well in the long run. Only really smart people remember that 'r' is the default. The rest of us have to look it up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T15:40:03.200", "Id": "5092", "Score": "0", "body": "@S.Lott: Weird. I thought this was generally known, and am not so smart." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T15:42:38.053", "Id": "5093", "Score": "0", "body": "@Tshepang: \"generally known\" is really hard to determine. However, I do (1) Explicit is better than implicit and (2) I have to look up the defaults and (3) I've had other programmers unable to remember this kind of default. So, for those reasons, I suggest avoiding defaults for this kind of thing. It may be \"generally known\", but it still doesn't work out well in the long run." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T20:54:56.860", "Id": "5133", "Score": "0", "body": "I agree with Lott on this one. If not for all the reasons but one.......'Explicit' is better than 'Implicit'." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T12:36:50.023", "Id": "5292", "Score": "0", "body": "@S.Lott: I don't see how anyone can misread `for i in open(f)` as opening the file for writing. Do you similarly specify the slice step as 1 when slicing a sequence (e.g. `chunk = seq[10:20:1]`)? That's certainly more explicit, but readability suffers from the extra noise." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T13:05:05.190", "Id": "5295", "Score": "0", "body": "@Don Spaulding: \"I don't see how anyone can misread `open(f)` as opening the file for writing.\" Sadly, however, some folks are not as cognizant of the defaults as others. I'm not making a blanket statement about all defaults for all language constructs. I'm making one point about one default for one specific function that has caused confusion in the past." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T18:18:22.783", "Id": "3332", "ParentId": "3295", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-05T13:57:34.133", "Id": "3295", "Score": "5", "Tags": [ "python", "python-2.x", "random", "generator" ], "Title": "Random Topic Generator" }
3295
<p>I'm a pretty visual person and I like to see all the cool information about objects, arrays and different variables in PHP. In the beginning I would just <code>echo '&lt;pre&gt;', var_dump($var), '&lt;/pre&gt;';</code> liberally throughout my code. Then I was introduced to MVC and started grasping the concept of OOP and the Front Controller design pattern. Now, after having built my own little personal framework for academic reasons and understanding the need for reusable code a little part of my soul is eaten away every time I have to manually type this out.</p> <p>This was my attempt at an OOP-style debugger that will spit out various information about the passed variable. The <code>debug()</code> method is the only <code>public</code> method and it takes two parameters, 1 being the variable you want to know more about and the other an optional <code>boolean</code>, default <code>true</code>, to toggle echoing a message to Firebug/Webkit Inspector console or straight to the browser screen.</p> <p>My question is: Does this look horribly bad? Are there ways that my code can be improved? Is my logic illogical? </p> <pre><code>/** * Returns useful information about variables or objects for debugging purposes * * @package sprayfire * @subpackage core */ class SprayFireDebugger { /** * The original variable that needs to be debugged * * @var mixed */ private $_debugVar; /** * True if the debug message should be sent to console.log and false if it * doesn't * * @var bool */ private $_doConsoleLog; /** * The final message that should be echod * * @var mixed */ private $_debugMessage; /** * SprayFireDebugger should never rely on __construct dependencies * * @return void */ public function __construct() { } /** * Will emit useful information about the given variable. If the second * parameter is set to false the message gets displayed on the screen * as compared to the debug console * * @param mixed $var * @param bool $toJsConsole * @return void */ public function debug($var, $toJsConsole = true) { try { $this-&gt;_debugVar = $var; $this-&gt;_doConsoleLog = $toJsConsole; if (is_object($this-&gt;_debugVar)) { $this-&gt;_debugObject(); } else { $this-&gt;_debugMessage = $this-&gt;_debugVar; } $this-&gt;_send(); $this-&gt;_cleanUpDebug(); return true; } catch (Exception $Exception) { // here to catch exceptions from _debugObject() error_log($Exception-&gt;__toString()); $this-&gt;_cleanUpDebug(); return false; } } /** * Will determine if an object is an exception or not and return * appropriate information for an object * * @return void */ private function _debugObject() { $exc = 'Exception'; $Reflection = new ReflectionClass($this-&gt;_debugVar); if ($Reflection-&gt;getName() === $exc) { return $this-&gt;_debugException(); } if ($Reflection-&gt;getParentClass()) { if ($Reflection-&gt;getParentClass()-&gt;getName() === $exc) { return $this-&gt;_debugException(); } } $debugInfo = $Reflection-&gt;export($this-&gt;_debugVar, true); $this-&gt;_debugMessage = $debugInfo; return; } /** * Takes an Exception object and turns it into an appropriate array to * be sent to the console or screen * * @return void */ private function _debugException() { $debugInfo = array( 'message' =&gt; $this-&gt;_debugVar-&gt;getMessage(), 'code' =&gt; $this-&gt;_debugVar-&gt;getCode(), 'file' =&gt; $this-&gt;_debugVar-&gt;getFile(), 'line' =&gt; $this-&gt;_debugVar-&gt;getLine(), 'trace' =&gt; $this-&gt;_debugVar-&gt;getTrace() ); $this-&gt;_debugMessage = $debugInfo; return; } /** * Sends $this-&gt;_debugMessage to the screen or a JS console * * @return void */ private function _send() { if ($this-&gt;_doConsoleLog) { $this-&gt;_sendToConsole(); } else { $this-&gt;_sendToScreen(); } if (empty($this-&gt;_debugMessage)) { throw new Exception('There was no error message to show. This likely means something is royally messed up!', E_USER_ERROR); } echo $this-&gt;_debugMessage; return true; } /** * Echos out a script that logs a JSON ecoded $this-&gt;_debugMessage in the * browser console window. If you are testing with IE please ensure you * pass false to $this-&gt;debug() * * @return void */ private function _sendToConsole() { $consoleMsgMarkup = '&lt;p style="position: absolute; bottom: 0; right: 1em;" class="sprayfire-debug-message"&gt;Debug info sent to console!&lt;/p&gt;'; $scriptMarkup = '&lt;script type="text/javascript"&gt;'; $scriptMarkup .= 'console.log(' . json_encode($this-&gt;_debugMessage) . ')'; $scriptMarkup .= '&lt;/script&gt;'; $this-&gt;_debugMessage = $consoleMsgMarkup . $scriptMarkup; return; } /** * Echo the message to the main browser window * * @return void */ private function _sendToScreen() { ob_start(); var_dump($this-&gt;_debugMessage); $varDump = ob_get_clean(); if (!$varDump) { throw new Exception('The output buffer was not initiated for dumping to the screen!', E_USER_ERROR); } $screenMarkup = '&lt;pre&gt;' . $varDump . '&lt;/pre&gt;'; $this-&gt;_debugMessage = $screenMarkup; return; } /** * Reset the class properties to be ready for the next debug call * * @return void */ private function _cleanUpDebug() { $this-&gt;_debugVar = NULL; $this-&gt;_doConsoleLog = NULL; $this-&gt;_debugMessage = NULL; return; } } // End SprayFireDebugger </code></pre> <p>The code appears to work right, but I'm also a solo-developer with no kind of peer review. I guess I don't know what I don't know. Thanks for taking a look, I appreciate any feedback.</p>
[]
[ { "body": "<blockquote>\n <p>Does this look horribly bad? </p>\n</blockquote>\n\n<p>It actually looks great: </p>\n\n<ul>\n<li>Perfectly consistent</li>\n<li>Code is self documented, simple and broken into appropriate blocks (your functions <em>make sense</em>)</li>\n<li>phpDoc everywhere! </li>\n</ul>\n\n<p>I would go as far as saying it's the second most well written piece of php code I've seen on my fairly limited time on Code Review. And it's actually useful. I'm using a similar class on a 2*10^6 sloc project and it's extremely helpful. You should explore integrating <a href=\"http://xdebug.org/\">xdebug</a> into your class, for some bonus points.</p>\n\n<blockquote>\n <p>Are there ways that my code can be improved? </p>\n</blockquote>\n\n<p>There always are. But your code is at a point that you should probably spent time on other stuff, than trying to go the extra mile. </p>\n\n<p>A very minor suggestion: I absolutely <em>hate</em> prefixing private / protected methods and members with an underscore. This: </p>\n\n<pre><code>private $_debugVar;\n</code></pre>\n\n<p>doesn't work for me. It's a well known convention that's used all around, but what happens if at a later point you decide to make one of those public? Proponents of the underscore prefix always say it's a readability thing. Well it might be, but it doesn't matter:</p>\n\n<ul>\n<li>All half decent IDEs have code explorers / outlines with different coloring schemes for different visibility scopes. Most of those views are sortable on visibility too.</li>\n<li>All half decent IDEs will only expose public methods / members via code completion when using the class.</li>\n</ul>\n\n<blockquote>\n <p>Is my logic illogical?</p>\n</blockquote>\n\n<p>Nope.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-12T04:07:52.107", "Id": "5980", "ParentId": "3301", "Score": "5" } }, { "body": "<p>You've got a great idea with the console logging. I'll have to set that to my debugging stuff at some point. A few suggestions as far as the verbosity and approach:</p>\n\n<p>Currently, you're going to have to do this:</p>\n\n<pre><code>$debugger = new SprayFireDebugger(); // Instantiate the object\n$debugger-&gt;debug($test_var_3); // Method call on the object with a variable\n$debugger-&gt;debug($test_var_8); // Duplicate that work for another variable.\n</code></pre>\n\n<p>Every single time you want to debug. You're going to be introducing a variable to the global scope or you're going to have at least two lines per debug + 1 for every new variable you want to debug. Another problem is that without any \"environmental\" configuration, you're going to run into this problem: If you leave a debug variable in your code, it will debug on the live servers. As a result of all this, you have a very verbose process that you're going to have to be adding and removing all the time and commenting out or deleting whenever you make the code live.</p>\n\n<p>Here's the simple function that I use:</p>\n\n<pre><code>function debug($args) {\n if (DEBUG) { // Don't make anything public on live servers.\n $vals = func_get_args(); // Every new argument will be a new debug.\n foreach($vals as $val){ // Loop over each argument\n // Do whatever you want to output the debugging.\n echo \"&lt;pre class='debug' style='font-size:12pt;background-color:white;color:black;position:relative;z-index:10'&gt;\";\n var_dump($val);\n echo \"&lt;/pre&gt;\";\n }\n }\n}\n</code></pre>\n\n<p>As such, here are my suggestions:</p>\n\n<ul>\n<li>Use a function wrapper to decrease verbosity (I use <code>debug()</code>).</li>\n<li><p>Account for multiple variables as arguments, e.g. (<code>debug($something, $somethingelse, $another)</code>).</p></li>\n<li><p>Prevent debugging on live servers (e.g. using a DEBUG constant setting).</p></li>\n</ul>\n\n<p>In your case, you've got a great idea with the unobtrusive console logging. As such, your function signature would have to be modified from my suggestion to add:</p>\n\n<ol>\n<li>two split function wrappers, e.g. <code>debug($arg, $arg5, $arg8, $arg7)</code> and <code>console_debug($arg, $arg5, $arg8)</code></li>\n<li>or an additional, always there argument <code>debug(true, $arg, $arg5,\n$arg8)</code></li>\n<li>or to always use an array <code>debug(array($arg, $arg5, $arg8), true)</code> </li>\n</ol>\n\n<p>I recommend the first option for absolute minimum complexity when you're debugging.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-13T16:40:11.063", "Id": "6011", "ParentId": "3301", "Score": "0" } } ]
{ "AcceptedAnswerId": "5980", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-06T01:09:17.280", "Id": "3301", "Score": "6", "Tags": [ "php", "object-oriented" ], "Title": "PHP Debugger Object needs review" }
3301
<p>I am currently developing a login script for my application. The login will use SSL and all required resources will be served through this. It is not protecting anything like a bank however I would like to know what is right and wrong especially for learning purposes</p> <p>I would love some feedback on my class that I have developed. I have been reading various sources on the net and a lot seems to be contradictory. I would love to know if there is anything else I can do with regard to this code and also the login process as a whole</p> <p>Areas I feel need improvement:</p> <ul> <li>Use something stronger than sha1 for storing passwords.</li> <li>Maintaining login - currently it times out after 20 minutes.</li> </ul> <p></p> <pre><code>class User extends Model{ private $logLocation; private $loginLog; public function __construct(){ $this-&gt;logLocation = 'system/logs/'; $this-&gt;loginLog = "logins"; } /** * * Add User * @param array $data An array of data that will get added to User table. */ public function add($data){ $db = Database::getInstance(); $salt = substr(md5(uniqid(rand(), true)),0,3); $query = 'INSERT INTO user( user_id, user_username, user_password, user_salt, user_forename, user_lastname, user_email, user_attempts) VALUES( :user_id, :user_username, sha1(:user_password), :user_salt, :user_forename, :user_lastname, :user_email, 0)'; $args = array( ':user_id' =&gt; $data['user_id'], ':user_username' =&gt; $data['user_username'], ':user_password' =&gt; $data['user_password'].$salt, ':user_salt' =&gt; $salt, ':user_forename' =&gt; $data['user_forename'], ':user_lastname' =&gt; $data['user_lastname'], ':user_email' =&gt; $data['user_email']); $db-&gt;query($query, $args); SessionRegistry::instance()-&gt;addFeedback('user Saved Successfully'); return true; } public function getUserId($username){ $db = Database::getInstance(); //Check to see if the username exists $query = "SELECT user_id FROM user WHERE user_username = :username LIMIT 1"; $results = $db-&gt;query($query, array(':username' =&gt; $username)); return $results[0]['user_id']; } public function getUsername($userId){ $db = Database::getInstance(); //Check to see if the username exists $query = "SELECT user_username FROM user WHERE user_username = :username LIMIT 1"; $results = $db-&gt;query($query, array(':username' =&gt; $username)); return $results[0]['user_username']; } /** * * Checks login details against that in the database * @param string $username * @param string $password */ public function checkLogin($username, $password){ $db = Database::getInstance(); //Check to see if the username exists $query = "SELECT user_salt, user_password, user_attempts FROM user WHERE user_username = :username LIMIT 1"; $results = $db-&gt;query($query, array(':username' =&gt; $username)); //No results return false if(count($results) &lt; 1){ $this-&gt;logLoginAttempt($username, 'Incorrect Username'); return false; } //Check to see if the user is blocked if((int)$results[0]['user_attempts'] &gt;= 3){ $this-&gt;logLoginAttempt($username, 'Blocked User Login'); return false; } //Check to see if the passwords match if(sha1($password.$results[0]['user_salt']) == $results[0]['user_password']){ $this-&gt;setLogin($username); return true; } else{ //Incorrect Password $this-&gt;logLoginAttempt($username, 'Incorrect Password'); $this-&gt;failedLoginIncrement($username); return false; } } /** * * Increments the failed login attempt for a user. * 3 Strikes and they get locked out. * @param string $username */ private function failedLoginIncrement($username){ $db = Database::getInstance(); //Update the IP address of the user from where they last logged in $query = 'UPDATE user SET user_attempts = user_attempts + 1 WHERE user_username = :username'; $db-&gt;query($query, array(':username' =&gt; $username)); //Check to see if the user has reached 3 strikes if so block them. $query = 'SELECT user_attempts FROM user WHERE user_username = :username LIMIT 1'; $results = $db-&gt;query($query, array(':username' =&gt; $username)); if($results[0]['user_attempts'] &gt;= 3){ //We need to block the user $query = 'UPDATE user SET user_blocked = 1 WHERE user_username = :username'; $db-&gt;query($query, array(':username' =&gt; $username)); } return true; } /** * * Logs a failed login attempt to a log file so these can be monitored * @param string $username * @param string $reason */ private function logLoginAttempt($username, $reason){ $fh = fopen($this-&gt;logLocation.$this-&gt;loginLog, 'a+') or die("can't open file"); $logLine = date('d/m/Y h:i') . ' Login Attempt: ' . $username . ' Failure Reason: ' . $reason . " IP: " . $_SERVER['REMOTE_ADDR'] . "\n"; fwrite($fh, $logLine); fclose($fh); return true; } /** * * Sets the login data in the session. Also logs IP and resets the failed attempts. * @param string $username */ private function setLogin($username){ $db = Database::getInstance(); //Update the IP address of the user from where they last logged in $query = 'UPDATE user SET user_ip = :ip, user_attempts = 0 WHERE user_username = :username'; $db-&gt;query($query, array(':username' =&gt; $username, ':ip' =&gt; $_SERVER['REMOTE_ADDR'])); ini_set("session.use_only_cookies", TRUE); //Forces the session to be stored only in cookies and not passed over a URI. ini_set("session.use_trans_sid", FALSE); //Stop leaking session IDs onto the URI before browser can check to see if cookies are enabled. ini_set("session.cookie_lifetime", 1200); //Time out after 20mins //Now add the session vars to set the user to logged in. session_start(); session_regenerate_id(true); //Regenerate the session Id deleting old session files. $_SESSION['valid'] = 1; $_SESSION['userid'] = sha1($this-&gt;getUserId($_POST['username'] . "SALTHERE")); } /** * * Checks to see if a user is currently logged in. */ public function loggedIn(){ if($_SESSION['valid']){ return true; } else{ return false; } } /** * * Logs a current user out by destroying the session */ public function logout(){ // Unset all of the session variables. $_SESSION = array(); // If it's desired to kill the session, also delete the session cookie. // Note: This will destroy the session, and not just the session data! if (ini_get("session.use_cookies")) { $params = session_get_cookie_params(); setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"] ); } // Finally, destroy the session. session_destroy(); } } </code></pre> <p>I then use this class like so:</p> <pre><code>require_once('User.php'); $user = new User(); $loggedIn = $user-&gt;checkLogin($_POST['username'], $_POST['password']); if($loggedIn){ //redirect to member area } else{ //show login screen } </code></pre> <p>Then on a page where I need to check if a user is logged in</p> <pre><code>require_once('User.php'); $user = new User(); if(!$user-&gt;loggedIn()){ //redirect to login page } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-06T10:02:39.997", "Id": "4964", "Score": "0", "body": "take care of sql injection: mysql_real_escape_string(form[data])" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-06T10:51:21.623", "Id": "4966", "Score": "2", "body": "Thanks Rahul but I am using the PDO library to escape the data. Sorry I should of mentioned that in the Post as it is not apparent." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T12:22:59.300", "Id": "4996", "Score": "0", "body": "Looks like a good effort. A simple thing I'd suggest is check if your select query actually returns anything before trying to access the array: ` $results[0]['user_username'];`. Depending on your error_reporting level you will notice warnings on this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T11:01:26.270", "Id": "5080", "Score": "0", "body": "Ahh yes Fanis very good point. Little things like that add more polish to the code. I will go back through and add some of the details." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-13T18:20:43.207", "Id": "9265", "Score": "0", "body": "https://gist.github.com/1151912 for some nice blowfish crypt function wrappers. Not that the latest sha isn't okay, though." } ]
[ { "body": "<p>Like Fanis said in his comment, you might want to put error checking on both your <code>getUserId()</code> and <code>getUsername()</code>.</p>\n\n<p>Good code overall (except maybe the singleton for your database object), few minor things like replacing <code>rand()</code> with <a href=\"http://php.net/manual/en/function.mt-rand.php\" rel=\"nofollow noreferrer\"><code>mt_rand()</code></a>. If you're worried about the security, you could check out <a href=\"http://php.net/manual/en/function.crypt.php\" rel=\"nofollow noreferrer\"><code>crypt()</code></a> too.</p>\n\n<p>Although getting user IP's is never 100% reliable you shoulud to look into using something like <a href=\"https://stackoverflow.com/questions/5785931/most-reliable-way-to-get-ip-address-of-users-using-php\">this</a> function for getting the IP of a user.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T11:00:21.200", "Id": "5079", "Score": "0", "body": "A thanks for the tips Stoosh. I know singleton isn't really a good pattern for the DB however I was more concentrating on the security side of things." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T17:02:46.500", "Id": "5357", "Score": "0", "body": "+1 for crypt, in my research blowfish crypt is the way to go for passwords, it's a slow hash that also allows you to store the salted + hashed password in a single field because the salt and the hash become a single entity, so that when you need the salt, the first bit of the hash acts as the salt, and they're never in different places from each-other." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T00:32:39.930", "Id": "3386", "ParentId": "3308", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-06T09:53:35.167", "Id": "3308", "Score": "3", "Tags": [ "php", "security" ], "Title": "Login script for an application" }
3308
<p>Is this good or not? Input arguments for <code>OsFile_Open</code> must be in UTF8 format. </p> <pre><code>#include &lt;stdio.h&gt; #ifdef WIN32 #include &lt;Windows.h&gt; #endif // Types declaration, originally they are located in header file // typedef int Bool_T; typedef signed long long Int64_T; #define true 1 #define false 0 #define IN #define OUT Bool_T OsFile_Open( IN const char * name, IN const char * mode, OUT FILE ** file ) { FILE * handle; #ifdef WIN32 wchar_t unicodeMode[MAX_PATH]; wchar_t unicodeName[MAX_PATH]; int unicodeNameLen; int unicodeModeLen; unicodeNameLen = MultiByteToWideChar( CP_UTF8, 0, name, -1, unicodeName, 0 ); if( unicodeNameLen != 0 ) { if( MultiByteToWideChar( CP_UTF8, 0, name, -1, unicodeName, unicodeNameLen ) != 0 ) { unicodeModeLen = MultiByteToWideChar( CP_UTF8, 0, mode, -1, unicodeMode, 0 ); if( unicodeModeLen != 0 ) { if( MultiByteToWideChar( CP_UTF8, 0, mode, -1, unicodeMode, unicodeModeLen ) != 0 ) { handle = _wfopen( unicodeName, unicodeMode ); if( handle != NULL ) { *file = handle; return true; }else{ return false; } }else{ return false; } }else{ // if( unicodeModeLen != 0 ) return false; } }else{ // if( MultiByteToWideChar( CP_UTF8, 0, name, -1, unicodeName, unicodeNameLen ) != 0 ) return false; } }else{ // if( unicodeNameLen != 0 ) return false; } #else handle = fopen64( name, mode ); if( handle != NULL ) { *file = handle; return true; }else{ return false; } #endif } Bool_T OsFile_Close( IN FILE * file ) { return ( fclose( file ) == 0 ) ? true : false; } Bool_T OsFile_Seek( IN FILE * file, IN Int64_T offset, IN int origin ) { int result; #ifdef WIN32 result = _fseeki64( file, offset, origin ); #else result = fseeko64( file, offset, origin ); #endif return ( result == 0 ) ? true : false; } Bool_T OsFile_GetPos( IN FILE * file, OUT Int64_T * curPos ) { #ifdef WIN32 *curPos = _ftelli64( file ); #else *curPos = ftello64( file ); #endif return ( *curPos != -1 ) ? true : false; } size_t OsFile_Read( IN FILE * file, IN int numOfBytes, OUT unsigned char * buffer ) { return fread( buffer, sizeof( unsigned char ), numOfBytes, file ); } int OsFile_Eof( IN FILE * file ) { return feof( file ); } </code></pre>
[]
[ { "body": "<p>I'd re-structure (the Win32 part of) the open function to something like this:</p>\n\n<pre><code>#ifdef WIN32\n\n wchar_t unicodeMode[MAX_PATH];\n wchar_t unicodeName[MAX_PATH];\n\n if (MultiByteToWideChar( CP_UTF8, 0, name, -1, unicodeName, MAX_PATH) &amp;&amp; \n MultiByteToWideChar( CP_UTF8, 0, mode, -1, unicodeMode, MAX_PATH) &amp;&amp; \n (handle = _wfopen( unicodeName, unicodeMode)) != NULL) \n {\n *file = handle;\n return true;\n }\n return false;\n\n#else\n</code></pre>\n\n<p>You don't need to call MultiByteToWideChar twice for each conversion -- the first call not only returns the length, but does the conversion as well. As it stands, your code has potential buffer overruns as well -- it used the first call to MultiByteToWideChar to measure the length that would be needed for the result, but never checked that this was less than or equal to the buffer space you provided.</p>\n\n<p>It can be legitimate to do the two consecutive calls, especially if (for example) you want to ensure you can handle any possible input by using the first call the measure the necessary length, then allocating the necessary space dynamically, and then doing the second call using the dynamically allocated space.</p>\n\n<p>Several places, you have things like:</p>\n\n<pre><code>return ( fclose( file ) == 0 ) ? true : false;\n</code></pre>\n\n<p>These should be written as:</p>\n\n<pre><code>return fclose(file) == 0;\n</code></pre>\n\n<p>or just:</p>\n\n<pre><code>return !fclose(file);\n</code></pre>\n\n<p>There's no need to select and return a Boolean literal -- the Boolean values yielded by <code>==</code> and <code>!</code> will work nicely as-is.</p>\n\n<p>Edit: You also have a couple of things like:</p>\n\n<pre><code>#ifdef WIN32\n *curPos = _ftelli64( file );\n#else\n *curPos = ftello64( file );\n#endif \n</code></pre>\n\n<p>spread throughout the code. Where you're just dealing with different function names like this, I think I'd have one block up-front to deal with the name differences, and then use a single name through the rest of the code:</p>\n\n<pre><code>#ifdef WIN32\n #define ftello64(x) _ftelli64(x)\n #define fseeko64(x) _fseeki64(x)\n#endif\n\n/* ... */\n\nBool_T OsFile_Seek( IN FILE * file, IN Int64_T offset, IN int origin )\n{\n return !fseeko64(file, offset, origin);\n}\n</code></pre>\n\n<p>You might want to read <a href=\"http://doc.cat-v.org/henry_spencer/ifdef_considered_harmful.pdf\"><code>#ifdef considered harmful</code></a> for more about what to do and what to avoid.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-06T15:38:54.530", "Id": "3311", "ParentId": "3309", "Score": "5" } }, { "body": "<p>Consider replacing a code structure like this:</p>\n\n<pre><code>if (predicate)\n{\n // many lines of code here\n if (predicate2)\n {\n // even more lines of code here\n }\n else\n {\n return false;\n }\n}\nelse\n{\n return false;\n}\n</code></pre>\n\n<p>to the much simpler:</p>\n\n<pre><code>if (!predicate)\n return false;\n\n// long code here\n\nif (!predicate2)\n return false\n\n// second long paragraph \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T04:40:14.857", "Id": "4975", "Score": "0", "body": "Prior to reading Code Complete, I structured my code as you showed. When you structured code like you showed, it hard to get the main idea of code, when there is a lot of 'if' conditions. In my opinion it is more important to make focus in the operation which must be executed when program executed normally, instead of focusing on exceptional situations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T08:59:41.010", "Id": "4978", "Score": "0", "body": "It is definitely not clear that your 'if' is an exit condition. The simple 'return false' is so far below, to the user it is not evident what the two outcomes of the ifs are. while in my version you do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T09:51:39.373", "Id": "4980", "Score": "0", "body": "In this case I agree with you, but in situations, when prior to exit, you must do some operations(deallocate memory, ...), it becomes complicated, because when you're reading the code you concentrated on things, which are not important as the main idea of the code, IMHO." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-06T19:23:41.557", "Id": "3314", "ParentId": "3309", "Score": "4" } } ]
{ "AcceptedAnswerId": "3311", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-06T12:23:12.933", "Id": "3309", "Score": "4", "Tags": [ "c", "stream" ], "Title": "File stream functions" }
3309
<p><em>Moved originally from <a href="https://stackoverflow.com/questions/6592763/how-might-i-improve-the-structure-of-this-haskell-source">StackOverflow</a>, not knowing the existence of this sister site ...</em></p> <p>Must say I find programming in Haskell to require much more cognitive intensity than any other language I've tried. I'm not certain I care about lazy evaluation or monads very much, but I do appreciate certain functional aspects, static type checking and not needing a huge VM to run.</p> <p>I've been writing a short program to rename images based on EXIF and now have something that works. I'd like someone Haskell expert opinions on the overall structure of the source code in terms of what I've done right/wrong, and how I might improve and make the code more succinct. I won't bother posting the entire program but a lot of the overall structure is below.</p> <pre><code>import Control.Applicative import Control.Monad.Error import Data.Char import Data.Either import Data.List import Data.Maybe import Data.Time.Format import Data.Time.LocalTime import System.Console.GetOpt import System.Directory import System.Environment import System.FilePath import System.Locale import System.IO.Error import Text.Printf import Album.Utils import Album.Exif import Album.Error -- ----------------------------------------------------------------------- -- Main main = do r &lt;- try main0 case r of Left err -&gt; do printf "Error type: %s\n" $ (show $ ioeGetErrorType err) printf "Error string: %s\n" $ (ioeGetErrorString err) printf "Error filename: %s\n" $ (maybe "None" id $ ioeGetFileName err) printf "Error handle: %s\n" $ (maybe "None" show $ ioeGetHandle err) Right _ -&gt; return () -- Process arguments main0 = do args &lt;- getArgs case processArgs args desc of (True, _, usage) -&gt; showUsage usage (False, (flags, fns, []), usage) -&gt; do rv &lt;- runErrorT $ main1 flags fns either (\e -&gt; showErrs [show e] usage) (const $ return ()) rv (False, (_, _, errs), usage) -&gt; showErrs errs usage where desc = "Rename and catalog media.\n" ++ "Usage: album -n &lt;albumname&gt; &lt;options&gt; &lt;media files&gt;\n" -- Sanity check main1 flags fns = do -- Check name albName &lt;- maybe (throwError AlbumNameError) return $ albumName flags -- Check for duplicate media let dups = nub $ fns \\ nub fns unless (null dups) $ throwError $ MediaDuplicateError dups -- Check for valid filenames (haves, havenots) &lt;- liftIO $ filesExist fns unless (null havenots) $ throwError $ MediaNotFoundError havenots when (null haves) $ throwError MediaNotSpecifiedError -- Check exiftool existence tool0 &lt;- liftIO $ findExecutable "exiftool" tool &lt;- maybe (throwError ExifToolNotFoundError) return tool0 -- Get EXIF attributes exifs0 &lt;- liftIO $ getExifs tool fns exifs &lt;- either (throwError . ExifParseError) return exifs0 -- Check for exiftool errors let bads = findExifs "ExifTool:Error" exifs unless (null bads) $ throwError $ MediaBadError $ map fst bads -- Check for timestamps let infos0 = map (\(n,e) -&gt; (n, exifToDateTime e)) exifs let nodates = filter (isNothing . snd) infos0 unless (null nodates) $ throwError $ MediaDateTimeTagError $ map fst nodates let infos = map (\(n,Just dt) -&gt; (n,dt)) infos0 main2 albName infos -- Do renames main2 albName infos = do -- Album folder name let mints = minimum $ map snd infos let mintsiso = formatTime defaultTimeLocale "%Y%m%d" mints let albFolder = printf "%s - %s" mintsiso albName -- Get list of existing media albExist &lt;- liftIO $ doesDirectoryExist albFolder (albCreate, existing) &lt;- case albExist of False -&gt; return (True, []) True -&gt; do e &lt;- liftIO $ filter ((/= ".") . nub) &lt;$&gt; getDirectoryContents albFolder return (False, e) -- Rename list let rens0 = mediaNames albName infos existing let rens1 = map (\(a,b) -&gt; (a, combine albFolder b)) rens0 let len = maximum $ map (length . fst) rens1 if albCreate then do liftIO $ printf "Creating folder: %s\n" albFolder liftIO $ createDirectory albFolder else return () forM_ rens1 $ \(oldf, newf) -&gt; do liftIO $ printf "%*s &gt;&gt;&gt; %s\n" len oldf newf liftIO $ renameFile oldf newf return () showErrs errs usage = do putStrLn $ concatMap ("Error: " ++ ) errs return () showUsage usage = do putStrLn usage return () -- ----------------------------------------------------------------------- -- Rename mediaNames albName infos existing = go existing (map cands infos) where go es [] = [] go es ((fn,cs):css) = let p = unused cs es in (fn,p):go (p:es) css unused cs es = fromJust $ find (`notElem` es) cs cands (fn,dt) = (fn, map (++ ext) (pref:alts)) where pref = printf "%s - %s" (ft dt) albName ft dt = formatTime defaultTimeLocale "%Y%m%dT%H%M%S" dt alts = map (printf "%s (%02d)" pref) ([1..] :: [Int]) ext = map toLower (takeExtension fn) -- ----------------------------------------------------------------------- -- Arguments data Option = OptionAlbumName String | OptionHelp deriving (Eq, Show) processArgs args desc = (elem OptionHelp flags, opts, usage) where opts@(flags, fns, errs) = getOpt RequireOrder conf args usage = usageInfo desc conf conf = [ Option "n" ["name"] (ReqArg OptionAlbumName "NAME") "Album name", Option "h" ["help"] (NoArg OptionHelp) "Help"] albumName (OptionAlbumName n:xs) = Just n albumName (x:xs) = albumName xs albumName [] = Nothing </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T13:45:11.743", "Id": "5002", "Score": "2", "body": "This may be a nitpick for a small program but it's a _really_ good habit to give functions explicit type signatures. It's good documentation and it helps sanity check your mental model of the program against the compiler." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T21:59:22.200", "Id": "5201", "Score": "0", "body": "Another suggestion: Even if you're only asking for feedback on key parts of the code (a good idea!) it would help if you uploaded the rest somewhere else, or at least enough of it so that people can load it into GHCi." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-13T18:18:08.083", "Id": "176939", "Score": "0", "body": "You should start by renaming `main0`, `main1` & `main2`..." } ]
[ { "body": "<p>I'm definitely <em>not</em> a Haskell expert, but here are my 2 cents:</p>\n\n<ul>\n<li>You should break your main functions in several methods. The amount of code running inside the IO monad should be minimized.</li>\n<li>You often use <code>case ... of</code> where a separate function with pattern matching would be more readable </li>\n<li><code>albumName</code> could use a fold</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T11:44:44.100", "Id": "3324", "ParentId": "3310", "Score": "2" } }, { "body": "<p>At this place:</p>\n\n<pre><code>if albCreate\n then do\n liftIO $ printf \"Creating folder: %s\\n\" albFolder\n liftIO $ createDirectory albFolder\n else \n return ()\n</code></pre>\n\n<p>You could use the combinator <code>when</code> to make it a little bit shorter:</p>\n\n<pre><code>when albCreate $ do\n liftIO $ printf \"Creating folder: %s\\n\" albFolder\n liftIO $ createDirectory albFolder \n</code></pre>\n\n<p>You can also pull out the <code>liftIO</code>:</p>\n\n<pre><code>when albCreate . liftIO $ do\n printf \"Creating folder: %s\\n\" albFolder\n createDirectory albFolder \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T10:42:24.293", "Id": "3437", "ParentId": "3310", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-07-06T14:36:42.100", "Id": "3310", "Score": "6", "Tags": [ "haskell", "file", "image" ], "Title": "Haskell program to rename images based on EXIF data" }
3310
<p>My current setup is a 3 layered application: UI > BLL > DAL. Each layer is set up as a separate project. The UI is an ASP.Net website and the BLL &amp; DAL are Class Library projects.</p> <p>I've shown some sample code from each of my layers. Hopefully you guys can critique my application design and give me some tips/pointers or I'm doing this wrong, steer me in the right direction. Thanks!</p> <p><strong>DAL Method</strong>:</p> <pre><code>public static object Get_UserId(string username) { ConnectionSettings connectionSettings = new ConnectionSettings(); SqlConnection sqlConnection = new SqlConnection(connectionSettings.ConnectionString); string sql = String.Format("select UserId from Users where Username = '{0}'", username); try { sqlConnection.Open(); SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection); return sqlCommand.ExecuteScalar(); } catch { throw new DALException("Unable to retreive User ID"); } finally { sqlConnection.Close(); } } </code></pre> <p><strong>The BLL method responsible for retreiving User ID</strong>:</p> <pre><code> public static int GetUserId(string username) { try { int userId = Int32.Parse(UserDAL.Get_UserId(username).ToString()); return userId; } catch (Exception ex) { throw new BLLException(ex.Message); } } </code></pre> <p><strong>The call to the BLL from UI:</strong></p> <pre><code>try { int id = UserBLL.GetUserId("bobloblaw"); Response.Write(id); } catch (DALException dalEx) { Response.Write(dalEx.Message); } catch (BLLException bllEx) { Response.Write(bllEx.Message); } </code></pre>
[]
[ { "body": "<p>Things I would change in your code/approach:</p>\n\n<ul>\n<li>log errors</li>\n<li>get rid of static service methods</li>\n<li>hide dll exceptions in ui. Catch it in BLL and log it/do something with it.</li>\n<li>change DLL so the method in BLL instead of:</li>\n</ul>\n\n<p><code>int userId = Int32.Parse(UserDAL.Get_UserId(username).ToString());</code></p>\n\n<p>would use:</p>\n\n<p><code>int userId = new UserDAL().Get_UserId(username);</code></p>\n\n<p>These are first things that come to my head.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T16:23:33.923", "Id": "4984", "Score": "1", "body": "What is the problem using static methods, since the BLL and DAL methods don't require any class variables?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T05:24:33.477", "Id": "3321", "ParentId": "3312", "Score": "2" } }, { "body": "<p>I'd second getting rid of the static methods. Data access should be instance based in my opinion. </p>\n\n<p>My main grip however is that you are not using parameterized queries. This code:</p>\n\n<pre><code>string sql = String.Format(\"select UserId from Users where Username = '{0}'\", username);\n</code></pre>\n\n<p>Should be: </p>\n\n<pre><code>string sql = @\"select UserId from Users where Username = @username\");\nSqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);\nsqlCommand.Parameters.AddWithValue(\"@username\", username);\n</code></pre>\n\n<p>Doing this will mitigate your SQL Injection issue using <code>string.Format(...)</code>. I make it a habit of always using parameterized queries no matter if it's being passed data from data entry or not. There is just no reason not to. </p>\n\n<p>Also in place of using <code>finally</code> wrap things up in a <code>using</code> statement to close and dispose your Data objects like <code>SqlCommand</code> and <code>SqlConnection</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-06T03:16:30.520", "Id": "3911", "ParentId": "3312", "Score": "2" } }, { "body": "<ol>\n<li><p>I agree with <a href=\"https://codereview.stackexchange.com/questions/3312/3-layered-asp-net-app-need-critique-advice/3321#3321\">IAmDeveloper</a> that BLL method should be: </p>\n\n<pre><code>int userId = new UserDAL().Get_UserId(username);\n</code></pre></li>\n<li><p>I agree with <a href=\"https://codereview.stackexchange.com/questions/3312/3-layered-asp-net-app-need-critique-advice/3911#3911\">Tim Meers</a> that you should use <strong>parameterized queries</strong>.</p></li>\n<li><p>I would change the whole approach to the exceptions handling:</p>\n\n<ul>\n<li><p>It's wrong to catch all exceptions in your <code>DAL.Get_UserId</code> and replace them with <code>DALException</code>. By doing so, you lose all information about the original exception, such as the stack trace, and only keep the message (which itself can be pretty useless sometimes). Instead, create change <code>BLLException</code> constructor to accept an inner exception:</p>\n\n<pre><code>public BLLException (string message, Exception inner)\n : base (message, inner) { }\n</code></pre>\n\n<p>and throw it accordingly:</p>\n\n<pre><code>throw new BLLException (\"Error getting user ID\", ex);\n</code></pre>\n\n<p>The inner exception then will be accessible through <code>InnerException</code> property.</p></li>\n<li><p>You are trying to catch <code>DALException</code> in your UI layer but it will never occur because the business layer already replaces them with <code>BLLException</code>s.</p></li>\n</ul></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-06T08:18:35.827", "Id": "3914", "ParentId": "3312", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-06T17:58:42.833", "Id": "3312", "Score": "7", "Tags": [ "c#", ".net", "asp.net" ], "Title": "3-layer ASP.NET app - Need critique/advice" }
3312
<pre><code>#region GetBookListByPriority private static List&lt;BCBook&gt; GetBookListByPriority(List&lt;BCBook&gt; listBcBook) { List&lt;BCBook&gt; newList = new List&lt;BCBook&gt;(); try { List&lt;BCBook&gt; listNonPriorityBcBooks = new List&lt;BCBook&gt;(); List&lt;BCBook&gt; listPriorityBcBooks = new List&lt;BCBook&gt;(); foreach (BCBook bcBook in listBcBook) { BookHistoryDto historyDto = new BookHistoryFacade().FindHistoryByBookIdByPriority(bcBook.id.ToString(CultureInfo.CurrentCulture)); if (historyDto != null &amp;&amp; historyDto.HistoryId &gt; 0) { bcBook.Priority = historyDto.Priority; listPriorityBcBooks.Add(bcBook); } else { listNonPriorityBcBooks.Add(bcBook); } } int count = 0; int prio = 0; foreach (BCBook bcBook in listNonPriorityBcBooks) { for (int j = count + 1; j &lt;= 5; j++) { List&lt;BCBook&gt; listBook = new List&lt;BCBook&gt;(); listBook = ListBookPriority(listPriorityBcBooks, j, newList); count++; if (listBook.Count() &gt; 0) { prio++; } else { break; } foreach (BCBook bc in listBook) { newList.Add(bc); } } newList.Add(bcBook); } } catch (Exception ex) { ErrorLogger.WriteErrorToLog(ex); } return newList; } #endregion #region ListBookPriority private static List&lt;BCBook&gt; ListBookPriority(List&lt;BCBook&gt; list, int priority, List&lt;BCBook&gt; newList) { List&lt;BCBook&gt; listBook = new List&lt;BCBook&gt;(); try { foreach (BCBook vid in list) { if (!IsExists(newList, vid.id.ToString(CultureInfo.CurrentCulture))) { if (vid.Priority == priority) { listBook.Add(vid); } } } } catch (Exception ex) { ErrorLogger.WriteErrorToLog(ex); } return listBook; } #endregion </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-06T21:26:08.287", "Id": "4972", "Score": "0", "body": "You have several loops there. Which one is \"*this loop*?\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T13:26:55.307", "Id": "4981", "Score": "0", "body": "Step 1 is to add comments to your code explaining the intent. There is probably a better approach to what you are trying to do. Keeping track of count and prior seem odd since you never use either one." } ]
[ { "body": "<p>I would get rid of <code>foreach</code> and use <code>for</code>. I have found (and read about) a huge performance difference between the 2 (<strong><em>EDIT</strong>, but not always, see below</em>). </p>\n\n<p><strong>Example (untested code):</strong></p>\n\n<pre><code>int c = listBcBook.Count;\n\nfor (int i = 0; i &lt; c; i++)\n{\n BCBook bcBook = listBcBook[i];\n\n BookHistoryDto historyDto = new BookHistoryFacade().FindHistoryByBookIdByPriority(bcBook.id.ToString(CultureInfo.CurrentCulture));\n if (historyDto != null &amp;&amp; historyDto.HistoryId &gt; 0)\n {\n bcBook.Priority = historyDto.Priority;\n listPriorityBcBooks.Add(bcBook);\n }\n else\n {\n listNonPriorityBcBooks.Add(bcBook);\n }\n}\n</code></pre>\n\n<p><strong>EDIT:</strong> I just read that the performance difference isn't always there because in some cases, the compiler will optimize your <code>foreach</code> loops into <code>for</code> loops. Here is a good read over on SO: <a href=\"https://stackoverflow.com/questions/1124753/for-vs-foreach-loop-in-c\">https://stackoverflow.com/questions/1124753/for-vs-foreach-loop-in-c</a>. </p>\n\n<p>In your case, because you're using a <code>List</code>, directly using <code>for</code> should be faster. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-06T23:07:22.927", "Id": "3316", "ParentId": "3315", "Score": "2" } }, { "body": "<p>While I don't have time at the moment to look through the code at the moment (and due to the lack of comments) I can't give a broad answer but I can already note two things.</p>\n\n<p>Initialize your facade outside of the for loop.</p>\n\n<pre><code>BookHistoryFacade() facade = new BookHistoryFacade();\nforeach (BCBook bcBook in listBcBook)\n{\n BookHistoryDto historyDto =\n facade.FindHistoryByBookIdByPriority(bcBook.id.ToString(CultureInfo.CurrentCulture));\n ...\n}\n</code></pre>\n\n<p>Use <a href=\"http://msdn.microsoft.com/en-us/netframework/aa904594\" rel=\"nofollow\">LINQ</a> for your queries, which will also allow you to easily attempt <a href=\"http://msdn.microsoft.com/en-us/library/dd460688.aspx\" rel=\"nofollow\">Parallel LINQ</a>. This would give you the opportunity to use several cores for your query ... aka as increased speed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T00:22:14.313", "Id": "3318", "ParentId": "3315", "Score": "2" } }, { "body": "<p>You can replace two foreach loops in GetBookListByPriority where you're adding the whole sublist to a new list with these:</p>\n\n<pre><code>newList.AddRange(listBook);\nnewList.AddRange(listNonPriorityBcBooks);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T18:49:27.520", "Id": "3334", "ParentId": "3315", "Score": "0" } }, { "body": "<p>Its pretty unclear what the code does/needs to do. But I've tried to cut down on some of the code so try this (obviously untested) and see if its faster and does the same thing :)</p>\n\n<pre><code> private static List&lt;BCBook&gt; GetBookListByPriority(List&lt;BCBook&gt; listBcBook)\n {\n List&lt;BCBook&gt; newList = new List&lt;BCBook&gt;();\n try\n {\n List&lt;BCBook&gt; listNonPriorityBcBooks = new List&lt;BCBook&gt;();\n List&lt;BCBook&gt; listPriorityBcBooks = new List&lt;BCBook&gt;();\n // move the variable historyDto outside the for loop so you create the object less.\n BookHistoryDto historyDto;\n foreach (BCBook bcBook in listBcBook)\n {\n historyDto = new BookHistoryFacade().FindHistoryByBookIdByPriority(bcBook.id.ToString(CultureInfo.CurrentCulture));\n if (historyDto != null &amp;&amp; historyDto.HistoryId &gt; 0)\n {\n bcBook.Priority = historyDto.Priority;\n listPriorityBcBooks.Add(bcBook);\n }\n else\n {\n listNonPriorityBcBooks.Add(bcBook);\n }\n }\n\n int count = 1; \n foreach (BCBook bcBook in listNonPriorityBcBooks)\n {\n // move the variable listBook outside the for loop so you create the object less.\n List&lt;BCBook&gt; listBook;\n // if you are only having a maximum of 5 then there is no need to create an extra variable, use the existing count\n for (count; count &lt;= 5; count++)\n {\n listBook = ListBookPriority(listPriorityBcBooks, count, newList);\n // Count() is slower than Count, note the difference in the removal of the brackets\n if (listBook.Count &gt; 0)\n {\n // Only if the count is greater than 0 do we want to begin to enumerate the collection\n foreach (BCBook bc in listBook)\n {\n newList.Add(bc);\n }\n }\n else\n {\n break;\n }\n }\n newList.Add(bcBook);\n }\n }\n catch (Exception ex)\n {\n ErrorLogger.WriteErrorToLog(ex);\n }\n\n return newList;\n } \n</code></pre>\n\n<p>If you could comment your original code you would get a better response i'm sure</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-09T20:08:34.780", "Id": "3366", "ParentId": "3315", "Score": "0" } }, { "body": "<p>You are not optimizing anything with that:</p>\n\n<pre><code>int count = 1; \n// Some code here\nfor (count; count &lt;= 5; count++)\n{\n</code></pre>\n\n<p>This is equal in speed, but inferior in style to:</p>\n\n<pre><code>// Some code here\nfor (int count = 1; count &lt;= 5; count++)\n{\n</code></pre>\n\n<p>Avoid these \"micro-optimizations\". Even if done right, it is often the case that you will have much better things to improve.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-09T23:22:34.540", "Id": "3369", "ParentId": "3315", "Score": "0" } }, { "body": "<p>If you don't want to use LINQ as Steven suggests, have you considered a SortedList? Just implement the IComparable interface on the priority object if it doesn't already. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T20:26:40.410", "Id": "3482", "ParentId": "3315", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-06T21:08:28.037", "Id": "3315", "Score": "4", "Tags": [ "c#", "performance", "sorting" ], "Title": "Listing books by priority" }
3315
<p>I created a function which has, I believe, truly private variables. It's not quite production ready for several reasons:</p> <ul> <li>It's using <code>Object.defineProperty</code> -- I can deal with this</li> <li>It is re-defining every function in the prototype by doing <code>eval( fn.toString() )</code> -- I do <strong><em>not</em></strong> like this</li> <li>I'm re-defining the prototypes, hence doing-away with the advantage of prototypes! -- deal breaker</li> </ul> <p>Anyway, I'm putting this out there for critique / suggestions / recommendations for how to fix the above points. I'm not sure I'll ever really do anything with it, but I find it to be an interesting problem:</p> <pre><code>function foo(){ this.definePrivateProperties('foo', 'bar'); } foo.prototype.setFoo = function(x){ this.foo = x; }; foo.prototype.getFoo = function(){ return this.foo; }; foo.prototype.definePrivateProperties = function(){ var self = this, args = arguments, validFns = {}, proto = this.__proto__; // replace all functions in prototype with new ones! // set a random key on each new function // (not 100% secure, but close enough for now) // this ensures that the function is unique to -this- object for(var fn in proto){ this[ fn ] = eval( '(' + proto[fn] + ')' ); validFns[ this[ fn ].key = Math.random() ] = 1; } for(var i=0, l=args.length; i&lt;l; i++){ (function(){ var val; Object.defineProperty(self, args[i], { get : function getter(){ if(validFns[ arguments.callee.caller.key ]) return val; }, set : function setter(v){ if(validFns[ arguments.callee.caller.key ]) val = v; }, configurable : true, enumerable : false }); })(); } }; &gt; var x = new foo(); &gt; x.setFoo(42); &gt; x.foo = 20; 20 &gt; x.foo; undefined &gt; x.getFoo(); 42 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T01:19:36.677", "Id": "4973", "Score": "1", "body": "You will likely get more informed comments if you ask on the Usenet forum comp.lang.javascript, which can be accessed using a newsreader (referable), or using [Google Groups](http://groups.google.com/group/comp.lang.javascript/topics?gvc=2)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-03T16:28:02.017", "Id": "8760", "Score": "1", "body": "Why not use the `closure` mechanism for creating truly private JS variables as described here: http://javascript.crockford.com/private.html." } ]
[ { "body": "<p>It looks like you can get rid of the eval</p>\n\n<pre><code>this[ fn ] = eval( '(' + proto[fn] + ')' );\n</code></pre>\n\n<p>by replacing it with</p>\n\n<pre><code>this[fn] = (proto[fn]);\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/somethingkindawierd/BRVcP/\" rel=\"nofollow\">Here's a jsfiddle</a> showing this change logs the same results as your sample.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-24T20:09:05.657", "Id": "6540", "Score": "0", "body": "Actually that won't work. The reason I `eval`'d the function was so that I could get a new function with the same code that I could then set `.key` on (the next line). This `.key` has to be bound to a unique instance of the function otherwise there is confusion between class instances and everything falls apart... So what you did will work with one instance of the class, but not two." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-24T16:47:36.323", "Id": "4358", "ParentId": "3319", "Score": "2" } }, { "body": "<pre><code>this[ fn ] = eval( '(' + proto[fn] + ')' );\n</code></pre>\n\n<p>will lose the relationship between the function and any variables it closes over. Better to do </p>\n\n<pre><code>this[ fn ] = (function (f) { return f.apply(this, arguments); })(proto[fn]);\n</code></pre>\n\n<p>You're also using non-standard constructs like <code>__proto__</code>. Maybe it would be better to use <a href=\"http://ejohn.org/blog/objectgetprototypeof/\" rel=\"nofollow\"><code>getPrototypeOf</code></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-24T22:58:04.460", "Id": "5559", "ParentId": "3319", "Score": "0" } }, { "body": "<p>As for the code:</p>\n\n<ul>\n<li><p>The property getter and setter should probably throw an exception if the check against the caller failed. If you attempt to set it from any function besides one defined on the prototype, you don't want it to silently fail -- if it does, you'll be wasting lots of time trying to figure out why your changes aren't sticking. (Particularly in light of other issues below.)</p></li>\n<li><p>If you're going to assign a different key to each member function, you might consider making <code>validFns[key]</code> be the function with that key, rather than just '1', so you can check it against the caller. (Ensures the key doesn't ever accidentally match.)</p></li>\n<li><p>You're setting keys on each thing you copy from the prototype, regardless of whether it's a function. Only functions need keys; other stuff (well, anything really, but particularly non-function members) might have its own purpose for <code>key</code>.</p></li>\n<li><p>The way the access checks are now, only member functions can use them. Though that may be the intent, it is way more crippling than it sounds.</p></li>\n</ul>\n\n<p>Observe:</p>\n\n<pre><code>foo.prototype.doStuff = function() {\n var self = this;\n $('input.some_selector').each(function() {\n self.foo += parseInt(this.value);\n });\n};\n</code></pre>\n\n<p>We're in a private function, which should have access to <code>foo</code>. But since the actual access is within an anonymous function, and not <code>doStuff</code>, it's not allowed. In order to fix this (and fix it you should), your access check would need to go down the call stack (check the caller, then the caller's caller, and so on) til it finds a function with a key. Recursive functions seem to cause such a search massive amounts of trouble, though; a depth limit might help with that.</p>\n\n<ul>\n<li><code>definePrivateProperties</code> can be run a second time. And a third, fourth, etc. And each time you call it, it obliterates the previous property's value in order to add the new one. Read: <em>external code can mess up your private variables</em>.</li>\n</ul>\n\n<p>Say:</p>\n\n<pre><code>foo.prototype.mangleFoo = function() { this.foo = 100; };\nx.definePrivateProperties('foo');\ndelete foo.prototype.mangleFoo;\nx.mangleFoo();\n</code></pre>\n\n<p>(BTW, see what we just did there? We can add a function and give it access to the \"private\" properties pretty much at will.) In order to prevent that...i dunno. redefine <code>definePrivateProperties</code> after it's run once?</p>\n\n<p>In contrast, the standard method (hiding the variable away in a closure) is not prone to such hackery. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-31T23:11:39.453", "Id": "5721", "ParentId": "3319", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T01:16:26.007", "Id": "3319", "Score": "6", "Tags": [ "javascript" ], "Title": "Truly private JavaScript variables" }
3319
<p>Could you please review the following code, and point out how I can make it cleaner, more idiomatic and easier to understand? </p> <pre><code>module Cabbage ( solve ) where data Place = Here | There deriving (Eq, Show) data Pos = Pos { cabb :: Place , goat :: Place , wolf :: Place , farmer :: Place } deriving (Eq, Show) opp :: Place -&gt; Place opp Here = There opp There = Here valid :: Pos -&gt; Bool valid (Pos {cabb = c, goat = g, wolf = w, farmer = f}) = (c /= g &amp;&amp; g /= w) || g == f findMoves :: Pos -&gt; [Pos] findMoves pos@(Pos {cabb = c, goat = g, wolf = w, farmer = f}) = filter valid $ moveCabb ++ moveGoat ++ moveWolf ++ moveFarmer where moveCabb | c == f = [pos {cabb = opp c, farmer = opp f}] | otherwise = [] moveGoat | g == f = [pos {goat = opp g, farmer = opp f}] | otherwise = [] moveWolf | w == f = [pos {wolf = opp w, farmer = opp f}] | otherwise = [] moveFarmer = [pos {farmer = opp f}] findSolution :: Pos -&gt; Pos -&gt; [Pos] findSolution from to = head $ loop [[from]] where loop pps = do ps &lt;- pps let moves = filter (flip notElem ps) $ findMoves $ head ps if to `elem` moves then return $ reverse $ to:ps else loop $ map (:ps) moves solve :: [Pos] solve = findSolution (setAll Here) (setAll There) where setAll x = Pos{ cabb = x, goat = x, wolf = x, farmer = x } </code></pre> <p>IMHO the <code>findMoves</code> function seems to be quite verbose, and the <code>findSolutions</code> function looks confusing.</p> <p>Thank you!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T17:19:38.633", "Id": "5662", "Score": "0", "body": "Oh, I can write `data Pos = Pos {cabb, goat, wolf, farmer :: Place} deriving (Eq, Show)`." } ]
[ { "body": "<p>Haskell's record system is not really good at providing you uniform access to record entries. That is the reason your <code>findMoves</code> implementation has to be so verbose: You cannot generalize over the fields.</p>\n\n<p>There are a number of ways to get around that. One could be using a library such as <a href=\"http://hackage.haskell.org/package/fclabels\" rel=\"nofollow\">fclabels</a> that facilitates this job for you. You set it up like follows:</p>\n\n<pre><code>import Data.Record.Label\n\ndata Pos = ....\n\n$( mkLabels [''Pos] )\n</code></pre>\n\n<p>This will give you \"labels\" with names such as <code>lCabb</code> that you can use with functions such as <code>getL</code> or <code>modL</code>. Without all this boilerplate, it is possible to write a much more satisfying <code>findMoves</code> function:</p>\n\n<pre><code>findMoves :: Pos -&gt; [Pos]\nfindMoves pos = filter valid moves\n where\n moves = [ foldr (\\obj -&gt; modL obj opp) pos objs\n | objs &lt;- moveComb, same $ map (`getL` pos) objs\n ]\n moveComb = [[lCabb, lFarmer], [lGoat, lFarmer], [lWolf, lFarmer], [lFarmer]]\n same xs = all (== head xs) xs\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T13:24:09.290", "Id": "3327", "ParentId": "3322", "Score": "4" } }, { "body": "<p>I'd be inclined to change your representation. At each step, the farmer moves from his current location to the opposite location. It makes life much simpler if you just represent each state as a pair consisting of the list of things at the farmer's current location and the list of things at the other location.</p>\n\n<p>My Haskell is a bit rusty, but under this scheme you get something like this:</p>\n\n<pre><code>move (withFmr, awayFromFmr) = [(awayFromFmr, withFmr) | map f withFmr]\n where f x = (x :: awayFromFmr, filter (== x) withFmr)\n\nvalid (withFmr, awayFromFmr) = \n not (elem Goat awayFromFmr &amp;&amp; (elem Wolf awayFromFmr || elem Cabbage awayFromFmr))\n</code></pre>\n\n<p>The location of <code>withFmr</code> for each successive state is the opposite of that for the preceding state.</p>\n\n<p>Hope this helps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T06:20:29.373", "Id": "4989", "Score": "0", "body": "I already had this representation, but in order to avoid to go back to a position we already had, the lists must be compared, which means they must be sorted. I also tried `Set`s instead of lists, which worked somewhat better, but had to be translated back to lists in `findSolution`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T00:24:17.117", "Id": "3336", "ParentId": "3322", "Score": "2" } }, { "body": "<p>I kept the record syntax (but it's good to know about the alternatives). This is my last version:</p>\n\n<pre><code>import Data.Maybe(catMaybes)\n\ndata Place = Here | There deriving (Eq, Show)\n\ndata Pos = Pos {cabb, goat, wolf, farmer :: Place} deriving (Eq, Show)\n\ntype Path = [Pos]\n\nfindMoves :: Path -&gt; [Path]\nfindMoves path@(pos@(Pos c g w f) : prev) =\n catMaybes [ c ??? pos {cabb = opp c} , g ??? pos {goat = opp g}\n , w ??? pos {wolf = opp w} , f ??? pos ] where\n opp Here = There\n opp There = Here\n\n valid (Pos c g w f) = (c /= g &amp;&amp; g /= w) || g == f\n\n x ??? p = let p' = p {farmer = opp f}\n in if x == f &amp;&amp; valid p' &amp;&amp; notElem p' prev \n then Just (p' : path) else Nothing\n\nfindSol :: Pos -&gt; Path -&gt; [Path]\nfindSol pos path@(p : _) \n | p == pos = [reverse path] \n | otherwise = findMoves path &gt;&gt;= findSol pos \n\n\nsolve :: [Path]\nsolve = findSol endPos [startPos] where\n setPos place = Pos place place place place\n startPos = setPos Here\n endPos = setPos There\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T13:15:05.497", "Id": "3762", "ParentId": "3322", "Score": "1" } }, { "body": "<p>Here's my attempt using arrays and list comprehensions:</p>\n\n<pre><code>import Data.Array\nimport Data.List\n\ntype Pos = Array Obj Place\n\ndata Place = Here | There deriving (Eq, Show)\n\ndata Obj = Cabb | Goat | Wolf | Farmer deriving (Ord, Eq, Ix, Show, Enum)\n\nobjs = [Cabb .. Farmer]\n\nallAre a = listArray (Cabb, Farmer) $ map (const a) objs\n\nstart = allAre Here\nend = allAre There\n\nopp Here = There\nopp There = Here\n\nvalid arr = (arr ! Cabb /= arr ! Goat &amp;&amp; arr ! Goat /= arr ! Wolf) || arr ! Goat == arr ! Farmer\n\nmove arr obj = [(o, opp (arr ! o)) | o &lt;- [Farmer, obj]]\n\nnextStates arr = [ nextState | obj &lt;- objs, let nextState = arr // move arr obj, arr ! Farmer == arr ! obj, valid nextState]\n\nnextMove paths = [nextState : path | path &lt;- paths, nextState &lt;- nextStates (head path)]\n\nfilterSolutions = filter (\\path -&gt; head path == end) \n\nshortestPath = head $ concatMap filterSolutions $ iterate nextMove [[start]]\n\nmain = print $ length shortestPath\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-04T19:15:55.997", "Id": "24852", "Score": "0", "body": "That looks very clean. I'll meditate over it :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-04T16:59:35.307", "Id": "15330", "ParentId": "3322", "Score": "1" } } ]
{ "AcceptedAnswerId": "3327", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T07:33:05.660", "Id": "3322", "Score": "2", "Tags": [ "haskell" ], "Title": "Cabbage-Goat-Wolf puzzle in Haskell" }
3322
<p>I was wondering if someone could have a look at this <a href="http://jsfiddle.net/sta444/Zz8yM/3/" rel="nofollow">BBC iPlayer style content accordion/slider</a> I've just made, and help me to get it working properly? I'm no expert in jQuery and I'm sure I haven't done this correctly, or if there are more efficient ways of doing it. </p> <p>The problem seems to be the clicking. It sometimes requires two clicks, and the sliding of the content, the left panel seems to re-size when animating. </p> <p><a href="http://jsfiddle.net/sta444/Zz8yM/3/" rel="nofollow">Here is all of the code</a>.</p> <p><strong>Snippet from jsfiddle:</strong></p> <pre><code>$('#accordion &gt; li.bg1 .heading').toggle( function () { $('#accordion &gt; li.bg2').stop().animate({'width':'718px'},1000); $('#accordion &gt; li.bg1').stop().animate({'width':'50px'},1000); $('#accordion &gt; li.bg1 .heading').stop(true,true).fadeOut(1000); $('#accordion &gt; li.bg1 .heading-side').stop(true,true).fadeIn(2000); $('a.see-more-p').css('display','none'); }, function () { $('#accordion &gt; li.bg1').stop().animate({'width':'374px'},1000); $('#accordion &gt; li.bg2').stop().animate({'width':'394px'},1000); $('#accordion &gt; li.bg1 .heading-side').stop(true,true).fadeOut(1000); $('#accordion &gt; li.bg1 .heading').stop(true,true).fadeIn(2000); $('a.see-more-p').css('display','block'); } ); $('#accordion &gt; li.bg2 .heading, a.see-more-p').toggle( // same as above ); $('#accordion &gt; li.bg1 .heading-side').toggle( // same as above ); </code></pre>
[]
[ { "body": "<p>I'd normally suggest you post this on <a href=\"http://stackoverflow.com\">StackOverflow</a> as it doesn 't work properly.</p>\n\n<p>Firstly:</p>\n\n<ol>\n<li><p>You have the same two functions repeated over and over .... don't. Put them in one big selector.</p>\n\n<pre><code>$('#accordion &gt; li.bg1 .heading, #accordion &gt; li.bg2 .heading, a.see-more-p, #accordion &gt; li.bg1 .heading-side').toggle\n</code></pre></li>\n<li><p>You have two headings for each. Semantically this is wrong. change your <code>.heading-side</code> to <code>.heading.side</code>. then all you need is an <code>addClass('side');</code> and <code>removeClass('side');</code><br>\nalso you will need:</p>\n\n<pre><code>ul.accordion li .heading.side .right{ display: none; }\n</code></pre>\n\n<p>to hide the <code>&gt;</code>.<br>\nTo get the fadeIn/Out:</p>\n\n<pre><code>.fadeOut(500).queue(function(next) {\n $(this).addClass(\"side\");\n next();\n}).fadeIn(500);\n</code></pre>\n\n<p>That looks confusing with the <code>.queue(...</code> but that's just to make sure it happens between the fading so the user doesn't see any oddness.</p></li>\n<li><p>The toggle only toggles for that specific context <em>(i.e. the element being clicked)</em> so it will toggle for each element, hence the double clickyness.<br>\nMy solution is to roll your own toggling:</p>\n\n<pre><code>$(function() {\n var first = true;\n $('#accordion &gt; li.bg1 .heading, #accordion &gt; li.bg2 .heading, a.see-more-p, #accordion &gt; li.bg1 .heading-side')\n .click(function() {\n if (first) {\n //do first stuff\n }else{\n // do second stuff\n }\n first = !first; // &lt; --- Toggling done here!!!!\n });\n});\n</code></pre></li>\n</ol>\n\n<p>Viola! see <a href=\"http://jsfiddle.net/Zz8yM/5/\" rel=\"nofollow\">jsFiddle</a> for my awesomeness!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-21T04:31:54.627", "Id": "4931", "ParentId": "3325", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T11:53:46.697", "Id": "3325", "Score": "4", "Tags": [ "javascript", "jquery" ], "Title": "'iplayer' style content accordion/slider" }
3325
<p>In response to <a href="https://stackoverflow.com/questions/6539461/any-value-in-javascript-html-decoupling-if-so-how/6539734">my own question</a> on Stack Overflow, I'm attempting a solution to decouple JavaScript and html. I'd appreciate any comments, proposed refactoring, or criticism.</p> <p>I have a fiddle of it in use <a href="http://jsfiddle.net/sheldonj/awgaM/11/" rel="nofollow noreferrer">here</a></p> <p>Here's the code:</p> <pre><code>(function (window, $, undefined) { "use strict"; var ab = window.ab = window.autoBinder = {}, elements; ab.exportSymbol = function (publicPath, object) { var tokens = publicPath.split("."), target = window, i; for (i = 0; i &lt; tokens.length - 1; i++) { target = target[tokens[i]]; } target[tokens[tokens.length - 1]] = object; }; ab.exportProperty = function (owner, publicName, object) { owner[publicName] = object; }; ab.extensions = (function () { return { datePicker: function (element) { var params = { minDate: 0, showButtonPanel: false }, e = $(element); if (e.data("mindate") !== undefined) { params.minDate = e.data("mindate"); } if (e.data("showpanel") !== undefined) { params.showButtonPanel = e.data("showpanel"); } e.datepicker(params); } }; })(); ab.hookups = (function () { return { make: function (value, element) { if (ab.extensions[value]) { ab.extensions[value](element); } }, publish: function (value, $element) { if (!value) { return; } $element.change(function () { $element.trigger(value, $element); }); }, subscribe: function (value, $element) { var trigger = $element.data("trigger"); if (trigger === undefined) { throw "Found Subscribe without Trigger."; } if (!ab.extensions[trigger]) { throw "Found Subscribe without Trigger."; } $(document).bind(value, function (event, htmlElement) { ab.extensions[trigger](event, htmlElement, $element); }); } }; })(); ab.exportSymbol("ab.extensions.datePicker", ab.extensions.datePicker); ab.exportSymbol("ab.hookups.make", ab.hookups.make); ab.exportSymbol("ab.hookups.publish", ab.hookups.publish); ab.exportSymbol("ab.hookups.subscribe", ab.hookups.subscribe); $(window).load(function () { elements = $("*").filter(function () { var data = $(this).data(), p; if (data === undefined) { return false; } for (p in data) { if (data.hasOwnProperty(p)) { return true; } } return false; }); elements.each(function () { var obj = $(this), data = obj.data(), p; for (p in data) { if (data.hasOwnProperty(p)) { if (ab.hookups[p]) { ab.hookups[p](data[p], obj); } } } }); }); } (window, jQuery)); // #region Example of Extending extensions window.ab.extensions.effectiveDateChanged = function (event, triggerElement, subscribedElement) { var $element = jQuery(triggerElement); subscribedElement.val("Value set to: " + $element.val()); }; window.ab.extensions.dropDownChanged = function(event, triggerElement, subscribedElement) { var $element = jQuery(triggerElement), value = $element.val(); if (value === "") { subscribedElement.attr("disabled", "disabled"); subscribedElement.html(""); return; } subscribedElement.removeAttr("disabled"); subscribedElement.html("&lt;option&gt;" + value + "&lt;/option&gt;"); }; // #endregion </code></pre>
[]
[ { "body": "<p>Update here: <a href=\"http://jsfiddle.net/5ej8G/3/\" rel=\"nofollow\">http://jsfiddle.net/5ej8G/3/</a> (code is also pasted below)</p>\n\n<p>Main suggestions:</p>\n\n<ul>\n<li>your exportSymbol function can be refactored to handle an array of publicPaths and Objects.</li> \n<li>The subscribe conditions can be consolidated since they throw the same message.</li> \n<li>check your parameters before using. typeOf checks don't work well with all objects, but there are techniques to have them work with all objects. One from Angus Croll(http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/) is included in the link above.</li> \n<li>Explicitly state which elements you want your code to act on, maybe by passing in a parameter object. doing a $(\"*\"), on medium to large pages (with lots of dom elements) can be a performance hit.</li> \n</ul>\n\n<pre><code>(function (window, $, undefined) {\n \"use strict\";\n var ab = window.ab = window.autoBinder = {},\n elements,\n\n toType = function(obj) {\n return ({}).toString.call(obj).match(/\\s([a-zA-Z]+)/)[1].toLowerCase()\n };\n //can handle an array of publicPaths and objects\n ab.exportSymbols = function (paramArray) {\n var tokens,\n target = window,\n i,\n index,\n len,\n limit,\n exportSymbol;\n if(toType(paramArray) !== 'array') { \n throw \"You must pass an array into this function.\"; \n }\n\n //Export Symbol now becomes a inner helper function\n exportSymbol = function(pubPath, obj) {\n tokens = pubPath.split(\".\");\n lastIndex = tokens.Length;\n\n for (i = 0; i &lt; lastIndex ; i++) {\n target = target[tokens[i]];\n }\n target[tokens[lastIndex]] = obj;\n };\n\n //validate and run helper function on each object in array\n for(index= 0, len=paramArray.length; i &lt; len; i++) {\n if(toType(paramArray.publicPath) !== 'string' \n || toType(paramArray.publicPath) !== 'object') {\n continue;\n }\n exportSymbol(paramArray[index].publicPath, paramArray[index].obj); \n }\n };\n\n ab.exportProperty = function (owner, publicName, object) {\n owner[publicName] = object;\n };\n\n ab.extensions = function () {\n return {\n datePicker: function (element) {\n var params = {\n minDate: 0,\n showButtonPanel: false\n },\n e = $(element);\n\n if (e.data(\"mindate\") !== undefined) {\n params.minDate = e.data(\"mindate\");\n }\n\n if (e.data(\"showpanel\") !== undefined) {\n params.showButtonPanel = e.data(\"showpanel\");\n }\n\n e.datepicker(params);\n }\n };\n }();\n\n ab.hookups = (function () {\n return {\n make: function (value, element) {\n\n if (ab.extensions[value]) {\n ab.extensions[value](element);\n }\n },\n publish: function (value, $element) {\n\n if (!value) {\n return;\n }\n\n $element.change(function () {\n $element.trigger(value, $element);\n });\n },\n subscribe: function (value, $element) {\n var trigger = $element.data(\"trigger\");\n\n //Conditions can be consolidate since they trow the same message\n if ((trigger === undefined) || !ab.extensions[trigger]) {\n throw \"Found Subscribe without Trigger.\";\n } \n\n $(document).bind(value, function (event, htmlElement) {\n ab.extensions[trigger](event, htmlElement, $element);\n });\n }\n };\n })();\n\n //can pass in a an array of object instead of mutiple calls\n ab.exportSymbols([\n {pubPath : \"ab.extensions.datePicker\", obj : ab.extensions.datePicker},\n {pubPath : \"ab.hookups.make\" , obj : ab.hookups.make},\n {pubPath : \"ab.hookups.publish\" , obj : ab.hookups.publish},\n {pubPath : \"ab.hookups.subscribe\" , obj : ab.hookups.subscribe}\n ]);\n\n\n $(window).load(function () {\n elements = $(\"*\").filter(function () {\n var data = $(this).data(),\n p;\n if (data === undefined) {\n return false;\n }\n for (p in data) {\n if (data.hasOwnProperty(p)) {\n return true;\n }\n }\n return false;\n });\n\n elements.each(function () {\n var obj = $(this),\n data = obj.data(),\n p;\n\n for (p in data) {\n if (data.hasOwnProperty(p)) {\n if (ab.hookups[p]) {\n ab.hookups[p](data[p], obj);\n }\n }\n }\n });\n });\n} (window, jQuery));\n\n// Example Extending extensions\n window.ab.extensions.effectiveDateChanged = function (event, triggerElement, subscribedElement) {\n var $element = jQuery(triggerElement);\n subscribedElement.val(\"Value set to: \" + $element.val());\n };\n\nwindow.ab.extensions.dropDownChanged = function(event, triggerElement, subscribedElement) {\n var $element = jQuery(triggerElement),\n value = $element.val();\n\n if (value === \"\") {\n subscribedElement.attr(\"disabled\", \"disabled\");\n subscribedElement.html(\"\");\n return;\n }\n\n subscribedElement.removeAttr(\"disabled\");\n subscribedElement.html(\"&lt;option&gt;\" + value + \"&lt;/option&gt;\");\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-28T12:00:59.703", "Id": "4445", "ParentId": "3328", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T14:02:27.883", "Id": "3328", "Score": "3", "Tags": [ "javascript" ], "Title": "Decoupling JavaScript and Html" }
3328
<p>I've recently come across some areas of code in our solution that have a few thread-safety problems. Thread-safety is a minefield at best so I thought I'd have an attempt at writing a few little utility classes that would make it easier to write safe multi-threaded code.<br> The general idea is to link a resource with the lock(s) that protect it. If the resource is accessed outside of all of it's locks then a runtime exception is thrown.</p> <p>Imagine a developer had written the following (example) caching object but had forgotten to take the _imageLock when clearing the cache. </p> <p>Using the traditional .net locking mechanism (of just locking on an Object) we might corrupt the Dictionary if two threads call Add() and ClearCache() at the same time. </p> <p>Using these utility classes, Padlock and Protected&lt;T&gt;, will instead throw an exception in the ClearCache() method because the Protected&lt;T&gt; object is being accessed outside of it's lock. This exception should surface during the developers normal testing procedure, before the code is even checked in.</p> <pre><code>public class SomeThreadSafeCache { Padlock _imageLock = new Padlock(); Protected&lt;Dictionary&lt;string, byte[]&gt;&gt; _imageCache; public SomeThreadSafeCache() { //The variable _imageCache is associate with the _imageLock Padlock //i.e. _imageCache is only available when we're locking on _imageLock. _imageCache = new Protected&lt;Dictionary&lt;string, byte[]&gt;&gt;( new Dictionary&lt;string, byte[]&gt;(), _imageLock); } public void AddImage(string key, byte[] data) { using (_imageLock.Lock()) { _imageCache.Value.Add(key, data); } } public void ClearCache() { //Throws an exception because the protected //resource is accessed outside of it's lock. _imageCache.Value.Clear(); } } </code></pre> <p>(I know that .net now comes with Concurrent collections which make my example pointless but the general idea of linking a resource with it's lock is what I'm trying to get at)</p> <p>The Protected&lt;T&GT; class is able to be associated with as many Padlocks as you might want.</p> <pre><code>public class SomeOtherThreadSafeObject { Padlock _lock1 = new Padlock(); Padlock _lock2 = new Padlock(); Protected&lt;int&gt; _i; public SomeOtherThreadSafeObject() { _i = new Protected&lt;int&gt;(0, _lock1, _lock2); } public void IncrementI() { using (_lock1.Lock()) { using (_lock2.Lock()) { _i.Value++; } } } } </code></pre> <p>(A trivial example for illustrative purposes only, the Interlocked.Increment function would do a better job.)</p> <p>If either _lock1 or _lock2 is not taken then </p> <pre><code>_i.Value++ </code></pre> <p>will throw an exception stating that the object is not fully locked. </p> <p>Enforcing the order in which the locks are taken are outside the scope of the utility classes. I'm also trying to avoid the old ICollection.SyncRoot pattern by not allowing </p> <pre><code>Protected&lt;T&gt;.Padlock.Lock() </code></pre> <p>The locking policy itself should be up to the implementors of the class. All Protected&lt;T&gt; is interested is in is knowing if it's fully protected before allowing access to it's internal value.</p> <p>What I'm asking for a review of is the general approach/idea. Does this seem like a sensible system? Are there any glaring problems with it that I've not thought of? If anyone wants to see the actual implementation code then I can post it on Github (or somewhere similar).</p> <p>(I'm aware that this abuses the IDisposable/Using pattern but for added thread-safety I think it will be worth it for us).</p>
[]
[ { "body": "<p>This looks promising, though without the ability to enforce ordering i would remove the ability to associate multiple locks with a protected object, because you are just asking for a deadlock.</p>\n\n<p>Also, how do you protect against something like this:</p>\n\n<pre><code>Protected&lt;Reference&gt; _i = new Protected&lt;Reference&gt;(0, lock);\nReference unprotected_i;\nusing (lock.Lock()) \n{\n unprotected_i = _i.Value;\n}\nunprotected_i.boom();// any modifying operation.\n</code></pre>\n\n<p>I think that what you would really want to do is create a dynamic proxy object under the hood and return that in the Value getter, then you could enforce the protection.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T06:32:30.543", "Id": "4990", "Score": "0", "body": "Yes, I did think about that. I tried to overload the assignment operater but then realized that C# (quite rightly) won't let you. I would hope that people using Protected<T> would be able to see why copying the reference would be a bad idea. I'll have a go at building the dynamic proxy as well though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T09:51:04.550", "Id": "4995", "Score": "0", "body": "I've had a look at building up a dynamic proxy but it won't work in all cases. The generated proxy object must have the same IS-A relationship as the type it is proxying for. This means that the type must either implement an interface (and that interface must be the type argument T to Protected<T>) or be inheritable so the proxy object can derive from the original. In my example above an int is neither of those two things so we can't create a dynamic proxy for it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T18:35:20.600", "Id": "5012", "Score": "0", "body": "Yeah, no amount of Dynamic Proxying would let you handle an int. So you could just limit Protected<T> to only take reference types as parameter (add a where T : class clause). But it still seems overly complicated." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-06T16:37:11.733", "Id": "5877", "Score": "0", "body": "Since the OP alluded to the .Net concurrent collections, and stated *'which make my example pointless'*, I highly recommend giving them a look." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T15:23:28.580", "Id": "3330", "ParentId": "3329", "Score": "0" } }, { "body": "<p>I am not sure I understand the question. What are these classes going to give me that a standard lock wouldn't? </p>\n\n<p>I would write that first class something like this:</p>\n\n<pre><code>public sealed class SomeThreadSafeCache\n{\n static readonly object l = new object();\n static volatile SomeThreadSafeCache instance;\n\n readonly Dictionary&lt;string, byte[]&gt; _imageCache;\n\n SomeThreadSafeCache()\n {\n _imageCache = new Dictionary&lt;string, byte[]&gt;();\n }\n\n public static SomeThreadSafeCache Instance\n {\n get\n {\n if (instance == null)\n {\n lock (l)\n {\n if (instance == null)\n instance = new SomeThreadSafeCache();\n }\n }\n\n return instance;\n }\n }\n\n public void AddImage(string key, byte[] data)\n {\n if (data == null) \n throw new ArgumentNullException(\"data\");\n if (key == null) \n throw new ArgumentNullException(\"key\");\n\n var v = (byte[]) data.Clone();\n lock (l)\n {\n _imageCache.Add(key, );\n }\n }\n\n public byte[] GetImage(string key) \n {\n if (key == null) \n throw new ArgumentNullException(\"key\");\n\n byte[] v;\n lock (l)\n {\n _imageCache.TryGetValue(key, out v);\n }\n if (v == null) \n {\n return null;\n }\n return (byte[]) v.Clone();\n }\n\n public void ClearCache()\n {\n lock(l)\n {\n _imageCache.Clear();\n }\n }\n}\n</code></pre>\n\n<p>(unable to check correctness right now due to not sitting at my work machine, but barring any syntax errors I think that is right) Am I doing something wrong here? </p>\n\n<p>I think a static constructor is fine for the singleton pattern as well, but I am not 100% sure it covers all thread safety issues. I don't see how a single lock object wouldn't though.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-03T01:15:30.397", "Id": "11424", "ParentId": "3329", "Score": "0" } }, { "body": "<p>I confess that I think your approach looks painful. As you can see from the other answers, it's insufficient to protect your data outside the container class. And there's confusion in your example code as to whether Protected is the container or ThreadSafeCache is the container. I think instead that you need to revisit the principle of encapsulation. When you have a collection that requires multi-threaded updates and access, you protect that collection with a wrapper class. The wrapper encapsulates the underlying collection in its entirety. Think \"private\". If you don't want to expose the lock, then you don't expose an iterator/enumerator. Rather, you do something similar to the List's ForEach method:</p>\n\n<pre><code>public void ForEach(Action&lt;T&gt; t){\n lock(_items) foreach(var item in _items) t.Invoke(item);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T04:03:55.723", "Id": "13107", "ParentId": "3329", "Score": "3" } }, { "body": "<p>Is there any reason for making \"Exception\" branch for accessing \"Value\"? Maybe it's better to use something like</p>\n\n<pre><code>using(var lockedDictionary = _imageCache.Lock())\n{\n lockedDictionary.Value.Add(key, data);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-24T11:51:56.190", "Id": "19890", "ParentId": "3329", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T14:46:15.070", "Id": "3329", "Score": "7", "Tags": [ "c#", "multithreading", "locking" ], "Title": "Associating a lock/mutex with the data it protects" }
3329
<p>I am parsing a huge XML file. It contains some million article entries like this one:</p> <pre><code>&lt;article key="journals/cgf/HaeglerWAGM10" mdate="2010-11-12"&gt; &lt;author&gt;Simon Haegler&lt;/author&gt; &lt;author&gt;Peter Wonka&lt;/author&gt; &lt;author&gt;Stefan Müller Arisona&lt;/author&gt; &lt;author&gt;Luc J. Van Gool&lt;/author&gt; &lt;author&gt;Pascal Müller&lt;/author&gt; &lt;title&gt;Grammar-based Encoding of Facades.&lt;/title&gt; &lt;pages&gt;1479-1487&lt;/pages&gt; &lt;year&gt;2010&lt;/year&gt; &lt;volume&gt;29&lt;/volume&gt; &lt;journal&gt;Comput. Graph. Forum&lt;/journal&gt; &lt;number&gt;4&lt;/number&gt; &lt;ee&gt;http://dx.doi.org/10.1111/j.1467-8659.2010.01745.x&lt;/ee&gt; &lt;url&gt;db/journals/cgf/cgf29.html#HaeglerWAGM10&lt;/url&gt; &lt;/article&gt; </code></pre> <p>I step through the file and parse those articles by LXML. If I let the code without storing the items into my database it makes some 1000 entries in ~3 seconds. But if I activate the storage which is done by the function below it makes some 10 entries per second. Is this normal? I remember parsing the file once upon a time and the database was not such a bottleneck. But I had a different approach... (looking through my files to find it)</p> <pre><code>def add_paper(paper, cursor): questionmarks = str(('?',)*len(paper)).replace("'", "") # produces (?, ?, ?, ... ,?) for oursql query keys, values = paper.keys(), paper.values() keys = str(tuple(keys)).replace("'", "") # produces (mdate, title, ... date, some_key) query_paper = '''INSERT INTO dblp2.papers {0} VALUES {1};'''.\ format(keys, questionmarks) values = tuple(v.encode('utf8') for v in values) cursor.execute(query_paper, values) paper_id = cursor.lastrowid return paper_id def populate_database(paper, authors, cursor): paper_id = add_paper(paper, cursor) query_author ="""INSERT INTO dblp2.authors (name) VALUES (?) ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)""" query_link_table = "INSERT INTO dblp2.author_paper (author_id, paper_id) VALUES (?, ?)" for author in authors: cursor.execute(query_author, (author.encode('utf8'),)) author_id = cursor.lastrowid cursor.execute(query_link_table, (author_id, paper_id)) </code></pre> <p><strong>Edit:</strong></p> <p>I was able to narrow the problem to those three <code>cursor.execute</code>s. Perhaps it is a database problem. I will ask over at Stack Overflow, if someone has an idea, why it is that slow. Meanwhile I would be interested if the code can be refactored to be more pythonic. Any ideas?</p> <p><strong>Edit 2:</strong></p> <p>If use a similar approach like me storing row per row into the database, don't use the InnoDB engine. It's slower in orders of magnitude. The code is speeding up again, after I changed the engine.</p>
[]
[ { "body": "<p>You might want to try doing everything inside a transaction. It may be faster that way. I think with InnoDB you might be creating a committing a transaction for every statement which will be slow.</p>\n\n<pre><code>keys = str(tuple(keys)).replace(\"'\", \"\")\n</code></pre>\n\n<p>That's an odd way of doing that, use</p>\n\n<pre><code>keys = '(%s)' % ','.join(keys)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T16:28:03.830", "Id": "5010", "Score": "0", "body": "Would you please explain what you mean by *doing everything inside a transactio*, @Winston?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T23:30:25.287", "Id": "5016", "Score": "1", "body": "@Aufwind, lookup database transactions. They allow you to group together statements so that either they all happen or none of them happen. InnoDB supports them whereas the other MySQL engine's don't. I think that might the reason for the speed diference." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T08:38:05.950", "Id": "3341", "ParentId": "3331", "Score": "3" } }, { "body": "<p>Have you considered <code>cursor.executemany</code>? You could potentially build up a list of several articles, and then process all at once. The only limitation to doing this would be how much memory you have.</p>\n\n<p>If you've got relatively few authors and lots of papers, you could potentially hold a dictionary of author names to database id. This would make it easier to get the database id without querying the database.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-23T14:27:18.670", "Id": "55025", "ParentId": "3331", "Score": "3" } } ]
{ "AcceptedAnswerId": "3341", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T16:52:46.007", "Id": "3331", "Score": "2", "Tags": [ "python", "performance", "mysql" ], "Title": "Function to store data in MySQL database (using OurSQL)" }
3331
<p>I've created and launched our first HTML5 site. I've done a lot of research in to the "best practices" for writing a page in HTML5 and put a majority of them to use. I was hoping someone wouldn't mind looking over the site and shouting back any comments, issues, or recommendations on it. I'm looking for anything, from code improvements, accessibility improvements, or optimization.</p> <p>Some things I should share:</p> <ul> <li>It doesn't work well in Internet Explorer 6, and I don't care!</li> <li>It's using remy's html5shiv and a conditional stylesheet <code>display:block</code>'ing all the HTML5 elements for Internet Explorer 7/8 and Firefox 3.</li> <li>The included JavaScript file probably will appear empty to anyone looking at it in a modern browser. I'm aware of the wasted HTTP request.</li> <li>The CSS file includes a <code>@import</code> (barf), that I cannot control; it's part of our University's required header bar.</li> </ul> <p>Site URL: <a href="http://ulabs.illinoisstate.edu/" rel="nofollow">http://ulabs.illinoisstate.edu/</a></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;meta name="description" content="University Computer Labs at Illinois State University" /&gt; &lt;meta name="keywords" content="university labs ulabs u-labs illinois state computer" /&gt; &lt;title&gt;University Labs - Illinois State University&lt;/title&gt; &lt;link rel="stylesheet" href="/templates/style.1309283866.php" /&gt; &lt;link rel="shortcut icon" href="http://illinoisstate.edu/favicon.ico" /&gt; &lt;script src="/templates/js.1309283871.php"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="iguide-container"&gt; &lt;a id="skip-iguide" href="#skipiguide" title="Skip the iGuide"&gt;&lt;/a&gt; &lt;script src="http://iguides.illinoisstate.edu/?red"&gt;&lt;/script&gt; &lt;noscript&gt; &lt;div id="iguide"&gt; &lt;span id="iguide-isu"&gt;&lt;a href="http://illinoisstate.edu"&gt;&lt;/a&gt;&lt;/span&gt; &lt;span id="iguide-admissions"&gt;&lt;a href="http://admissions.illinoisstate.edu"&gt;&lt;/a&gt;&lt;/span&gt; &lt;span id="iguide-academics"&gt;&lt;a href="http://illinoisstate.edu/home/academics"&gt;&lt;/a&gt;&lt;/span&gt; &lt;span id="iguide-events"&gt;&lt;a href="http://events.illinoisstate.edu"&gt;&lt;/a&gt;&lt;/span&gt; &lt;span id="iguide-map"&gt;&lt;a href="http://maps.illinoisstate.edu"&gt;&lt;/a&gt;&lt;/span&gt; &lt;span id="iguide-AtoZ"&gt;&lt;a href="http://illinoisstate.edu/home/find"&gt;&lt;/a&gt;&lt;/span&gt; &lt;span id="iguide-access"&gt;&lt;a href="http://illinoisstate.edu/home/accessibility"&gt;&lt;/a&gt;&lt;/span&gt; &lt;/div&gt; &lt;/noscript&gt; &lt;/div&gt; &lt;a id="skipiguide"&gt;&lt;/a&gt; &lt;div id="container"&gt; &lt;header&gt; &lt;h1&gt;&lt;a href="/"&gt;&lt;span&gt;University Labs&lt;/span&gt;&lt;/a&gt;&lt;/h1&gt; &lt;/header&gt; &lt;nav&gt; &lt;a id="home" href="/" title="Home"&gt;&lt;/a&gt; &lt;a id="hd" href="http://helpdesk.illinoisstate.edu/" title="Help Desk"&gt;&lt;/a&gt; &lt;a id="emp" href="/employees/" title="Employees"&gt;&lt;/a&gt; &lt;/nav&gt; &lt;div id="contentarea"&gt; &lt;section id="welcome"&gt; &lt;header&gt; &lt;h2&gt;What is uLabs?&lt;/h2&gt; &lt;/header&gt; &lt;p&gt;uLabs at Illinois State is comprised of six computer labs containing a total of over 400 seats around campus open to Illinois State University students. These labs are located in Milner Library, Schroeder Hall, Stevenson Hall, Vrooman Center, Watterson Towers, and Whitten Hall.&lt;/p&gt; &lt;p&gt;Supported by &lt;a href="http://ctsg.illinoisstate.edu/ciss/"&gt;Computer Infrastructure Support Services&lt;/a&gt;, the labs are equipped with state-of-the-art computers and printers. Each computer lab is equipped with basic software, such as Microsoft Office. Some uLabs also have specialized software and equipment.&lt;/p&gt; &lt;p&gt;For information on each uLab, including hours, location, equipment, and software available, visit the links below.&lt;/p&gt; &lt;/section&gt; &lt;aside&gt; &lt;header&gt; &lt;h2&gt;&lt;span&gt;uPrint&lt;/span&gt;&lt;/h2&gt; &lt;/header&gt; &lt;p&gt;Each uLab, with the exception of Milner, is fitted with a uPrint station. Milner Library's uPrint station is located behind the General Reference Desk.&lt;/p&gt; &lt;p&gt;With uPrint, you can print from any computer on campus, including your own computer in your residence hall! For more information on uPrint and how to use it, follow the links below.&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="http://helpdesk.illinoisstate.edu/kb/1134/"&gt;Overview of uPrint Mobile Printing&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://helpdesk.illinoisstate.edu/downloads/1028/"&gt;Download uPrint Client for Windows&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://helpdesk.illinoisstate.edu/downloads/1028/"&gt;Download uPrint Client for Mac OSX&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/aside&gt; &lt;section id="locations"&gt; &lt;header&gt; &lt;h3&gt;uLab Locations&lt;/h3&gt; &lt;p&gt;Click a location for more information&lt;/p&gt; &lt;/header&gt; &lt;div id="buildings"&gt; &lt;div id="mlb"&gt;&lt;a href="/loc/milner/"&gt;Milner Library 213B&lt;/a&gt;&lt;/div&gt; &lt;div id="sch"&gt;&lt;a href="/loc/schroeder/"&gt;Schroeder Hall 230&lt;/a&gt;&lt;/div&gt; &lt;div id="stv"&gt;&lt;a href="/loc/stevenson/"&gt;Stevenson Hall 250&lt;/a&gt;&lt;/div&gt; &lt;div id="vro"&gt;&lt;a href="/loc/vrooman/"&gt;Vrooman Center 4&lt;/a&gt;&lt;/div&gt; &lt;div id="wat"&gt;&lt;a href="/loc/watterson/"&gt;Watterson Towers 110&lt;/a&gt;&lt;/div&gt; &lt;div id="wht"&gt;&lt;a href="/loc/whitten/"&gt;Whitten Hall 6&lt;/a&gt;&lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;/div&gt; &lt;footer&gt; &lt;section id="contact_methods"&gt; &lt;p&gt;&lt;a href="mailto:ulabs@illinoisstate.edu"&gt;ulabs@IllinoisState.edu&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href="http://ctsg.illinoisstate.edu/ciss/"&gt;Computer Infrastructure Support&lt;/a&gt;&lt;br/&gt;Campus Box 3430&lt;br/&gt;Normal, IL 61790-3430&lt;br/&gt;Phone: (309) 438-8800&lt;/p&gt; &lt;/section&gt; &lt;section id="legal_statements"&gt; &lt;p&gt;Copyright 2011 &amp;#169; &lt;a href="http://www.illinoisstate.edu/"&gt;Illinois State University&lt;/a&gt; &amp;bull; &lt;a href="http://www.ilstu.edu/home/diversity/"&gt;An equal opportunity/affirmative action university encouraging diversity.&lt;/a&gt; &amp;bull; &lt;a href="http://www.ilstu.edu/home/privacy/web_privacy_notice.pdf"&gt;Privacy Policy&lt;/a&gt;&lt;/p&gt; &lt;/section&gt; &lt;section id="university_initiatives"&gt; &lt;p&gt;&lt;a href="http://illinoisstate.edu/"&gt;&lt;img src="/templates/images/footerReggieGrey.png" width="40" height="46" alt="Illinois State University" /&gt;&lt;/a&gt;&lt;/p&gt; &lt;/section&gt; &lt;/footer&gt; &lt;/div&gt; &lt;script src="http://analytics.illinoisstate.edu/"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-26T20:37:53.337", "Id": "28645", "Score": "0", "body": "Why are you using javascript for the menu? I don't see anything with the menu that can't be done without JS. This would also eliminate the `noscript` problem that RoToRa addressed below. Why not maintain only one version of the menu and do it in html/css only?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-26T20:58:15.297", "Id": "28655", "Score": "0", "body": "I believe you're referring to the section containing the iGuide as a menu? If so, that's not a menu. It's a required piece for our University. The reason it is based in JS is for emergencies on campus and other more technical reasons." } ]
[ { "body": "<p>I only have a few small points:</p>\n\n<ul>\n<li><p>The CSS Validator warns about the missing <code>type</code> attribute in the style sheet <code>link</code>. I'm aware it's not really needed, but I would add it nevertheless.</p></li>\n<li><p>Some people say, that <code>&lt;noscript&gt;</code> should be avoided, so it's something one can think about. However in this case, I believe, it's sensible to use it.</p></li>\n<li><p>I would use longer <code>id</code>s. Some are unnecessarily short such as <code>hd</code>, <code>emp</code> and the ones of the buildings.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T13:39:35.320", "Id": "5001", "Score": "0", "body": "Thanks for taking the time to leave some feedback! I think the validator only warns about a missing type if you validate against CSS 2.1 rules, but against CSS3 rules, it doesn't. I know the HTML5 spec says it's optional. Would you still add it back? Also, the `<noscript>` is something I really can't control, because that's how ISU does their header bar. It's annoying and I wish there was a better way to handle that. Lastly, why would you use longer ID's? I've actually never heard of anyone suggesting that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T13:50:08.947", "Id": "5003", "Score": "0", "body": "I get the warning validating against CSS 3, too: http://jigsaw.w3.org/css-validator/validator?uri=http%3A%2F%2Fulabs.illinoisstate.edu%2F&profile=css3&usermedium=all&warning=1&vextwarning=&lang=de#warnings" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T13:51:30.053", "Id": "5004", "Score": "0", "body": "IMHO it's no different than variables in programming, where cryptically abbreviated variable names should be avoided, too." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T12:42:42.047", "Id": "3345", "ParentId": "3335", "Score": "4" } }, { "body": "<p>I've been working on my first \"robust\" html5 project - and I generally find that usage guidelines for semantic markup is \"still being worked out\", or to put it another way, that standards for semantic grouping haven't yet been well established. </p>\n\n<p>That being said, I've found the basic pattern of </p>\n\n<pre><code>&lt;header&gt;\n&lt;section&gt;\n&lt;footer&gt;\n</code></pre>\n\n<p>to be quite useful, and I've been running with that rule. So, if I was to comment on your otherwise quite clean markup, it would just be to question if some of your structural <code>&lt;div&gt;</code> may be better purposed as <code>&lt;section&gt;</code>s (specifically <code>&lt;div id=\"contentarea\"&gt;</code>). Just a thought.</p>\n\n<p>You use <code>&lt;ul&gt;</code> to contain helpdesk links, but <code>&lt;div&gt;</code> to contain building links. Any reason you went with a <code>&lt;div&gt;</code> for <code>id=\"buildings\"</code>?</p>\n\n<p>I also feel like <code>&lt;noscript&gt;</code> is questionable, but probably used appropriately here. </p>\n\n<p>Overall - nice markup. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T18:33:52.277", "Id": "3399", "ParentId": "3335", "Score": "1" } } ]
{ "AcceptedAnswerId": "3345", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T18:53:21.053", "Id": "3335", "Score": "6", "Tags": [ "html5" ], "Title": "First HTML5 site for a university computer lab" }
3335
<p>Due to the fact that Entity does not support Enums, I am converting them to strings, string lists, and back again.</p> <p>The reason is two fold: type-safety, and consistency in the database.</p> <p>Now, I have a bunch of these, but I will use Credit Cards as an example:</p> <pre><code> public enum CreditCardName { VISA, Master_Card, Discover, American_Express } </code></pre> <p>Originally, I decided on writing the same method for them, over and over again:</p> <pre><code> public static List&lt;string&gt; GetCreditCardTypes() { var list = Enum.GetNames(typeof(CreditCardName)); return list.Select(n =&gt; n.Replace("_", " ")).ToList(); } </code></pre> <p>Then it occurred to me that I could make one private method to do this:</p> <pre><code> public static List&lt;string&gt; GetCreditCardTypes() { return EnumToList(typeof(CreditCardName)); } private static List&lt;string&gt; EnumToList(Type type) { var list = Enum.GetNames(type); return list.Select(n =&gt; n.Replace("_", " ")).ToList(); } </code></pre> <p>Now I'm also doing something similar in reverse, but will skip the code. The question I have is if this is a good way to go about this? I know there are other workarounds for Entity's lack of enum support, but they are a bit cumbersome for my simple needs. I have never used Types in this way, so I just wanted to check that this is how Type/typeof are intended to be used, and that this will not cause unforeseen runtime issues.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-08T17:52:10.053", "Id": "107329", "Score": "0", "body": "Are you talking about Entity Framework when talking about Entity?" } ]
[ { "body": "<p>I solved a similar issue by inventing a DisplayName attribute, so I can define my enums like this:</p>\n\n<pre><code>public enum CreditCardName\n{\n [DisplayName(\"VISA\")]\n Visa,\n\n [DisplayName(\"MasterCard\")]\n MasterCard,\n\n [DisplayName(\"Discover\")]\n Discover,\n\n [DisplayName(\"American Express\")]\n AmericanExpress\n}\n</code></pre>\n\n<p>This has a number of advantages. For one, apps like Resharper will stop complaining about your naming scheme. Also, your string doesn't have to actually correspond to an English name, it could correspond to an entry in a translation strings file or something like that.</p>\n\n<p>Source for DisplayName:</p>\n\n<pre><code>[AttributeUsage(AttributeTargets.Field)]\npublic class DisplayName : Attribute\n{\n public string Title { get; private set; }\n\n public DisplayName(string title)\n {\n this.Title = title;\n }\n}\n</code></pre>\n\n<p>Source for the method to retrieve your DisplayName objects</p>\n\n<pre><code> IEnumerable&lt;DisplayName&gt; attributes = from attribute in typeof(CreditCardName).GetCustomAttributes(true)\n let displayName = attribute as DisplayName\n where displayName != null\n select displayName;\n</code></pre>\n\n<p>You can roll this into a more complete generic method too:</p>\n\n<pre><code>public string[] GetNames&lt;TEnum&gt;()\n{\n return (from attribute in typeof(CreditCardName).GetCustomAttributes(true)\n let displayName = attribute as DisplayName\n where displayName != null\n select displayName.Title).ToArray();\n}\n</code></pre>\n\n<p>Unfortuately, I there isn't a way you can enforce that TEnum is an enum at compile time, but you could make it throw an exception instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-09T07:22:45.013", "Id": "5026", "Score": "0", "body": "Wow, this is a **much** better solution! It solves issues I didn't even mention (you even caught the VISA/Visa one). But I had few other naming issues where underscores weren't cutting it. Thank you!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-28T11:32:37.367", "Id": "9850", "Score": "1", "body": "Another issue that is solved by Rashkolnikov's solution is what happens if you ever decide to start making use of an obfuscator." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T14:57:26.313", "Id": "3350", "ParentId": "3337", "Score": "9" } } ]
{ "AcceptedAnswerId": "3350", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T05:00:35.037", "Id": "3337", "Score": "6", "Tags": [ "c#", "enum" ], "Title": "Is this a good/safe way to convert enums?" }
3337
<p>The program finds the largest palindrome made from the product of two <em>n</em>-digit numbers, where <em>n</em> is specified by the user.</p> <p>The code included works, however, when the user enters 5 or greater, the program runs very slowly. I believe it is \$O(n^2)\$ (feel free to correct that estimate if needed).</p> <p>I'd like feedback/reviews regarding any "best practices" I should follow, along with performance and readability.</p> <p><strong>Class:</strong></p> <pre><code>#include &lt;math.h&gt; class FindPalindrome { private: //multiplicand 1 int number_one; //multiplicand 2 int number_two; //holds current product int current; //copy of current product copy so as the current var values is not manipulated as its original will be needed int copy; //holds most recently discovered palindrome int palindrome; //holds greatest palindrome discovered int greatest; //as determined by number of digits for operand int upper_limit; int lower_limit; public: //Constructor FindPalindrome(int digits_requiered); //Accessors int Greatest_Palindrome_Found(); //Mutators void Product_Generator(); void Determine_if_Palindrome(); }; FindPalindrome::FindPalindrome(int digits_requiered){ upper_limit = pow(10, digits_requiered) - 1; lower_limit = pow(10, digits_requiered -1); number_two = number_one = upper_limit; current = 0; copy = 0; palindrome = 0; greatest = 0; } int FindPalindrome::Greatest_Palindrome_Found(){ return greatest; } void FindPalindrome::Product_Generator(){ while (number_one &gt;= lower_limit) { number_two = upper_limit; while (number_two &gt;= lower_limit) { if(number_one &gt;= number_two) { //test initial numbers to see if they generate palindrome Determine_if_Palindrome(); } number_two = number_two - 1; } number_one = number_one - 1; } } void FindPalindrome:: Determine_if_Palindrome(){ //used in determining length of array and storing product into array int array_length = 0; //copy of array length so that original length value is still available int array_length_cpy = 0; //vars for checking for palindrome properties int head = 0; int tail = 0; int retrieve_one = 0; int retrieve_two = 0; current = number_one * number_two; copy = current; //get length of number and create array to hold number while (copy != 0) { copy /= 10; ++array_length; } int store[array_length]; //restore to products value for extraction manipulations copy = current; array_length_cpy = array_length; //extract digits from number and poopulate array for (int i = array_length_cpy; i&gt;0; --i) { store[i-1] = copy%10; copy/=10; --array_length_cpy; } //Compare last and first digits then move "inwards" comparing the digits tail = array_length -1; retrieve_one = store[head]; retrieve_two = store[tail]; if (retrieve_one == retrieve_two) { for (int i = (array_length/2); i &gt; 0; --i) { tail = tail -1; head = head + 1; retrieve_one = store[head]; retrieve_two = store[tail]; if (retrieve_one != retrieve_two) { return; } } palindrome = current; //it is a palindrome //test for if it is the biggest one found yet if (current &gt; greatest) { greatest = current; } } } </code></pre> <p><strong><code>main()</code></strong></p> <pre><code>#include &lt;sys/time.h&gt; #include &lt;iostream&gt; #include "FindPalindrome.h" using namespace std; int main () { int digits_specified = 0; cout &lt;&lt; "Please enter the number of digits: "; cin&gt;&gt;digits_specified; cout &lt;&lt; "\n"; //For testing purposes to print out all palindromes generated /* std::cout &lt;&lt; "Operand 1" &lt;&lt;"\t\t"; std::cout &lt;&lt; "Operand 2" &lt;&lt;"\t\t"; std::cout &lt;&lt; "Product" &lt;&lt;"\t\t\n\n"; */ FindPalindrome trial1(digits_specified); //find palindrome and record the time it took to do this struct timeval start, end; long mtime, seconds, useconds; gettimeofday(&amp;start, NULL); //start actual calculation for palindrome trial1.Product_Generator(); gettimeofday(&amp;end, NULL); seconds = end.tv_sec - start.tv_sec; useconds = end.tv_usec - start.tv_usec; mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5; cout &lt;&lt; "\n"; printf("Elapsed time: %ld milliseconds\n", mtime); cout &lt;&lt; "\n"; cout&lt;&lt;endl&lt;&lt; "Largest palimdromic number: "&lt;&lt; trial1.Greatest_Palindrome_Found()&lt;&lt;endl; cout &lt;&lt; "\n"; return 0; } </code></pre>
[]
[ { "body": "<p>First, as a general observation, you've made created essentially all your variables as belonging to the <code>FindPalindrome</code> object. IMO, this is a mistake. Each variable should have the minimum scope necessary to do its job. Any variable that's only used inside a particular function, for example, should be local to that function, not the class. A variable that's used only in a specific loop should be local to that loop, etc.</p>\n\n<p>After that, I'd take a look at <code>DetermineIfPalindrome</code>. First, I'd change it to something like:</p>\n\n<pre><code>bool is_palindrome(int number);\n</code></pre>\n\n<p>It should be just a pure function that tells you whether its input is palindromic or not. You then use that to decide what (if anything) to do with a particular number.</p>\n\n<p>As far as how that's implemented, I'd start by observing that the length of a product is (at most) the sum of the lengths of the inputs (e.g., the product of 2 5-digit numbers will be no more than 10 digits). That means you can pre-allocate space for the converted number instead of doing most of the work for a conversion to find the size, then allocating space, then doing the conversion. This should roughly double the speed of that part of the code.</p>\n\n<p>Looking at the next step up, <code>Product_Generator</code> uses while loops where it seems to be that <code>for</code> loops would make more sense. It also seems to generate (and then ignores) some numbers you apparently don't care about. It appears that it should be something like this:</p>\n\n<pre><code>int Product_Generator() { \n int greatest = 0;\n for (int i=upper; i&gt;=lower; --i)\n for (int j=upper; j&gt;=i; --j) {\n int product = i * j;\n if (product &gt; largest &amp;&amp; is_palindromic(product))\n greatest = product;\n }\n return greatest;\n}\n</code></pre>\n\n<p>Looking at the overall design of the class, I'd note two things: first, you've made essentially everything <code>public</code>, where it should all (or nearly all) be <code>private</code>. Second, its name signifies an action (a verb) which indicates that it should probably act like a function. Ultimately, it takes a single input (number of digits) and produces a single output (the desired palindrome).</p>\n\n<p>As such, the class definition should look something like:</p>\n\n<pre><code>class FindPalindrome { \n int lower, upper;\n\n bool is_palindrome(int);\npublic:\n FindPalindrome(int digits) : \n lower(pow(10, digits_required -1)),\n upper(pow(10, digits_required)-1))\n {}\n\n int operator()() {\n // This is a renamed version of what's shown above as Product_Generator\n }\n};\n</code></pre>\n\n<p>The other thing to consider would be whether it's worth going at this in the other direction -- start by generating palindromes, and factor each palindrome to see if we can find factors with the right number of digits. Factoring large numbers gets pretty slow, but as factoring goes, we're dealing with fairly small numbers here (for factoring, \"large\" generally means something like 100 digits or more). I'm not sure that would end up faster, but it might. It would also be fairly easy to generate the palindromes in strictly decreasing order, so the first one we found with factors the right size would be the final answer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T18:28:09.200", "Id": "5100", "Score": "0", "body": "Hi thanks for the insightful answer, the local variable tip was especially helpful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-23T22:23:43.827", "Id": "186144", "Score": "0", "body": "Excellent tip to start with the palindromes. For example, for six digit numbers there are 405 billion possible products, but only 900,000 twelve digit palindromes. In addition, you can check these palindromes in descending order, so when you found the first one that is the product of two n digit numbers you are done." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-23T22:47:43.557", "Id": "186147", "Score": "1", "body": "Using that tip, you can easily find 9 = 3 * 3, 9009 = 99 * 91, 906609 = 993 * 913, 99000099 = 9999 * 9901, 9966006699 = 99979 * 99681, 999000000999 = 999999 * 999001, 99956644665999 = 9998017 * 9997647, 9999000000009999 = 99999999 * 99990001, 999900665566009999 = 999980347 * 999920317, and for ten digits the largest product is likely 999990000000099999 = 9999999999 * 9999900001." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T22:02:41.560", "Id": "3357", "ParentId": "3338", "Score": "11" } }, { "body": "<p><strong>1) Style guide</strong></p>\n\n<p>I would like to start off with a few style tipps. Take these with a large grain of salt as it is subjective. </p>\n\n<p>1) C++ functions are usually lowercase while classes are uppercase.</p>\n\n<p>2) C++ class members usually have some sort of special identifiers, such as a trailing underscore or the prefix \"m_\".</p>\n\n<p>That't it for the style guide, let's talk class design :) </p>\n\n<p><strong>2) Finding the Palindrome</strong></p>\n\n<p>You called your class FindPalindrome which is nice, but a little confusing. I like to name classes after their behaviour, e.g. PalindromeFinder. Also, you used FindPalindrome in the singular, but do you want to constrain each instance to only one palindrome? Your design suggests not.</p>\n\n<p>Secondly, you aren't using the STL to your advantage. Let's think about the nature of palindromes for a bit. Excluding strings, a palindrome is any number that can be read the same way front to back, e.g. </p>\n\n<p><code>reverse(10011001) = 10011001</code>.</p>\n\n<p>Your determine_palindrome function seems to suggest that you are breaking the array into digits and then comparing them one-by-one. Great, you're on the right track; now let the STL help you.</p>\n\n<pre><code>std::vector&lt;int&gt; digits = Utility::toArray&lt;int&gt;(number);\nstd::vector&lt;int&gt; reverse = digits;\nstd::reverse(reverse.begin(), reverse.end());\n</code></pre>\n\n<p>Instead of an array, I have used a vector so I don't need to burden myself with array count or ugly functions that take care of that for me. It also has a copy-constructor that lets me define a second array with exactly the same digits as the first one. The third line reverses that sequence of digits.</p>\n\n<p>Now all that's left to do is to check if reverse and digit are the same digit for digit:</p>\n\n<pre><code>for (int i(0); i &lt; digits.size(); ++i)\n if (digits[i] != reverse[i])\n return false;\nreturn true;\n</code></pre>\n\n<p>This is my entire <code>bool isPalindrome(int number)</code> function. Nothing else was needed, I just had to use the STL to my advantage. If you haven't read up on the <code>&lt;algorithm&gt;</code> header yet I strongly suggest you do :) </p>\n\n<p>As for runtime performance, this function performs in O(n) (linear) time.</p>\n\n<p><strong>3) Responsibilities</strong></p>\n\n<p>This is an OOP principle. Always try to give each class and function exactly one responsibility. </p>\n\n<p>Did you see the function <code>Utility::toArray&lt;int&gt;(number)</code> in my section on finding the palindrome? You had it inside your function. My question to you is: is it the responsibility of a function, that determines whether or not a number is a palindrome, to also break a number into digits? </p>\n\n<p>The answer is no. The <code>isPalindrome</code> functions finds a palindrome, that's it. You can refactor the code that splits the number into digits into its own function like I have. Templatize it and there you go, you can reuse it for a whole bunch of other numbers (well, integral numbers...).</p>\n\n<p><strong>4) Const-correctness</strong></p>\n\n<p>This is a big one. Make everything const that can be const. Why? Safety. Why else? Other programmers might rely on guarantees given by the functions they are calling.</p>\n\n<p>An easy rule for const-correctness is: if the function isn't modifying any arguments, make it const. Your function <code>greatest_palindrome</code> only returns the greatest palindrome and nothing else. Make it const.</p>\n\n<p>As Jerry pointed out, all of your needed variables are declared in the class itself, not the functions. If you changed that, you could possibly make some other functions const as well. Always strive for this!</p>\n\n<p><strong>5) Know your functions</strong></p>\n\n<p>Look at the overloads for pow (from cplusplus.com):</p>\n\n<pre><code>double pow ( double base, double exponent );\nlong double pow ( long double base, long double exponent );\nfloat pow ( float base, float exponent );\ndouble pow ( double base, int exponent );\nlong double pow ( long double base, int exponent );\n</code></pre>\n\n<p>They all use doubles and return doubles. Doubles are slow, you are only working with integral values. Do the multiplication yourself. This also applies to the <code>&lt;algorithm&gt;</code> library. Look around! Valuable stuff.</p>\n\n<hr>\n\n<p>I think this has gone on long enough. Along with the suggestions from Jerry, your code should work faster now. Here is my implementation (without the function for upper and lower limits. Instead it just takes numbers from the command line.).</p>\n\n<pre><code>#include &lt;vector&gt;\n#include &lt;algorithm&gt;\n\nnamespace Utility\n{\n // See boost::noncopyable for details.\n class Uncopyable\n {\n protected:\n Uncopyable() {}\n virtual ~Uncopyable() {}\n\n private:\n Uncopyable(Uncopyable const&amp;);\n Uncopyable&amp; operator=(Uncopyable const&amp;);\n };\n\n // We can apply template specialization to handle more than just integral data types.\n template &lt;typename T&gt;\n std::vector&lt;T&gt; toArray(T num)\n {\n std::vector&lt;T&gt; ret;\n\n while (num)\n {\n ret.push_back(num % 10);\n num /= 10;\n }\n\n return ret;\n }\n}\n\n// Alternate to Uncopyable is boost::noncopyable.\nclass PalindromeFinder : public Utility::Uncopyable\n{\npublic:\n PalindromeFinder();\n\n void feed(int number);\n\n int greatestPalindrome() const;\n\n void operator()(int number);\n\nprivate:\n bool isPalindrome(int number) const;\n\nprivate:\n int greatestPalindrome_;\n};\n\n// Make sure our members are not in an undefined state.\nPalindromeFinder::PalindromeFinder()\n : greatestPalindrome_(0)\n{ }\n\n// Replace me with your upper- and lower-limit implementation :3\nvoid PalindromeFinder::feed(int number)\n{\n if (isPalindrome(number) &amp;&amp; number &gt; greatestPalindrome_)\n greatestPalindrome_ = number;\n}\n\nbool PalindromeFinder::isPalindrome(int number) const\n{\n std::vector&lt;int&gt; digits = Utility::toArray&lt;int&gt;(number);\n std::vector&lt;int&gt; reverse = digits;\n std::reverse(reverse.begin(), reverse.end());\n\n // We could optimize this further by only going through half the vector's elements.\n for (int i(0); i &lt; digits.size(); ++i)\n if (digits[i] != reverse[i])\n return false;\n\n return true;\n}\n\n// No numbers fed? Then our palindrome is 0.\nint PalindromeFinder::greatestPalindrome() const\n{\n return greatestPalindrome_;\n}\n\nvoid PalindromeFinder::operator()(int number)\n{\n feed(number);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T16:54:05.890", "Id": "3426", "ParentId": "3338", "Score": "6" } } ]
{ "AcceptedAnswerId": "3357", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T06:25:53.873", "Id": "3338", "Score": "6", "Tags": [ "c++", "performance", "palindrome" ], "Title": "Finding the largest palindrome from the product of two n-digit numbers" }
3338
<p>My BLL's function is like:</p> <pre><code> public Categorymaster GetByPrimaryKey(CategorymasterKeys keys) { return _dataObject.SelectByPrimaryKey(keys); } </code></pre> <p>// above funciton is calling function written below</p> <pre><code> public Categorymaster SelectByPrimaryKey(CategorymasterKeys keys) { SqlCommand sqlCommand = new SqlCommand(); sqlCommand.CommandText = "dbo.[categorymaster_SelectByPrimaryKey]"; sqlCommand.CommandType = CommandType.StoredProcedure; // Use connection object of base class sqlCommand.Connection = MainConnection; try { sqlCommand.Parameters.Add(new SqlParameter("@category_id", SqlDbType.Int, 4, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Proposed, keys.Category_id)); if (MainConnection.State == ConnectionState.Closed) { MainConnection.Open(); } IDataReader dataReader = sqlCommand.ExecuteReader(); if (dataReader.Read()) { Categorymaster businessObject = new Categorymaster(); PopulateBusinessObjectFromReader(businessObject, dataReader); return businessObject; } else { return null; } } catch (Exception ex) { throw new Exception("Categorymaster::SelectByPrimaryKey::Error occured.", ex); } finally { MainConnection.Close(); sqlCommand.Dispose(); } } </code></pre> <p>In my web page i have written below code:</p> <p>BusinessLayer.Product_category_transFactory pctf = new Product_category_transFactory();</p> <pre><code> Categorymaster cm = cmf.GetByPrimaryKey(new CategorymasterKeys(catid));//throws exception when it returns null </code></pre> <p>Now the issue i am facing is that when there is no result for the query then it returns null and throw exception.</p> <p>The same model is used in whole application. Please tell me what all minimum and optimum changes should i do handle null (when no result).</p> <p>NOTE: i am using .net framework 4.0</p> <p>Thanks</p>
[]
[ { "body": "<p>What is the exception you are getting? What do you mean returns null and throws Exception?</p>\n\n<p>From putting this code into a class and executing a test on it, I get back an object or null when the record exists or does not respectively.</p>\n\n<p>If you're getting an exception from the above call with cmf.GetByPrimaryKey, is the exception in the call to the constructor of CategorymasterKeys?</p>\n\n<p>Here is the test I used:</p>\n\n<pre><code>[TestMethod()]\npublic void TestWhenPassingAnIdNotInTheResultSetToSelectByPrimaryKey_ThenNullIsTheResult()\n{\n var target = new Class2();\n CategorymasterKeys keys = new CategorymasterKeys { Category_id = 0 };\n Categorymaster actual = target.SelectByPrimaryKey(keys);\n Assert.IsNull(actual);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-12T12:16:26.977", "Id": "4057", "ParentId": "3339", "Score": "4" } }, { "body": "<p>You could use a nullable type for this. Then you can flag if it is actually null or just an empty result set. <a href=\"http://msdn.microsoft.com/en-us/library/1t3y8s4s%28v=vs.80%29.aspx\" rel=\"nofollow\">MSDN on nullable types</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-16T09:40:58.033", "Id": "4141", "ParentId": "3339", "Score": "1" } } ]
{ "AcceptedAnswerId": "4057", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T06:56:58.453", "Id": "3339", "Score": "3", "Tags": [ "c#", "asp.net" ], "Title": "Handling Null Result with class object" }
3339
<p>The task is to write a function <code>findFraction maxDen number</code> to find a short but good rational approximation to a decimal representation of a number — <a href="http://www.topcoder.com/stat?c=problem_statement&amp;pm=11073&amp;rd=14236" rel="nofollow">problem statement on TopCoder</a>:</p> <blockquote> <p>Given a fraction F = A/B, where 0 &lt;= A &lt; B, its quality of approximation with respect to number is calculated as follows:</p> <ul> <li>Let S be the decimal fraction (infinite or finite) representation of F.</li> <li>Let N be the number of digits after the decimal point in number. If number has trailing zeros, all of them are considered to be significant and are counted towards N.</li> <li>If S is infinite or the number of digits after the decimal point in S is greater than N, only consider the first N decimals after the decimal point in S. Truncate the rest of the digits without performing any kind of rounding.</li> <li>If the number of digits after the decimal point in S is less than N, append trailing zeroes to the right side until there are exactly N digits after the decimal point.</li> <li>The quality of approximation is the number of digits in the longest common prefix of S and number. The longest common prefix of two numbers is the longest string which is a prefix of the decimal representations of both numbers with no extra leading zeroes. For example, "3.14" is the longest common prefix of 3.1428 and 3.1415.</li> </ul> <p>[…] You are only allowed to use fractions where the denominator is less than or equal to <code>maxDen</code>. Find an approximation F = A/B of number such that 1 &lt;= B &lt;= <code>maxDen</code>, 0 &lt;= A &lt; B, and the quality of approximation is maximized. Return a String formatted "A/B has X exact digits" (quotes for clarity) where A/B is the approximation you have found and X is its quality. If there are several such approximations, choose the one with the smallest denominator among all of them. If there is still a tie, choose the one among those with the smallest numerator.</p> </blockquote> <pre><code>import Data.Char import Data.List import Data.Maybe showResult :: (Int, Int, Int) -&gt; String showResult (a, b, x) = show a ++ "/" ++ show b ++ " has " ++ show x ++ " exact digits" compareDigits :: [Int] -&gt; [Int] -&gt; Ordering compareDigits xs [] = EQ compareDigits (x:xs) (y:ys) = case compare x y of EQ -&gt; compareDigits xs ys order -&gt; order toDigit :: Char -&gt; Int toDigit c = ord c - ord '0' preciseDivision :: Int -&gt; Int -&gt; [Int] preciseDivision a b = div a' b : preciseDivision (mod a' b) b where a' = 10 * a estimate :: [Int] -&gt; Double estimate = sum . zipWith (flip (/)) (iterate (*10) 10) . map fromIntegral bestNumerator :: [Int] -&gt; Double -&gt; Int -&gt; Maybe Int bestNumerator ds p b = case find atLeast . map (pair ds b) $ [pivot .. ] of Just (a, EQ) -&gt; Just a otherwise -&gt; Nothing where pivot = truncate $ p * fromIntegral b pair ds b a = (a, compareDigits (preciseDivision a b) ds) atLeast (a, order) = order /= LT bestResult :: Int -&gt; [Int] -&gt; Maybe (Int, Int, Int) bestResult n ds = fromMaybe Nothing . find isJust . map (toResult ds $ estimate ds) $ [1..n] where toResult ds p b = case bestNumerator ds p b of Just a -&gt; Just (a, b, 1 + length ds) Nothing -&gt; Nothing findFraction' :: Int -&gt; [Int] -&gt; (Int, Int, Int) findFraction' n = fromJust . last . takeWhile isJust . map (bestResult n) . inits findFraction :: Int -&gt; String -&gt; String findFraction n = showResult . findFraction' n . map toDigit . tail . tail </code></pre> <p>I'm most worried by <code>bestNumerator</code> and <code>bestResult</code> here. I'm using a <code>find</code> idiom that I invented myself, and I wonder if cleaner, more Haskelly alternatives exist.</p>
[]
[ { "body": "<p>Hmmm, not much ideas, only syntax:</p>\n\n<pre><code>showResult :: (Int, Int, Int) -&gt; String\nshowResult (a, b, x) = concat [show a, \"/\", show b, \" has \", show x, \" exact digits\"]\n\n\npreciseDivision :: Int -&gt; Int -&gt; [Int]\npreciseDivision a b = let (d,r) = divMod (10*a) b in d : preciseDivision r b \n\n\n...where toResult ds p b = fmap (\\a -&gt; (a, b, 1 + length ds)) $ bestNumerator ds p b\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T07:05:11.103", "Id": "5295", "ParentId": "3340", "Score": "5" } }, { "body": "<p><code>Ordering</code> is an instance of <code>Monoid</code>.</p>\n\n<pre><code>import Data.Monoid\n\ncompareDigits :: [Int] -&gt; [Int] -&gt; Ordering\ncompareDigits _ [] = EQ\ncompareDigits (x:xs) (y:ys) = compare x y `mappend` compareDigits xs ys\n</code></pre>\n\n<p><code>toDigit</code> is not exactly necessary; <code>Data.Char</code> has <code>digitToInt</code>, which does about the same thing. The difference is that it supports hex numbers and will fail if the character is not a valid hex digit, whereas your function assumes a decimal digit, is more efficient, but will silently give incorrect results for non-digits.</p>\n\n<p>Whether you replace it or not, though, <code>toDigit</code> is backwards, since the function takes a digit and gives you the numeric value.</p>\n\n<p>In <code>bestNumerator</code>'s <code>pair</code>, you shadow the <code>ds</code> and <code>b</code> parameters. That confuses me. In <code>bestResult</code>, <code>toResult</code> also has a shadowing <code>ds</code>.</p>\n\n<p>In general, I think many of your parameter names are too short. I realize that this is common in Haskell, but I still find it abhorrent for things that aren't abstract. For example, <code>n</code> instead of <code>maxDenominator</code> (or <code>maxDen</code>, as in the problem statement, but \"den\" is an obscure abbreviation).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T19:01:45.187", "Id": "40768", "ParentId": "3340", "Score": "1" } } ]
{ "AcceptedAnswerId": "5295", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T07:46:34.993", "Id": "3340", "Score": "5", "Tags": [ "algorithm", "haskell", "programming-challenge", "rational-numbers" ], "Title": "BestApproximationDiv2 problem in Haskell" }
3340
<p>I feel like repeating myself but i don't know how to refactor this. Linq condition is the same but property to compare is different (BookingDate ,CheckInDate ,CheckOutDate) </p> <pre><code> protected void FilterByDateRange(ref IEnumerable&lt;ViewBooking&gt; pObjListBooking) { DateTime startDate; DateTime endDate; startDate = DateTime.ParseExact(txtStartDate.Text, "d", System.Globalization.CultureInfo.CurrentCulture); endDate = DateTime.ParseExact(txtEndDate.Text, "d", System.Globalization.CultureInfo.CurrentCulture).AddDays(1); switch(ddlOrderBy.Text) { case "Booking Date": pObjListBooking = pObjListBooking.Where(item =&gt; item.BookingDate &gt;= startDate &amp;&amp; item.BookingDate &lt; endDate); break; case "Check In Date": pObjListBooking = pObjListBooking.Where(item =&gt; item.CheckInDate &gt;= startDate &amp;&amp; item.CheckInDate &lt; endDate); break; case "Check Out Date": pObjListBooking = pObjListBooking.Where(item =&gt; item.CheckOutDate &gt;= startDate &amp;&amp; item.CheckOutDate &lt; endDate); break; } } </code></pre>
[]
[ { "body": "<p>You could do something like this, but I don't know, whether it's a good idea:</p>\n\n<pre><code>Func&lt;ViewBooking,DateTime&gt; getDate = null;\nswitch(...)\n{\n case ...:\n getDate = (ViewBooking item) =&gt; item.BookingDate;\n break;\n}\n\npObjListBooking = pObjListBooking.Where(item =&gt; getDate(item) &gt;= startDate &amp;&amp; getDate(item) &lt; endDate);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T11:06:13.187", "Id": "3343", "ParentId": "3342", "Score": "4" } } ]
{ "AcceptedAnswerId": "3343", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T08:49:17.093", "Id": "3342", "Score": "2", "Tags": [ "c#", "linq" ], "Title": "Property to compare in Linq is different by criteria." }
3342
<p>Normally I could just declare the 'email' variable as the base class for both of EmailInbound &amp; EmailOutbound, then cast-up to the inherited class. However, I don't think when defining EF codefirst classes you can use inherited classes, only POCOs. I could be wrong. Hence I've used the dynamic keyword. Could I use Object() instead? Some direction appreciated here...</p> <pre><code> if (source.ActionTypeId == (int)ActionTypes.EmailInbound || source.ActionTypeId == (int)ActionTypes.EmailOutbound) { dynamic email; if ( source.ActionTypeId == (int)ActionTypes.EmailInbound ) { email = source.EmailMessage.EmailInbound; } else { email = source.EmailMessage.EmailOutbound; } return new ActionModel { ActionTypeId = (ActionTypes)source.ActionTypeId, Content = email.Body, Created = email.DateSent, GravatarUrl = HtmlHelperExtensions.getGravatarUrl(email.FromAddress, 25), Subject = email.Subject, User = Mapper.Map&lt;User, UserModel&gt;(source.EmailMessage.User), EmailReplyTo = email.From, ShowReplyButton = true, ThreadUid = source.ThreadUid, IsReply = source.IsReply }; } ... </code></pre>
[]
[ { "body": "<p>I think it is quite defendable to use <code>dynamic</code> here. I'm not too familiar with EF, but it could very well be that you can't make the objects type-compatible. </p>\n\n<p>Even if you could, I would not do it if it was only to make this piece of code work. </p>\n\n<p>Declaring <code>email</code> as <code>object</code> will not help in any way. </p>\n\n<p>The only alternative I can think of is to have two code paths for both cases: </p>\n\n<pre><code> if ( source.ActionTypeId == (int)ActionTypes.EmailInbound )\n {\n email = source.EmailMessage.EmailInbound;\n return new ActionModel\n {\n ActionTypeId = (ActionTypes)source.ActionTypeId,\n Content = email.Body,\n Created = email.DateSent,\n GravatarUrl = HtmlHelperExtensions.getGravatarUrl(email.FromAddress, 25),\n Subject = email.Subject,\n User = Mapper.Map&lt;User, UserModel&gt;(source.EmailMessage.User),\n EmailReplyTo = email.From,\n ShowReplyButton = true,\n ThreadUid = source.ThreadUid,\n IsReply = source.IsReply\n };\n }\n else\n {\n email = source.EmailMessage.EmailOutbound;\n return new ActionModel\n {\n ActionTypeId = (ActionTypes)source.ActionTypeId,\n Content = email.Body,\n Created = email.DateSent,\n GravatarUrl = HtmlHelperExtensions.getGravatarUrl(email.FromAddress, 25),\n Subject = email.Subject,\n User = Mapper.Map&lt;User, UserModel&gt;(source.EmailMessage.User),\n EmailReplyTo = email.From,\n ShowReplyButton = true,\n ThreadUid = source.ThreadUid,\n IsReply = source.IsReply\n };\n }\n</code></pre>\n\n<p>But I think the solution with <code>dynamic</code> is better. You can't catch all errors at compile time. I would reccomend a unit test (two really) so that if anybody changes the database schema, this is detected at build time. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T15:42:24.650", "Id": "5503", "Score": "0", "body": "Sorry didn't get back to you sooner & thanks for the answer.\nI was also thinking of using a IEmailBase interface which both classes implement. Then I can set the interface to point to the correct object. Is this overhead?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T19:41:34.667", "Id": "3413", "ParentId": "3348", "Score": "3" } } ]
{ "AcceptedAnswerId": "3413", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T14:27:04.920", "Id": "3348", "Score": "4", "Tags": [ "c#", "entity-framework" ], "Title": "Dynamic variable - is that best way to dynamically assign?" }
3348
<p>I am developing some software that uses a pretty ancient low-level TCP/IP protocol from (I think) the eighties. I can send messages to the server very reliably, but I am a little unsure about receiving them. I cannot predict when the server will send me a message, so I have this method in an infinite loop. GetNextMessage() blocks the thread until it receives a message, whereupon the message is acted upon, and the loop repeats.</p> <p>Messages are sent at a rate of about maybe 5 or 6 a minute, and I can process them in less than a quarter of a second, so I'm not currently spinning off a new thread when I receive them.</p> <p>This code fragment contains all the relevant symbols and the logic that I am unsure of:</p> <pre><code> /// this is filled earlier in the program private Socket _socket; private const int BufferSize = 4096; /// &lt;summary&gt; /// This byte (hex 02) indicates the start of the message. /// &lt;/summary&gt; private const byte RecordStart = 2; /// &lt;summary&gt; /// This byte (hex 03) indicates the end of the message. /// &lt;/summary&gt; private const byte RecordEnd = 3; private string GetNextMessage() { byte[] bytesReceived = new byte[BufferSize]; // ReSharper disable PossibleNullReferenceException _socket.Receive(bytesReceived); // ReSharper restore PossibleNullReferenceException if (_socket.Poll(1, SelectMode.SelectRead)) { throw new SocketException((int)SocketError.ConnectionReset); } IEnumerable&lt;byte&gt; bytes = bytesReceived .Where(character =&gt; character != RecordStart) .TakeWhile(character =&gt; character != RecordEnd); return Encoding.ASCII.GetString(bytes.ToArray()); } </code></pre> <p>My concerns:</p> <ol> <li>I am not sure if _socket.Poll() is the correct way to determine if the socket has gone away. It most certainly works and is very necessary, but I'm sure I should be doing something else.</li> <li>I once performed an operation that sent three messages immediately after each other, but I only appeared to receive two of them. It is possible that there is a bug in the product I am developing for (seems likely), but I am worried that the method I have chosen is somehow causing messages to be discarded. </li> </ol>
[]
[ { "body": "<p>A: 1. Here's a better way to check if a socket has disconnected.</p>\n\n<pre><code> bool SocketConnected(Socket s)\n {\n bool part1 = s.Poll(1000, SelectMode.SelectRead);\n bool part2 = (s.Available == 0);\n if (part1 &amp; part2)\n return false;\n else\n return true;\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T17:57:02.983", "Id": "3398", "ParentId": "3349", "Score": "1" } }, { "body": "<p>One thing I do with reading from sockets is separate receiving of the data from what the data contains.</p>\n\n<p>Meaning, you may get your information in progressive chunks..... so receive a chunk of data, then see if you have a complete \"Message\". If not, wait for the next chunk of data. When you have your full \"Message\" then you can pass that on to whatever wants it.</p>\n\n<p>In fact what I have done is abstract the idea of a streaming connection so I can interchange serial ports / tcp sockets / and any other streaming type connection. Have something that receives from a connection, and then do interpreting.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T02:56:48.670", "Id": "3403", "ParentId": "3349", "Score": "3" } } ]
{ "AcceptedAnswerId": "3403", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T14:46:55.137", "Id": "3349", "Score": "3", "Tags": [ "c#" ], "Title": "Is this a good way to receive a message from a server?" }
3349
<pre><code>public partial class CreateAdmin : System.Web.UI.Page { #region Events. protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { LoadOrganizations(); } } // Save Admin and Organization Admin in db. protected void btnSave_Click(object sender, ImageClickEventArgs e) { try { // Save user info in aspnet_Users and aspnet_Membership MembershipUser user = SaveMemberShipUser(); // If user is saved successfully. if (user != null) { using (TransactionScope transaction = new TransactionScope()) { using (var context = new RideshareEntities()) { Save(context, (Guid)user.ProviderUserKey); // Commit transaction and save all changes in db. transaction.Complete(); context.AcceptAllChanges(); } } } } catch (Exception ex) { if (ex.Message.Equals("The username is already in use.")) { lblMessage.Text = "The username(Email) is alrady in use."; return; } // TODO: Remove throw and handle exception(Log error in file) throw; } } #endregion #region Class Methods. // Load organizations in CheckboxList private void LoadOrganizations() { chklstOrganizations.DataTextField = "Name"; chklstOrganizations.DataValueField = "OrganizationId"; // More than 2 will break formatting if user add long organization name chklstOrganizations.RepeatColumns = 2; chklstOrganizations.DataSource = RidersService.GetOrganizations(); chklstOrganizations.DataBind(); } // Save user info in aspnet_Users and aspnet_Membership private MembershipUser SaveMemberShipUser() { MembershipUser user = null; //Adds a new user. user = Membership.CreateUser(txtEmail.Text, txtPassword.Text, txtEmail.Text); user.IsApproved = true; user.Comment = Utility.RandomString(15); Membership.UpdateUser(user); return user; } // Save Admin and Organizations. private void Save(RideshareEntities context, Guid userId) { // Get admin object with data. Admin admin = GetNewAdminWithData(); // Assign userId to admin. admin.UserId = userId; // Add in context and save. context.Admins.AddObject(admin); context.SaveChanges(); // Save selected organizations. SaveOrganizations(context, admin.AdminId); } // Save Organizations. private void SaveOrganizations(RideshareEntities context, int adminId) { // Loop through each items in checked list bxo. foreach (ListItem item in chklstOrganizations.Items) { if (item.Selected) { int organizationid = 0; // If item successfully parsed in int then save data in OrganizationAdmin table. if (int.TryParse(item.Value, out organizationid)) { OrganizationAdmin organizationAdmin = new OrganizationAdmin(); organizationAdmin.AdminId = adminId; organizationAdmin.OrganizationId = organizationid; context.OrganizationAdmins.AddObject(organizationAdmin); context.SaveChanges(); } } } } // Get New Admin object with data populated.. private Admin GetNewAdminWithData() { Admin admin = new Admin(); admin.Email = txtEmail.Text.Trim(); admin.FirstName = txtFirstName.Text.Trim(); admin.LastName = txtLastName.Text.Trim(); admin.ContactNo = !string.IsNullOrEmpty(txtContNumber.Text.Trim()) ? txtContNumber.Text.Trim() : null; admin.Address = !string.IsNullOrEmpty(txtAddress.Text.Trim()) ? txtAddress.Text.Trim() : null; admin.City = !string.IsNullOrEmpty(txtCity.Text.Trim()) ? txtCity.Text.Trim() : null; admin.State = !string.IsNullOrEmpty(txtState.Text.Trim()) ? txtState.Text.Trim() : null; admin.Zip = !string.IsNullOrEmpty(txtZip.Text.Trim()) ? txtZip.Text.Trim() : null; return admin; } #endregion } </code></pre>
[]
[ { "body": "<p>I don't like that you are using exceptions to determine if the email address is already in use. Exceptions are for <strong>exceptional behaviour</strong>, not something that is to be (reasonably) expected. It's not that unlikely that someone will try to use the same email address to register on a website (they may have forgotten that they had registered). Checks like that should be done in a separate method, eg:</p>\n\n<pre><code>private bool IsValid()\n{\n //check if username is valid by querying the database\n //display an error message if it is and return false. \n //return true otherwise.\n}\n\nprotected void btnSave_Click(object sender, ImageClickEventArgs e)\n{\n if (!IsValid())\n {\n return\n }\n\n //perform your save logic.\n}\n</code></pre>\n\n<p>The following method should have a lowercase S for the \"ship\" as that is how the class is named.</p>\n\n<pre><code>private MembershipUser SaveMemberShipUser()\n</code></pre>\n\n<p>This line has got <a href=\"http://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow\" title=\"SQL Injection\">SQL injection</a> written all over it:</p>\n\n<pre><code>user = Membership.CreateUser(txtEmail.Text, txtPassword.Text, txtEmail.Text);\n</code></pre>\n\n<p>Never use user inputted text directly, use a prepared statement instead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T21:09:07.830", "Id": "3356", "ParentId": "3351", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T15:51:46.577", "Id": "3351", "Score": "2", "Tags": [ "c#", "asp.net", "exception" ], "Title": "Critical review of a Simple Class" }
3351
<p>I've recently got into an habit where I've used extension methods for giving things fluent-like properties - such as the below example or as another example <code>entity.AssertNotNull()</code></p> <pre><code>public static class GenericHelper { public static void AssignOrThrowIfNull&lt;T&gt;(this T obj, ref T assignTo, string paramName) { if (obj == null) throw new ArgumentNullException(paramName, "Unallowed null argument of type: " + typeof(T).FullName); assignTo = obj; } } </code></pre> <p>This is then used as follows:</p> <pre><code>public class SmtpClient public SmtpServerAddress Server { get { return smtpServer; } } private SmtpServerAddress smtpServer; public SmtpClient(SmtpServerAddress smtpServer) { smtpServer.AssignToOrThrow(ref this.smtpServer, "smtpServer"); } </code></pre> <p>as opposed to</p> <pre><code>public SmtpClient(SmtpServerAddress smtpServer) { if(smtpServer == null) throw new ArgumentNullException("smtpServer"); } </code></pre> <p>Do you think this is readable? Is it in any way preferable to regular checks everywhere? The fact that I can't really decide if I like it or not makes me nervous, so I'd like some external input!</p> <p><em>UPDATE</em>:</p> <p>Yes, you made me open my eyes. Hopefully, you will agree with me that the following is a bit more agreeable. I used expressions because I want to include as much information as possible in the exception.</p> <pre><code>public static class Require { public static void That(Expression&lt;Func&lt;bool&gt;&gt; func) { if (!func.Compile()()) throw new ContractException("Contract not fulfilled: " + func.Body, func); } } </code></pre> <p>Atleast I think this makes it a bit clearer, even though the lambda syntax is not very nice (I don't think <code>smtpServer != null</code> can be inferred to an Expression).</p> <pre><code>Require.That(() =&gt; smtpServer != null); SmtpServer = smtpServer; </code></pre> <p>Since I compile the expression each time, there will surely be some performance penalty.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T10:50:09.047", "Id": "8164", "Score": "0", "body": "You can omit usage of `Expression<Func<bool>>` and replace it usage with `Func<T,bool>` with captured variables within the scope of the expression, as i did in my extended example. You can combine it to trace the debug output using assertions and you can use standart mechanizms, like trace listeners to get more info on the exception stack;" } ]
[ { "body": "<p>I think that your instincts are right, I don't like it and it seems to be over-architected. The general pattern of checking if an parameter is null and throwing an exception is well established and programmers are used to it - so much so that they can understand it with a quick glance. Your refactored version is unusual and so they'll have to step into the method and look at it.</p>\n\n<p>Extension methods are fanastic on the whole but I don't think that this is a valid use of one.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-09T13:10:43.527", "Id": "5029", "Score": "0", "body": "You are right - over-architected plus the fact that I abused extension methods was over the line. What do you think of the latest update at the bottom of my post? It might still be over-architected though, but a bit more useful atleast!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T20:28:00.987", "Id": "5053", "Score": "0", "body": "I still think it's over-architected. Why not use [code contracts](http://msdn.microsoft.com/en-us/devlabs/dd491992) instead or just follow the pattern of throwing an exception if a required parameter is null?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T20:55:50.527", "Id": "3355", "ParentId": "3352", "Score": "1" } }, { "body": "<p>Doesn't make the code shorter. </p>\n\n<p>Doesn't make it clearer to someone who is new to your code.</p>\n\n<p>If there was more logic in the extension method, may be. But in this case - no.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-09T10:10:12.810", "Id": "3361", "ParentId": "3352", "Score": "1" } }, { "body": "<p>You might want to look into <a href=\"http://research.microsoft.com/en-us/projects/contracts/\" rel=\"nofollow\">code contracts</a> instead, which allows you to write:</p>\n\n<pre><code>Contract.Requires&lt;ArgumentNullException&gt;(smtpServer != null);\n</code></pre>\n\n<p>This expresses clearly what you are trying to do, and has the added advantage of allowing additional static checking by the code contracts tool to check the code that calls your method for possible violations of the contract.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-09T13:03:49.413", "Id": "5028", "Score": "0", "body": "I agree that code contracts would be nice - the irritating thing is that it is not supported \"out of box\" with VS2010 - you need to install the pack, even though the classes are part of .net 4 (you just get a real ugly message box otherwise). I ended rewriting a bit of that functionality - see my update if you want to comment on the latest version I wrote! :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-09T11:09:56.137", "Id": "3362", "ParentId": "3352", "Score": "3" } }, { "body": "<p>I whould suggest you to use generics and non-generics version as well as special wrapper to generic class handle exceptions. This is all about using anonymous functions, extension methods and static functions. </p>\n\n<p>I whould like to suggust you to use prototyping using <code>Func&lt;T&gt;</code> and <code>Func&lt;T,U&gt;</code> for non-generic and generic methods respectively; </p>\n\n<p>Additionally, you will not be required to install CodeContracts to use <strong>contract requrents</strong>.\nAfter applying following source code, readability for you code can improve significantly, and have a more elegant look'n'feel:</p>\n\n<pre><code>public SmtpClient(SmtpServerAddress smtpServer, bool dummy1, bool dummy2) \n{ \n Server = smtpServer \n .RequireNotNull() \n .RequireIsNullOrWhitespace((obj) =&gt; obj.UNC) \n .RequireEqualsZero((obj) =&gt; obj.UID);\n}\n</code></pre>\n\n<p>or (full sources):</p>\n\n<pre><code>public class SmtpClient\n{\n public SmtpServerAddress Server { get; private set; }\n public SmtpClient(SmtpServerAddress smtpServer)\n {\n AssertionContracts.ThrowOnTrue&lt;ArgumentNullException&gt;(() =&gt; smtpServer == null);\n Server = smtpServer;\n }\n public SmtpClient(SmtpServerAddress smtpServer, bool dummy1, bool dummy2)\n {\n smtpServer\n .RequireNotNull()\n .RequireIsNullOrWhitespace((obj) =&gt; obj.UNC)\n .RequireEqualsZero((obj) =&gt; obj.UID);\n Server = smtpServer;\n } \n}\n\npublic class SmtpServerAddress \n{\n public string UNC { get; set; }\n public long UID { get; set; } \n}\n</code></pre>\n\n<p>Source code:</p>\n\n<pre><code>public static class AssertionContracts\n{\n private static class Exceptions&lt;U&gt; where U : Exception, new()\n {\n public static T ThrowOnTrue&lt;T&gt;(T obj, Func&lt;T, bool&gt; function, params object[] args)\n {\n if (function(obj) == true)\n {\n Throw(obj, args);\n }\n return obj;\n }\n public static T ThrowOnFalse&lt;T&gt;(T obj, Func&lt;T, bool&gt; function, params object[] args)\n {\n if (function(obj) == false)\n {\n Throw(obj, args);\n }\n return obj;\n }\n public static void Throw&lt;T&gt;(T obj, params object[] args)\n {\n throw CreateException(obj, args);\n }\n private static U CreateException&lt;T&gt;(T obj, params object[] args)\n {\n return (U)Activator.CreateInstance(typeof(U), args);\n }\n }\n public class ContractException : Exception\n {\n public ContractException() : base() { }\n public ContractException(string message) : base(message) { }\n protected ContractException(SerializationInfo info, StreamingContext context) : base(info, context) { }\n public ContractException(string message, Exception innerException) : base(message, innerException) { }\n }\n public static T ThrowOnTrue&lt;T, U&gt;(this T obj, Func&lt;T, bool&gt; function, params object[] args) where U : Exception, new()\n {\n return AssertionContracts.Exceptions&lt;ContractException&gt;.ThrowOnTrue(obj, function);\n }\n public static T ThrowOnFalse&lt;T, U&gt;(this T obj, Func&lt;T, bool&gt; function, params object[] args) where U : Exception, new()\n {\n return AssertionContracts.Exceptions&lt;ContractException&gt;.ThrowOnFalse(obj, function);\n }\n public static void Throw&lt;T, U&gt;(this T obj, Func&lt;T, bool&gt; function, U ex) where U : Exception\n {\n AssertionContracts.Exceptions&lt;ContractException&gt;.Throw(obj, function);\n }\n public static T NoThrowContractException&lt;T&gt;(this T obj, Func&lt;T, bool&gt; function)\n {\n return AssertionContracts.Exceptions&lt;ContractException&gt;.ThrowOnTrue(obj, function);\n }\n public static T ThrowContractException&lt;T&gt;(this T obj, Func&lt;T, bool&gt; function)\n {\n return AssertionContracts.Exceptions&lt;ContractException&gt;.ThrowOnFalse(obj, function);\n }\n public static T AssertTrue&lt;T&gt;(this T obj, Func&lt;T, bool&gt; function)\n {\n Trace.Assert(function(obj) == true);\n return obj;\n }\n public static T AssertFalse&lt;T&gt;(this T obj, Func&lt;T, bool&gt; function)\n {\n Trace.Assert(function(obj) == false);\n return obj;\n }\n public static T AssertIsNullOrEmpty&lt;T&gt;(this T obj, Func&lt;T, string&gt; function)\n {\n Trace.Assert(string.IsNullOrEmpty(function(obj)));\n return obj;\n }\n public static T AssertIsNullOrWhitespace&lt;T&gt;(this T obj, Func&lt;T, string&gt; function)\n {\n Trace.Assert(string.IsNullOrWhiteSpace(function(obj)));\n return obj;\n }\n public static T AssertIsNotNullOrEmpty&lt;T&gt;(this T obj, Func&lt;T, string&gt; function)\n {\n Trace.Assert(!string.IsNullOrEmpty(function(obj)));\n return obj;\n }\n public static T AssertIsNotNullOrWhitespace&lt;T&gt;(this T obj, Func&lt;T, string&gt; function)\n {\n Trace.Assert(!string.IsNullOrWhiteSpace(function(obj)));\n return obj;\n }\n public static T AssertEquals&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function, U value)\n {\n Trace.Assert(object.Equals(function(obj), value));\n return obj;\n }\n public static T AssertNotEquals&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function, U value)\n {\n Trace.Assert(!object.Equals(function(obj), value));\n return obj;\n }\n public static T AssertDefault&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function)\n {\n Trace.Assert(object.Equals(function(obj), default(U)));\n return obj;\n }\n public static T AssertNonDefault&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function)\n {\n Trace.Assert(!object.Equals(function(obj), default(U)));\n return obj;\n }\n public static T AssertNotNull&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function)\n {\n Trace.Assert(!object.Equals(function(obj), default(U)));\n return obj;\n }\n public static T AssertNotNull&lt;T&gt;(this T obj)\n {\n Trace.Assert(!object.Equals(obj, default(T)));\n return obj;\n }\n public static T AssertNull&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function)\n {\n Trace.Assert(object.Equals(function(obj), default(U)));\n return obj;\n }\n public static T AssertNull&lt;T&gt;(this T obj)\n {\n Trace.Assert(object.Equals(obj, default(T)));\n return obj;\n }\n public static T AssertPositive&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n Trace.Assert(function(obj) &gt; 0);\n return obj;\n }\n public static T AssertPositive&lt;T&gt;(this T obj, Func&lt;T, long&gt; function)\n {\n Trace.Assert(function(obj) &gt; 0);\n return obj;\n }\n public static T AssertNegative&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n Trace.Assert(function(obj) &lt; 0);\n return obj;\n }\n public static T AssertNegative&lt;T&gt;(this T obj, Func&lt;T, long&gt; function)\n {\n Trace.Assert(function(obj) &lt; 0);\n return obj;\n }\n public static T AssertEqualsZero&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n Trace.Assert(function(obj) == 0);\n return obj;\n }\n public static T AssertEqualsZero&lt;T&gt;(this T obj, Func&lt;T, long&gt; function)\n {\n Trace.Assert(function(obj) == 0);\n return obj;\n }\n public static T AssertNotEqualsZero&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n Trace.Assert(function(obj) != 0);\n return obj;\n }\n public static T AssertNotEqualsZero&lt;T&gt;(this T obj, Func&lt;T, long&gt; function)\n {\n Trace.Assert(function(obj) != 0);\n return obj;\n }\n public static T AssertGreaterThan&lt;T&gt;(this T obj, Func&lt;T, int&gt; function, int value)\n {\n Trace.Assert(function(obj) &gt; value);\n return obj;\n }\n public static T AssertGreaterThan&lt;T&gt;(this T obj, Func&lt;T, long&gt; function, long value)\n {\n Trace.Assert(function(obj) &gt; value);\n return obj;\n }\n public static T AssertLessThan&lt;T&gt;(this T obj, Func&lt;T, int&gt; function, int value)\n {\n Trace.Assert(function(obj) &lt; value);\n return obj;\n }\n public static T AssertLessThan&lt;T&gt;(this T obj, Func&lt;T, long&gt; function, long value)\n {\n Trace.Assert(function(obj) &lt; value);\n return obj;\n }\n public static T AssertGreaterOrEqualsThan&lt;T&gt;(this T obj, Func&lt;T, int&gt; function, int value)\n {\n Trace.Assert(function(obj) &gt;= value);\n return obj;\n }\n public static T AssertGreaterOrEqualsThan&lt;T&gt;(this T obj, Func&lt;T, long&gt; function, long value)\n {\n Trace.Assert(function(obj) &gt;= value);\n return obj;\n }\n public static T AssertLessOrEqualsThan&lt;T&gt;(this T obj, Func&lt;T, int&gt; function, int value)\n {\n Trace.Assert(function(obj) &lt;= value);\n return obj;\n }\n public static T AssertLessOrEqualsThan&lt;T&gt;(this T obj, Func&lt;T, long&gt; function, long value)\n {\n Trace.Assert(function(obj) &lt;= value);\n return obj;\n }\n public static T AssertGreaterOrEqualsZero&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n Trace.Assert(function(obj) &gt;= 0);\n return obj;\n }\n public static T AssertGreaterOrEqualsZero&lt;T&gt;(this T obj, Func&lt;T, long&gt; function, long value)\n {\n Trace.Assert(function(obj) &gt;= 0);\n return obj;\n }\n public static T AssertLessOrEqualsZero&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n Trace.Assert(function(obj) &lt;= 0);\n return obj;\n }\n public static T AssertLessOrEqualsZero&lt;T&gt;(this T obj, Func&lt;T, long&gt; function)\n {\n Trace.Assert(function(obj) &lt;= 0);\n return obj;\n }\n public static T RequireTrue&lt;T&gt;(this T obj, Func&lt;T, bool&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) == true);\n }\n public static T RequireFalse&lt;T&gt;(this T obj, Func&lt;T, bool&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) == false);\n }\n public static T RequireIsNullOrEmpty&lt;T&gt;(this T obj, Func&lt;T, string&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; string.IsNullOrEmpty(function(obj)));\n }\n public static T RequireIsNullOrWhitespace&lt;T&gt;(this T obj, Func&lt;T, string&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; string.IsNullOrWhiteSpace(function(obj)));\n }\n public static T RequireIsNotNullOrEmpty&lt;T&gt;(this T obj, Func&lt;T, string&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; !string.IsNullOrEmpty(function(obj)));\n }\n public static T RequireIsNotNullOrWhitespace&lt;T&gt;(this T obj, Func&lt;T, string&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; !string.IsNullOrWhiteSpace(function(obj)));\n }\n public static T RequireEquals&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function, U value)\n {\n return obj.ThrowContractException((o) =&gt; object.Equals(function(obj), value));\n }\n public static T RequireEquals&lt;T, U&gt;(this T obj, T value)\n {\n return obj.ThrowContractException((o) =&gt; object.Equals(obj, value));\n }\n public static T RequireNotEquals&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function, U value)\n {\n return obj.ThrowContractException((o) =&gt; !object.Equals(function(obj), value));\n }\n public static T RequireNotEquals&lt;T, U&gt;(this T obj, T value)\n {\n return obj.ThrowContractException((o) =&gt; !object.Equals(obj, value));\n }\n public static T RequireDefault&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; object.Equals(function(obj), default(U)));\n }\n public static T RequireDefault&lt;T&gt;(this T obj)\n {\n return obj.ThrowContractException((o) =&gt; object.Equals(obj, default(T)));\n }\n public static T RequireNonDefault&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; !object.Equals(function(obj), default(U)));\n }\n public static T RequireNonDefault&lt;T, U&gt;(this T obj)\n {\n return obj.ThrowContractException((o) =&gt; !object.Equals(obj, default(T)));\n }\n public static T RequireNotNull&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; !object.Equals(function(obj), default(U)));\n }\n public static T RequireNotNull&lt;T&gt;(this T obj)\n {\n return obj.ThrowContractException((o) =&gt; !object.Equals(obj, default(T)));\n }\n public static T RequireNull&lt;T, U&gt;(this T obj, Func&lt;T, U&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; object.Equals(function(obj), default(U)));\n }\n public static T RequireNull&lt;T&gt;(this T obj)\n {\n return obj.ThrowContractException((o) =&gt; object.Equals(obj, default(T)));\n }\n public static T RequirePositive&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &gt; 0);\n }\n public static T RequirePositive&lt;T&gt;(this T obj, Func&lt;T, long&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &gt; 0);\n }\n public static T RequireNegative&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &lt; 0);\n }\n public static T RequireNegative&lt;T&gt;(this T obj, Func&lt;T, long&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &lt; 0);\n }\n public static T RequireEqualsZero&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) == 0);\n }\n public static T RequireEqualsZero&lt;T&gt;(this T obj, Func&lt;T, long&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) == 0);\n }\n public static T RequireNotEqualsZero&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) != 0);\n }\n public static T RequireNotEqualsZero&lt;T&gt;(this T obj, Func&lt;T, long&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) != 0);\n }\n public static T RequireGreaterThan&lt;T&gt;(this T obj, Func&lt;T, int&gt; function, int value)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &gt; value);\n }\n public static T RequireGreaterThan&lt;T&gt;(this T obj, Func&lt;T, long&gt; function, long value)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &gt; value);\n }\n public static T RequireLessThan&lt;T&gt;(this T obj, Func&lt;T, int&gt; function, int value)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &lt; value);\n }\n public static T RequireLessThan&lt;T&gt;(this T obj, Func&lt;T, long&gt; function, long value)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &lt; value);\n }\n public static T RequireGreaterOrEqualsThan&lt;T&gt;(this T obj, Func&lt;T, int&gt; function, int value)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &gt;= value);\n }\n public static T RequireGreaterOrEqualsThan&lt;T&gt;(this T obj, Func&lt;T, long&gt; function, long value)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &gt;= value);\n }\n public static T RequireLessOrEqualsThan&lt;T&gt;(this T obj, Func&lt;T, int&gt; function, int value)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &lt;= value);\n }\n public static T RequireLessOrEqualsThan&lt;T&gt;(this T obj, Func&lt;T, long&gt; function, long value)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &lt;= value);\n }\n public static T RequireGreaterOrEqualsZero&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &gt;= 0);\n }\n public static T RequireGreaterOrEqualsZero&lt;T&gt;(this T obj, Func&lt;T, long&gt; function, long value)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &gt;= 0);\n }\n public static T RequireLessOrEqualsZero&lt;T&gt;(this T obj, Func&lt;T, int&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &lt;= 0);\n }\n public static T RequireLessOrEqualsZero&lt;T&gt;(this T obj, Func&lt;T, long&gt; function)\n {\n return obj.ThrowContractException((o) =&gt; function(obj) &lt;= 0);\n }\n public static void ThrowOnFalse&lt;U&gt;(Func&lt;bool&gt; function, params object[] args) where U : Exception, new()\n {\n if (function() == false)\n {\n throw (U)Activator.CreateInstance(typeof(U), args);\n }\n }\n public static void ThrowOnTrue&lt;U&gt;(Func&lt;bool&gt; function, params object[] args) where U : Exception, new()\n {\n if (function() == true)\n {\n throw (U)Activator.CreateInstance(typeof(U), args);\n }\n }\n public static void Throw&lt;U&gt;(Func&lt;bool&gt; function, U ex) where U : Exception\n {\n if (function() == false)\n {\n throw ex;\n }\n }\n public static void AssertTrue(Func&lt;bool&gt; function)\n {\n Trace.Assert(function() == true);\n }\n public static void AssertFalse(Func&lt;bool&gt; function)\n {\n Trace.Assert(function() == false);\n }\n public static void AssertIsNullOrEmpty(Func&lt;string&gt; function)\n {\n Trace.Assert(string.IsNullOrEmpty(function()));\n }\n public static void AssertIsNullOrWhitespace(Func&lt;string&gt; function)\n {\n Trace.Assert(string.IsNullOrWhiteSpace(function()));\n }\n public static void AssertIsNotNullOrEmpty(Func&lt;string&gt; function)\n {\n Trace.Assert(!string.IsNullOrEmpty(function()));\n }\n public static void AssertIsNotNullOrWhitespace(Func&lt;string&gt; function)\n {\n Trace.Assert(!string.IsNullOrWhiteSpace(function()));\n }\n public static void AssertEquals&lt;U&gt;(Func&lt;U&gt; function, U value)\n {\n Trace.Assert(object.Equals(function(), value));\n }\n public static void AssertNotEquals&lt;U&gt;(Func&lt;U&gt; function, U value)\n {\n Trace.Assert(!object.Equals(function(), value));\n }\n public static void AssertDefault&lt;U&gt;(Func&lt;U&gt; function)\n {\n Trace.Assert(object.Equals(function(), default(U)));\n }\n public static void AssertNonDefault&lt;U&gt;(Func&lt;U&gt; function)\n {\n Trace.Assert(!object.Equals(function(), default(U)));\n }\n public static void AssertNotNull&lt;U&gt;(Func&lt;U&gt; function)\n {\n Trace.Assert(!object.Equals(function(), default(U)));\n }\n public static void AssertNull&lt;U&gt;(Func&lt;U&gt; function)\n {\n Trace.Assert(object.Equals(function(), default(U)));\n }\n public static void AssertPositive(Func&lt;int&gt; function)\n {\n Trace.Assert(function() &gt; 0);\n }\n public static void AssertPositive(Func&lt;long&gt; function)\n {\n Trace.Assert(function() &gt; 0);\n }\n public static void AssertNegative(Func&lt;int&gt; function)\n {\n Trace.Assert(function() &lt; 0);\n }\n public static void AssertNegative(Func&lt;long&gt; function)\n {\n Trace.Assert(function() &lt; 0);\n }\n public static void AssertEqualsZero(Func&lt;int&gt; function)\n {\n Trace.Assert(function() == 0);\n }\n public static void AssertEqualsZero(Func&lt;long&gt; function)\n {\n Trace.Assert(function() == 0);\n }\n public static void AssertNotEqualsZero(Func&lt;int&gt; function)\n {\n Trace.Assert(function() != 0);\n }\n public static void AssertNotEqualsZero(Func&lt;long&gt; function)\n {\n Trace.Assert(function() != 0);\n }\n public static void AssertGreaterThan(Func&lt;int&gt; function, int value)\n {\n Trace.Assert(function() &gt; value);\n }\n public static void AssertGreaterThan(Func&lt;long&gt; function, long value)\n {\n Trace.Assert(function() &gt; value);\n }\n public static void AssertLessThan(Func&lt;int&gt; function, int value)\n {\n Trace.Assert(function() &lt; value);\n }\n public static void AssertLessThan(Func&lt;long&gt; function, long value)\n {\n Trace.Assert(function() &lt; value);\n }\n public static void AssertGreaterOrEqualsThan(Func&lt;int&gt; function, int value)\n {\n Trace.Assert(function() &gt;= value);\n }\n public static void AssertGreaterOrEqualsThan(Func&lt;long&gt; function, long value)\n {\n Trace.Assert(function() &gt;= value);\n }\n public static void AssertLessOrEqualsThan(Func&lt;int&gt; function, int value)\n {\n Trace.Assert(function() &lt;= value);\n }\n public static void AssertLessOrEqualsThan(Func&lt;long&gt; function, long value)\n {\n Trace.Assert(function() &lt;= value);\n }\n public static void AssertGreaterOrEqualsZero(Func&lt;int&gt; function)\n {\n Trace.Assert(function() &gt;= 0);\n }\n public static void AssertGreaterOrEqualsZero(Func&lt;long&gt; function, long value)\n {\n Trace.Assert(function() &gt;= 0);\n }\n public static void AssertLessOrEqualsZero&lt;T&gt;(Func&lt;int&gt; function)\n {\n Trace.Assert(function() &lt;= 0);\n }\n public static void AssertLessOrEqualsZero(Func&lt;long&gt; function)\n {\n Trace.Assert(function() &lt;= 0);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T10:23:06.727", "Id": "5418", "ParentId": "3352", "Score": "0" } } ]
{ "AcceptedAnswerId": "3362", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T19:22:52.273", "Id": "3352", "Score": "3", "Tags": [ "c#", "extension-methods" ], "Title": "Using an extension method for a small helper task that (ab)uses the fact that the object is not dereferenced" }
3352
<p>I'm currently trying to brush up on ADT implementations, specifically an implementation for a Linked List (I'm using Java 5 to do this).</p> <p>Is this implementation I've written for <code>add(i, x)</code> correct and efficient?</p> <pre><code>public void add(int i, Object x) { // Possible Cases: // // 1. The list is non-empty, but the requested index is out of // range (it must be from 0 to size(), inclusive) // // 2. The list itself is empty, which will only work if i = 0 // // This implementation of add(i, x) relies on finding the node just before // the requested index i. // These will be used to traverse the list Node currentNode = head; int indexCounter = 0; // This will be used to mark the node before the requested index node int targetIndex = i - 1; // This is the new node to be inserted in the list Node newNode = new Node(x); if (currentNode != null) { while (indexCounter &lt; targetIndex &amp;&amp; currentNode.getNext() != null) { indexCounter++; currentNode = currentNode.getNext(); } if (indexCounter == targetIndex) { newNode.setNext(currentNode.getNext()); currentNode.setNext(newNode); } else if (i == 0) { newNode.setNext(head); head = newNode; } } else if (i == 0) { head = newNode; } } </code></pre>
[]
[ { "body": "<p>First: Java-1.5 and a List of Object, not a generic List? But a CS-degree and intermediate level? </p>\n\n<p>Second: Your comment complicates 2 cases: List is empty or not - if not ... - well, if you don't distinguish the cases, from: </p>\n\n<pre><code>// 1. The list is non-empty, but the requested index is out\n// of range (it must be from 0 to size (), inclusive)\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>// it must be from 0 to size (), inclusive. \n</code></pre>\n\n<p>Now look at condition 2:</p>\n\n<pre><code>// 2. The list itself is empty, which will only work if i = 0\n</code></pre>\n\n<p>If the size is 0, and i=0, then i is in the range of 0 to 0 inclusive, isn't it? So it is just one condition, and a much shorter condition. </p>\n\n<p>However, the code seems right, and can't be simplified like the condition*), and it isn't that easy, even if it looks easy in the end. Several days seems a lot, but several hours can vanish like nothing, expecially, if you get a wrong start. I remember John Bentley, who wrote, that a simple binary search wasn't correctly implemented by most of the professional developers he interviewed. By none of them, if I remember correctly ('Programming Pearls'). </p>\n\n<p>*) This claim isn't proved. Disprove it, friends!</p>\n\n<p>I would expect an IndexOutOfBoundsException if the index is negative or too big. A size-Method would be useful for that. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-09T03:12:44.410", "Id": "3359", "ParentId": "3353", "Score": "2" } }, { "body": "<p><strong>This method looks totally counterintuitive</strong>, probably because it shouldn't even be a part of your interface (<code>insert OBJECT by index in the linked list</code>, seriously?)</p>\n\n<p>See, if you're trying to <em>\"to brush up on ADT implementations\"</em>, you should probably know, that the <code>linked list</code> doesn't allow inserting the elements by index (that would be odd, because <code>list</code> is not an array and insertion like that is a <code>O(n)</code>operation).</p>\n\n<hr>\n\n<p>Now, I think that the best way for you to dive into the <code>ADT</code> programming would mean writing something like a <strong>template doubly-linked list</strong>. Insertion and deletion operations would require some thinking about the references and usage of generics makes you think a bit \"more generic\" :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-07T15:25:57.597", "Id": "6948", "Score": "2", "body": "I disagree. There is nothing wrong in trying to implement such method. All the more since it is done as an exercise." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-08T09:08:11.877", "Id": "3961", "ParentId": "3353", "Score": "0" } }, { "body": "<p>Usually implementation of <code>LinkedList&lt;T&gt;</code> assumes that there are public methods like <code>addBefore(Note&lt;T&gt;, T value)</code> and <code>addAfter(Note&lt;T&gt;, T value)</code>. </p>\n\n<p>Therefore your implementation should look like the one bellow:</p>\n\n<pre><code>public void add(int index, Object x) {\n // There is a small optimization can be made if index == size of the linked list. \n // Hence you can insert just after the tail of the list \n // without the traversal of the whole list.\n Node node = findNode(index); \n addBefore(node, x); // use the existing method.\n}\n</code></pre>\n\n<p>The implementation of <code>addBefore(node, x)</code> should not be very complex.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-07T09:55:11.393", "Id": "4634", "ParentId": "3353", "Score": "1" } }, { "body": "<p>In your solution, you have to deal with an annoying corner case : if the node is to be inserted in front of the list, then you cannot just apply a <code>setNext(newNode)</code> to the previous node, since there is no previous node. Instead, you have to deal with the attribute <code>head</code> just for this specific case.</p>\n\n<p>You can greatly simplify things if you <strong>introduce a \"root\" node</strong>. This root node will always exist in the LinkedList (So, an empty list is composed of only one Node : the root).</p>\n\n<p>Using this convention, I can implement your method with 9 lines of code, containing only one loop. I will post this solution if you want to (I don't know if it is ok to give his own solution on this site, and maybe you'd like to try on your own before I post my implementation).</p>\n\n<p>to answer the question 2, I think implementing such a method is not an easy task, because it is not natural for our human brain to reason about a recursive data type. And if you introduce corner cases as you did, you quickly become overwhelmed by what you have to keep in mind in order to design your algorithm.</p>\n\n<p>Here is what I did in order to implement your method :</p>\n\n<ol>\n<li>I <strong>drew example lists</strong>, with boxes and arrows with a pencil and paper. An empty list, a list with one element, with 2 and with 3.</li>\n<li>Then I <strong>drew the expected result</strong>, when I insert at 0 for the empty list, at 0 and 1 for the singleton list, etc.</li>\n<li>I tried to <strong>find an approximative algorithm</strong> in my head, and with the help of the drawings, and focusing on the nominal case (an insertion between 2 nodes).</li>\n<li>I put this algorithm in code (or at least what seemed about right)</li>\n<li>I mentally <strong>executed on my drawings</strong> the algorithm I wrote (you can draw step by step modifications, if you prefer)</li>\n<li>I found a case where the algorithm fails. I spotted the flaw in my initial algorithm, rethought it, then went back to step 4</li>\n</ol>\n\n<p>After some iterations, I realized it was almost working, except for the corner case (insertions in front of the list). I introduced the root Node, and my algorithm worked.</p>\n\n<h3>Edit</h3>\n\n<p>Here is my implementation :</p>\n\n<pre><code>public class LinkedList&lt;T&gt; {\n private static class Node&lt;T&gt; {\n private T value;\n private Node next;\n\n public Node(T value) {\n this.value = value;\n } \n }\n\n private Node root = new Node(null);\n\n public void add(int i, T v) {\n Node n = root;\n while(i&gt;0) {\n if (n.next == null) {\n throw new ArrayIndexOutOfBoundsException();\n }\n n = n.next;\n i--;\n }\n Node newNode = new Node(v);\n newNode.next = n.next;\n n.next = newNode;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-07T16:35:15.063", "Id": "4647", "ParentId": "3353", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T20:14:19.497", "Id": "3353", "Score": "5", "Tags": [ "java", "linked-list" ], "Title": "Java Implementation of linked list add(i, x) method" }
3353
<p>What I'm trying to do here is get an RSS feed and append an Enclosure XML node to each item, which has a link to a video file (wmv).</p> <p>Try the below code with</p> <pre><code>url = "http://www.microsoft.com/events/series/digitalblackbelt.aspx?tab=rss" </code></pre> <p>for eg to get the point</p> <p>The performance hit here consists of two parts: the LONG "foreach" loop, along with the HUGE number of requests done to retrieve the media link (marked in the code by the comment "This part needs attention"). Any advice concerning how to get the media link a much faster manner would really be appreciated!</p> <p>You can get a glimpse of what that code do, by comparing this feed (the URL):</p> <p><a href="http://www.microsoft.com/events/series/digitalblackbelt.aspx?tab=rss" rel="nofollow">http://www.microsoft.com/events/series/digitalblackbelt.aspx?tab=rss</a></p> <p>to this feed (created by the code below), note that it will be slow and might give error, if it did just refresh the page:</p> <p><a href="http://mshady.apphb.com/feeds/index?url=http://www.microsoft.com/events/series/digitalblackbelt.aspx?tab=rss" rel="nofollow">http://mshady.apphb.com/feeds/index?url=http://www.microsoft.com/events/series/digitalblackbelt.aspx?tab=rss</a></p> <pre><code>public class FeedsController : Controller { private XmlDocument _Xml; [OutputCache(VaryByParam = "url", Duration=86400)] public string Index(string url) { string feed = ""; _Xml = new XmlDocument(); _Xml.Load(url); foreach (XmlNode node in _Xml.ChildNodes[0].ChildNodes[0].ChildNodes) { if (node.Name == "item") { XmlNode childnode = GetEnclosureXmlNode(node); node.AppendChild(childnode); } } feed = _Xml.OuterXml; return feed; } private string GetMediaUrl(string articleUrl) { string mediaUrl = ""; //////////////////////////////////////////// // This part needs attention //////////////////////////////////////////// Regex regex = new Regex(@"&lt;a href=""(.*?)""&gt;WMV Download&lt;/a&gt;"); var request = HttpWebRequest.Create(articleUrl); var response = request.GetResponse(); string responseHtml = new StreamReader(response.GetResponseStream()).ReadToEnd(); var match = regex.Match(responseHtml); //////////////////////////////////////////// // This part needs attention //////////////////////////////////////////// if (match.Success) mediaUrl = match.Groups[1].Value; return mediaUrl; } private XmlNode GetEnclosureXmlNode(XmlNode node) { string articleUrl = node["link"].InnerText; string mediaUrl = GetMediaUrl(articleUrl); XmlElement childnode = CreateEnclosureXmlNode(mediaUrl); return childnode; } private XmlElement CreateEnclosureXmlNode(string mediaUrl) { XmlElement childnode = _Xml.CreateElement("enclosure"); childnode.SetAttribute("url", mediaUrl); childnode.SetAttribute("type", "video/wmv"); return childnode; } } </code></pre>
[]
[ { "body": "<p>I would bet that the regex.Match is the performance problem, as Jeff Atwood describes <a href=\"https://blog.codinghorror.com/regex-performance/\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>One thing that I would do is move regex definition to a static variable outside of the function defined as below:</p>\n<pre><code>static Regex regex = new Regex(@&quot;&lt;a href=&quot;&quot;(.*?)&quot;&quot;&gt;WMV Download&lt;/a&gt;&quot;, RegexOptions.Compiled);\n</code></pre>\n<p>That's the only real thing that jumps out at me. Try taking a look at <a href=\"https://web.archive.org/web/20150628063008/http://blogs.msdn.com:80/b/bclteam/archive/2010/06/25/optimizing-regular-expression-performance-part-i-working-with-the-regex-class-and-regex-objects.aspx\" rel=\"nofollow noreferrer\">this blog post</a> for more ideas and information.</p>\n<p>Should give you something to try until guys with more experience glance their eyes over it :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-07-09T20:39:12.817", "Id": "3368", "ParentId": "3354", "Score": "2" } }, { "body": "<p>I'm not sure there is too great a performance hit on the foreach loop, but you could isolate out all the items with xpath first, such as:</p>\n\n<pre><code>var itemNodes = _Xml.SelectNodes(@\"//channel/item\");\nforeach (XmlNode node in itemNodes)\n{\n XmlNode childnode = GetEnclosureXmlNode(node);\n node.AppendChild(childnode);\n}\n</code></pre>\n\n<p>The problem I see is the time to go and bring back a page not knowing if it will even have the media link you're looking for. If there is no other way than to get each rss url, bring back the bits and then look for the media file url, then adding some form of multi-threading to this and processing several at a time should cut down on the overall length. Finding the balance of how many at one time is then the bottleneck.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-12T21:28:28.567", "Id": "4059", "ParentId": "3354", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-08T20:19:10.613", "Id": "3354", "Score": "1", "Tags": [ "c#", "performance", "regex" ], "Title": "A faster way to look up for a url in a WebRequest/WebResponse html" }
3354
<p>I'm a beginner and have written my first Python module that parses a XML file containing some events and prints them out to <code>stdout</code> as JSON. I would appreciate some feedback about design, code layout, best practices, what can be optimized and so on.</p> <pre><code>from __future__ import with_statement import json import xml.etree.ElementTree as etree def _sanitize_string(string): """docstring for _clean_string""" string = string.replace('\n', '').split() return ' '.join(string) class Event(object): """docstring for Event""" def __init__(self, date, event, organizer, time, venue): self.date = date self.event = event self.organizer = organizer self.time = time self.venue = venue def provide_data(self): """docstring for provide_data""" data = {} data['date'] = self.date data['event'] = self.event data['organizer'] = self.organizer data['time'] = self.time data['venue'] = self.venue return data class EventCollection(list): """docstring for EventCollection""" def __init__(self): super(EventCollection, self).__init__([]) def as_json(self): """docstring for as_json""" print json.dumps([event.provide_data() for event in self], sort_keys=True, indent=2) def read_file(event_collection, filename='events.xml'): """docstring for read_file""" try: with open(filename) as f: tree = etree.parse(f) for row in tree.findall('.//row'): # event = [_sanitize_string(node.text) for node in row] # if event[0] and event[0][0].isdigit(): # print event tmpl = [_sanitize_string(node.text) for node in row] if tmpl[0] and tmpl[0][0].isdigit(): event = Event(tmpl.pop(0), tmpl.pop(0), tmpl.pop(0), tmpl.pop(0), tmpl.pop(0)) event_collection.append(event) except IOError as ioerr: print "File Error: %s" % str(ioerr) def main(): """docstring for main""" event_collection = EventCollection() read_file(event_collection) event_collection.as_json() # event_collection.as_csv() if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T07:17:30.600", "Id": "5033", "Score": "0", "body": "I would stay away from using module names for anything else. In your case, it's `string`. It threw me off a little." } ]
[ { "body": "<pre><code>from __future__ import with_statement\n\nimport json\nimport xml.etree.ElementTree as etree\n\n\ndef _sanitize_string(string):\n \"\"\"docstring for _clean_string\"\"\"\n</code></pre>\n\n<p>Docstrings should contain a description of the function, not some old name for the function.</p>\n\n<pre><code> string = string.replace('\\n', '').split()\n</code></pre>\n\n<p>Do you really want \"green\\ngrass' to come through as 'greengrass'?</p>\n\n<pre><code> return ' '.join(string)\n\n\nclass Event(object):\n \"\"\"docstring for Event\"\"\"\n def __init__(self, date, event, organizer, time, venue):\n self.date = date\n self.event = event\n self.organizer = organizer\n self.time = time\n self.venue = venue\n\n def provide_data(self):\n \"\"\"docstring for provide_data\"\"\"\n data = {}\n data['date'] = self.date\n data['event'] = self.event\n data['organizer'] = self.organizer\n data['time'] = self.time\n data['venue'] = self.venue\n return data\n</code></pre>\n\n<p>The class as it stands doesn't really do anything. If this is all its ever going to do, just use a dictionary instead. </p>\n\n<pre><code>class EventCollection(list):\n \"\"\"docstring for EventCollection\"\"\"\n\n\n def __init__(self):\n super(EventCollection, self).__init__([])\n</code></pre>\n\n<p>Passing the [] is wasteful, because the empty argument constructor will have the same effect without building a temporary list. There is no need to override the constructor here. The default behavior will build the list just fine.</p>\n\n<pre><code> def as_json(self):\n \"\"\"docstring for as_json\"\"\"\n print json.dumps([event.provide_data() for event in self],\n sort_keys=True, indent=2)\n</code></pre>\n\n<p>This would really be better as a seperate function rather then an entire class. Its misplaced in a list class because its not really dealing with the list per se. </p>\n\n<pre><code>def read_file(event_collection, filename='events.xml'):\n \"\"\"docstring for read_file\"\"\"\n try:\n with open(filename) as f:\n tree = etree.parse(f)\n for row in tree.findall('.//row'):\n # event = [_sanitize_string(node.text) for node in row]\n # if event[0] and event[0][0].isdigit():\n # print event\n</code></pre>\n\n<p>Don't keep dead code in comments, delete it.</p>\n\n<pre><code> tmpl = [_sanitize_string(node.text) for node in row]\n</code></pre>\n\n<p>I can't guess what tmpl is supposed to mean. This being xml, does these nodes have tags that you should be checking for correctness?</p>\n\n<pre><code> if tmpl[0] and tmpl[0][0].isdigit():\n</code></pre>\n\n<p>I have no idea what this test is doing. It should probably be commented to explain the signficance of that first character being a digit.</p>\n\n<pre><code> event = Event(tmpl.pop(0), tmpl.pop(0), tmpl.pop(0),\n tmpl.pop(0), tmpl.pop(0))\n</code></pre>\n\n<p>Use:\n date, event, time, organizer, venue = tmpl\n event = Event(date, event, time, organizer, venue)</p>\n\n<p>It makes is easier to see what is going on</p>\n\n<pre><code> event_collection.append(event)\n except IOError as ioerr:\n print \"File Error: %s\" % str(ioerr)\n</code></pre>\n\n<p>If you catch an error, simply printing it out is insufficient. You should really either recover or abort. You could call sys.exit() here to shutdown the program. I'd probably rethrow the exception and catch it in my main() function. If the script is supposed to be quick and dirty, just don't catch the exception and let the default handling show the error when it dies.</p>\n\n<pre><code>def main():\n \"\"\"docstring for main\"\"\"\n event_collection = EventCollection()\n\n read_file(event_collection)\n</code></pre>\n\n<p>Avoid functions which modify arguments. Use a return value. Have read_file create and return event_collection.</p>\n\n<pre><code> event_collection.as_json()\n # event_collection.as_csv()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>** EDIT **</p>\n\n<p>Ways of doing exception handling:</p>\n\n<ol>\n<li>Don't. Just take your try and except out. If something goes wrong, your program will die with a stack trace. Not very professional, but in some cases that's just fine</li>\n<li><p>Use sys.exit()</p>\n\n<p>try:\n do_stuff()\nexcept IOError:\n print \"Went wrong\"\n sys.exit() # program will exit here</p></li>\n<li>Use your own exception class (my preffered method)</li>\n</ol>\n\n<p>Code:</p>\n\n<pre><code>class UserError(Exception):\n \"\"\"\n This error is thrown when it the user's fault\n Or at least the user should see the error\n \"\"\"\n\n# later\ntry:\n do_stuff()\nexcept IOError as error:\n raise UserError(error)\n\n# later\ndef main():\n try:\n do_program()\n except UserError as error:\n print error\n</code></pre>\n\n<p>Its a bit bulky for a simple script like this, but for bigger programs I think its the best solution.</p>\n\n<p>Two other issues:</p>\n\n<ol>\n<li>You should really <code>print &gt;&gt; sys.stderr, \"your error message\"</code> so that your errors go to standard error and not standard out</li>\n<li>You should also end by calling <code>sys.exit(some non-zero number)</code> when an error happens to indicate failure.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T12:42:07.730", "Id": "5046", "Score": "0", "body": "Very helpful answer! Thx\n\nPlease, could you a bit more precise about the exception handling? Maybe with an example?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T16:55:30.930", "Id": "5048", "Score": "0", "body": "Tried to follow your suggestions. Updated code: http://paste.pocoo.org/show/435307/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T00:07:15.767", "Id": "5063", "Score": "0", "body": "@Phillip, added discussion of exceptions as EDIT" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T00:01:54.913", "Id": "3370", "ParentId": "3365", "Score": "3" } } ]
{ "AcceptedAnswerId": "3370", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-09T18:38:38.053", "Id": "3365", "Score": "1", "Tags": [ "python", "beginner", "parsing", "json", "xml" ], "Title": "Parsing XML file containing some events" }
3365
<p>Please review this:</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html &gt; &lt;html dir="ltr" lang="en-UK"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;Fahad | Just another web designer&lt;/title&gt; &lt;!--Styling Starts--&gt; &lt;/script&gt; &lt;style type="text/css"&gt; h1 { font-size:100px; display:inline-block; vertical-align:top; padding:5px; width:300px; } .menu { padding-top:90px; width:200px; display:inline-block; float:left; } .menu ul { list-style-type:none; } .container { color:#666; } a:link { color:#666; } a:hover { color:#333; } a:active { color:#666; } a:visited { color:#666; } a { text-decoration:none; } p { font-family:Verdana, Geneva, sans-serif; font-size:24px; } x { font-size:36px; font-family:Verdana, Verdana, Geneva, sans-serif; color:#06F; } #para { ; padding-left:200px; padding-right:200px; } #bio { float:left; height:200px; width:200px; } #bio h2 { font-size:40px; display:inline-block; vertical-align:top; padding:5px; width:300px; } #achievements { height:200px; width:200px; float:right; } #achievements h2 { font-size:40px; display:inline-block; vertical-align:top; padding:5px; width:300px; } #dreams { float:left; height:200px; width:200px; padding-left:150px; } #dreams h2 { font-size:40px; display:inline-block; vertical-align:top; padding:5px; width:300px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;h1&gt;Fahad&lt;/h1&gt; &lt;div class="menu"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="http://www.facebook.com/fahd92"&gt;Home&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="http://www.facebook.com/fahd92"&gt;Blog&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://www.facebook.com/fahd92"&gt;About&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://www.facebook.com/fahd92"&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div &gt; &lt;div id="para"&gt; &lt;p&gt;I m a &lt;x&gt;programmer&lt;/x&gt; and &lt;del&gt;now starting my career as&lt;/del&gt; a &lt;x&gt;Web designer&lt;/x&gt; . It takes a lot of time to start writing &lt;x&gt;beutifully&lt;/x&gt;. I am not very good at spelling so do not point out &lt;x&gt;spelling mistakes&lt;/x&gt;.&lt;/p&gt; &lt;div id="bio"&gt;&lt;!--Biography starts--&gt; &lt;h2&gt;Biography&lt;/h2&gt; &lt;p&gt;I was born in bla year &lt;x&gt;foo&lt;/x&gt; date. I like working on &lt;x&gt;computers&lt;/x&gt;&lt;/p&gt; &lt;/div&gt;&lt;!--Biography ends--&gt; &lt;div id="achievements"&gt;&lt;!--Achievements starts--&gt; &lt;h2&gt;Achievements&lt;/h2&gt; &lt;p&gt;Don't know what to put in it. I have a lot of dreams to &lt;x&gt;accomplish&lt;/x&gt;&lt;/p&gt; &lt;/div&gt;&lt;!--Achievements ends--&gt; &lt;div id="dreams"&gt;&lt;!--Dreams starts--&gt; &lt;h2&gt;Dreams&lt;/h2&gt; &lt;p&gt;I &lt;x&gt;dream&lt;/x&gt; a lot. Why shouldn't I? Dreams are &lt;x&gt;cool&lt;/x&gt;. They make us &lt;x&gt;ambitious&lt;/x&gt;.&lt;/p&gt; &lt;/div&gt;&lt;!--Dreams ends--&gt; &lt;/div&gt;&lt;!--para ends--&gt; &lt;!--menu div ends--&gt;&lt;/div&gt;&lt;!--Container Div ends--&gt; &lt;/body&gt; &lt;/html&gt; &lt;!-- www.000webhost.com Analytics Code --&gt; &lt;script type="text/javascript" src="http://analytics.hosting24.com/count.php"&gt;&lt;/script&gt; &lt;noscript&gt;&lt;a href="http://www.hosting24.com/"&gt;&lt;img src="http://analytics.hosting24.com/count.php" alt="web hosting" /&gt;&lt;/a&gt;&lt;/noscript&gt; &lt;!-- End Of Analytics Code --&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T19:07:36.870", "Id": "5052", "Score": "0", "body": "You should not put `script` or `noscript` or any other tags outside of the `html` tag itself. Use the [online version of the W3C validator](http://validator.w3.org/) or try the [Firefox add-on HTML TIdy](https://addons.mozilla.org/en-US/firefox/addon/html-validator/) (which I really like for ease of use)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T17:18:45.990", "Id": "21165", "Score": "1", "body": "The entire Code Review site is about improving code. Your title here is extremely unhelpful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-18T07:45:40.000", "Id": "62854", "Score": "0", "body": "Put the CSS in a separate file and link to it, in case you make more pages in the future that use the same look." } ]
[ { "body": "<p>When writing HTML code (forgive me if I am wrong since I do not do a lot in HTML), the code doesn't really matter (sort of). As long as it's clean (which yours is) and with clear organizational pattern, the actual content of code shouldn't matter because HTML is based on laying out information in a nice visual manner, and is not really logic, like programming on c++, C#, python, etc. But, be aware that this is with HTML code and if you have a scripting language like javascript, python, or php, then you should look at yours code's performance, readability, and maintainability.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T04:22:29.977", "Id": "3372", "ParentId": "3367", "Score": "0" } }, { "body": "<p>Two notes:</p>\n<ul>\n<li>Line <strong>2</strong>: use <code>en-GB</code></li>\n<li>Line <strong>5</strong>: <code>&lt;/script&gt;</code> without <code>&lt;script&gt;</code></li>\n</ul>\n<p>You had better not use the 000webhost.com analytics code, but other services such as <a href=\"http://www.google.com/analytics/\" rel=\"nofollow noreferrer\">Google Analytics</a> or <a href=\"http://getclicky.com/\" rel=\"nofollow noreferrer\">Clicky</a>.</p>\n<p>And there is no <code>&lt;x&gt;</code> tag in HTML. You should use <code>&lt;b&gt;</code> instead, or even <code>&lt;span class=&quot;x&quot;&gt;</code></p>\n<h2>Shorten your code</h2>\n<p>Instead of:</p>\n<pre><code> .container\n {\n color:#666;\n }\n a:link\n {\n color:#666;\n }\n a:hover\n {\n color:#333;\n }\n a:active\n {\n color:#666;\n } \n a:visited\n {\n color:#666;\n } \n</code></pre>\n<p>use:</p>\n<pre><code> .container,a:link,a:visited\n {\n color:#666;\n }\n a:hover\n {\n color:#333;\n }\n a:active\n {\n color:#666;\n }\n</code></pre>\n<p>Finally, there is a problem with 1042x768 screens: The <strong>Dreams</strong> box isn't in the correct position.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T17:55:38.820", "Id": "5127", "Score": "0", "body": "Can't I create my own tags like I have done here ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T20:43:52.617", "Id": "5132", "Score": "0", "body": "@fahad No, except if you want to create your own [DTD](http://en.wikipedia.org/wiki/Document_Type_Definition) ([example tutorial](http://www.w3schools.com/dtd/default.asp))" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T15:52:15.093", "Id": "3410", "ParentId": "3367", "Score": "3" } } ]
{ "AcceptedAnswerId": "3410", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-09T20:17:48.500", "Id": "3367", "Score": "1", "Tags": [ "html", "css", "html5" ], "Title": "Website built with HTML and CSS" }
3367
<p>I'm writing a function to take an anagram pair (words or phrases spelled with the same letters) and determine how you could move the letters to change one into the other.</p> <p>For example: Admirer -> Married</p> <p>The results would be something like this:</p> <pre><code>[[0, 1], [1, 6], [2, 0], [3, 4], [4, 2], [5, 5], [6, 3]] </code></pre> <p>The character in the 0 (a) position moves to 1, the character in position 1 (d) moves to 6, etc. I've already successfully solved this but perhaps there's a better way!</p> <p>Language of choice (required!) is javascript. Here's my current, working function:</p> <pre><code>function _get_new_positions(source, target) { // convert both strings to arrays - uppercase so we can find the destination // spot without worrying about cases source = source.toUpperCase().split(''); target = target.toUpperCase().split(''); var transform = []; var repeated = []; var found = 0; for(var i=0; i&lt;source.length; i++) { // keep track of how many times we've found and 'moved' this letter repeated[source[i]] = repeated[source[i]] ? repeated[source[i]] + 1 : 1; found = 0; want = repeated[source[i]]; for(var j=0; j&lt;target.length; j++) { if( target[j] == source[i] ) { found++; console.log('found is ' + found); if( found == want ) { transform.push([i,j]); break; } } } } return transform; } </code></pre> <p>Thank you for your input.</p>
[]
[ { "body": "<p>You can simplify the logic by setting each character you find in target to NULL. I also like to use a \"while\" loop as shown below.</p>\n\n<pre><code>function _get_new_positions(source, target) {\n var transform = [], i, j, found, want;\n// convert both strings to arrays - uppercase so we can find the destination without worrying about cases\n source = source.toUpperCase().split('');\n target = target.toUpperCase().split('');\n for(i=0; i&lt;source.length; i++) {\n j = 0;\n found = false;\n want = source[i];\n while((j &lt; target.length) &amp;&amp; !(found = (target[j] == want))){j++}\n if (! found) {\n console.log(\"Cannot find character: \" + want + \" at [i]: \" + i);\n } else {\n console.log(\"Found character: \" + want + \" at [i,j]: \" + i + j);\n target[j] = ''; //blank out the character for future searches\n transform.push([i,j])\n }\n }\n return transform;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T00:59:02.333", "Id": "5140", "Score": "0", "body": "That's a nice improvement over my original design, thanks :-)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T20:26:30.223", "Id": "3400", "ParentId": "3371", "Score": "2" } }, { "body": "<p>It can be simplify by not converting to array using <code>charAt</code>, also using <code>replace</code> to perform the second loop and erasing found matches. Also, the return value can be reduced to an array of ints since the array index tracks the position in the source.</p>\n\n<pre><code>function _get_new_position (source, target){\n source = source.toUpperCase()\n target = target.toUpperCase();\n\n var result = []\n , l = target.length;\n\n while(l--){ // Starting from the end, swaps doubled letters index\n target = target.replace( source.charAt(l) // \n , function (char, index){ // charAt, index\n result.unshift(index); // Add the found offset inverted\n return ' '; // Suppress the char in source\n }); \n }\n return result;\n} \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-28T04:16:28.973", "Id": "4441", "ParentId": "3371", "Score": "1" } } ]
{ "AcceptedAnswerId": "3400", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T03:09:30.280", "Id": "3371", "Score": "1", "Tags": [ "javascript" ], "Title": "Rearrange string to an anagram of the string - get new position, old position values" }
3371
<p>I have some code that I've included in a project I want to release. Here is one such block:</p> <pre><code>NSString *path = nil; if (delegate &amp;&amp; [delegate respondsToSelector:@selector(toolbarAssociatedXibName:)]) { path = [delegate toolbarAssociatedXibName:_toolbar]; if (![[NSBundle mainBundle] pathForResource:path ofType:@"nib"]) { IFLog(@"Delegate responded with an invalid value (%@) for `toolbarAssociatedXibName:`. Attempting default value (%@).", path, _identifier); path = _identifier; } } else { path = _identifier; } </code></pre> <p>The equivalent pseudocode:</p> <pre class="lang-none prettyprint-override"><code>Variable declaration (set to null value) If there is an option to set the variable to a custom value Set it to that custom value If the value is not valid Log the error Set the value to a specified default Otherwise Set the value to a specified default </code></pre> <p>Is it possible to shorten/compact this block of code? I have also tried combining this block into a single line of code, ending up with this:</p> <pre><code>(delegate &amp;&amp; [delegate respondsToSelector:@selector(toolbarAssociatedXibName:)] ? !![[NSBundle mainBundle] pathForResource:[delegate toolbarAssociatedXibName:_toolbar] ofType:@"nib"] ? path = [delegate toolbarAssociatedXibName:_toolbar] : IFLog(@"Delegate responded with an invalid value (%@) for `toolbarAssociatedXibName:`. Attempting default value (%@).", [delegate toolbarAssociatedXibName:_toolbar], _identifier), path = _identifier : path = _identifier); </code></pre> <p>That does absolutely nothing for readability. Any suggestions?</p>
[]
[ { "body": "<p>Maybe you want something like this, (you will also need to log the error though)</p>\n\n<pre><code>(delegate &amp;&amp; [delegate respondsToSelector:@selector(toolbarAssociatedXibName)]) ? path = [delegate toolbarAssociatedXibName:_toolbar] : path = _identifier;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T15:27:19.830", "Id": "5152", "Score": "0", "body": "I went with this approach at first, but the problem is is that this does no checks for validity and does not log any problems..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T13:48:34.167", "Id": "3422", "ParentId": "3373", "Score": "0" } }, { "body": "<p>In the spirit of <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY</a>, how about:</p>\n\n<pre><code>NSString *path = nil;\nif (delegate &amp;&amp; [delegate respondsToSelector:@selector(toolbarAssociatedXibName:)]) {\n path = [delegate toolbarAssociatedXibName:_toolbar];\n if (![[NSBundle mainBundle] pathForResource:path ofType:@\"nib\"]) {\n IFLog(@\"Delegate responded with an invalid value (%@) for `toolbarAssociatedXibName:`. Attempting default value (%@).\", path, _identifier);\n path = nil;\n }\n}\nif (!path) path = _identifier;\n</code></pre>\n\n<p>In your pseudocode:</p>\n\n<pre><code>Variable declaration (set to null value)\nIf there is an option to set the variable to a custom value\n Set it to that custom value\n If the value is not valid\n Log the error\n Set the value back to null\nIf value is null\n Set the value to a specified default\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T18:07:17.497", "Id": "5191", "Score": "0", "body": "Well, that's almost line-for-line the same as my original code, and achieves the same effect. Thanks for the effort, though..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T18:39:51.477", "Id": "5194", "Score": "0", "body": "Agreed; the difference is minor, but you asked about optimizing the style. Oversimplified, you're setting it to A then maybe to B then maybe back to A again. Instead, set it to B, and if that doesn't work, set it to A. Makes it easier to read and would run a tiny bit faster, and in similar cases, avoid any side effects of accessing identifier." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T20:28:30.240", "Id": "5198", "Score": "0", "body": "That's certainly true, but in that case, why not use my original code? Instead of executing another if-statement, just use the else case. That's more of what I'm wondering about." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T20:43:17.153", "Id": "5199", "Score": "0", "body": "Because you still have two separate references to the default case. DRY suggests that anytime you repeat code, find a way to coalesce. My goal in writing code isn't to find the physically shortest code (e.g. your ternary scenario), but the simplest/clearest. Say at some future time, you need to change the default to a different version, then you have to change both places. Again, I certainly acknowledge this is not the most critical example of it, but every little bit helps..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T20:53:58.780", "Id": "5200", "Score": "0", "body": "I see your point." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T13:11:18.113", "Id": "3453", "ParentId": "3373", "Score": "5" } } ]
{ "AcceptedAnswerId": "3453", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T06:34:22.797", "Id": "3373", "Score": "1", "Tags": [ "objective-c", "comparative-review", "delegates", "cocoa" ], "Title": "Setting the path to toolbarAssociatedXibName, with fallback" }
3373
<p>Is there any other way to do this without all the extra outside parens here?</p> <pre><code>((ScheduledTask)(scheduledTasks[intCount])).TaskIntervalType </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T03:53:17.857", "Id": "5035", "Score": "4", "body": "You can drop the parentheses surrounding `scheduledTasks[intCount]` but that's as far as you can go without changing to `as` casting or using local variables..." } ]
[ { "body": "<p>Somewhat better:</p>\n\n<pre><code>(scheduledTasks[intCount] as ScheduledTask).TaskIntervalType\n</code></pre>\n\n<p>Note that the behavior would be somewhat different: The as cast will not throw an exception when not successful, but return <code>null</code> - so you would get a <code>NullReferenceException</code> (when trying to access the property on a <code>null</code> reference) instead of a cast exception.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T03:55:01.253", "Id": "5037", "Score": "9", "body": "Not equivalent statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T03:57:45.340", "Id": "5038", "Score": "0", "body": "If you are sure that that the value is `ScheduledTask` and that it is not null then using `((ScheduledTask)(scheduledTasks[intCount]))` is better form performance than using `as` keyword" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T03:59:49.757", "Id": "5039", "Score": "3", "body": "Indeed, not equivalent. Not only does it throw a `NullReferenceException` instead of an `InvalidCastException` (thus making it harder to debug what went wrong), the `as` operator also doesn't use custom conversions defined by classes which the original does." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T04:03:23.680", "Id": "5040", "Score": "1", "body": "@Sven It does not throw `NullReferenceException`. It simply returns `null`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T04:25:14.507", "Id": "5041", "Score": "2", "body": "The `as` operator itself doesn't throw a `NullReferenceException`, but his code does because it tries to use the result without checking for `null`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T08:40:13.597", "Id": "5144", "Score": "0", "body": "I don't like this code. `as` is for when you're not sure about if what you're casting is of the type you cast to. But in your code it will only work correctly if the cast always succeeds." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-24T10:39:58.520", "Id": "172330", "Score": "0", "body": "You could do a `ScheduledTask.TryParse ()` so you get the output as well as a boolean if you can Parse or not" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T03:53:35.253", "Id": "3375", "ParentId": "3374", "Score": "5" } }, { "body": "<pre><code>var task = (ScheduledTask)scheduledTasks[intCount];\nvar interval = task.TaskIntervalType;\n</code></pre>\n\n<p>You could use the <code>as</code> keyword instead:</p>\n\n<pre><code>var task = scheduledTasks[intCount] as ScheduledTask;\nvar interval = task.TaskIntervalType;\n</code></pre>\n\n<p>but it would change the behaviour of the cast. For one, as noted, it will return <code>null</code> instead of throwing an exception for a failed conversion. For another, it will not perform any custom conversions between types that you might have.</p>\n\n<p>Although with that said, using <code>as</code> is probably better than casting because it behaves in a more consistent and reliable way than a cast.</p>\n\n<p>And with all <em>that</em> said, perhaps the right approach would be to change your array to be strongly typed or expose the TaskIntervalType as a property on an interface or base class? That way casting would not be needed at all.</p>\n\n<p>For example,</p>\n\n<pre><code>public interface ITask\n{\n IntervalType TaskIntervalType { get; }\n}\n\npublic ScheduledTask : ITask\n{}\n\npublic MyStuff()\n{\n List&lt;ITask&gt; scheduledTasks = new List&lt;ITask&gt;();\n // populate the list, etc...\n\n /// ... and back to your example:\n var type = scheduledTasks[intCount].TaskIntervalType;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T04:20:15.647", "Id": "5042", "Score": "0", "body": "If I was a var advocate this would rock. Unfortunately my preference is that I don't like the var keyword. I don't want to get into that debate either but thanks for your post...this is a useful reply to people who are var advocates or willing to embrace var :)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T04:35:54.817", "Id": "5043", "Score": "2", "body": "@CoffeeAddict Nothing I wrote requires you to use `var`. Feel free to replace it with explicit types. :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T03:56:26.640", "Id": "3376", "ParentId": "3374", "Score": "4" } }, { "body": "<p>It could be safer (not sure about the variable names and types):</p>\n\n<pre><code> ScheduledTask Task = scheduledTasks[intCount] as ScheduledTask;\n\n IntervalType TaskType;\n\n if (Task != null)\n {\n TaskType = Task.TaskIntervalType;\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T04:00:22.857", "Id": "3377", "ParentId": "3374", "Score": "0" } } ]
{ "AcceptedAnswerId": "3375", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-25T03:50:44.273", "Id": "3374", "Score": "1", "Tags": [ "c#" ], "Title": "Cleaner Cast Syntax" }
3374
<p>On most my $_post data inputted on my site I use the following php:</p> <pre><code>$example = $_POST['textfield']; $example = strip_tags($example); $example = mysql_real_escape_string($example); </code></pre> <p>And then I would interact with the MySQL database...</p> <p>Is this 'secure' / 'safe'?</p> <p>Any major exploits to the above code?</p> <p>-How could I make it secure?</p> <p>Thanks alot.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T19:01:34.377", "Id": "5051", "Score": "2", "body": "I believe it's considered more secure to do prepared statements using [PDO](http://php.net/manual/en/book.pdo.php)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T00:10:18.970", "Id": "5064", "Score": "2", "body": "Wow @Jared Farrish, I use to do straight PHP->MySQL calls the 'old school' way, but now after you pointed out PDO and I looked into it a bit, it looks quite awesome. Next project I start, I'm using this!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T00:22:00.907", "Id": "5066", "Score": "1", "body": "PDO's a good suggestion, but not necessarily the only game in town. A key principle to extract from the suggestion: Security can't be something you have to remember to do EVERY TIME you write a db interaction (or filter user input for other uses, or whatever). Build your app in such a way that validation/cleansing is automatic and uses the same code every time." } ]
[ { "body": "<p>It doesn't seem like there are any security issues with your code. But like grossvogel said, you shouldn't try to implement security by constantly writing that function every time you have a query, because maybe you'll forget. What I would recommend is that you write a helper function that automatically escapes the input for you. That or you could use prepared statements. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T00:57:31.753", "Id": "3388", "ParentId": "3381", "Score": "0" } }, { "body": "<p>Apart from what has already been mentioned, a crucial part you're missing is a <code>magic_quotes</code> check and taking according action, this means <strong>reversing</strong> all its effects. (unless you do that at the beginning after your script starts).</p>\n\n<p>If enabled, magic_quotes will escape all quotes with a backslash, and each backslash with a backslash.</p>\n\n<p>Read more about <code>magic_quotes</code> <a href=\"http://php.net/manual/en/security.magicquotes.php\" rel=\"nofollow\">here</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T22:34:02.847", "Id": "5105", "Score": "0", "body": "This is a bad idea for a lot of reasons. The first one is stated directly in the link you provided: \"Warning\nThis feature has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.\". Other than that, `magic_quotes` isn't secure at all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T22:43:35.210", "Id": "5106", "Score": "0", "body": "@PiZzL3: I didn't suggest the feature. I suggested being *aware* of it. That's why you need to reverse its effects! \"taking according action\" Maybe I should have made it more clear." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T23:39:56.343", "Id": "5107", "Score": "0", "body": "He's not even using it in his code, so why would that need reversing? You should just say to never use `magic_quotes` and never use `mysql_real_escape_string` (both methods have publicly known flaws and can easily be exploited, even when used together(which can cause more problems and exploits to appear that were previously do-able by themselves)). He should use `PDO` or other methods of using prepared statements, along with very specific custom filtering depending on each data type he's working with (examples: numbers, letters a-z only, etc..)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T23:43:33.710", "Id": "5108", "Score": "0", "body": "\"He's not even using it in his code\" Apparently you don't know what it is. I have never seen anybody using `magic_quotes` in his code... You cannot always control whether `magic_quotes` is enabled or not. That's why your script has to *adapt* and reverse everything `magic_quotes` has done in case it is enabled. Using PDOs does not save you from enabled `magic_quotes`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T08:39:27.967", "Id": "5111", "Score": "0", "body": "@PiZzL3: See, someone in exactly this situation, only a few minutes ago. An ignorant already posted a very rude answer telling him to just disable magic_quotes and use PDO...: http://stackoverflow.com/questions/6661406/best-method-of-disabling-php-magic-quotes-without-php-ini-or-htaccess" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T21:47:24.573", "Id": "3401", "ParentId": "3381", "Score": "-1" } }, { "body": "<p>I recommend getting yourself a simple, simple function that uses PDO and parameterizing of queries by default behind the scenes.</p>\n\n<p>Here are sample use cases for query functions that use PDO in the background that I use all the time:</p>\n\n<pre><code>$iterable_resultset = query('select * from users where email = :email and username ~* :username or user_id = :user_id', array(':email'=&gt;$email, ':username'=&gt;$username, ':user_id'=&gt;(int)$user_id));\n// Results a resultset that is able to be foreached over.\n\n$multidimensional_array = query_array('select * from users where email = :email and username ~* :username or user_id = :user_id', array(':email'=&gt;$email, ':username'=&gt;$username, ':user_id'=&gt;(int)$user_id));\n// Results in a multidimensional array with each subarray corresponding to a database row, or null.\n\n\n$row_of_data = query_row('select * from users limit 1');\n//Results in a single dimensional array or null.\n\n$item = query_item(\"select max(score) from players where username ~* :username\", array(':username'=&gt;$username));\n// Returns a single piece of information, or null.\n</code></pre>\n\n<p>There's a lot of advantage from a refactoring viewpoint to having simple function-based parameterizing of sql queries. PDO is often verbose, and sometimes when you're securing bad code you need simple, terse functions to fit in the place of old <code>mysql_query()</code> calls and the like.</p>\n\n<p>In your specific case, I think that you are making the mistake of escaping before it's time, which can often introduce weird bugs.</p>\n\n<pre><code>$untrusted_input = @$_REQUEST['password'];\n</code></pre>\n\n<p>is all that you should do when getting the input. Don't strip tags, don't do anything until it comes time to <strong>-use-</strong> that untrusted input in sql or in html:</p>\n\n<ul>\n<li>In the sql, parameterize it while using the sql, filter/modify the data based on the circumstances.</li>\n<li>When outputting to html, escape it then, e.g. via <code>.htmlentities($example).</code> or using a templating engine.</li>\n</ul>\n\n<p>Here's an example of your code turning a non-existent get/post variable (that would normally result in <code>null</code>) into an empty string, for just the first of many subtle things that happen when you escape too early: <a href=\"http://ideone.com/r7bSr\" rel=\"nofollow\">http://ideone.com/r7bSr</a></p>\n\n<p>In general, when you're first getting used to the security issues that php can throw your way, I really recommend using a template engine (e.g. smarty) to help you keep your business logic and your display templates separate. A lot of people will argue about whether you need a templating engine with php because php is a templateable system already. Engine or not doesn't matter, but a template-based approach to separate your manipulation logic from your display logic is very necessary, which most programmers would probably agree on. And personally, I found it easier to learn how that separation benefits php when I was first starting out by just learning how a templating engine does things, before I could understand how to apply those principles to native php without a templating engine.</p>\n\n<p>TL;DR; - Set up a templating engine, it'll get you using best practices faster.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T16:39:09.977", "Id": "3565", "ParentId": "3381", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T17:59:48.407", "Id": "3381", "Score": "1", "Tags": [ "php", "mysql", "security" ], "Title": "How could I make this PHP $_POST more secure? -Or is it secure already?" }
3381
<p>I have written the code below and I am trying to work out if there is a more efficient way of doing it: i.e. less lines of code and quicker etc.</p> <p>I am also wondering whether it is OK to declare variables inside of an <code>if</code> ... <code>else if</code> statement.</p> <pre><code>function test() { var x = 3; if (x &gt; 5) { var msg = "m", state = "d"; } else if (x &lt; 5) { var msg = "a", state = "d"; } else { var msg = "e", state = "n"; } $('#id1').removeClass().addClass(state); $('#id2').html("Some text " + msg + " and more text."); $('#id3').attr('title', "Different text " + msg + " still different text."); } </code></pre> <p>As background, the following code is the original code I had before refactoring/rewriting:</p> <blockquote> <pre><code>function test() { var x = 3; if (x &gt; 5) { $('#id1').removeClass().addClass('d'); $('#id2').html("Some text message and more text."); $('#id3').attr('title', "Different text message still different text."); } else if (x &lt; 5) { $('#id1').removeClass().addClass('d'); $('#id2').html("Some text message2 and more text."); $('#id3').attr('title', "Different text message2 still different text."); } else { $('#id1').removeClass().addClass('n'); $('#id2').html("Some text message3 and more text."); $('#id3').attr('title', "Different text message3 still different text."); } } </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-03T15:16:08.510", "Id": "98500", "Score": "1", "body": "Just had a 'collaboration' with Jamal. There is a lot of history on this question, and you're right, the code has not significantly changed, and your edits added more context. To be clear though, if this question was new, it would be closed as 'example code', and 'not real'. I'll restore the question with a few small modifications." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-03T18:22:56.427", "Id": "98564", "Score": "0", "body": "Thanks @rolfl. Just for the record, the code was 'real' code I used in a project. I'd simply reduced it down to the most relevant code for clarity and the benefit of those answering the question, so that it would be easy to read and didn't go on for lines and lines." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-03T18:39:38.300", "Id": "98571", "Score": "0", "body": "You're welcome, but, to be clear, your code, as it stands, can be reduced further because `x` is always `3` ... because the code makes no sense.... it's example code ;-)" } ]
[ { "body": "<p>I don't know what the purpose of declaring your variable within your <code>if</code> statement is supposed to be here. For readability, I would declare those variables at the beginning of your function, like so:</p>\n\n<pre><code>function test() {\n var x = 3, \n msg, \n state;\n if (x &gt; 5) {\n msg = \"m\", state = \"d\";\n } else if (x &lt; 5) {\n msg = \"a\", state = \"d\";\n } else {\n msg = \"e\", state = \"n\";\n }\n $('#id1').removeClass().addClass(state);\n $('#id2').html(\"Some text \" + msg + \" and more text.\");\n $('#id3').attr('title', \"Different text \" + msg + \" still different text.\");\n}\n</code></pre>\n\n<p>That being said, I don't know a reason why you couldn't do so; it most depends on readability and the best practices you are following.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T23:40:40.767", "Id": "5055", "Score": "0", "body": "The idea behind it was simple. I wanted the variable to be different based on the different scenarios. So I thought I should just re/define the variable in each scenario." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T23:43:24.073", "Id": "5056", "Score": "0", "body": "But... How you declare that variable is not important. You'll see that the variable is declared anyways." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T23:46:41.420", "Id": "5057", "Score": "0", "body": "You don't want to be defining your `msg` variable inside the `if` scope because strictly speaking it shouldn't be accessible outside the `if`. Unfortunaely javascript allows us to write code like this, but its not a good idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T23:57:04.657", "Id": "5058", "Score": "0", "body": "@James - Yes, unfortunately JS is more forgiving than that. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T23:57:25.060", "Id": "5059", "Score": "0", "body": "@james and @jared I understand what you are saying. But in this version, when the values are changed in the if else if statement, should they not then both have semicolons after them instead of being seperated by a comma." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T23:59:32.267", "Id": "5060", "Score": "0", "body": "@tw16 - If you're declaring your variables in a single statement, you need to use a comma; a semicolon delimits a statement (meaning end-of-statement)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T00:01:57.787", "Id": "5061", "Score": "0", "body": "@jared - But you aren't declaring the variables any more in the if else if statement. You declared them outside of it. So now aren't you simply changing their value inside the if else if. Should that not be done as two separate lines of code i.e. separated by a semicolon?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T00:05:02.870", "Id": "5062", "Score": "1", "body": "@tw16 - Think about this for a second. If your question is whether or not your value should be set within or before an `if` statement, I think you have just answered your own question - it should be declare your variable and then set it accordingly. While the alternative is certainly possible, the best practice is to declare the (known) variables and then set them before working on them later in your script." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T00:19:37.333", "Id": "5065", "Score": "0", "body": "Ok so as I said earlier. I understand declaring it before the if statement. But then as you can see my function relies on changing the value of the variables depending on different scenarios. The first thing I was asking about your current code is when setting(not declaring) the values in the if statement should they not be seperate lines of code i.e. ended with a semicolon. And then the second thing is - In my main question I did also ask is there a more efficient way to do what I am trying to achieve i.e. another way to achieve this if what I have done is a bad idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T00:24:35.677", "Id": "5067", "Score": "0", "body": "@tw16 - I don't see any benefits to caching a specific or series of specific elements in your code, since you only access them once. Once you have your `if` statement setup, with your variable declarations setup according, what happens after according to your included code should be singular and non-optimizable. If it's otherwise, please post some more specific code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T00:34:41.673", "Id": "5068", "Score": "0", "body": "All I was trying to do was make some code I already had written shorter/better/more efficient etc. If you look at my question now you can now see the original code I had before I rewrote it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T00:39:24.680", "Id": "5069", "Score": "0", "body": "@tw16 - I think you can make this code into a function, which is what you seem to be asking. It's never perfect to every situation, so I suggest going with your gut here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T00:41:59.560", "Id": "5070", "Score": "0", "body": "This is a one off case. I don't intend to use this code in other situations. I am just always looking to learn and improve. So I thought I would see if I could shorten (refactor) my code. So which code is better then? My original code or my 'improved' code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T00:45:31.930", "Id": "5071", "Score": "0", "body": "I would say the *improved* code, but it's not a great improvement unless it's called many times." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T00:46:53.923", "Id": "5072", "Score": "0", "body": "If x=3, how shall it be gt 5 or not less than 5?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T00:48:54.437", "Id": "5073", "Score": "0", "body": "@jared I understand it might not be a huge improvement in the circumstances, but as I said, I am always looking to learn and improve. Which means next time a project comes along I will already have a better idea of where to start.\n\nAnd you cannot see a better way of coding it other than my two versions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T00:51:43.673", "Id": "5074", "Score": "0", "body": "@tw16 - Best practices usually mean you're handling the scenarios that happen to nearly every situation. I can't say that I have covered all of those scenarios, but I would say that until you need better performance, you will probably be ok. Keep in mind that using `count()` in a for loop is considered hazardous..." } ], "meta_data": { "CommentCount": "17", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T22:52:06.567", "Id": "3385", "ParentId": "3382", "Score": "4" } }, { "body": "<p>admittedly readability usually takes a second seat to speed for me (I know a lot of you won't like that), but for me I would probably use some inline logic for smaller, faster code:</p>\n\n<pre><code>function test(){\n var x=3;\n $('#id1').removeClass().addClass((x==5?'n':'d'));\n $('#id2').html(\"Some text \" + (x&lt;5?'a':(x&gt;5?'m':'e')) + \" and more text.\");\n $('#id3').attr('title', \"Different text \" + (x&lt;5?'a':(x&gt;5?'m':'e')) + \" still different text.\");\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-12T21:03:16.397", "Id": "20148", "Score": "1", "body": "there is certainly a lot less of your code than in the other examples. But I think your code is not easily readable or flexible. I loathe encountering code like this. It's just my preference." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-12T22:40:52.413", "Id": "20159", "Score": "0", "body": "Like I said, I know a lot of you wouldn't like this, but I develop social networks almost exclusively and in my experience speed trumps readability as long as you're experienced enough to understand the code you write" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T20:07:38.870", "Id": "3414", "ParentId": "3382", "Score": "0" } } ]
{ "AcceptedAnswerId": "3385", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T19:10:17.863", "Id": "3382", "Score": "2", "Tags": [ "javascript", "jquery", "optimization" ], "Title": "Setting variables inside if / else-if statment blocks" }
3382
<p>I'm on a project involving converting HTML code to HTML5, and I'd like some feedback as to whether my code is correct or not.</p> <p>Here's my stripped-down code:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Page Title Goes Here&lt;/title&gt; &lt;!--[if IE 9]&gt; &lt;script src="/jsp/fileFolderPath/js/html5shiv.js"&gt;&lt;/script&gt; &lt;![endif]--&gt; &lt;link rel="stylesheet" href="/jsp/fileFolderPath/css/global.css"&gt; &lt;!--[if IE 7]&gt; &lt;html class="ie7" lang="en"&gt; &lt;![endif]--&gt; &lt;!--[if IE 8]&gt; &lt;html class="ie8" lang="en"&gt; &lt;![endif]--&gt; &lt;script src="/jsp/fileFolderPath/js/jquery-1.4.2.min.js"&gt;&lt;/script&gt; &lt;script src="/jsp/fileFolderPath/js/jquery.colorbox-min.js"&gt;&lt;/script&gt; &lt;script src="/jsp/fileFolderPath/js/tip.js"&gt;&lt;/script&gt; &lt;script src="/jsp/fileFolderPath/js/jquery.calendar.js"&gt;&lt;/script&gt; &lt;script src="/jsp/fileFolderPath/js/modernizer-2.0.6.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { $('#whatsthis').mouseover(function(){ tooltip.show('Tooltip text goes here'); }).mouseout(function(){ tooltip.hide(); }); $('#printthis').mouseover(function(){ tooltip.show('&amp;lt;strong&amp;gt;Print&amp;lt;/strong&amp;gt;'); }).mouseout(function(){ tooltip.hide(); }).click(function(){ printCalendar(); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- container start --&gt; &lt;div id="container"&gt; &lt;!-- header start --&gt; &lt;header&gt; &lt;figure&gt; &lt;img src="headerImg.png" width="600" height="100" alt="header image"&gt; &lt;/figure&gt; &lt;div class="clear"&gt;&amp;nbsp;&lt;/div&gt; &lt;nav&gt; &lt;!-- header code goes here - this is actually an include file --&gt; &lt;/nav&gt; &lt;/header&gt; &lt;!-- header end --&gt; &lt;nav&gt; &lt;!-- primary navigation start --&gt; &lt;div class="clear"&gt;&amp;nbsp;&lt;/div&gt; test &lt;!-- primary navigation end --&gt; &lt;/nav&gt; &lt;!-- Application Name start --&gt; &lt;div id="applicationName"&gt;mySchedule &lt;a href="#" id="whatsthis"&gt;&lt;img src="images/what-this.png" width="21" height="21" alt=""&gt;&lt;/a&gt; &lt;!-- breadcrumbs start --&gt; &lt;nav&gt; &lt;div id="breadcrumbs"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#MyConnections"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&amp;rarr;&lt;/li&gt; &lt;li&gt;&lt;a href="#Exhibitors"&gt;mySchedule&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/nav&gt; &lt;!-- breadcrumbs end --&gt; &lt;/div&gt; &lt;!-- Application Name end --&gt; &lt;!-- Features Toolbar start --&gt; &lt;div id="features" class="right"&gt; &lt;div class="featuresAddOn"&gt; &lt;a href="#" id="printthis"&gt;Print mySchedule&lt;/a&gt;&lt;/div&gt; &lt;/div&gt; &lt;!-- Features Toolbar end --&gt; &lt;div class="clear"&gt;&amp;nbsp;&lt;/div&gt; &lt;!-- Left Side Bar start --&gt; &lt;div class="left"&gt; &lt;nav&gt; &lt;!-- Application Navigation start --&gt; &lt;div id="appMenuContainer"&gt; &lt;div class="appMenu"&gt; &lt;h4 class="firstitem"&gt;&lt;a href="/jsp/Myclients/Myclients.jsp?action=ClientMyMatchTab"&gt;Client Matching&lt;/a&gt;&lt;/h4&gt; &lt;/div&gt; &lt;div class="appMenu"&gt; &lt;h4 id="MyClient" class="menuitem header"&gt;&lt;span&gt;&lt;a href="/jsp/Myclients/Myclients.jsp"&gt;MyClients&lt;/a&gt;&lt;/span&gt;&lt;/h4&gt; &lt;/div&gt; &lt;div class="appMenu"&gt; &lt;h4 id="MySched" class="menuitem header"&gt; &lt;span&gt;&lt;a style ="cursor:default"&gt;MySchedule&lt;/a&gt;&lt;/span&gt;&lt;/h4&gt; &lt;/div&gt; &lt;div class="appMenu"&gt; &lt;h4 id="MyHel" class="menuitem lastitem"&gt; &lt;span&gt;&lt;a href="/jsp/Myclients/help.jsp"&gt;Help&lt;/a&gt;&lt;/span&gt;&lt;/h4&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Application Navigation end --&gt; &lt;nav&gt; &lt;!-- Alert Box start --&gt; &lt;aside&gt; &lt;div id="AlertBox" class="margin-bottom margin-top"&gt; &lt;div class="title"&gt;Alert&lt;/div&gt; &lt;div class="contentAlert lastItem"&gt; You have &lt;span class="count New_Time"&gt;0&lt;/span&gt; New Time Proposed Notifications. &lt;/div&gt; &lt;/div&gt; &lt;/aside&gt; &lt;!-- Alert Box ends --&gt; &lt;/div&gt; &lt;!-- Left Side Bar end --&gt; &lt;section&gt; &lt;!-- Content --&gt; &lt;div id="calendar"&gt;&lt;/div&gt; &lt;/section&gt; &lt;div class="clear"&gt;&amp;nbsp;&lt;/div&gt; &lt;/div&gt; &lt;!-- container end --&gt; &lt;footer&gt; © MyCompany, Inc. 2011 &lt;/footer&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <ul> <li>Among the requirements of the project are that the website use HTML5, and support IE7, IE8, and IE9.</li> <li>I have more than one nav. <strong>Do each of these require an id?</strong></li> <li>This is one page of several. The content on all of the pages appears within the div id="calendar" tag. This is dynamically replaced depending on the client. This page looks like a calendar/schedule, for which clients can set appointments.</li> <li>I encased the alert box underneath the left side navigation in aside tags. The alert box content is related to the calendar content - it alerts a client if an appointment has been set on the calendar - but wouldn't make sense if it stood on it's own. <strong>Is this use of the aside tag correct in this instance?</strong></li> <li>Regarding the header and footer, previously I had divs that had styles attached to them. Since I removed them, I'll now add the styles to the header and footer tags. <strong>Is that the correct way to do this? If not, where do the styles go?</strong></li> </ul> <p>BTW, I'm a web development contractor brought in on this project. So I'm basically updating existing code.</p> <p>Thanks.</p> <p>Stephen</p>
[]
[ { "body": "<ul>\n<li>give the site heading in a <code>h1</code> (probably in <code>header</code>); if the \"headerImg.png\" is your site name/logo, enclose it in <code>h1</code> instead (and give the site name in <code>alt</code>)</li>\n<li>if your \"headerImg.png\" is a typical site header image, you shouldn't use <code>figure</code></li>\n<li><code>&lt;div class=\"clear\"&gt;&amp;nbsp;&lt;/div&gt;</code> is no good style. You can probably use CSS instead.</li>\n<li>it's not clear to me why you have one <code>nav</code> inside of <code>header</code> <em>and</em> one after. Is the one in <code>header</code> not for major navigation of the site? Then you shouldn't use <code>nav</code> for it</li>\n<li><code>&lt;li&gt;&amp;rarr;&lt;/li&gt;</code>: don't add this on its own <code>li</code> (better use CSS for it)</li>\n<li><code>&lt;div class=\"title\"&gt;Alert&lt;/div&gt;</code>: use a heading instead (you can use <code>h1</code> here)</li>\n<li>you could enclose \"© MyCompany, Inc. 2011\" in a <code>small</code> element (inside of <code>footer</code>)</li>\n</ul>\n\n<p>Is \"applicationName\" some kind of (main) content on the page? In this case you should give a heading here and/or enclose it in a sectioning element (<code>section</code> resp. <code>article</code>). Otherwise the Left Side Bar <code>nav</code> would be in the scope of the whole page.</p>\n\n<p>Because your <code>aside</code> is related to the main content in <code>section</code>, the <code>aside</code> should be inside of that <code>section</code>. At the moment it is related to the whole page.</p>\n\n<hr>\n\n<blockquote>\n <p>I have more than one nav. Do each of these require an id?</p>\n</blockquote>\n\n<p>You don't <em>have</em> to use an <code>id</code> for <code>nav</code>. Only use it if you need/want page anchors (so users can jump to a certain place).</p>\n\n<blockquote>\n <p>Regarding the header and footer, previously I had divs that had styles attached to them. Since I removed them, I'll now add the styles to the header and footer tags. Is that the correct way to do this? If not, where do the styles go?</p>\n</blockquote>\n\n<p>Yes, you can (and probably should) style the elements directly. Only use <code>div</code> for styling if you need to group several elements.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-28T21:59:52.557", "Id": "18020", "ParentId": "3384", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T22:39:57.843", "Id": "3384", "Score": "5", "Tags": [ "html5" ], "Title": "Is the HTML5 code correct?" }
3384
<p>I am working on a Web chat application. In the app, users can run commands (such as /nick, /msg, etc) by starting with a / and then typing the command followed by parameters. For example, if someone wanted to change their username to "foobar", they would enter this in: </p> <pre><code>/whois foobar </code></pre> <p>However, I cannot think of a good way to organize the code for this. This is what I have so far: </p> <p><strong>In User.php</strong></p> <pre><code>function User_command(array $args) { $command = $args['command']; list($command_name, $command_parameters) = explode(' ', $command, 2); $command_name = str_replace('/', '', strtolower($command_name)); $result = Command::process($command_name, $command_parameters); if (!$result) return responseFailure(); addQueueEntry($result['json'], $result['user_id'], $result['room_id'], $result['added_by']); return responseSuccess(); } </code></pre> <p><strong>* In Command.php *</strong></p> <pre><code>class Command { public function process($command, $parameters) { $method = 'MinteCommand_' . $command; if (function_exists($method)) return $method($parameters); return null; } } /* Note: When implementing commands, you must specify all fields for $response */ /* If you don't, then they might not work correctly or as intended. */ function MinteCommand_notice($message) { $response = array(); $response['json'] = array('addChatNotice' =&gt; $message); $response['user_id'] = null; $response['room_id'] = MINTE; $response['added_by'] = SYSTEM; return $response; } function MinteCommand_announce($message) { $response = array(); $response['json'] = array('addChatAnnouncement' =&gt; $message); $response['user_id'] = null; $response['room_id'] = MINTE; $response['added_by'] = SYSTEM; return $response; } function MinteCommand_announcement($message) { // Command "announcement" is an alternative spelling for command "announce" return MinteCommand_announce($message); } function MinteCommand_clear($message) { $response = array(); $response['json'] = array('clearChat' =&gt; $message); $response['added_by'] = SYSTEM; $response['user_id'] = MINTE; $response['room_id'] = null; return $response; } function MinteCommand_whois($username) { $response = array(); $response['added_by'] = 'SYSTEM'; $query = DB::query('SELECT ip_address, user_agent, last_activity, room_id FROM mt_users WHERE username = ? LIMIT 1', $username); $exists = $query['num_rows'] &gt; 0; $ip_address = $user_agent = $last_activity = $room_id = ""; if ($exists) { $row = $query['rows'][0]; $ip_address = $row['ip_address']; $user_agent = $row['user_agent']; $last_activity = $row['last_activity']; $room_id = $row['room_id']; } $response['json'] = array('addChatNotice' =&gt; !$exists ? 'User ' . $username . ' does not exist' : '[' . $username . '] ' . $ip_address . '/' . $user_agent . ', last_activity=' . $last_activity . ', room_id=' . $room_id); $response['added_by'] = SYSTEM; $response['user_id'] = MINTE; $response['room_id'] = null; return $response; } function MinteCommand_msg($args) { list($username, $message) = explode(' ', $args, 2); } </code></pre> <p>How can I go about improving the code and making it more organized and elegant? In total there will be around 30 commands. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T16:27:06.707", "Id": "5354", "Score": "0", "body": "Just a note that you really want to whitelist the possible commands that can match, to be secure." } ]
[ { "body": "<p>Just an idea, but maybe this will help you from a manageability point of view:</p>\n\n<pre><code> public function process($command, $parameters) {\n $method = 'MinteCommand_' . $command; \n $methodFile = dirname(__FILE__) . 'commands/' . $method . \".php\";\n if (file_exists($methodFile)) {\n require_once($methodFile);\n if (function_exists($method)) { \n return $method($parameters); \n } else { \n throw \"invalid function\";\n }\n } else {\n throw \"invalid function file\";\n }\n }\n</code></pre>\n\n<p>The only benefit to this is that you simply create a new file with the new command (function) inside of that file and it'll automatically search for it if the command is issued. One caveat will be the limit on the number of commands you can have is a limit on the number of files you can have in a single directory on the filesystem...</p>\n\n<p><strong>Note</strong> The code may not be perfect from a syntax point of view. It's just to give you the general idea / concept.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T21:58:45.530", "Id": "5103", "Score": "2", "body": "You cannot throw strings." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T05:40:17.117", "Id": "5109", "Score": "0", "body": "It was to provide a general suggestion .. see the **Note** in the post..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T12:57:18.410", "Id": "3391", "ParentId": "3389", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T00:58:41.053", "Id": "3389", "Score": "4", "Tags": [ "php" ], "Title": "Suggestions for improving collection of related PHP functions?" }
3389
<p>I have zones</p> <pre><code>public class Zone { public string Caption { get; set; } public IList&lt;Module&gt; Contents { get; set; } } public class Zone1 : Zone { } public class Zone2 : Zone { } public class Zone3 : Zone { public enum Direction { Up = 1, Down = 2, Left = 3, Right = 4 } public Direction Direction { get; set; } } </code></pre> <p>I have json string <code>[{"Caption":"Tab1","IDs":[4,6]},{"Caption":"Tab2","IDs":[9]}]</code> that corresponds to the regular zones like Zone1,Zone2</p> <p><code>{"Caption":"Tab1","IDs":[4,6]}</code> means that the name of this zone is <strong>Tab1</strong> and it will contain Modules <strong>#4</strong> and <strong>#6</strong>.</p> <p>I have default parser that will create modules according to IDs(4,6 AND 9).</p> <pre><code>public interface IZoneParser&lt;T&gt; { IList&lt;T&gt; Parse(string json); } public abstract class ZoneParserBase : IZoneParser&lt;Zone&gt; { public virtual IList&lt;Zone&gt; Parse(string json) { IList&lt;Zone&gt; zones = new List&lt;Zone&gt;(); try { IList&lt;ZoneJson&gt; parsedZones = json.FromJSON&lt;IList&lt;ZoneJson&gt;&gt;(); foreach (var parsedZone in parsedZones) { var zone = new Zone { Caption = parsedZone.Caption, Contents = new List&lt;Module&gt;() }; foreach (var id in parsedZone.IDs) { var module = currentPage.CreateModule(id); zone.Contents.Add(module); } zones.Add(zone); } return zones; } catch { return null; } } } </code></pre> <p>So, in order to parse the above json I'll need some class like</p> <pre><code>[DataContract] private class ZoneJson { [DataMember] public string Caption { get; set; } [DataMember] public IList&lt;int&gt; IDs { get; set; } } </code></pre> <p>If I'll need to parse Zone3 with json string <code>[{"Caption":"Tab1","IDs":[4,6],"Direction":"1"},{"Caption":"Tab2","IDs":[9]},"Direction":"3"]</code>, so I'll create</p> <pre><code>public class ZoneParserA : ZoneParserBase { publice override IList&lt;Zone3&gt; Parse(string json) { .... IList&lt;Zone3Json&gt; parsedZones = json.FromJSON&lt;IList&lt;Zone3Json&gt;&gt;(); foreach (var parsedZone in parsedZones) { var zone = new Zone3 { Caption = parsedZone.Caption, Direction = parsedZone.Direction, Contents = new List&lt;Module&gt;() }; foreach (var id in parsedZone.IDs) { var module = currentPage.CreateModule(id); zone.Contents.Add(module); } zones.Add(zone); } .... } } </code></pre> <p>and </p> <pre><code>[DataContract] [KnownType(typeof(Direction))] public class Zone3Json : ZoneJson { public Direction Direction { get; set; } } </code></pre> <p>So, for each type of Zone(Zone,Zone1,Zone2,Zone3...) I'll need some kind Zone(X)Json that will differ from Zone(X) just with <code>IList&lt;int&gt; IDs</code> property. I can add this property to <code>class Zone</code>, but I don't want that anybody could access it from outside.</p> <p>In addition, the functionality of method <code>Parse</code> is more or less the same for <code>ZoneParserA</code> and <code>ZoneParserBase</code>. </p> <p>Is there way to avoid Zone(X)Json classes and/or maybe there are any suggestions to rewriting ZoneParsers?</p> <p>I hope I explained myself properly.</p> <p>Thank you</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T13:12:31.437", "Id": "5083", "Score": "0", "body": "Have you tried [gson](http://code.google.com/p/google-gson/)? It will probably work for Zone as well, and if not, you can create custom serializers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T14:28:22.537", "Id": "5090", "Score": "0", "body": "@Nell, butt I still have to crate Zone & ZoneJson, Zone3 & Zone3Json, Zone2 & Zone2Json..., right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T16:00:44.997", "Id": "5094", "Score": "0", "body": "You can, yes, though you can just as easily load everything in a map and use `gson.toJson(map)` to convert it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T18:42:27.727", "Id": "5101", "Score": "0", "body": "@Neil, that's not I want! Currently for every new ZoneX type I'll add I will need to create ZoneXJson class that will be the same as ZoneX but with ONE additional property 'IDs'. And I don't want to \"duplicate\" the classes" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T08:51:08.280", "Id": "5113", "Score": "0", "body": "You can add the IDs to the ZoneX classes and you can hide the conversion to JSON of these IDs by marking it as transient. You can accomplish it in other ways as well if you didn't want to mark it transient." } ]
[ { "body": "<blockquote>\n <p>I can add this property to class Zone, but I don't want that anybody\n could access it from outside.</p>\n</blockquote>\n\n<p>Which 'access' do you have in mind? through JSON (send you a 'fake' direction for zone1,2) or through code?</p>\n\n<p>Either way, I don't think that by not adding it to the Zone class you will improve the security of your solution?</p>\n\n<p>How do you decide on which parser to use when you receive a json string? BTW, your second json string looks wrong to me (the last direction param)</p>\n\n<blockquote>\n <p>[{\"Caption\":\"Tab1\",\"IDs\":[4,6],\"Direction\":\"1\"},{\"Caption\":\"Tab2\",\"IDs\":[9]},\"Direction\":\"3\"]</p>\n</blockquote>\n\n<p>Why do you need Zone1 and Zone2? They're identical so why not simply use Zone? Even your ZoneBaseParser creates Zone objects and has no notion of Zone1 or Zone2.</p>\n\n<p>Maybe you have a predefined set of zones (up to 4) and you need an index. Add an index property, if that's the case.</p>\n\n<p>Your question is interesting but, instead of implementing a solution to the current problem (which would involve reflection), I'd focus on rethinking the json format and the classes and remove the problem altogether.</p>\n\n<p>Quick and easy:</p>\n\n<pre><code>[DataContract] \nprivate class ZoneJson\n{\n [DataMember]\n public int ZoneType { get; set; }//could use an enum instead of int\n [DataMember]\n public int ZoneIndex { get; set; }//if a zone index is needed\n [DataMember]\n public string Caption { get; set; }\n [DataMember]\n public IList&lt;int&gt; IDs { get; set; }\n [DataMember]\n public Direction Direction { get; set; }\n}\n</code></pre>\n\n<p>Or, a more generic approach:</p>\n\n<pre><code>[DataContract] \nprivate class ZoneJson\n{\n [DataMember]\n public int ZoneType { get; set; }//could use an enum instead of int\n [DataMember]\n public int ZoneIndex { get; set; }//if a zone index is needed\n [DataMember]\n public string Caption { get; set; }\n [DataMember]\n public IList&lt;int&gt; IDs { get; set; }\n\n\n //a json string containing additional params\n //might be set for certain ZoneTypes and it's contents can vary, based on ZoneType\n [DataMember]\n public string JsonParams { get; set; }\n}\n</code></pre>\n\n<p>Next, you can add a Zone3Params class to implement the storage for Zone3 params (direction):</p>\n\n<pre><code>[DataContract]\n[KnownType(typeof(Direction))]\npublic class Zone3ParamsJson : ZoneParamsBase\n{ \n [DataMember]\n public Direction Direction { get; set; }\n}\n</code></pre>\n\n<p>and parse any defined zone type like this:</p>\n\n<pre><code>public class ZoneParserBase : IZoneParser&lt;Zone&gt;\n{\n public virtual IList&lt;Zone&gt; Parse(string json)\n {\n IList&lt;Zone&gt; zones = new List&lt;Zone&gt;();\n try\n {\n IList&lt;ZoneJson&gt; parsedZones = json.FromJSON&lt;IList&lt;ZoneJson&gt;&gt;();\n\n foreach (var parsedZone in parsedZones)\n {\n var zone = new Zone\n {\n //don't forget the index and type\n ZoneType = parsedZone.ZoneType,\n Caption = parsedZone.Caption,\n Contents = new List&lt;Module&gt;()\n };\n foreach (var id in parsedZone.IDs)\n {\n var module = currentPage.CreateModule(id);\n zone.Contents.Add(module);\n }\n //parseParams\n if(zone.ZoneType==3)\n {\n var params = parsedZone.JsonParams.FromJSON&lt;Zone3ParamsJson&gt;();\n zone.Params = params;//zone.Params would be something like ZoneParamsBase\n }\n zones.Add(zone);\n }\n\n return zones;\n }\n catch\n {\n return null;\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-07T20:18:20.273", "Id": "4653", "ParentId": "3392", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T13:05:14.800", "Id": "3392", "Score": "6", "Tags": [ "c#" ], "Title": "Is my way for parser written properly?" }
3392
<p>I just completed my first real application (command line app). It's simple, but I had no prior knowledge of Python. Everything was hit and miss, with many Python books and help from those in this community to guide me. Now, I am trying to see where I can refine my code and make things more efficient, as well as become a more efficient Python programmer. I would appreciate any feedback on what I could change, add or eliminate.</p> <pre><code> #!c:\Python27 """ This is a simple command line tool used to extract .tgz and .tar files and perform 3 different type of searches (single file w/ user string, multiple file w/ user string (converted into ascii, hex), and multiple file with re pattern) of .log and .txt files. It also performs ascii, hex, and octal conversion""" import cmd import os import sys, tarfile import time import datetime import re import string import fileinput import os.path class SQAST(cmd.Cmd): from time import strftime #os.system("clear") print strftime("%Y-%m-%d %H:%M:%S") print " *****************************" print " * Company Name *" print " *****************************" prompt = 'sqa@gilbarco &gt;&gt; ' intro = " Security Tool " doc_header = 'Attributes' misc_header = 'misc_header' undoc_header = 'Commands' ruler = '-' COMMANDS = ['ascii', 'files', 'help', 'hex', 'path', 'print', 'exit', 'search'] def do_prompt(self, line): "Change the interactive prompt" self.prompt = line + ': ' def do_hex(self, line): text=raw_input("Enter string to convert: ") #Add exception error handling print "HEX: " + text.encode('hex') def do_octal(self, line): text=raw_input("Enter string to convert: ") #Add exception error handling condint = re.compile(r'[0-9]+') if condint.match(text): convtint = int(text) print "OCTAL: " + oct(convtint) else: print "YOU ENTERED AN INVALID CHARACTER/s!" def do_ascii(self, line): text=raw_input("Enter string to convert: ").strip() #Add exception error handling print "ASCI: " + ' '.join(str(ord(char)) for char in text) def do_files(self, line): path=os.getcwd() #Set log path here dirlist=os.listdir(path) for fname in dirlist: if fname.endswith(('.log','.txt')): print '\n' print fname def do_movefiles(self, line): defaultFolder = "Log_Text_Files" if not defaultFolder.endswith(':') and not os.path.exists('c:\\Extracted \Log_Text_Files'): os.mkdir('C:\\Extracted\\Log_Text_Files') print 'ALL FILES WILL BE MOVED TO c:\Extracted\Log_Text_Files!\n' chPath = raw_input('\nEnter root folder to move all .log and .txt files from ... (eg. c:\Extracted\NameofFolder):\n') try: os.chdir(chPath) except: print "YOU ENTERED INVALID DATA OR AN INVALID PATH ... TRY AGAIN!!!" def print_tgzLogs (arg, dir, files): for file in files: path = os.path.join (dir, file) path = os.path.normcase (path) if path.endswith(".txt") or path.endswith(".log"): if os.path.exists('C:\\Extracted\\Log_Text_Files\\%s' % file): os.remove('C:\\Extracted\\Log_Text_Files\\%s' % file) os.rename(path, 'C:\\Extracted\\Log_Text_Files\\%s' % file) print path os.path.walk(os.getcwd(), print_tgzLogs, 0) def do_path(self, line): print "Current Path: " + os.getcwd() print " " print "(Eg. Windows path: c:\Python, Linux path: /var/opt/crindbios)" print " " changePath = raw_input("Enter new path: ") try: os.chdir(changePath) except: print "YOU ENTERED AN INVALID PATH ... exiting path!" #os.chdir(changePath) print "Current Path: " + os.getcwd() def do_fileExtract(self, line): print "If a CRC error occurs, this usually means that the archived file or some parts thereof is corrupt!\n" defaultFolder = "Extracted" if not defaultFolder.endswith(':') and not os.path.exists('c:\\Extracted'): os.mkdir('c:\\Extracted') raw_input("PLACE .tgz FILES in c:\Extracted AT THIS TIME!!! PRESS ENTER WHEN FINISHED!") else: pass def extract(tar_url, extract_path='.'): print tar_url tar = tarfile.open(tar_url, 'r') for item in tar: tar.extract(item, extract_path) if item.name.find(".tgz") != -1 or item.name.find(".tar") != -1: extract(item.name, "./" + item.name[:item.name.rfind('/')]) userpath = "Extracted" directory = os.path.join("c:\\", userpath) os.chdir(directory) path=os.getcwd() #Set log path here dirlist=os.listdir(path) files = [fname for fname in os.listdir(path) if fname.endswith(('.tgz','.tar'))] for item in enumerate(files): print "%d- %s" % item try: idx = int(raw_input("\nEnter the file's number:\n")) except ValueError: print "You fail at typing numbers." try: chosen = files[idx] except IndexError: print "Try a number in range next time." file_extensions = ('tar', 'tgz') # Edit this according to the archive types you want to extract. Keep in # mind that these should be extractable by the tarfile module. def FileExtension(file_name): """Return the file extension of file 'file' should be a string. It can be either the full path of the file or just its name (or any string as long it contains the file extension.) Examples: input (file) --&gt; 'abc.tar' return value --&gt; 'tar' """ match = re.compile(r"^.*[.](?P&lt;ext&gt;\w+)$", re.VERBOSE|re.IGNORECASE).match(file_name) if match: # if match != None: ext = match.group('ext') return ext else: return '' # there is no file extension to file_name def AppropriateFolderName(folder_name, parent_fullpath): """Return a folder name such that it can be safely created in parent_fullpath without replacing any existing folder in it. Check if a folder named folder_name exists in parent_fullpath. If no, return folder_name (without changing, because it can be safely created without replacing any already existing folder). If yes, append an appropriate number to the folder_name such that this new folder_name can be safely created in the folder parent_fullpath. Examples: folder_name = 'untitled folder' return value = 'untitled folder' (if no such folder already exists in parent_fullpath.) folder_name = 'untitled folder' return value = 'untitled folder 1' (if a folder named 'untitled folder' already exists but no folder named 'untitled folder 1' exists in parent_fullpath.) folder_name = 'untitled folder' return value = 'untitled folder 2' (if folders named 'untitled folder' and 'untitled folder 1' both already exist but no folder named 'untitled folder 2' exists in parent_fullpath.) """ if os.path.exists(os.path.join(parent_fullpath,folder_name)): match = re.compile(r'^(?P&lt;name&gt;.*)[ ](?P&lt;num&gt;\d+)$').match(folder_name) if match: # if match != None: name = match.group('name') number = match.group('num') new_folder_name = '%s %d' %(name, int(number)+1) return AppropriateFolderName(new_folder_name, parent_fullpath) # Recursively call itself so that it can be check whether a # folder named new_folder_name already exists in parent_fullpath # or not. else: new_folder_name = '%s 1' %folder_name return AppropriateFolderName(new_folder_name, parent_fullpath) # Recursively call itself so that it can be check whether a # folder named new_folder_name already exists in parent_fullpath # or not. else: return folder_name def Extract(tarfile_fullpath, delete_tar_file=True): """Extract the tarfile_fullpath to an appropriate* folder of the same name as the tar file (without an extension) and return the path of this folder. If delete_tar_file is True, it will delete the tar file after its extraction; if False, it won`t. Default value is True as you would normally want to delete the (nested) tar files after extraction. Pass a False, if you don`t want to delete the tar file (after its extraction) you are passing. """ tarfile_name = os.path.basename(tarfile_fullpath) parent_dir = os.path.dirname(tarfile_fullpath) extract_folder_name = AppropriateFolderName(tarfile_name[:\ -1*len(FileExtension(tarfile_name))-1], parent_dir) # (the slicing is to remove the extension (.tar) from the file name.) # Get a folder name (from the function AppropriateFolderName) # in which the contents of the tar file can be extracted, # so that it doesn't replace an already existing folder. extract_folder_fullpath = os.path.join(parent_dir, extract_folder_name) # The full path to this new folder. try: tar = tarfile.open(tarfile_fullpath) tar.extractall(extract_folder_fullpath) tar.close() if delete_tar_file: os.remove(tarfile_fullpath) return extract_folder_name except Exception as e: # Exceptions can occur while opening a damaged tar file. print 'Error occured while extracting %s\n'\ 'Reason: %s' %(tarfile_fullpath, e) return def WalkTreeAndExtract(parent_dir): """Recursively descend the directory tree rooted at parent_dir and extract each tar file on the way down (recursively). """ try: dir_contents = os.listdir(parent_dir) except OSError as e: # Exception can occur if trying to open some folder whose # permissions this program does not have. print 'Error occured. Could not open folder %s\n'\ 'Reason: %s' %(parent_dir, e) return for content in dir_contents: content_fullpath = os.path.join(parent_dir, content) if os.path.isdir(content_fullpath): # If content is a folder, walk it down completely. WalkTreeAndExtract(content_fullpath) elif os.path.isfile(content_fullpath): # If content is a file, check if it is a tar file. # If so, extract its contents to a new folder. if FileExtension(content_fullpath) in file_extensions: extract_folder_name = Extract(content_fullpath) if extract_folder_name: # if extract_folder_name != None: dir_contents.append(extract_folder_name) # Append the newly extracted folder to dir_contents # so that it can be later searched for more tar files # to extract. else: # Unknown file type. print 'Skipping %s. &lt;Neither file nor folder&gt;' % content_fullpath if __name__ == '__main__': tarfile_fullpath = chosen # pass the path of your tar file here. extract_folder_name = Extract(tarfile_fullpath, False) # tarfile_fullpath is extracted to extract_folder_name. Now descend # down its directory structure and extract all other tar files # (recursively). extract_folder_fullpath = os.path.join(os.path.dirname(tarfile_fullpath), extract_folder_name) WalkTreeAndExtract(extract_folder_fullpath) # If you want to extract all tar files in a dir, just execute the above # line and nothing else. """try: extract(chosen) print 'Done' except: print ' '""" def complete_files(self, text, line, begidx, endix): if not text: completions = self.COMMANDS[:] else: completions = [f for f in self.COMMANDS if f.startswith(text)] return completions def do_search(self, line): print '\nCurrent dir: '+ os.getcwd() print '\nALL LOG FILES WILL BE CREATED IN: c:\Temp_log_files!' userpath = raw_input("\nPlease enter a path to search (only enter folder name, eg. SQA\log): ") try: directory = os.path.join("c:\\",userpath) os.chdir(directory) except: print "Path name does not exist!!!" print "\n SEARCHES ARE CASE SENSITIVE" print " " line = "[1]Single File [2]Multiple Files [3]STATIC HEX" col1 = line[0:14] col2 = line[15:32] col3 = line[33:46] print " " + col1 + " " + col2 + " " + col3 print '\n' print "\nCurrent Dir: " + os.getcwd() searchType = raw_input("\nSelect type of search: ") if searchType == '1': print "\nFile result1.log will be ceated in c:\Temp_log_files." print "\nFILES:\n" #self.do_files(89) files = [fname for fname in os.listdir(os.getcwd()) if fname.endswith(('.txt','.log'))] for item in enumerate(files): print "%d- %s" % item try: idx = int(raw_input("\nEnter the file's number:\n")) except ValueError: print "You fail at typing numbers." try: chosen = files[idx] except IndexError: print "Try a number in range next time." paths = "c:\\Temp_log_files\\result1.log" temp = file(paths, "w") #logfile = raw_input("\nEnter filename to search (eg. name.log): ") logfile = chosen try: fiLe = open(logfile, "r") except: print "Filename does not exist!!!" userString = raw_input("\nEnter a string name to search: ") for i,line in enumerate(fiLe.readlines()): if userString in line: ln = str(i) print "String: " + userString print "File: " + os.path.join(directory,logfile) print "Line: " + ln temp.write('\nLine:' + ln + '\nString:' + userString + '\nFile: ' + os.path.join(directory,logfile) + '\n') break else: print "%s NOT in %s" % (userString, logfile) fiLe.close() elif searchType =='2': print "\nDirectory to be searched: " + directory print "\nFile result2.log will be created in: c:\Temp_log_files." paths = "c:\\Temp_log_files\\result2.log" temp = file(paths, "w") userstring = raw_input("Enter a string name to search: ") userStrHEX = userstring.encode('hex') userStrASCII = ''.join(str(ord(char)) for char in userstring) regex = re.compile(r"(%s|%s|%s)" % ( re.escape( userstring ), re.escape( userStrHEX ), re.escape( userStrASCII ))) goby = raw_input("Press Enter to begin search (search ignores whitespace)!\n") for root,dirname, files in os.walk(directory): for file1 in files: if file1.endswith(".log") or file1.endswith(".txt"): f=open(os.path.join(root, file1)) for i,line in enumerate(f.readlines()): result = regex.search(line) if result: ln = str(i) pathnm = os.path.join(root,file1) template = "\nLine: {0}\nFile: {1}\nString Type: {2}\n\n" output = template.format(ln, pathnm, result.group()) print output temp.write(output) break else: print "String Not Found in: " + os.path.join(root,file1) temp.write("\nString Not Found: " + os.path.join(root,file1) + "\n") f.close() re.purge() elif searchType =='3': print "\nDirectory to be searched: " + directory print "\nFile result3.log will be created in: c:\Temp_log_files." #directory = os.path.join("c:\\","SQA_log") paths = "c:\\Temp_log_files\\result3.log" temp = file(paths, "w") regex = re.compile(r'(?:3\d){6}') #with file('c:\\Temp_log_file\\result3.log', 'w') as logfile: for root,dirname, files in os.walk(directory): for afile in files: if afile.endswith(".log") or afile.endswith(".txt"): f=open(os.path.join(root,afile)) for i, line in enumerate(f): searchedstr = regex.findall(line) ln = str(i) for word in searchedstr: print "\nString found: " + word print "Line: " + ln print "File: " + os.path.join(root,afile) print " " #logfile = open('result3.log', 'a') temp.write('\nLine:' + ln + '\nString:' + word + '\nFile: ' + os.path.join(root,afile) + '\n') f.close() re.purge() def do_exit(self, line): return True if __name__ == '__main__': SQAST().cmdloop() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T12:45:34.327", "Id": "5085", "Score": "0", "body": "There's something wrong with your indentation. This is not valid python code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T12:51:17.050", "Id": "5086", "Score": "1", "body": "Five level of nested blocks is a scary thing, too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T12:53:17.703", "Id": "5087", "Score": "0", "body": "@itsadok - Maybe I added more or less spaces when adding and making adjustments to abide by code rules on this forum. However, I have no problems with indentation when running the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T13:06:12.787", "Id": "5089", "Score": "0", "body": "I always sort the result of os.walk(), since this makes your programm use the same ordering each time you run it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T16:44:34.927", "Id": "5096", "Score": "3", "body": "@user706808: \"I have no problems with indentation when running the code\". That's irrelevant. The code -- as posted in the question -- cannot possibly work. Please fix it rather than say that some other copy happens to work. We can't see the other copy, can we?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-23T18:25:08.317", "Id": "6489", "Score": "0", "body": "http://stackoverflow.com/questions/4295799/how-to-improve-performance-of-this-code/4299378#4299378" } ]
[ { "body": "<ol>\n<li><p>Your indentation is wrong in the posted code. Please <strong>edit</strong> your question to (a) paste the code then (b) select all the code and (c) click the <code>{}</code> button to get it <em>all</em> indented correctly.</p></li>\n<li><p>A single large class which does everything is a poor design. Each individual \"command\" should be a separate class.</p></li>\n<li><p>Your overall command-line processing loop (<code>SQAST.cmdloop()</code>) should be a separate class which relies on instances of the other command classes. Each of the various <code>do_this()</code> methods would then create an instance of one of the other classes, and then execute a method of that other class.</p>\n\n<p>Yes, it seems like a lot of extra classes. However, breaking the individual commands into separate classes allows you to reuse the commands in other applications without copying and pasting code. Also, making separate classes for each command makes the shared information among the commands absolutely explicit.</p></li>\n<li><p>The stuff done at the class level inside the <code>SQAST</code> class (and outside any of the method functions) is often a Very Bad Idea. Use <code>__init__</code> for this kind of thing.</p></li>\n<li><p>Try to avoid using <code>filename.endswith('.txt')</code>. It's slightly better to use <code>os.splitext</code> to split the name and the extension and then compare the results. <code>base, ext = os.path.splitext(filename)</code>. Yes, it's an extra line of code, but it makes your script slightly more portable to operating systems that might have peculiar file name rules (like Open VMS, for example). </p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T14:08:25.560", "Id": "3394", "ParentId": "3393", "Score": "4" } }, { "body": "<p>Well... first thing I'd do right off is get out an axe (buzz-saw or some other violent tool) and hack this sucker into two programs. A log parser/hex-converter is just plain weird.</p>\n\n<p>Once that's done, learn to use the <a href=\"http://docs.python.org/library/profile.html\" rel=\"nofollow\">python profiler tools</a>, assuming you actually need to improve performance. That will give you some idea where your programs are spending all their time. (I'm assuming you did the chopping in half thing here. ;)</p>\n\n<p>Here's a quick head-start. I wrote this little util when I had to profile a small ftp file gathering utility. Just copy the code and drop it into a file named ShowProf.py:</p>\n\n<pre><code>\"\"\"\nSimple little harness to dump Python profiler data.\n\nBasic usage:\n\n python -m cProfile -o SomeProgram.prof SomeProgram.py -some_args_for_SomeProgram\n\n ShowProf.py SomeProgram.prof | less\n\nor for Windows folks who don't install unix commands on their systems...\n\n ShowProf.py SomeProgram.prof | more\n\"\"\"\nimport pstats\nimport sys\n\np = pstats.Stats(sys.argv[1])\np.strip_dirs().sort_stats(-1).print_stats()\n</code></pre>\n\n<p>Also, take a little time to work through the Python Tutorial in the help files that come with Python. And do a little module browsing. One of the common mistakes newcomers to Python make is to start reinventing the wheel. There are many very useful modules that make Python programming a breeze and a joy.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T15:21:02.557", "Id": "3424", "ParentId": "3393", "Score": "2" } } ]
{ "AcceptedAnswerId": "3394", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T12:35:24.557", "Id": "3393", "Score": "0", "Tags": [ "python", "beginner", "strings", "converting", "console" ], "Title": "Command line tool for extracting, searching, and converting" }
3393
<p>I have a situation where I have to connect to multiple schema to populate a single page.</p> <p>I altered our singleton db class in to help me do this.</p> <p>It will now destroy and re-declare itself whenever we pass a new set of db credential.</p> <p>Will the PHP pros mind code-reviewing this? we do not have code reviews here and this is a pretty big change as it will affect just about everything in our system... so I'm hoping maybe someone here can lend me a second pair of eyes...</p> <p>I'm a bit iffy on the destroy() method, maybe there's a better to do this?</p> <pre><code>&lt;?PHP Class DB{ private static $instance; //instance of db. private $cursor; //connection cursor private $db_user; //db username private $db_pass; //db password private $db_sid; //schema id /** * not allowed to publicly create this. Should be called ONLY from self::get_instance. * Should be the ONLY place where db cursor is set. * * @see self::get_instance($db_user, $db_pass, $db_sid); */ private function __construct($db_user, $db_pass, $db_sid){ $this-&gt;db_user = $db_user ? $db_user : DATABASE_USER; $this-&gt;db_pass = $db_pass ? $db_pass : DATABASE_PASS; $this-&gt;db_sid = $db_sid ? $db_sid : DATABASE_SID; $this-&gt;get_cursor(); } /* * not allowed to publicly clone this. */ public final function __clone(){} /* * retrieves the db connection. */ private function get_cursor(){ if(isset($this-&gt;cursor)){ return true; } $this-&gt;cursor = oci_pconnect($this-&gt;db_user, $this-&gt;db_pass, $this-&gt;db_sid); if($this-&gt;cursor == false){ throw new exception__DBException(); return false; } return true; } /** * THE ONLY PUBLIC METHOD FOR GRABBING DB INSTANCE. * Will automatically self destruct and reconnect with a new connection if new db_user/db_pass@db_sid is passed. * * @param string $db_user * @param string $db_pass * @param string $db_sid * @return db the DB instance. * */ public static function get_instance($db_user, $db_pass, $db_sid){ /* We check if the instance is declared. If not declared we simply create a new DB instance and return. */ if(!(self::$instance instanceof DB)){ self::$instance = new DB($db_user, $db_pass, $db_sid); return self::$instance; } /* If we're here, there must be a db instance already declared. We will check if that instance have the same user/pass@sid as the function params. If not, it means we want to connect to a different DB. We destroy previous connection and reset instance again with new credential. Else we proceed as normal (return instance w/o doing anything). */ if((self::$instance-&gt;get_user() !== $db_user) || (self::$instance-&gt;get_pass() !== $db_pass) || (self::$instance-&gt;get_sid() !== $db_sid)){ self::$instance-&gt;destroy(); self::$instance = new DB($db_user, $db_pass, $db_sid); } return self::$instance; } //unsets cursor, frees resource. private function destroy(){ if(isset($this-&gt;cursor)){ oci_close($this-&gt;cursor); unset($this-&gt;cursor); } } //getters public function get_user(){ return $this-&gt;db_user; } public function get_pass(){ return $this-&gt;db_pass; } public function get_sid(){ return $this-&gt;db_sid; } /** * executes the sql statement. * @param string $statement * @return the result. * */ public function execute_query($statement){ $rows_returned = 0; $result_set = array(); $stmt = oci_parse($this-&gt;cursor, $statement); ocisetprefetch($stmt, 10000); if(oci_execute($stmt)){ while($result = oci_fetch_array($stmt, OCI_ASSOC + OCI_RETURN_NULLS)){ $rows_returned += 1; $result = array_change_key_case($result, CASE_LOWER); $result_set[] = $result; } }else{ throw new exception__DBException(...); } return $result_set; } /** * executes the sql statement with binding vars. * @param string $statement SQL statement * @param array $variables looks like array[binding_key]=variable. * @return the result. */ public function execute_query_by_bind($statement, $variables){ $rows_returned = 0; $result_set = array(); $stmt = oci_parse($this-&gt;cursor, $statement); if(is_array($variables)){ foreach($variables as $key =&gt; $value){ oci_bind_by_name($stmt, ':'.$key, $variables[$key]); } } ocisetprefetch($stmt, 10000); if (oci_execute($stmt)){ while($result = oci_fetch_array($stmt, OCI_ASSOC + OCI_RETURN_NULLS)){ $rows_returned += 1; $result = array_change_key_case($result, CASE_LOWER); $result_set[] = $result; } oci_free_statement($stmt); }else{ throw new exception__DBException(); } return $result_set; } } ?&gt; </code></pre>
[]
[ { "body": "<p>I'm not sure if I necessarily agree with the idea of destroying the singleton and recreating the connection with different credentials. Perhaps there's a specific use-case for this that you have in mind, but I would personally not want to do this.</p>\n\n<p>I once solved an issue that I think is similar to yours. The application had a singleton that controlled access to the database, in a similar manner to your application right now. We received a new requirement that involved us making a new connection to an accounting database on another host. I simply added a new getter method called getAccountsConnection(), which would return a database instance that behaved in a similar fashion with different credentials.</p>\n\n<p>Now, I'm not sure if you'd necessarily call this a \"singleton\" any more, but I felt it was a very clean solution to the issue, and as far as I know, it's still in use today. The important thing to note here is that the two connections would exist at the same time when they were called, and the behaviour of our database layer was to not actually connect until the connection was required.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T21:42:31.920", "Id": "5312", "Score": "0", "body": "Cool, thanks for the reply, I thought about doing this as well, but it's so rare that this happens that I thought I would just keep it as one connection. Also, this class gets called as a part of a report generator that loops over hundreds of schemas and generates hundreds of separate reports sequentially. I organized them so that no two schemas are ever needed at the same time though, to make destroying and reconnecting more efficient, which is part of the reason I kept this as a constant single connection." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T12:42:41.833", "Id": "78740", "Score": "0", "body": "@Steve could you show an example about the `getAccountsConnection()` ?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T18:48:33.853", "Id": "3412", "ParentId": "3402", "Score": "1" } } ]
{ "AcceptedAnswerId": "3412", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T22:05:20.547", "Id": "3402", "Score": "4", "Tags": [ "php", "php5" ], "Title": "Accessing multiple schemas using singleton pattern" }
3402
<p>I have a MySQL database with several columns and two rows of data, so far. I'm using mysql_fetch_assoc to return the data in database, but I don't know how to put it all together in a table so that I can display it in another file.</p> <p>Here is the code of the file that does the process (<code>query.php</code>):</p> <pre><code>&lt;?php // Configure connection settings $db = 'scorecard'; $db_admin = 'root'; $db_password = '********'; $tablename = 'scoreboard'; // Title //echo "&lt;b&gt;DIV!&lt;/b&gt;"; // Connect to DB $sql = mysql_connect("localhost", $db_admin, $db_password) or die(mysql_error()); mysql_select_db("$db", $sql); // Fetch the data $query = "SELECT * FROM $tablename"; $result = mysql_query($query); echo mysql_error(); echo "&lt;table width='100%'&gt;\n"; echo "&lt;tr&gt;\n"; // Return the results, loop through them and echo while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $codcliente = $row['codcliente']; $nombre = $row['nombre']; $ejecutivo = $row['ejecutivo']; $banca_as400 = $row['banca_as400']; $banca_real = $row['banca_real']; $ingresos = $row['ingresos']; $ciiu = $row['ciiu']; $division = $row['division']; $actividad = $row['actividad']; $riesgo_industria = $row['riesgo_industria']; $riesgo_cliente = $row['riesgo_cliente']; $fecha = $row['fecha']; $analista = $row['analista']; echo "&lt;tr&gt;&lt;td&gt;$codcliente&lt;/td&gt;&lt;td&gt;$nombre&lt;/td&gt;&lt;td&gt;$ejecutivo&lt;/td&gt;&lt;td&gt;$banca_as400&lt;/td&gt;&lt;td&gt;$banca_real&lt;/td&gt;&lt;td&gt;$ingresos&lt;/td&gt;&lt;td&gt;$ciiu&lt;/td&gt;&lt;td&gt;$division&lt;/td&gt;&lt;td&gt;$actividad&lt;/td&gt;&lt;td&gt;$riesgo_industria&lt;/td&gt;&lt;td&gt;$riesgo_cliente&lt;/td&gt;&lt;td&gt;$fecha&lt;/td&gt;&lt;td&gt;$analista&lt;/td&gt;&lt;/tr&gt;\n"; echo "&lt;tr&gt;&lt;td&gt;$codcliente&lt;/td&gt;&lt;td&gt;$nombre&lt;/td&gt;&lt;td&gt;$ejecutivo&lt;/td&gt;&lt;td&gt;$banca_as400&lt;/td&gt;&lt;td&gt;$banca_real&lt;/td&gt;&lt;td&gt;$ingresos&lt;/td&gt;&lt;td&gt;$ciiu&lt;/td&gt;&lt;td&gt;$division&lt;/td&gt;&lt;td&gt;$actividad&lt;/td&gt;&lt;td&gt;$riesgo_industria&lt;/td&gt;&lt;td&gt;$riesgo_cliente&lt;/td&gt;&lt;td&gt;$fecha&lt;/td&gt;&lt;td&gt;$analista&lt;/td&gt;&lt;/tr&gt;\n"; echo "&lt;/table&gt;\n"; } </code></pre> <p>And this is the result from the page that displays the process (<code>index.php</code>):</p> <p>CAN'T DISPLAY SINCE I DON'T HAVE ENOUGH REPUTATION POINTS :(</p> <p>As you can see, I have a table already in place and I would like the results to fall below as additional rows, but they come out all squashed together. I've tried several mysql_fetch types, but nothing works. The query results are displayed in a JavaScript DIV that is automatically refreshed by an AJAX script from another file (<code>ajax.js</code>). If you need to see the code for <code>index.php</code> or <code>ajax.js</code>, I could provide it.</p> <p>Thanks!</p>
[]
[ { "body": "<p>Aren't you forgetting something, called <code>&lt;td&gt;</code>?</p>\n\n<p>Try</p>\n\n<pre><code>&lt;?php\n\n// Configure connection settings\n\n$db = 'scorecard';\n$db_admin = 'root';\n$db_password = '********';\n$tablename = 'scoreboard';\n\n// Title\n\n//echo \"&lt;b&gt;DIV!&lt;/b&gt;\";\n\n// Connect to DB\n\n$sql = mysql_connect(\"localhost\", $db_admin, $db_password)\nor die(mysql_error());\n\nmysql_select_db(\"$db\", $sql);\n\n// Fetch the data\n\n$query = \"SELECT * FROM $tablename\";\n$result = mysql_query($query);\necho mysql_error();\n\necho \"&lt;table width='100%'&gt;\\n\";\n\n// Return the results, loop through them and echo\n\nwhile($row = mysql_fetch_assoc($result))\n{\n echo '&lt;tr&gt;'.\"\\n\";\n echo \"&lt;td&gt;{$row['codcliente']}&lt;/td&gt;\\n\" . \"&lt;td&gt;{$row['nombre']}&lt;/td&gt;\\n\" . \"&lt;td&gt;{$row['ejecutivo']}&lt;/td&gt;\\n\" . \"&lt;td&gt;{$row['banca_as400']}&lt;/td&gt;\\n\" . \"&lt;td&gt;{$row['banca_real']}&lt;/td&gt;\\n\" . \"&lt;td&gt;{$row['ingresos']}&lt;/td&gt;\\n\" . \"&lt;td&gt;{$row['ciiu']}&lt;/td&gt;\\n\" . \"&lt;td&gt;{$row['division']}&lt;/td&gt;\\n\" . \"&lt;td&gt;{$row['actividad']}&lt;/td&gt;\\n\" . \"&lt;td&gt;{$row['riesgo_industria']}&lt;/td&gt;\\n\" . \"&lt;td&gt;{$row['riesgo_cliente']}&lt;/td&gt;\\n\" . \"&lt;td&gt;{$row['fecha']}&lt;/td&gt;\\n\" . \"&lt;td&gt;{$row['analista']}&lt;/td&gt;\\n\";\n\n echo '&lt;/tr&gt;'.\"\\n\";\n}\n\necho \"&lt;/table&gt;\\n\";\n\n?&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T12:44:55.507", "Id": "5123", "Score": "0", "body": "Hi @maz...I actually didn't forget, I posted a fork on my original code, sorry. I edited the question to reflect what I had before, since I can't paste it in the comment box." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T12:53:55.510", "Id": "5124", "Score": "0", "body": "it works! All I have to do now is get it to align it with the headers in the `index.php` table. Thanks!\n\nP.S. Can you tell me what I was doing wrong? (look at updated code)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T19:11:13.603", "Id": "5128", "Score": "0", "body": "You should look up how to format tables, I put a td around each cell, and a tr around each row, whereas you just had a tr around the entire thing. http://www.w3schools.com/html/html_tables.asp" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T19:52:54.550", "Id": "5129", "Score": "0", "body": "Thanks @maz, I had tried several ways to generate the table, but I had never used the `.\"\\n\"` in the rows or the `\\n\" .` in the cells. Don't know if that made a difference. When I did it my way, it would return the first row in the DB formatted and the second squashed together." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T20:01:49.063", "Id": "5131", "Score": "0", "body": "That is just so the code formatted more clearly (when you view the source), and isn't needed at all, the big difference were the `<td>`s surrounding each field, and the `<tr>` inside the loop." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T06:37:45.233", "Id": "3406", "ParentId": "3405", "Score": "1" } } ]
{ "AcceptedAnswerId": "3406", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T04:19:20.703", "Id": "3405", "Score": "0", "Tags": [ "mysql", "php5", "ajax" ], "Title": "How can I display the results of mysql_fetch_assoc in a dynamic table?" }
3405
<p>I am developing a high level OpenCL binding in Haskell, and I need peer-review and testing. It currently only gets platform and device info from OpenCL.</p> <p>I have lots of functions that only change the returned type and the size of the type passed to the C library, but I don't know how to fix it.</p> <p><a href="http://github.com/zhensydow/opencl" rel="nofollow">GitHub</a></p> <pre><code>getDeviceInfoUlong :: CLDeviceInfo_ -&gt; CLDeviceID -&gt; IO (Either CLError CLulong) getDeviceInfoUlong infoid device = alloca $ \(dat :: Ptr CLulong) -&gt; do whenSuccess (raw_clGetDeviceInfo device infoid size (castPtr dat) nullPtr) $ peek dat where size = fromIntegral $ sizeOf (0::CLulong) getDeviceInfoSizet :: CLDeviceInfo_ -&gt; CLDeviceID -&gt; IO (Either CLError CSize) getDeviceInfoSizet infoid device = alloca $ \(dat :: Ptr CSize) -&gt; do whenSuccess (raw_clGetDeviceInfo device infoid size (castPtr dat) nullPtr) $ peek dat where size = fromIntegral $ sizeOf (0::CSize) </code></pre>
[]
[ { "body": "<p>Looking through the code, I see often the \"high level wrapper\" returns CLuints and such. I would say that is improper - Why not return the haskell type?</p>\n\n<p>Instead of returning, say, CLint, do</p>\n\n<pre><code>f :: Integral i =&gt; ... -&gt; i\n</code></pre>\n\n<p>so that the user doesn't have to litter his code with those types and fromIntegrals all over the place.</p>\n\n<p>Also, don't leave commented code in the repository. You can always recover via git if you need to.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T17:09:11.837", "Id": "5216", "Score": "0", "body": "In that case I return the same type that the C function, I convert things like enums, unsigned with flags and so on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T14:59:25.247", "Id": "5303", "Score": "0", "body": "I completed the library, and changed some of the Integral types, and it same to be better." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T15:55:56.920", "Id": "3443", "ParentId": "3407", "Score": "5" } } ]
{ "AcceptedAnswerId": "3443", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T09:12:20.820", "Id": "3407", "Score": "6", "Tags": [ "haskell", "opencl" ], "Title": "New Haskell package: OpenCL" }
3407
<p>I have this coding and I think it works. However, I would like to understand if there is a better way to do this. This would automatically create new textboxes or delete them based on the given selected number.</p> <pre><code>&lt;script&gt; var OLD_CASE_NUMBER = 1; $("#cornercases").ready(function () { CORNER_CASE_LOADING(); }); $("#cornercases").change(function () { CORNER_CASE_LOADING(); }); // FUNCTIONLITY TO CREATE THE DOWNDOWN MENUS function CORNER_CASE_LOADING() { var topvalue = $('#cornercases').val(); var counter = 0; var newvalue = parseInt(OLD_CASE_NUMBER) + 1; // ADD MORE VALUES IN CASE if (parseInt(topvalue) == 1 &amp;&amp; parseInt(OLD_CASE_NUMBER) == 1) { var counter = 1; var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter); newTextBoxDiv.html('&lt;label&gt;Textbox #'+ counter + ' : &lt;/label&gt;&lt;input type="text" name="textbox' + counter + '" id="textbox' + counter + '" value="" &gt;'); newTextBoxDiv.appendTo("#div_selection_section"); } if (newvalue &lt;= topvalue) { for (counter=newvalue;counter&lt;=topvalue;counter++) { var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv' + counter); newTextBoxDiv.html('&lt;label&gt;Textbox #'+ counter + ' : &lt;/label&gt;&lt;input type="text" name="textbox' + counter + '" id="textbox' + counter + '" value="" &gt;'); newTextBoxDiv.appendTo("#div_selection_section"); } } else if (parseInt(OLD_CASE_NUMBER) &gt; parseInt(topvalue)) { for (counter=10;counter&gt;topvalue;counter--) { $("#TextBoxDiv" + counter).remove(); } } OLD_CASE_NUMBER = topvalue; } &lt;/script&gt; &lt;select id=cornercases name=cornercases&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;option value="3"&gt;3&lt;/option&gt; &lt;option value="4"&gt;4&lt;/option&gt; &lt;option value="5"&gt;5&lt;/option&gt; &lt;option value="6"&gt;6&lt;/option&gt; &lt;option value="7"&gt;7&lt;/option&gt; &lt;option value="8"&gt;8&lt;/option&gt; &lt;option value="9"&gt;9&lt;/option&gt; &lt;option value="10"&gt;10&lt;/option&gt; &lt;/select&gt; &lt;div id='div_selection_section'&gt;&lt;/div&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T19:06:22.767", "Id": "5134", "Score": "1", "body": "this might be more appropriate for the code review exchange." } ]
[ { "body": "<pre><code>$(document.createElement('div')). ...\n</code></pre>\n\n<p>is the same as:</p>\n\n<pre><code>$('&lt;DIV&gt;&lt;/DIV&gt;'). ....\n</code></pre>\n\n<hr>\n\n<p>you can just build uppon your previus jQuery statements:</p>\n\n<pre><code>$('&lt;DIV&gt;&lt;/DIV&gt;')\n .attr('id','lol')\n .html('hey hey')\n .appendTo(\"#div_selection_section\");\n</code></pre>\n\n<hr>\n\n<pre><code>$(\"#cornercases\").change(function () {\n CORNER_CASE_LOADING();\n });\n</code></pre>\n\n<p>is the same as:</p>\n\n<pre><code>$(\"#cornercases\").change(CORNER_CASE_LOADING);\n</code></pre>\n\n<p>and you can bind 2 events in one with jQuery so:</p>\n\n<pre><code>$(\"#cornercases\").bind(\"change ready\",CORNER_CASE_LOADING)\n</code></pre>\n\n<hr>\n\n<p>you might want to \nparsInt topvalue in the line with te var</p>\n\n<pre><code>var topvalue = parseInt($('#cornercases').val());\n</code></pre>\n\n<p>you will not need to repeat pareInt in each 'if' if you do that.</p>\n\n<p>Also, I see that \n<code>OLD_CASE_NUMBER</code> is an integer (and if you do what is mesioned above), you won't need to parse that either</p>\n\n<hr>\n\n<p>as far as I see the second line of your function <code>var counter = 0;</code> is useless, because everywhere you use counter you first set it to something else</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T15:15:25.783", "Id": "5136", "Score": "0", "body": "the thing that blew my mind is the bind 2 events in one!!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T19:23:49.497", "Id": "3416", "ParentId": "3415", "Score": "3" } } ]
{ "AcceptedAnswerId": "3416", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-11T19:04:04.787", "Id": "3415", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Adding/remving dynamically text boxes" }
3415
<p>I've just written two new headers: one that integrates Box2D and SFML by a class called <code>BodyRep</code> which creates/ is a graphic representation of any body, and one that produces huge amounts of uniform shapes, as to reduce copy/pasting. </p> <p>Things I'm worried about:</p> <ul> <li><strong>Performance:</strong> very important here considering this is based on a physics engine.</li> <li><strong>Memory-management</strong>: using the least amount of memory possible. <ul> <li>More specifically, the <code>ShapeFactory</code> constructor, as I think I might be creating another body rep object by accident (the extra body parameter, which needs to be added, makes things a bit more tricky).</li> </ul></li> </ul> <p><strong>SFboxML.h</strong> </p> <pre><code>#ifndef SFboxML_H #define SFboxML_H #include &lt;Box2D.h&gt; #include &lt;SFML\Graphics.hpp&gt; #include &lt;SFML\System.hpp&gt; #include &lt;vector&gt; # define M_PI 3.14159265358979323846 float ConvToRad(float Angle){return (Angle* M_PI)/ 180;}; float ConvToDeg(float Radian){return (Radian*180)/M_PI;}; float32 ConvToB2(float Angle){return -ConvToRad(Angle);}; float ConvToSFML(float Radian){return -ConvToDeg(Radian);}; namespace sb{ class BodyRep : public sf::Body { private: b2Body* m_b2Body; public: BodyRep(b2Body* Body, sf::Color Color = sf::Color(255,255,255,255)): m_b2Body(Body){ //TODO: add other params like color //Iterate through all the fixtures for (b2Fixture* fixture = Body-&gt;GetFixtureList(); fixture; fixture = fixture-&gt;GetNext()){ signed short shapeType = fixture-&gt;GetType(); sf::Shape TempShape; // Circle shape if(shapeType == b2Shape::e_circle){ b2CircleShape* circleShape = (b2CircleShape*)fixture-&gt;GetShape(); TempShape = sf::Shape::Circle(sf::Vector2f(0,0), circleShape-&gt;m_radius*30, Color); } // Polygon Shape else if(shapeType == b2Shape::e_polygon){ b2PolygonShape* polygonShape = (b2PolygonShape*)fixture-&gt;GetShape(); for(unsigned short I=0; I&lt;polygonShape-&gt;GetVertexCount(); I++){ TempShape.AddPoint( polygonShape-&gt;GetVertex(I).x*30, polygonShape-&gt;GetVertex(I).y*30); } } //Defaults TempShape.EnableFill(true); TempShape.SetColor(Color); AddShape(TempShape); } }; void Draw(sf::RenderWindow&amp; target){ SetPosition(m_b2Body-&gt;GetPosition().x*30, m_b2Body-&gt;GetPosition().y*30); SetRotation(ConvToSFML(m_b2Body-&gt;GetAngle())); sf::Body::Draw(target); }; //TODO: make other functions and redo everything once // i've made the SFML body class }; }// namespace sb // TODO: sync the sfml shape and box2d polygon's centers.e #endif </code></pre> <p><strong>ShapeFactory.h</strong></p> <pre><code>#ifndef SHAPE_FACTORY_H #define SHAPE_FACTORY_H #include &lt;Box2D.h&gt; #include &lt;SFML\Graphics.hpp&gt; #include &lt;SFML\System.hpp&gt; #include &lt;vector&gt; #include &lt;My\SFboxML.h&gt; namespace my{ class ShapeFactory { protected: std::vector&lt;b2Body*&gt; Bodies; std::vector&lt;sb::BodyRep*&gt; GraphicReps; std::vector&lt;b2FixtureDef&gt; FixDefs; b2BodyDef BodyDef; b2World* World; unsigned int numb_bodies; public: void Draw(sf::RenderWindow&amp; target){ for(unsigned int I=0; I&lt; numb_bodies; I++) GraphicReps[I]-&gt;Draw(target); }; void Create(unsigned int numbBods){ for(unsigned int I=0; I&lt; numbBods; I++){ // Make another body in World. Bodies.push_back(World-&gt;CreateBody(&amp;BodyDef)); // Add the fixtures to the body. for(unsigned short i=0; i&lt;FixDefs.size(); i++) Bodies[I]-&gt;CreateFixture(&amp;FixDefs[i]); //Create Graphical rep. TODO: add coloring/ other visual options GraphicReps.push_back(new sb::BodyRep(Bodies[I])); numb_bodies++;} }; ////////////////////////// Constructors ///////////////////////////////////////////////////////////////////////////// ShapeFactory(b2World&amp; world, b2BodyDef&amp; bodyDef, b2FixtureDef&amp; fixtureDef, unsigned int numb){ World= &amp;world; BodyDef=bodyDef; FixDefs.push_back(fixtureDef); //TODO: make more than 1 fix possible numb_bodies=0; Create(numb); }; ShapeFactory(b2Body* Body, unsigned int numb){ // Set the world World= Body-&gt;GetWorld(); // Make the body def BodyDef.active= Body-&gt;IsActive(); BodyDef.angle= Body-&gt;GetAngle(); BodyDef.angularDamping= Body-&gt;GetAngularDamping(); BodyDef.angularVelocity= Body-&gt;GetAngularVelocity(); BodyDef.awake= Body-&gt;IsAwake(); BodyDef.bullet= Body-&gt;IsBullet(); BodyDef.fixedRotation= Body-&gt;IsFixedRotation(); BodyDef.inertiaScale= Body-&gt;GetInertia(); BodyDef.linearDamping= Body-&gt;GetLinearDamping(); BodyDef.linearVelocity= Body-&gt;GetLinearVelocity(); BodyDef.position= Body-&gt;GetPosition(); BodyDef.type= Body-&gt;GetType(); BodyDef.userData= Body-&gt;GetUserData(); // Make the fixture defs b2FixtureDef FixtureDef; for (b2Fixture* fixture = Body-&gt;GetFixtureList(); fixture; fixture = fixture-&gt;GetNext()){ FixtureDef.density = fixture-&gt;GetDensity(); FixtureDef.filter= fixture-&gt;GetFilterData(); FixtureDef.friction= fixture-&gt;GetFriction(); FixtureDef.isSensor= fixture-&gt;IsSensor(); FixtureDef.restitution= fixture-&gt;GetRestitution(); FixtureDef.shape= fixture-&gt;GetShape(); //TODO: make sure the specific shape vertexes pass in too FixtureDef.userData= fixture-&gt;GetUserData(); FixDefs.push_back(FixtureDef);} // Deal with the used Body Bodies.push_back(Body); GraphicReps.push_back(new sb::BodyRep(Bodies[0])); numb_bodies++; // Generate the Body in the world, add fixtures, make a graphical rep. numb_bodies=1; Create(numb); }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// }; // ShapeFactory }// namespace my #endif </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-19T17:52:13.373", "Id": "450241", "Score": "1", "body": "Can you please provide code that would use these headers as an example, or provide test cases for it." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T05:45:56.660", "Id": "3418", "Score": "3", "Tags": [ "c++", "performance", "memory-management", "sfml" ], "Title": "Integrating SFML and Box2D lib, and a Mass Production Shape Factory" }
3418
<p>How can I improve this code ? It takes an infinite time if i want to create un big maze (arguments 5000 5000 100 50 100)</p> <p>main.c</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; #include "maze.h" /*test: valgrind --show-reachable=yes --leak-check=full -v ./dungeon 50 50 100 50 100*/ int main(int argc, char *argv[]) { int maxx; int maxy; int randomness; int sparseness; int deadendremoval; if (argc != 6) { fprintf(stderr, "Five arguments needed =&gt; X, Y, randomness, sparseness, dead-end-removal\n"); return EXIT_FAILURE; } maxx = atoi(argv[1]); maxy = atoi(argv[2]); randomness = atoi(argv[3]); sparseness = atoi(argv[4]); deadendremoval = atoi(argv[5]); if (randomness &lt; 0 || randomness &gt; 100) { fprintf(stderr, "Randomness must be between 0 and 100.\n"); return EXIT_FAILURE; } if (sparseness &lt; 0 || sparseness &gt; 100) { fprintf(stderr, "Sparseness must be between 0 and 100.\n"); return EXIT_FAILURE; } if (deadendremoval &lt; 0 || deadendremoval &gt; 100) { fprintf(stderr, "Dead-end-removal must be between 0 and 100.\n"); return EXIT_FAILURE; } createmaze(maxx, maxy, randomness, sparseness, deadendremoval); return EXIT_SUCCESS; } </code></pre> <p>maze.c The most important file, algorithm is here:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; #include "maze.h" #include "deadend.h" #define visitCell(x, y) map[x][y].visited = 1; /* take a random cell wich is not visited */ void visitRand(int *px, int *py, int maxx, int maxy, struct cell **map) { int x, y; do { x = rand()%(maxx-1); y = rand()%(maxy-1); } while (map[x][y].visited != 0); visitCell(x, y); *px = x; *py = y; } /* take a random cell wich is already visited */ void visitRandVisited(int *px, int *py, int maxx, int maxy, struct cell **map) { int x, y; do { x = rand()%(maxx-1); y = rand()%(maxy-1); } while (map[x][y].visited != 1); *px = x; *py = y; } /* test if all the cells are visited */ int testEndMaze(int maxx, int maxy, struct cell **map) { int x, y; for (y = 0; y &lt; maxy; y++) { for (x = 0; x &lt; maxx; x++) { if (map[x][y].visited == 0) return 1; } } return 0; } /* select a direction, randomness determine the chance of the same direction that the last used (prevdir) */ int newDir(int x, int y, int maxx, int maxy, int prevdir, int randomness, struct cell **map) { int N = 0; int S = 0; int E = 0; int W = 0; int dir = -1; int tdir; if ((x == 0) || (map[x-1][y].visited == 1)) W = 1; if ((y == 0) || (map[x][y-1].visited == 1)) N = 1; if ((x == (maxx - 1)) || (map[x+1][y].visited == 1)) E = 1; if ((y == (maxy - 1)) || (map[x][y+1].visited == 1)) S = 1; if (N == 1 &amp;&amp; S == 1 &amp;&amp; E == 1 &amp;&amp; W == 1) return -1; tdir = rand()%100; if (tdir &lt; randomness) { if ((prevdir == north &amp;&amp; N != 1) || (prevdir == south &amp;&amp; S != 1) || (prevdir == east &amp;&amp; E != 1) || (prevdir == west &amp;&amp; W != 1)) { return prevdir; } } do { tdir = rand()%4; if (tdir == north &amp;&amp; N == 0) dir = north; else if (tdir == south &amp;&amp; S == 0) dir = south; else if (tdir == east &amp;&amp; E == 0) dir = east; else if (tdir == west &amp;&amp; W == 0) dir = west; } while (dir == -1); return dir; } /* select a direction for diging, with randomness */ int newDirdig(int x, int y, int maxx, int maxy, int prevdir, int randomness, struct cell **map) { int N = 0; int S = 0; int E = 0; int W = 0; int dir = -1; int tdir; if ((x == 0) || (map[x][y].wallW == 0)) W = 1; if ((y == 0) || (map[x][y].wallN == 0)) N = 1; if ((x == (maxx - 1)) || (map[x][y].wallE == 0)) E = 1; if ((y == (maxy - 1)) || (map[x][y].wallS == 0)) S = 1; /* Letters are at 1 if we can't take the direction associated */ /* do we chose the last dir used ? */ tdir = rand()%100; if (tdir &lt; randomness) { if ((prevdir == north &amp;&amp; N != 1) || (prevdir == south &amp;&amp; S != 1) || (prevdir == east &amp;&amp; E != 1) || (prevdir == west &amp;&amp; W != 1)) { return prevdir; } } do { tdir = rand()%4; if (tdir == north &amp;&amp; N == 0){ dir = north;} else if (tdir == south &amp;&amp; S == 0) dir = south; else if (tdir == east &amp;&amp; E == 0) dir = east; else if (tdir == west &amp;&amp; W == 0) dir = west; } while (dir == -1); return dir; } /* count the number of walls in a cell */ int countwall(int x, int y, struct cell **map, int dig) { int count = 0; if (map[x][y].wallN) count ++; if (map[x][y].wallS) count ++; if (map[x][y].wallE) count ++; if (map[x][y].wallW) count ++; if(dig) return (count == 3); /* if we are diging, we count 3 and 4 walls cells, but only 3 walls cells if we list the dead end */ return (count &gt;= 3); } /* calcul the percentage of the map that must not be a part of the maze */ int sparcount(int sparseness, int maxx, int maxy) { return ((sparseness * maxx * maxy) / 100); } /* calcul the number of unvisited cells */ int freecasecount(int maxx, int maxy, struct cell **map) { int x, y; int count = 0; for (x = 0; x &lt; maxx; x++) { for (y = 0; y &lt; maxy; y++) { if (map[x][y].visited == 0) count++; } } return count; } /* remove the dead end (3 walls cell) */ void deldeadend(int maxx, int maxy, struct deadend *liste, struct cell **map) { while (liste) { map[liste-&gt;x][liste-&gt;y].visited = 0; if (map[liste-&gt;x][liste-&gt;y].wallN == 0) { map[liste-&gt;x][liste-&gt;y].wallN = 1; if (liste-&gt;y != 0) { map[liste-&gt;x][liste-&gt;y-1].wallS = 1; } } else if (map[liste-&gt;x][liste-&gt;y].wallE == 0) { map[liste-&gt;x][liste-&gt;y].wallE = 1; if (liste-&gt;x != maxx-1) { map[liste-&gt;x+1][liste-&gt;y].wallW = 1; } } else if (map[liste-&gt;x][liste-&gt;y].wallS == 0) { map[liste-&gt;x][liste-&gt;y].wallS = 1; if (liste-&gt;y != maxy-1) { map[liste-&gt;x][liste-&gt;y+1].wallN = 1; } } else if (map[liste-&gt;x][liste-&gt;y].wallW == 0) { map[liste-&gt;x][liste-&gt;y].wallW = 1; if (liste-&gt;x != 0) { map[liste-&gt;x-1][liste-&gt;y].wallE = 1; } } liste = liste-&gt;next; } } /* list all the deadend */ void deadendshow(int maxx, int maxy, struct cell **map) { struct deadend *liste = NULL; int x, y; for (x = 0; x &lt; maxx; x++) { for (y = 0; y &lt; maxy; y++) { if (countwall(x, y, map, 0)) addend(&amp;liste, x, y); } } deldeadend(maxx, maxy, liste, map); dellist(&amp;liste); } /* choose if a corridor is a dead end or if we have to dig in the map */ int dodig(int deadendremoval) { return ((rand()%100) &lt; deadendremoval); } /* dig in the map */ void digin(int maxx, int maxy, int randomness, int deadendremoval, struct cell **map) { struct deadend *liste = NULL; struct deadend *run = NULL; int x, y; int prevdir; int dir; for (x = 0; x &lt; maxx; x++) { for (y = 0; y &lt; maxy; y++) { if (countwall(x, y, map, 1)) addend(&amp;liste, x, y); } } run = liste; /* while there are items in the list, decide if we let the cells or if we dig for creating a loop */ while (run) { if (dodig(deadendremoval)) { prevdir = -1; x = run-&gt;x; y = run-&gt;y; while (countwall(x, y, map, 1)) { visitCell(x, y); dir = newDirdig(x, y, maxx, maxy, prevdir, randomness, map); switch (dir) { case north: prevdir = north; map[x][y].wallN = 0; y--; map[x][y].wallS = 0; break; case south: prevdir = south; map[x][y].wallS = 0; y++; map[x][y].wallN = 0; break; case east: prevdir = east; map[x][y].wallE = 0; x++; map[x][y].wallW = 0; break; case west: prevdir = west; map[x][y].wallW = 0; x--; map[x][y].wallE = 0; break; } } } run = run-&gt;next; } dellist(&amp;liste); } /* initialize the map */ void clearmaze(int maxx, int maxy, struct cell **map) { int x, y; for (y = 0; y &lt; maxy; y++) { for (x = 0; x &lt; maxx; x++) { map[x][y].visited = 0; map[x][y].wallN = 1; map[x][y].wallS = 1; map[x][y].wallE = 1; map[x][y].wallW = 1; } } } /* write the maze in a file named donjon */ void writedungeon(int maxx, int maxy, struct cell **map) { FILE *donjon = NULL; int x, y; donjon = fopen("donjon", "w"); if (donjon == NULL) { fprintf(stderr, "Error while writing the map.\n"); } fputc(' ', donjon); for (x = 0; x &lt; maxx; x++) { fputs("_ ", donjon); } fputc('\n', donjon); for (y = 0; y &lt; maxy; y++) { fputc('|', donjon); for (x = 0; x &lt; maxx; x++) { if (map[x][y].visited == 0){ fputc('X', donjon); fputc('|', donjon); } else { if (map[x][y].wallS == 1) fputc('_', donjon); else fputc(' ', donjon); if (map[x][y].wallE == 1) fputc('|', donjon); else fputc(' ', donjon); } } fputc('\n', donjon); } fclose(donjon); } /* main algorithm */ int createmaze(int maxx, int maxy, int randomness, int sparseness, int deadendremoval) { struct cell **map; int dir = -1; int x, y = 0; int spar, i = 0; int prevdir; /* initialisation */ map = malloc(maxx * sizeof(struct cell*)); if(map == NULL) { fprintf(stderr,"Allocation impossible"); exit(EXIT_FAILURE); } for (x = 0; x &lt; maxx; x++) { map[x]=(struct cell *)malloc(maxy * sizeof(struct cell)); } clearmaze(maxx, maxy, map); srand(time(NULL)); /* initialisation finished */ /* choose a random unvisited cell */ visitRand(&amp;x, &amp;y, maxx-2, maxy-2, map); /* for the first time, there is no last direction, choose a random one */ prevdir = rand()%4; /* while there is an unvisited cell in the map, the maze is not finished */ while (testEndMaze(maxx, maxy, map)) { /* choose a direction */ dir = newDir(x, y, maxx, maxy, prevdir, randomness, map); switch (dir) { case north: prevdir = north; map[x][y].wallN = 0; y--; map[x][y].wallS = 0; break; case south: prevdir = south; map[x][y].wallS = 0; y++; map[x][y].wallN = 0; break; case east: prevdir = east; map[x][y].wallE = 0; x++; map[x][y].wallW = 0; break; case west: prevdir = west; map[x][y].wallW = 0; x--; map[x][y].wallE = 0; break; case -1: visitRandVisited(&amp;x, &amp;y, maxx, maxy, map); break; } visitCell(x, y); } /* detect all the dead end in the map the spar determine the number of map unvited, in removing dead end */ spar = sparcount(sparseness, maxx, maxy); while(i &lt; spar) { deadendshow(maxx, maxy, map); i = freecasecount(maxx, maxy, map); } /* select the dead end and dig for creating loop */ digin(maxx, maxy, randomness, deadendremoval, map); writedungeon(maxx, maxy, map); for (x = 0; x &lt; maxx; x++) { free(map[x]); } free(map); return EXIT_SUCCESS; } </code></pre> <p>maze.h</p> <pre><code>#ifndef MAZE_H #define MAZE_H enum { north, south, east, west }; struct cell { int visited; int wallN; int wallS; int wallE; int wallW; }; int createmaze(int maxx, int maxy, int randomness, int sparseness, int deadendremoval); #endif </code></pre> <p>deadend.c This file is a simple chained list tool.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include "deadend.h" void addfirst(struct deadend **tete, int x, int y) { struct deadend *element = NULL; element = malloc(sizeof(struct deadend)); element-&gt;x = x; element-&gt;y = y; element-&gt;next = *tete; *tete = element; } void addend(struct deadend **tete, int x, int y) { struct deadend *element= *tete; struct deadend *elemprec = NULL; /* cas liste vide */ if(element == NULL) { addfirst(tete, x, y); /* cas general */ } else { while (element != NULL) { elemprec = element; element = element-&gt;next; } addfirst(&amp;element, x, y); elemprec-&gt;next = element; } } void delfirst(struct deadend **liste) { struct deadend *tmp = NULL; if(*liste != NULL) { tmp = (*liste)-&gt;next; free(*liste); *liste = tmp; } } void dellist(struct deadend **liste) { struct deadend *tmp = *liste; while (tmp != NULL) { tmp = (*liste)-&gt;next; delfirst(liste); } } void runlist(struct deadend *liste) { while (liste) { printf("liste : x: %d y: %d\n", liste-&gt;x, liste-&gt;y); liste = liste-&gt;next; } } int countdead(struct deadend *liste) { int itemnb = 0; while (liste) { itemnb++; liste = liste-&gt;next; } return itemnb; } </code></pre> <p>deadend.h</p> <pre><code>#ifndef DEADEND_H #define DEADEND_H struct deadend { int x; int y; struct deadend *next; }; void addfirst(struct deadend **tete, int x, int y); void addend(struct deadend **tete, int x, int y); void delfirst(struct deadend **liste); void dellist(struct deadend **liste); void runlist(struct deadend *liste); int countdead(struct deadend *liste); #endif </code></pre> <p>And the funny Makefile (I know it is ugly)</p> <pre><code>CC = gcc CFLAGS=-O3 -Wall -Wextra -W -Werror -ansi -pedantic -pipe -ffast-math -fforce-addr -march=native -fomit-frame-pointer -finline-functions -funroll-loops -funsafe-loop-optimizations -combine LDFLAGS = ifeq ($(ARG), debug) CFLAGS += -g endif SRC = $(wildcard *.c) OBJ = $(SRC:.c=.o) EXEC = dungeon all: $(EXEC) $(EXEC): $(OBJ) $(CC) -o $@ $^ $(LDFLAGS) $(CFLAGS) main.o: %.o: %.c $(CC) -o $@ -c $&lt; $(CFLAGS) clean : rm -f *.o $(EXEC) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T16:25:22.483", "Id": "5153", "Score": "1", "body": "That is a lot of uncommented code for someone to look at and figure out to answer your question. Can you provide an explanation (ideally in comments) or a link to the algorithm you are using?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T17:41:09.377", "Id": "5159", "Score": "0", "body": "The algorithm is here: http://web.archive.org/web/20080203123815/www.aarg.net/~minam/dungeon_design.html. I'll edit my question for comment." } ]
[ { "body": "<p>I didn't look in great detail because there's no explanation of the algorithm you are using, but I did notice that you have several code blocks similar to the following:</p>\n\n<pre><code>do {\n x = rand()%(maxx-1);\n y = rand()%(maxy-1);\n} while (map[x][y].visited != 0);\n</code></pre>\n\n<p>That code runs quickly when the map is mostly unvisited, but as the percentage of the map that has been visited increases, thean increasing number of iterations is required to locate an unvisited spot.</p>\n\n<p>If your map is 1000 by 1000, there are 1,000,000 cells. When you get down to the last 10 cells, you have a 1 in 100,000 chance of locating an empty cell with each guess. You should devise a method of tracking used and unused cells separately so you can make a random pick in a single step.</p>\n\n<p><strong>Edit:</strong>\ntestEndMaze() may be another source of inefficiency. Instead of searching every cell to see if it has been visited, can you keep count of cells as you visit them? If so, then testEndMaze() is just comparing your current count of visited cells with the total number of cells in the maze.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T17:39:52.717", "Id": "5157", "Score": "0", "body": "Sorry for the explanations, I renamed all functions and variables so I thought it was easily readable.\nThe algorithme that I use is like described in this page http://web.archive.org/web/20080203123815/www.aarg.net/~minam/dungeon_design.html but without rooms.\n\nYou had a great point, do you have an idea about what kind of structure I have to use for tracking visited and univisited cells separately ?\nThat was one of my ideas at the first but I didn't succeed in creating a tool for that.\n\nOf course, thank you very much for your answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T17:40:38.697", "Id": "5158", "Score": "0", "body": "@Lutin Your function and variable names are not bad, but they are not necessarily enough. Your question contains hundreds of lines of code. That's a lot to sort through without knowing what you are looking at. Even a high-level description of your algorithm would have been helpful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T17:50:18.170", "Id": "5160", "Score": "0", "body": "@Lutin This may not be not very elegant, but the first thing that comes to mind is to build an array listing all of the unvisited cells, use rand()%(unvisitedCellCount-1) to pick one. After you pick one, copy the last unvisited cell to the array location you just picked and decrement your unvisitedCellCount." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T18:10:04.890", "Id": "5162", "Score": "0", "body": "@jimred That's a good idea, I will work in this direction. I've commented enough ? I never work in team and I don't realize if what I did is fairly described." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T18:33:29.080", "Id": "5164", "Score": "0", "body": "@Jerry Coffin I can't, because the random cells that I choose must be already visited, and I choose a random cell only when I there is no possible direction." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T16:43:26.717", "Id": "3425", "ParentId": "3423", "Score": "6" } } ]
{ "AcceptedAnswerId": "3425", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T15:10:23.250", "Id": "3423", "Score": "4", "Tags": [ "optimization", "c" ], "Title": "Maze generation, long random time" }
3423
<p>I'm looking for a single-pass algorithm for finding the topX percent of floats in a stream where I do not know the total number ahead of time ... but its on the order of 5-30 million floats. It needs to be single-pass since the data is generated on the fly and recreate the exact stream a second time.</p> <p>The algorithm I have so far is to keep a sorted list of the topX items that I've seen so far. As the stream continues I enlarge the list as needed. Then I use <code>bisect_left</code> to find the insertion point if needed.</p> <p>Below is the algorithm I have so far:</p> <pre><code>from bisect import bisect_left from random import uniform from itertools import islice def data_gen(num): for _ in xrange(num): yield uniform(0,1) def get_top_X_percent(iterable, percent = 0.01, min_guess = 1000): top_nums = sorted(list(islice(iterable, int(percent*min_guess)))) #get an initial guess for ind, val in enumerate(iterable, len(top_nums)): if int(percent*ind) &gt; len(top_nums): top_nums.insert(0,None) newind = bisect_left(top_nums, val) if newind &gt; 0: top_nums.insert(newind, val) top_nums.pop(0) return top_nums if __name__ == '__main__': num = 1000000 all_data = sorted(data_gen(num)) result = get_top_X_percent(all_data) assert result[0] == all_data[-int(num*0.01)], 'Too far off, lowest num:%f' % result[0] print result[0] </code></pre> <p>In the real case the data does not come from any standard distribution (otherwise I could use some statistics knowledge).</p> <p>Any suggestions would be appreciated.</p>
[]
[ { "body": "<pre><code>top_nums = sorted(list(islice(iterable, int(percent*min_guess)))) #get an initial guess\n</code></pre>\n\n<p>There is no reason to make a list out of it before you sort it.</p>\n\n<pre><code>for ind, val in enumerate(iterable, len(top_nums))\n</code></pre>\n\n<p>I dislike abbreviations. I think it makes it harder to figure out what ind and val are doing. </p>\n\n<pre><code> all_data = sorted(data_gen(num))\n</code></pre>\n\n<p>Why are you sorting your test data? </p>\n\n<p>As I understand your problem, your code is wrong. It only works in your test case because you sort the incoming data. </p>\n\n<p>Your algorithm regularly increases the size of the list of values. But when it does so, there have been previous numbers which have been thrown away which may greater then the value you insert at that point. As a result, you cannot be sure you've actually ended up with with the top 1%.</p>\n\n<p>How should you fix it? If you can upper bound the size of your input, then you can start with a list of sufficient size and then scale back at the end. Otherwise I don't think you can do it. The problem being that you cannot throw away any values because there is no way to be sure you won't need them later.</p>\n\n<p>You might consider using a heap. Python has a heapq module including a function heapq.nlargest which does pretty much what you are doing, (but uses a count rather then a percentage) A heap is pretty much a semi-sorted list and lets you do things like find/remove/replace the lowest value without the overhead of actually sorting.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T23:05:54.813", "Id": "5280", "Score": "2", "body": "Actually. Only a heap can possibly work. Consider the case where all the incoming data is in strictly descending order. No value can be discarded because the top *X* percent is always the first arrived items in descending order. Until the entire stream has been seen, no value can be discarded as the number of slots comprising *X* percent grows." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T06:59:29.220", "Id": "5287", "Score": "0", "body": "@S. Lott, I'm not seeing the connection between \"only a heap can possibly work\" and the rest of your comment. At the very least, I'd think a sorted list can do the same things a heap can, (with more computational cost)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T09:47:51.870", "Id": "5290", "Score": "0", "body": "True. A sorted list and lots of other expensive and bad ideas for keeping the data will \"work\". Since they'll be more costly, they aren't very good ideas are they? The heap, however, is a very good idea. I think it belongs up higher in your answer, because it's a very good ideas. The theoretical possibility of other less good ideas didn't seem very relevant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T13:03:33.710", "Id": "5294", "Score": "0", "body": "@S.Lott, you said that only a heap could possibly work. If we are considering what could possibly work the efficiency doesn't matter. A heap is better, although I'm not sure how much. If I recall correctly, I have O(log n) insertion for both a sorted list and a heap. The heap is at the end because I thought it more important to point out that the code doesn't work then how to optimize it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T13:10:50.917", "Id": "5296", "Score": "0", "body": "Your distinction between bad algorithms which may work eventually and a good algorithm is getting too subtle for me. I'm sure it's an important hair, but I can't understand splitting it. The algorithm as presented is fundamentally flawed -- as you noted. Further, the whole thing can be simplified to just a heap and nothing more. There's little more to say than you pointed out both flaws. Feel, free, however, to continue to split whatever hair you need to in your already complete answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T22:08:45.773", "Id": "5318", "Score": "0", "body": "@S. Lott, the fundamental flaw in his algoritm isn't solved by using a heap. Just using a heap leaves his algorithm fundamentally flawed. Whether using a heap or sorted list the algorithm will give the wrong answers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T22:16:24.380", "Id": "5319", "Score": "0", "body": "If the algorithm given is discarded, and a heap is used, then the top *X* percent is available in the heap. That sounds like what you said. That's what made sense to me. Discard the broken algorithm. Use a heap. Right? Isn't that what you said? That's what my comment meant. Use a heap. Just use a heap. Ignore the broken algorithm." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T22:24:30.210", "Id": "5321", "Score": "0", "body": "@S. Lott, we don't know how big to make the heap. We won't know how big to make the heap until we've seen all the data, but at that point its too late. We need to know from the beginning of the algorithm how many values to keep in the heap, but since we only have a percentage we have a problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T22:27:42.177", "Id": "5322", "Score": "0", "body": "@S. Lott, if we solve the problem of how many items to keep, then yes use a heap. But, we've moved from the area of accuracy (What's really really important) to effeciency (which is less important)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T02:37:03.853", "Id": "5325", "Score": "0", "body": "\"We won't know how big to make the heap until we've seen all the data\". Precisely. The only solution is a heap. \"if we solve the problem of how many items to keep\"? What kind of random hypothetical is that? We can't know that in advance under any circumstances. Hence the heap as the only sensible solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T09:45:16.413", "Id": "5331", "Score": "0", "body": "@S. Lott, wait, are you suggesting putting the entire contents of the incoming data in a heap?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T09:51:48.077", "Id": "5333", "Score": "0", "body": "I can't see how any other approach would work. Until you've seen `len(stream)` items you don't know how large `X*len(stream)` is, so you don't know how many to \"keep\". If the data arrives in strictly descending order, you can't discard anything until you've reached `(1-X)*len(stream)`. Anyway, that's what appears to be the case to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T10:41:26.103", "Id": "5339", "Score": "0", "body": "@S. Lott, ok I misunderstood what you were suggesting. I agree that unless you can determine an upper bound on input size, you are stuck with keeping all values in memory until the end. The confusion resulted because when I suggested a heap, I didn't intend as an entire algorithm merely to replace the sorted list the OP was using for part of his \"broken\" algorithm. Hence when you started talking about the heap as \"the\" solution, I was rather confused." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T10:44:13.607", "Id": "5340", "Score": "0", "body": "I also confused because of the emphasis you placed on the heap, which as the data structure seems to be a fairly minor component of the solution. I wasn't really attempting to provide a complete solution because what the OP seems to want (not keeping everything in memory and returning the top 1% doesn't seem to possible.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T10:51:43.657", "Id": "5341", "Score": "0", "body": "\"what the OP seems to want\" appears unworkable. The heap appears workable. That was my comment. Only a heap will work. Other structures that keep all the data may work, but will be inefficient and therefore unworkable. I'm trying to keep this simple. The heap is the only thing that's workable. That was my comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T11:16:23.483", "Id": "5343", "Score": "0", "body": "@S. Lott, I must submit that I could also put everything into a list and then use a variant of quickselect to find the top 1%. Its also not clear to me that the solution is workable because the OP may simply have too much data. I'm just not willing to agree that the heap is the only data structure which is workable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T11:35:03.433", "Id": "5344", "Score": "0", "body": "\"not willing to agree\". Doesn't mean anything. Rather than fail to agree, you really must propose an alternative." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T13:24:02.797", "Id": "5345", "Score": "0", "body": "@S.Lott, I have proposed an alternative: modified quickselect. A heap-based algorithm is not the only workable solution to this problem. (It is, I think, the best one). But my point is that you are making an absolute statement: no algorithm besides a heap-based one is workable. To be able to make that claim, you need to demonstrate good reason to believe that no other workable algorithm exists. (Also workable is a little bit vauge)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T13:46:12.297", "Id": "5346", "Score": "0", "body": "Algorithms must be finite, definite and effective. Effective usually means minimal. Any O(n log n) algorithm would be effective. If the quickselect is as fast as the heap insertion, then it seems like it's isomorphic to it. Perhaps I'm missing something in the quickselect, but the way that it builds partitions sure sounds a lot like way a heap is built." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T22:29:13.163", "Id": "5365", "Score": "0", "body": "@S. Lott, I would take effective to mean that is runs in a reasonable amount of time for the problem under consideration. i.e a program which takes several years is not effective. However, a program which takes two minutes rather the one is still effective, but not as efficient as the other one. But that would be a matter of definition." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T22:32:13.053", "Id": "5366", "Score": "0", "body": "O(n log n) isn't minimal for this problem. O(n log n) is enough time to sort and slice the data which is another technique. Quickselect will solve the problem in O(n). A heap could also solve it in O(n) although the niave heap-based solution will use O(n log n)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T22:38:19.137", "Id": "5367", "Score": "0", "body": "I'm not seeing enough similarity between heap-building and partitioning that they look isomorphic to me. Perhaps I'm missing something. But more to the point, does it matter? From the programmer's perspective the implementation looks fairly different and so you still have choose between one and the other?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T11:15:00.000", "Id": "5377", "Score": "0", "body": "\"A heap could also solve it in O(n)\". Correct. I was wrong because this is partitioning not a full sort. \"But more to the point, does it matter?\" I have no idea. I suggested that a heap was the only solution because they appear isomorphic to me. However, you have split (and resplit) that hair now many, many times. You tell me. \"does it matter?\" Evidence indicates that it does matter, since you appear to be convinced that it requires extensive discussion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T12:02:09.757", "Id": "5381", "Score": "0", "body": "@S. Lott, re: does it matter. That was specifically about your claim of isomorphism between quickselect and heap. Since the end programmer has to choose between heaps and quickselect, claiming that they are isomorphic doesn't help the programmer. He still has to make the choice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T12:06:19.117", "Id": "5383", "Score": "0", "body": "But let's put this in a practical context: what is the implication of claiming that \"heap is the only solution\"? As I read it, the implication is that no other algorithm should ever be implemented to solve this problem. But I don't think that statement is correct." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T12:16:54.570", "Id": "5384", "Score": "0", "body": "I also mystified by your claim that I'm splitting hairs. I have no idea what hair you think I'm splitting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T12:42:36.610", "Id": "5386", "Score": "0", "body": "But let's put this in a practical context: \"heap is the only solution\". The way I wrote it, all solutions that are O(n) are isomorphic to a heap, which is minimal. You **already** suggested this, and I liked your suggestion and wanted to emphasize that your suggestion was very very good. For some reason, you don't seem to like the idea that your suggestion was very, very good. What's the point of downgrading your own suggestion by splitting a hair on the *exact* meaning of \"only\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T21:05:13.270", "Id": "5403", "Score": "0", "body": "@S. Lott, I see where you are coming from now. The problem is that your definition of \"only\" is very different from mine. As a result, your original claim came across as bizarre. There isn't really any point in discussing the meaning of the word, so I'll leave it at that. I wasn't trying to split hairs, but I thought you were trying to claim something that you aren't." } ], "meta_data": { "CommentCount": "28", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T04:17:09.797", "Id": "3431", "ParentId": "3429", "Score": "5" } }, { "body": "<p>This can't work unless you stipulate a specific size for the partition and do not grow it.</p>\n\n<p>You can't discard any value from the input sequence or you won't get the actual maximum. The fact that you're popping a value means that you may be discarding a proper part of the solution subset.</p>\n\n<p>Consider a slightly contrived example where X = 0.25. The initial state is to process 1/X items (4 in this case) of which 1 is maximum and 3 are discarded. The values were 100, 99, 98 and 97. You keep 100 as the 25% maximum and discard 99, 98, 97. </p>\n\n<p>(You could try to keep all 4 or even the first 25 values. It doesn't matter how many you keep initially, the logic problem will still arise as soon as you pop a value. I think the contrived example makes the logic flaw easier to see.)</p>\n\n<p>At some point, you've seen 7 values. The maxima subset has 1 value (100); the remaining values (99, 98, 96, 95, 94 and 93) have been discarded as not part of the maxima set.</p>\n\n<p>You get value 8, it's 92. You need to append this to the top set. Yet, sadly, you discarded a value larger than this.</p>\n\n<p>When you get to value 12, you again need to expand the maxima subset. However, you will have discarded values that may be larger than the 12th value in the sequence.</p>\n\n<p>You cannot do a <code>pop()</code> from the maxima subset unless you can prove the value being popped must be less than all future values which may arrive.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T13:22:21.273", "Id": "3561", "ParentId": "3429", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T00:26:44.347", "Id": "3429", "Score": "4", "Tags": [ "python", "algorithm" ], "Title": "Single pass algorithm for finding the topX percent of items" }
3429
<p>Can this part of a view controller subclass be checked for memory leaks. I am not that good at finding leaks. I need this class to be able to be loaded many time over without it crashing due to memory leaks. The endgame gets called every time it needs to go back to the main menu. I want it to be able to go back to the main menu without leaving any memory footprint.</p> <pre><code>UIImageView* questionImage; UIImageView* questionImage2; UIButton* questionButton1; UIButton* questionButton2; UIButton* questionButton3; UIButton* questionButton4; UIButton* questionButton5; UIButton* questionButton6; UIButton* achievementbutton; UIButton* endbutton; UILabel* questionText; UILabel* ButtonLabel; - (void)viewDidLoad { [super viewDidLoad]; [self StartTimer]; TotalSeconds = 0; GameCenterTotalSeconds = 0; timeSec = 0; timeMin = 0; Background = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 480, 320)] ; Background.image = [UIImage imageWithContentsOfFile:[ [ NSBundle mainBundle] pathForResource:@"Background" ofType:@"png"]]; [self.view addSubview:Background]; timeLabel.textColor = [UIColor redColor]; [self.view addSubview:timeLabel]; NumberLabel = [[UIImageView alloc] initWithFrame:CGRectMake(0, -4, 60, 70)] ; NumberLabel.image = [UIImage imageWithContentsOfFile:[[ NSBundle mainBundle] pathForResource:@"Number" ofType:@"png"]]; [self.view addSubview:NumberLabel]; QuestionNumber = [[UILabel alloc] initWithFrame:CGRectMake(23, 17, 20, 20)] ; QuestionNumber.text = @"1"; QuestionNumber.textColor = [UIColor redColor]; QuestionNumber.backgroundColor = [UIColor clearColor]; [QuestionNumber setFont:[UIFont fontWithName:@"Marker Felt" size:30]]; [self.view addSubview:QuestionNumber]; numberLives = 1; appDelegate = (OppositeMoronTestAppDelegate *)[[UIApplication sharedApplication]delegate]; musicButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain] ; musicButton.frame = CGRectMake(5, 283, 35, 35); musicButton.backgroundColor = [UIColor clearColor]; if (appDelegate.shouldPlayMusic == YES) { UIImage *Image = [UIImage imageWithContentsOfFile:[[ NSBundle mainBundle] pathForResource:@"MusicOn" ofType:@"png"]]; [musicButton setBackgroundImage:Image forState:UIControlStateNormal]; [musicButton addTarget:self action:@selector(TurnMusicOff) forControlEvents:UIControlEventTouchUpInside]; } else { UIImage *Image = [UIImage imageWithContentsOfFile:[[ NSBundle mainBundle] pathForResource:@"MusicOff" ofType:@"png"]]; [musicButton setBackgroundImage:Image forState:UIControlStateNormal]; [musicButton addTarget:self action:@selector(TurnMusicOn) forControlEvents:UIControlEventTouchUpInside]; } [self.view addSubview:musicButton]; [self showQuestion1]; } - (void) showQuestion1 { questionImage = [[UIImageView alloc] initWithFrame:CGRectMake(15, 50, 430, 270)] ; questionImage.image = [UIImage imageWithContentsOfFile:[[ NSBundle mainBundle] pathForResource:@"Q1new" ofType:@"png"]]; [self.view addSubview:questionImage]; questionButton5 = [UIButton buttonWithType:UIButtonTypeCustom]; [questionButton5 addTarget:self action:@selector(showQuestion2Part1)forControlEvents:UIControlEventTouchDown]; questionButton5.frame = CGRectMake(109, 75, 90, 65); [self.view addSubview:questionButton5]; questionButton1 = [UIButton buttonWithType:UIButtonTypeCustom]; [questionButton1 addTarget:self action:@selector(wronganswer)forControlEvents:UIControlEventTouchDown]; questionButton1.frame = CGRectMake(230, 50, 120, 90); [self.view addSubview:questionButton1]; questionButton2 = [UIButton buttonWithType:UIButtonTypeCustom]; [questionButton2 addTarget:self action:@selector(wronganswer)forControlEvents:UIControlEventTouchDown]; questionButton2.frame = CGRectMake(300, 144, 100, 90); [self.view addSubview:questionButton2]; questionButton3 = [UIButton buttonWithType:UIButtonTypeCustom]; [questionButton3 addTarget:self action:@selector(wronganswer)forControlEvents:UIControlEventTouchDown]; questionButton3.frame = CGRectMake(203, 187, 95, 90); [self.view addSubview:questionButton3]; questionButton4 = [UIButton buttonWithType:UIButtonTypeCustom]; [questionButton4 addTarget:self action:@selector(wronganswer)forControlEvents:UIControlEventTouchDown]; questionButton4.frame = CGRectMake(67, 140, 120, 95); [self.view addSubview:questionButton4]; questionText = [[UILabel alloc] initWithFrame:CGRectMake(80, 20, 300, 30)] ; questionText.text = @"Press the Addition Sign"; questionText.textColor = [UIColor blackColor]; questionText.backgroundColor = [UIColor clearColor]; [questionText setFont:[UIFont fontWithName:@"Marker Felt" size:30]]; [self.view addSubview:questionText]; } - (void) endgame { [WrongBackground release]; [gameOver release]; [wrongLivesLeft release]; [questionImage release]; [questionText release]; [Background release]; [NumberLabel release]; [musicButton release]; [questionImage release]; [questionText release]; [self.view removeFromSuperview]; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T02:01:06.917", "Id": "5166", "Score": "2", "body": "You have to indent your code with the {} - button in the edit box. And look at it in the preview, which is below your edit section. Didn't you read the FAQ and HOWTOS? The posts in meta?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T12:49:25.130", "Id": "5180", "Score": "1", "body": "This is what Instruments in the dev package is for." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-29T22:01:34.510", "Id": "9929", "Score": "0", "body": "Also; try \"Build and Analyze\" as the Clang Static Humiliator is quite good at identifying incorrect memory management." } ]
[ { "body": "<p>There are several views that you're allocating and installing as subviews in <code>-viewDidLoad</code>. Among these are <code>NumberLabel</code>, <code>Background</code>, and <code>QuestionNumber</code>. (BTW, it'd be a little easier to follow your code if you stuck to Objective-C naming conventions and start variables with a lower-case letter.) These appear to be instance variables, but you didn't provide the class declaration so it's hard to be certain. Anyway, if you don't need to refer to these views again after their added as to the main view, it would be better to make them local variables instead of ivars and release them right away. (The view will retain them once they've been added.) When the view is unloaded, all those subviews will be released.</p>\n\n<p><code>QuestionNumber</code> isn't released in the code you've provided -- that may be a leak.</p>\n\n<p>It's not clear where <code>timelabel</code> comes from or if it actually points to a view.</p>\n\n<p>You're releasing <code>WrongBackground</code>, but that's not created in <code>-viewDidLoad</code>, so it's hard to know if that's correct or not.</p>\n\n<p>There are several variables like <code>questionButton1</code> and friends that look like file-scope global variables rather than instance variables, but there's no indication of why. Wouldn't it make sense to make them ivars?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-11T07:06:37.587", "Id": "4032", "ParentId": "3430", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T00:51:04.343", "Id": "3430", "Score": "2", "Tags": [ "objective-c", "memory-management" ], "Title": "Memory Question" }
3430
<p>I've created the following class to persist data by serializing/deserializing objects that are sent to it. I would like to know if there is a better way of writing this class, or if my class is fine the way it is.</p> <pre><code>using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Formatters.Soap; namespace Education_PersistingData { public class PersistData&lt;T&gt; { private readonly T _obj; private readonly string _filePath; private readonly string _fileName; public PersistData(T obj, string filePath, string fileName) { this._obj = obj; this._filePath = filePath; this._fileName = fileName; } /// &lt;summary&gt; /// Serializes objects to a SOAP .xml format /// &lt;/summary&gt; public void SerializeToSoapFormat() { try { SoapFormatter soapFormatter = new SoapFormatter(); Stream dataStream = File.Create(_filePath + _fileName); soapFormatter.Serialize(dataStream, _obj); dataStream.Close(); } catch (IOException ex) { throw new IOException(ex.Message); } } /// &lt;summary&gt; /// Serializes objects to a Binary .txt format /// &lt;/summary&gt; public void SerializeToBinaryFormat() { try { BinaryFormatter binaryFormatter = new BinaryFormatter(); Stream dataStream = File.Create(_filePath + _fileName); binaryFormatter.Serialize(dataStream, _obj); dataStream.Close(); } catch (IOException ex) { throw new IOException(ex.Message); } } /// &lt;summary&gt; /// Deserializes a SOAP .xml file format /// &lt;/summary&gt; /// &lt;returns&gt;Deserialized object&lt;/returns&gt; public T DeserializeSoapFormat() { try { SoapFormatter soapFormatter = new SoapFormatter(); Stream dataStream = File.OpenRead(_filePath + _fileName); T result = (T)soapFormatter.Deserialize(dataStream); dataStream.Close(); return result; } catch (IOException ex) { throw new IOException(ex.Message); } } /// &lt;summary&gt; /// Deserializes a Binary .txt file format /// &lt;/summary&gt; /// &lt;returns&gt;Deserialized object&lt;/returns&gt; public T DeserializeBinaryFormat() { try { BinaryFormatter binaryFormatter = new BinaryFormatter(); Stream dataStream = File.OpenRead(_filePath + _fileName); T result = (T)binaryFormatter.Deserialize(dataStream); dataStream.Close(); return result; } catch (IOException ex) { throw new IOException(ex.Message); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T00:02:23.313", "Id": "5246", "Score": "0", "body": "You say \"better way of writing\" the class. Better for what purpose?" } ]
[ { "body": "<p>There is no point in catching the IOException and then throwing a new exception. You only loose information here. Either handle it or remove the try-catch altogether.</p>\n\n<p>Also, use <code>using</code> to always dispose <code>IDisposable</code> objects.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T11:41:22.393", "Id": "5170", "Score": "0", "body": "Thanks for the advice. To be honest with you the reason why I threw the exception again is because I had seen another developer do that in a project I was working on. I actually knew not to do that, I just wasn't thinking." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T07:41:02.157", "Id": "3433", "ParentId": "3432", "Score": "7" } }, { "body": "<p>You could try making the class generic, with the restriction that it must implement IFormatter, as both SoapFormatter and BinaryFormatter does. </p>\n\n<pre><code>public class PersistData&lt;T, TY&gt; where TY : IFormatter, new()\n{\n private readonly T _obj;\n private readonly string _filePath;\n private readonly string _fileName;\n\n public PersistData(T obj, string filePath, string fileName)\n {\n this._obj = obj;\n this._filePath = filePath;\n this._fileName = fileName;\n }\n\n\n public void Serialize()\n {\n try\n {\n IFormatter formatter = new TY();\n\n using (Stream dataStream = File.Create(_filePath + _fileName))\n {\n formatter.Serialize(dataStream, _obj);\n }\n }\n catch (IOException ex)\n {\n // log and handle error\n }\n }\n\n\n\n public T Deserialize()\n {\n try\n {\n IFormatter formatter = new TY();\n\n using (Stream dataStream = File.OpenRead(_filePath + _fileName))\n {\n return (T) formatter.Deserialize(dataStream);\n }\n }\n catch (IOException ex)\n {\n // log and handle error\n }\n }\n\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T08:06:40.577", "Id": "3435", "ParentId": "3432", "Score": "6" } }, { "body": "<p>From the looks of the way you've used the class, I would say there is little point having <code>filePath</code> and <code>fileName</code> separate. Instead, I would just pass in the full path. That way, you have all the information you need without having to combine the two strings each time you use them (which if used a large amount could slightly affect performance). If you find you need them separate in some cases, you can always retrieve them using the helper methods in <code>System.IO.Path</code>.</p>\n\n<p>Also, since the formatters are generically used, I would re-use them. So instead of creating a new formatter each time you wish to serialize/deserialize some data, I would put the following (or something similar) at the top of your class:</p>\n\n<pre><code>private static readonly SoapFormatter SharedSoapFormatter = new SoapFormatter();\nprivate static readonly BinaryFormatter SharedBinaryFormatter = new BinaryFormatter();\n</code></pre>\n\n<p>One final point I would make, is to use a <code>using</code> statement when dealing with streams. This is much nicer and makes the stream disposal more explicit. i.e.</p>\n\n<pre><code>using (var stream = File.Create(filePath))\n{\n // Use the stream\n} // &lt;- This will call the stream's `Dispose` method.\n</code></pre>\n\n<p>Other than that (and the wrapping of <code>IOException</code> which has already been mentioned), I would say it appears to be fine.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T19:27:57.077", "Id": "3649", "ParentId": "3432", "Score": "2" } }, { "body": "<p>I would combine some of the suggestions already given and make the class stateless. Storing the object and path in fields does not really buy you anything, and it ensures that you have to construct a new object whenever you want to serialize/deserialize something else.</p>\n\n<p>In addition, I would probably change the name. PersistData is not a good class name (classes should be nouns). I am naming impaired, though, so I leave that as an exercise for the OP :)</p>\n\n<pre><code>public static class PersistData\n{\n public static void Serialize&lt;TFormatter&gt;(object obj, string path) where TFormatter : IFormatter, new()\n {\n try\n {\n var formatter = new TFormatter();\n\n using (Stream dataStream = File.Create(path))\n {\n formatter.Serialize(dataStream, obj);\n }\n }\n catch (IOException ex)\n {\n // log and handle error\n }\n }\n\n public static T Deserialize&lt;T,TFormatter&gt;(string path) where TFormatter : IFormatter, new()\n {\n try\n {\n var formatter = new TFormatter();\n\n using (Stream dataStream = File.OpenRead(path))\n {\n return (T) formatter.Deserialize(dataStream);\n }\n }\n catch (IOException ex)\n {\n // log and handle error\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-01T00:47:18.770", "Id": "55747", "ParentId": "3432", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T07:33:54.357", "Id": "3432", "Score": "5", "Tags": [ "c#", ".net", "formatting", "serialization" ], "Title": "Persist data by serializing/deserializing objects that are sent to it" }
3432
<p>I have the following type of many functions so many if condtions are there is there is any way to reduce no. of lines.</p> <pre><code>enter: function(request, callback, callback1){ request.on={}; if(callback==undefined &amp;&amp; NodeClientUI.initdata.join!=undefined){ callback=NodeClientUI.initdata.join; request.on.join=function(data){ callback(data); }; }else if(callback!=undefined ){ request.on.join=function(data){ callback(data); }; } if(callback1==undefined &amp;&amp; NodeClientUI.initdata.occupant!=undefined){ callback1=NodeClientUI.initdata.occupant; request.on.occupant=function(data){ callback1(data); }; }else if(callback1!=undefined ){ request.on.occupant=function(data){ callback1(data); }; } }; </code></pre> <p>No of paramerter the callbacks may be increased in many functions.</p> <p>Please suggest .</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T10:03:14.313", "Id": "5168", "Score": "0", "body": "Is there no way to receive an array of callbacks? Or perhaps make some sort of resizing array for callbacks prior to the calling of this method? It would allow you to reduce this quite a bit if you could generalize. Though without further information, it's difficult to say how this method would \"grow\" with increasing callbacks (NodeClientUI.initdata contains what?)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T11:00:46.510", "Id": "5169", "Score": "0", "body": "okay i got your point of converting callbacks to array Please update your answer according. i can give the key of array join for callback and occupant for callback1 respectively" } ]
[ { "body": "<p>Try this:</p>\n\n<pre><code>enter: function(request, callbacks){\n request.on={};\n for(var key in callbacks) {\n var callback = callbacks[key];\n if(callback === undefined) {\n callback = NodeClientUI.initData[key];\n }\n request.on[key]=function(data){\n callback(data);\n }\n }\n };\n</code></pre>\n\n<p>This permits you to call with callbacks defined as:</p>\n\n<pre><code>var callbacks = {};\ncallbacks['join'] = function(data) { // join logic ... };\ncallbacks['occupant'] = function(data) { // occupant logic ... };\ncallbacks['stuff'] = undefined; // Takes on value of NodeClientUI.initData.stuff\n...\n</code></pre>\n\n<p>Request would get assigned in the same manner. If you can't pass a map of callbacks in this way, you could create a function which creates a global variable callbacks for you to use inside the method (just ignore the callback parameter passed to enter method and use callbacks instead):</p>\n\n<pre><code>var callbacks = {};\nfunction addCallback(key, callback) {\n callbacks[key] = callback;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T13:23:29.037", "Id": "3438", "ParentId": "3434", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T08:00:25.060", "Id": "3434", "Score": "3", "Tags": [ "javascript", "node.js" ], "Title": "reduce no. of lines" }
3434
<p>It feels like pagination is one of the most discussed questions on the web, which always ends up with some quick and dirty hacks on how to paginate. I want to paginate a large result set from an SQL query on a website where I use Spring-JDBC for querying and <a href="http://www.displaytag.org/" rel="nofollow">Displaytag</a> for display. I thought about it for a while and eventually came up with implementing a <code>ResultSetExtractor</code> like this:</p> <pre><code>import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.displaytag.pagination.PaginatedList; import org.displaytag.properties.SortOrderEnum; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.ColumnMapRowMapper; import org.springframework.jdbc.core.ResultSetExtractor; public class PaginatingResultMapExtractor implements ResultSetExtractor&lt;PaginatedList&gt; { private final int page; private final int pageSize; private final String sortColumn; private final SortOrderEnum sortDirection; public PaginatingResultMapExtractor(int page, int pageSize, String sortColumn, SortOrderEnum sortDirection) { super(); this.page = page; this.pageSize = pageSize; this.sortColumn = sortColumn; this.sortDirection = sortDirection; } @Override public PaginatedList extractData(ResultSet rs) throws SQLException, DataAccessException { final ColumnMapRowMapper mapper = new ColumnMapRowMapper(); final List&lt;Object&gt; result = new ArrayList&lt;Object&gt;( pageSize); int i; for (i = 0; rs.next(); ++i) { if (i &gt; (page - 1) * pageSize &amp;&amp; i &lt; page * pageSize) result.add(mapper.mapRow(rs, i)); } return new PaginatedListImpl&lt;Object&gt;(result, i, pageSize, page, sortColumn, sortDirection); } } </code></pre> <p><code>PaginatedListImpl</code> is simply stores the values that I pass in the constructor and makes them available with getter-methods, fulfilling the requirements of the <code>PaginatedList</code> interface by displaytag.</p> <p>I can use this by simply calling:</p> <pre><code>jdbcTemplate.query("select ... from ...", new PaginatingResultMapExtractor(page, pageSize, sortColumn, sortDirection)); </code></pre> <p>At least this solution is very easy to use. But after all I have to iterate the whole result set. Can this code be improved?</p>
[]
[ { "body": "<p>Pagination should be done by the database server where applicable. There is really no point pushing data down the wire if it is not being used, so what you should think about doing, is passing in your page number and count variables to the query or preferable a stored procedure, and use SQL to select the subset of data you want. There are SQL constructs in most SQL language variants to do this.</p>\n\n<p>Here is an example using MySql:</p>\n\n<pre><code>SELECT `field1`, `field2` from `mycatalog` LIMIT start, (start + cnt)\n</code></pre>\n\n<p>And something similar with Sql Server:</p>\n\n<pre><code>WITH #set AS (SELECT [Field1], [Field2], ROW_NUMER() OVER (ORDER BY [Field1]) AS [Index] FROM [MyDatabase])\nSELECT [Field1], [Field2] FROM #set WHERE [INDEX] BETWEEN @start AND (@start + @count)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T14:19:54.420", "Id": "5182", "Score": "2", "body": "I agree 100% with having the DB do the paging as much as possible, but I would strongly avoid using stored procedures unless there is a clear, large (and necessary) performance win. Stored procedures are notoriously hard to maintain because they are separate from the codebase and are much harder to deal with that plain files. Also, in most cases, you don't get much perf. benefit from SProcs because query caches have gotten much better than in the past, as has query parsing time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-03T12:41:34.937", "Id": "30803", "Score": "2", "body": "But you could / should use a prepared statement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-08T18:03:25.503", "Id": "438541", "Score": "0", "body": "The second approach may bear an unnecessary overhead when order by is used over a massive table. Unless, of course, the table is clustered along the lines of the same \"order by\" expression." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T19:37:10.323", "Id": "3449", "ParentId": "3436", "Score": "9" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T09:17:48.127", "Id": "3436", "Score": "8", "Tags": [ "java", "pagination", "jdbc" ], "Title": "Paginating large SQL-Results" }
3436
<p>Here's a working version of my code - <a href="http://jsfiddle.net/sambenson/g3qsa/#base" rel="nofollow">http://jsfiddle.net/sambenson/g3qsa/#base</a><br> How can this be improved upon?</p> <pre><code>$(function(){ var box = {}, island = {}, canvas = {}; box.el = $('#box'); canvas.el = $('#arrow'); function go(el){ if(box.el.css('visibility') == 'hidden'){ reset_name(); $('.island').addClass('inactive'); box.top = box.el.offset().top; box.corner = {}; box.corner.left = box.el.offset().left; box.corner.right = box.corner.left + box.el.width(); island.el = el; island.top = island.el.offset().top; island.left = island.el.offset().left; island.el.removeClass('inactive').addClass('active'); canvas.width = island.left - box.corner.left; canvas.height = island.top - box.top; canvas.el.css({ top: box.top, left: box.corner.left }).attr({ width: canvas.width, height: canvas.height }); var context = canvas.el[0].getContext('2d'); context.beginPath(); context.moveTo(0, 0); context.lineTo(box.el.width(), 0); context.lineTo(canvas.width, canvas.height); context.closePath(); context.fillStyle = "#eaeaea"; context.fill(); box.el.css('visibility', 'visible'); canvas.el.show(); } else { close(); } } function reset_name(){ $('#name_holder').text('').css({ top: -9999, left: -9999 }) } function close(){ $('.island').removeClass('inactive active'); box.el.css('visibility', 'hidden'); canvas.el[0].width = canvas.el[0].width; canvas.el.hide(); } $('.island').hover(function(){ if(box.el.css('visibility') == 'hidden'){ var t = $(this), name = t.text(), holder = $('#name_holder'); top = t.offset().top - 60; left = t.offset().left - 50; holder.css({ top: top, left: left }).text(name); } }, function(){ reset_name(); }) .click(function(){ go($(this)); }) $('.close').click(function(){ close(); }) }) </code></pre> <p>Could it be made faster?<br> Could it be made more efficient?</p>
[]
[ { "body": "<p>My comments are more just on style as opposed to performance:</p>\n\n<p>Instead of using :</p>\n\n<pre><code>if(box.el.css('visibility') == 'hidden'){\n</code></pre>\n\n<p>it's more readable to use :</p>\n\n<pre><code>if(box.el.is(\":hidden\")){\n</code></pre>\n\n<p>And similarly, instead of using :</p>\n\n<pre><code>box.el.css('visibility', 'visible');\n</code></pre>\n\n<p>you can use :</p>\n\n<pre><code>box.el.hide();\n</code></pre>\n\n<p>A note on this one though, these are not exactly equivalent because <code>hide</code> actually sets <code>display: none</code>. In this case though I believe that's fine.</p>\n\n<p>And one final comment, it's a good practice to name variables which contain jQuery objects with a <code>$</code> at the beginning. This allows you to know that the variable is already a jQuery object without going back in the code to check and avoids accidentally creating jQuery objects out of objects that were already jQuery objects.</p>\n\n<p>So something like this:</p>\n\n<pre><code>var t = $(this),\n name = t.text()\n</code></pre>\n\n<p>would become this:</p>\n\n<pre><code>var $t = $(this),\n name = $t.text()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T14:05:05.680", "Id": "5172", "Score": "0", "body": "Thanks for your review. With regards to your first point: I had to use `visibility: hidden` instead of `.hide()` etc because the jQuery needs to be able to measure the width of the box whilst it's hidden. Your `$variable_name` suggestion is great though!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T14:08:27.723", "Id": "5173", "Score": "0", "body": "Ah okay, I looked to see if you had `visibility` for a reason but missed that. Can still use `:hidden` though I believe." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T13:57:52.043", "Id": "3440", "ParentId": "3439", "Score": "2" } }, { "body": "<p>Along with @kingjv's suggestions, you can improve the performance of your jQuery selections by making some simply tweaks to the selectors.</p>\n\n<p>Consider if I have the following html:</p>\n\n<pre><code>&lt;div id=\"container\"&gt;\n &lt;div class=\"cell\"&gt;Cell 1&lt;/div&gt;\n &lt;div class=\"cell\"&gt;Cell 2&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>If you I am using a class selector, such as <code>$(\".cell\")</code> then the selector engine has to do a little more than it needs to. In this example, the selector engine has to walk the entire DOM to match the correct elements. We can improve this a couple of ways:</p>\n\n<ul>\n<li><p>Specify a tag in the selector, e.g. <code>$(\"div.cell\")</code>. This allows the selector engine to use the native <code>getElementsByTagName</code> method to shrink the number of comparisons the engine has to do to match.</p></li>\n<li><p>Specify a root object to start searching from. E.g., if I've previously cache my selector <code>var root = $(\"#container\")</code>, I can reuse that selector: <code>$(\"div.cell\", root)</code> that way we don't walk the entire DOM for matches.</p></li>\n</ul>\n\n<p>These are small performance improvements, you'll appreciate them more if you are doing a lot of DOM manipulation and lookup. More simplistic applications won't have such an apparent performance improvement.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T19:23:16.390", "Id": "3447", "ParentId": "3439", "Score": "2" } } ]
{ "AcceptedAnswerId": "3447", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T13:33:07.860", "Id": "3439", "Score": "1", "Tags": [ "javascript", "performance", "jquery", "canvas" ], "Title": "Map markers on a canvas that pop up boxes when clicked" }
3439
<p>I am curious as to what the performance/functional differences are between:</p> <pre><code>private bool OftenCalledMethod(string s) { Regex reg = new Regex(@"^matchme$", RegexOptions.IgnoreCase); return (reg.IsMatch(s)); } </code></pre> <p>Versus:</p> <pre><code>readonly Regex reg = new Regex(@"^matchme$", RegexOptions.IgnoreCase); private bool OftenCalledMethod(string s) { return (reg.IsMatch(s)); } </code></pre> <p>Does the compiler optimize the former in such a way that it doesn't matter? Or is the object <code>reg</code> being allocated repeatedly and unnecessarily?</p>
[]
[ { "body": "<p>I would go with the former unless you profile your code and it tells you that the constructor for Regex is using a significant amount of time.</p>\n\n<p>Creating the Regex inside your method makes the clear statement that this given Regex is being used by only this method. The compiler doesn't care, but someone maintaining your code in the future might care.</p>\n\n<p>Running a profiler is necessary for really optimizing your code. There are some things that are always likely to be bad (O(n^3) algorithms for instance), but I've learned by experience that I <strong>can't</strong> tell just by looking where the time is being wasted in my code. Profile it and see what you learn.</p>\n\n<p>If your profiling results tell you that the constructor of Regex is using too much time, then definitely move it outside the method. If you do that though, you should add comments explaining why. (Keep thinking about the poor person maintaining your code in the future, it just might be you.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T15:40:15.293", "Id": "3442", "ParentId": "3441", "Score": "2" } }, { "body": "<p>Just the creation of the Regex class is unlikely to take too much time. You are just initializing two properties.</p>\n\n<p>Do not mistake the initialization with the much more costly execution.</p>\n\n<p>In any case, do not over optimize without backing up your assumptions with performance data gathered by a profiling tool.</p>\n\n<p>The added benefit of profiling your code, is that now you will know much better what actually happens during execution.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T19:15:50.803", "Id": "3446", "ParentId": "3441", "Score": "1" } }, { "body": "<p>Definitely profile your code before doing any optimization. It's certainly reasonable to make some up-front decisions based on what you think might be optimal code, but once you get reasonable and working code, don't start hacking away at it in the hopes of gaining some sort of optimization. Time it, profile it, etc to find the slow spots, then focus on those.</p>\n\n<p>As for the cost of initialization vs. use with regex objects, I'm not personally familiar with C#'s handling of them, but in Python, there is a cost to creating a regex which goes beyond just initializing a few member variables.</p>\n\n<pre><code>import re\nfrom timeit import Timer\n\ntest_str = 'abra, abra, cadabra'\ntest_re = 'c.d'\n\ndef inside(s):\n r = re.compile(test_re)\n return r.match(s)\n\nr = re.compile(test_re)\ndef outside(s):\n return r.match(s)\n\nprint \"inside =\", Timer(\"inside(test_str)\", \"from __main__ import inside, test_str\").timeit()\nprint \"outside =\", Timer(\"outside(test_str)\", \"from __main__ import outside, test_str\").timeit()\n</code></pre>\n\n<p>The output from the little test code above clearly shows that creating the regex inside the function each time it is called is a significant performance loss.</p>\n\n<pre><code>inside = 3.24013303367\noutside = 1.45581882614\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T18:30:25.950", "Id": "3465", "ParentId": "3441", "Score": "1" } } ]
{ "AcceptedAnswerId": "3442", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T15:31:45.917", "Id": "3441", "Score": "1", "Tags": [ "c#" ], "Title": "Performance difference between declaring Regex inside or outside of often-called method." }
3441
<p>I've created a JQuery script to help illustrate a few points for my teaching class, but I have having trouble slimming it down.</p> <pre><code>$(document).ready(function() { var red = $(".small-box"); var blue = $(".small-box2"); var green = $(".large-box"); red.hover( function () { red.addClass("selected-highlight"); blue.addClass("selected-highlight2"); green.addClass("selected-highlight3"); }, function () { red.removeClass("selected-highlight"); blue.removeClass("selected-highlight2"); green.removeClass("selected-highlight3"); } ); blue.hover( function () { red.addClass("selected-highlight3"); blue.addClass("selected-highlight"); green.addClass("selected-highlight2"); }, function () { red.removeClass("selected-highlight3"); blue.removeClass("selected-highlight"); green.removeClass("selected-highlight2"); } ); green.hover( function () { red.addClass("selected-highlight2"); blue.addClass("selected-highlight3"); green.addClass("selected-highlight"); }, function () { red.removeClass("selected-highlight2"); blue.removeClass("selected-highlight3"); green.removeClass("selected-highlight"); } ); }); </code></pre> <p>Everything works as it should, but I know there is a way to slim down the "removeClass" part to one single line. I am having trouble remembering how to do so. The idea is to whatever box you hover over is red and the colors follow accordingly in the order of: red, blue, and green.</p> <pre><code>.container-left { float:left; } .small-box { width:300px; height:300px; background-color:#FFF; border-top:1px #000 solid; border-left:1px #000 solid; } .small-box2 { width:300px; height:300px; background-color:#FFF; border-left:1px #000 solid; border-bottom:1px #000 solid; border-top:1px #000 solid;; } .container-right { float:left; } .large-box { width:300px; height:601px; background-color:#FFF; border:1px #000 solid; } .selected-highlight{ background-color:red; } .selected-highlight2 { background-color:blue; } .selected-highlight3 { background-color:#00FF00; } </code></pre>
[]
[ { "body": "<p>A little shorter:</p>\n\n<pre><code>$(document).ready(function() {\n var red = $(\".small-box\");\n var blue = $(\".small-box2\");\n var green = $(\".large-box\");\n var boxes = red.add(blue).add(green);\n\n boxes.mouseleave(function() {\n boxes.removeClass(\"selected-highlight selected-highlight2 selected-highlight3\");\n });\n\n red.mouseenter(\n function () {\n red.addClass(\"selected-highlight\");\n blue.addClass(\"selected-highlight2\");\n green.addClass(\"selected-highlight3\");\n }\n );\n blue.mouseenter(\n function () {\n red.addClass(\"selected-highlight3\");\n blue.addClass(\"selected-highlight\");\n green.addClass(\"selected-highlight2\");\n }\n );\n green.mouseenter(\n function () {\n red.addClass(\"selected-highlight2\");\n blue.addClass(\"selected-highlight3\");\n green.addClass(\"selected-highlight\");\n }\n );\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T16:49:36.893", "Id": "3445", "ParentId": "3444", "Score": "3" } }, { "body": "<p>Building on BumleB2na. The repeated calls to addClass seemed to cloud the intent of the code with the uninteresting details. </p>\n\n<pre><code>$(document).ready(function() {\n var red = $(\".small-box\");\n var blue = $(\".small-box2\");\n var green = $(\".large-box\");\n var boxes = red.add(blue).add(green);\n\n function highlight() { // optional params used, generalizable with a loop\n arguments[0].addClass(\"selected-highlight\");\n arguments[1].addClass(\"selected-highlight2\");\n arguments[2].addClass(\"selected-highlight3\");\n }\n\n boxes.mouseleave(function() {\n boxes.removeClass(\"selected-highlight selected-highlight2 selected-highlight3\");\n });\n\n red.mouseenter(\n function () {\n highlight(red, blue, green);\n }\n );\n blue.mouseenter(\n function () {\n highlight(blue, green, red);\n }\n );\n green.mouseenter(\n function () {\n highlight(green, red, blue);\n }\n );\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T14:22:56.470", "Id": "5502", "Score": "0", "body": "This is awesome. I had no idea you could pass unexpected params to a function like this, but I think it could get confusing if you do it often. When I want a function to have optional params, I specify them in the function definition and then check if optional params are != undefined. But still, very interesting that this can be done.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T19:51:24.407", "Id": "5512", "Score": "0", "body": "Glad that I've though you a new trick. I prefer explicit parameters as well. In this case the implicit optional parameters are just for show and because the name of the parameters did not just pop into my head :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T11:06:59.853", "Id": "3522", "ParentId": "3444", "Score": "3" } } ]
{ "AcceptedAnswerId": "3445", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T16:39:53.953", "Id": "3444", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Hover effects for red, blue, and green boxes" }
3444
<p>Yes I'm very slowly making my way through Purely Functional Data Structures. So I went through the section on Red Black Trees. What he presents is amazingly concise, except for the fact that he didn't include the delete function. Searching around didn't turn up many functional delete methods, well only two so far. One in Haskell the other in Racket (a version of Scheme I think). The Haskell code seemed rather impenetrable to me so I went with trying to grok the Racket version from <a href="http://matt.might.net/articles/red-black-delete/" rel="noreferrer">Matt Might</a>. My scheme experience is pretty rusty, but my Haskell knowledge is nill.</p> <p>The code below is what I came up with. You can see the complete implementation of <a href="https://www.assembla.com/code/purely-functional-data-structures-in-f-/subversion/nodes/trunk/PurelyFunctionalDataStructures/Chap3/RedBlackTree.fs?rev=49" rel="noreferrer">RedBlackTree.fs here</a>. I'm sure that there are still problems in this implementation since I haven't fully tested it yet. My main question for the more experienced guys is does what Matt has laid out here really make sense? And do you think the way I've tried to implement this in F# is going to work?</p> <p>If you read Matt's blog you'll see a description of how he is approaching the problem. He adds two new colors (double black and negative black) to the tree temporarily during the delete. He also has this notion of a double black leaf, and that is where my main point of confusion lies. After a delete a double black leaf is sometimes left behind (when the element being deleted has no children). So it appears that the double black leaf isn't temporary. It's not clear to me based on his description if this is what was intended or I still have some problem in my logic.</p> <p>Thanks for taking a look at this,</p> <p>Derek</p> <pre><code>// BB = double-black // NB = negative-black type Color = R | B | BB | NB type Tree&lt;'e when 'e :&gt; IComparable&gt; = | L | BBL // BBL = double-black leaf | T of Color * Tree&lt;'e&gt; * 'e * Tree&lt;'e&gt; module RedBlackTree = let empty = L ... let addBlack c = match c with | B -&gt; BB | R -&gt; B | NB -&gt; R | BB -&gt; failwith "BB Nodes should only be temporary" let subBlack c = match c with | B -&gt; R | R -&gt; NB | BB -&gt; B | NB -&gt; failwith "NB Nodes should only be temporary" let redden n = match n with | L | BBL -&gt; n | T(_,l,v,r) -&gt; T(R,l,v,r) let blacken node = match node with | BBL -&gt; L | T(_,l,v,r) -&gt; T(B,l,v,r) | _ -&gt; node let rec balanceNode clr tl e tr = match clr, tl, e, tr with | BB,T(R, T(R,a,x,b),y,c), z, d | BB,T(R,a,x, T(R,b,y,c)), z, d | BB,a,x, T(R, T(R,b,y,c),z,d) | BB,a,x, T(R,b,y, T(R,c,z,d)) | B,T(R, T(R,a,x,b),y,c), z, d | B,T(R,a,x, T(R,b,y,c)), z, d | B,a,x, T(R, T(R,b,y,c),z,d) | B,a,x, T(R,b,y, T(R,c,z,d)) -&gt; T((subBlack clr), T(B,a,x,b), y, T(B,c,z,d)) | BB,a,x,T(NB,T(B,b,y,c),z,(T(B,_,_,_) as d)) -&gt; T(B,T(B,a,x,b),y, balanceNode B c z (redden d)) | BB,T(NB,(T(B,_,_,_) as a),x,T(B,b,y,c)),z,d -&gt; T(B, (balanceNode B (redden a) x b), y, T(B,c,z,d)) | _,_,_,_ -&gt; T(clr,tl,e,tr) let bubble t = match t with | T(c,(T(lc,ll,lv,lr) as lt),v, (T(rc,rl,rv,rr) as rt)) -&gt; if lc = BB || rc = BB then balanceNode (addBlack c) (T(subBlack lc,ll,lv,lr)) v (T(subBlack rc,rl,rv,rr)) else t | _ -&gt; t let isLeaf node = match node with | L | BBL -&gt; true | _ -&gt; false let rec getMax node = match node with | L | BBL -&gt; None | T(c,l,v,r) -&gt; match (isLeaf l), (isLeaf r) with | false, true | true,true -&gt; Some(v) | _,_ -&gt; getMax r let rec remove node = match node with | L | BBL -&gt; node | T(nc, lchild, nv, rchild) -&gt; match (isLeaf lchild),(isLeaf rchild) with | true,true -&gt; match nc with | R -&gt; L | B -&gt; BBL | _ -&gt; failwith "Illegal black node" | true,false -&gt; match nc,rchild with | R,T(rc,rl,rv,rr) -&gt; rchild | B,T(rc,rl,rv,rr)-&gt; match rc with | R -&gt; T(B,rl,rv,rr) | B -&gt; T(addBlack rc,rl,rv,rr) | _ -&gt; failwith "Illegal black node" | _ -&gt; failwith "Illegal black node" | false,true -&gt; match nc,lchild with | R,T(lc,ll,lv,lr) -&gt; lchild | B,T(lc,ll,lv,lr) -&gt; match lc with | R -&gt; T(B,ll,lv,lr) | B -&gt; T(addBlack lc,ll,lv,lr) | _ -&gt; failwith "Illegal black node" | _ -&gt; failwith "Illegal black node" | false,false -&gt; let max = (getMax lchild).Value let t = removeMax lchild bubble (T(nc,t,max,rchild)) and removeMax node = match node with | T(c,l,v,r) -&gt; if isLeaf r then remove node else bubble (T(c,l,v, removeMax r)) | _ -&gt; node let delete key node = let rec del (key : IComparable) node = match node with | T(c,l,v,r) -&gt; match key.CompareTo v with | -1 -&gt; bubble (T(c,(del key l),v,r)) | 0 -&gt; remove node | _ -&gt; bubble (T(c,l,v,(del key r))) | _ -&gt; node blacken (del key node) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-12T11:31:58.393", "Id": "5176", "Score": "2", "body": "The built-in Set type is implemented using Red-Black trees and includes a remove function, so you could look at the source for that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T17:04:13.433", "Id": "5215", "Score": "0", "body": "Actually the Set.fs file isn't a red black tree. Probably an AVL tree which is close, but not quite the same." } ]
[ { "body": "<p>Google for \"left leaning red black trees\"; they're Sedgewick's (substantial) simplification of RB trees and the paper includes all the code, including delete. By adding the constraint that all \"three-nodes\" lean left, the number of cases you need to consider is reduced dramatically.</p>\n\n<p>Hope this helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T02:32:27.930", "Id": "3518", "ParentId": "3448", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-10T17:39:08.983", "Id": "3448", "Score": "9", "Tags": [ "f#", "functional-programming" ], "Title": "Deleting from Red Black Tree in F#" }
3448
<p><strong>Requirement:</strong> </p> <p>If the bookshop manager field changes from A to B, I need to email the person B saying that the new Bookshop has been allotted to him and he has to do certain activities. </p> <pre><code>private void SendEmailToAllottedManager() { EmailExpress mEmailExpress = new EmailExpress(); mEmailExpress.SendEmail(Shop.Bookstore.BookstoreName, Subject); } </code></pre> <p>In the method where I am calling <code>SendEmailToAllottedManager</code>, I am checking if the <code>Manager</code> has indeed changed or not as below:</p> <pre><code>if (OriginalManager != CurrentManager) { SendEmailToAllottedManager(); } </code></pre> <p>During code review, a colleague suggested that I move the check from outside the function <code>SendEmailToAllottedManager()</code> to inside it:</p> <p><strong>Proposed Code</strong></p> <pre><code>private void SendEmailToAllottedManager() { if (OriginalManager != CurrentManager) { EmailExpress mEmailExpress = new EmailExpress(); mEmailExpress.SendEmail(Shop.Bookstore.BookstoreName, Subject); } } </code></pre> <p>I maintain my stand that the function <code>SendEmailToAllottedManager</code> is only about emailing and not about performing the checks, etc.</p> <p>What do you think?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T12:28:21.220", "Id": "5179", "Score": "1", "body": "`SendEmailToManagerIfRequired`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T13:25:25.677", "Id": "5181", "Score": "0", "body": "Mr Disappointment: Sorry...could not understand what you are trying to convey here. If you mean to say that SendEmailToManagerIfRequired is the place for the check to go, can you please elaborate as to why?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T14:52:20.013", "Id": "5183", "Score": "0", "body": "I was just expressing that there is always the option to rename the method to include the fact that it will _only_ send the email if required (i.e. post checking.)" } ]
[ { "body": "<p>I agree with you. The performed action of a method should correspond to it's name. In your colleague's suggestion, an email sent to the allotted manager is, as you already pointed out, not always being sent and thus not 100% semantically accurate.</p>\n\n<p>However, for the sake of readability, it sometimes can be easier to put the if-then check in the same method, especially if you have a lot of if-then checks to be performed. But then you might want to consider doing some refactoring instead, if it becomes too bloated. It's always hard to know where to draw the line.</p>\n\n<p>Interesting question! Im looking forward to seeing others thoughts.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T11:51:08.627", "Id": "3452", "ParentId": "3451", "Score": "1" } }, { "body": "<p>I would say, that actually sending the email is part of the process of changing the store manager. It's part of the business logic (AFAIK), that when a store changes it's manager, the new manager should be notified, among other things.</p>\n\n<p>Thats why the check if the manager changes is not a job for the email sender at all. The email sender should be a utility, which can be reused.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T19:53:13.463", "Id": "3468", "ParentId": "3451", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T10:30:13.830", "Id": "3451", "Score": "2", "Tags": [ "c#" ], "Title": "Sending email for allotment" }
3451
<p>Can you please help me with the following script?</p> <p>At the moment the script is taking up to 20 mins to execute, depending on the amount of data being processed (each time the script is executed, it processes several thousand lines of data). I would like to make the script more responsive. Can you tell me how I can update the script for better performance?</p> <p>See comments in each of the main parts of the script:</p> <pre><code>#!/opt/SP/mdp/home/SCRIPTS/tools/Python-2.6.2/bin/python import glob import re as regex from datetime import datetime # Here I am getting two set of files which I am going to use to create two separate dictionaries Cnfiles = glob.glob('/logs/split_logs/Cn*_generic_activity.log') Prfiles = glob.glob('/logs/split_logs/Pr*_generic_activity.log') # Output file log = file('/logs/split_logs/processed_data.log', 'w') # First dictionary, holds received records Cn = {} for logfile in Cnfiles: with open(logfile) as logfile: filecontent = logfile.xreadlines() for line in filecontent: if 'SERV1' in line and 'RECV' in line or 'SERV2' in line and 'RECV' in line or 'SERV3' in line and 'RECV' in line: line = regex.sub('&lt;._', '', line) line = line.replace('&lt;', '') line = line.replace('&gt;', '') line = line.replace('.', ' ') line = line.replace(r'|', ' ') line = line.strip() field = line.split(' ') opco = field[4] service = field[5] status = field[6] jarid = field[10] Cn.setdefault(opco, {}).setdefault(service, {}).setdefault(status, {})[jarid] = jarid # Second dictionary, holds the various stages the records go through Pr = {} for logfile in Prfiles: with open(logfile) as logfile: filecontent = logfile.xreadlines() for line in filecontent: if 'status 7 to 13' in line or 'status 9 to 13' in line or 'status 7 to 14' in line or 'status 9 to 14' in line or 'status 5 to 504' in line or 'status 7 to 505' in line: line = line.replace('&lt;', '') line = line.replace('&gt;', '') line = line.replace('.', ' ') line = line.strip() field = line.split(' ') jarid = field[8] status = field[13] Pr.setdefault(status, {})[jarid] = jarid # Up to this point, the script performs quite well, even with big files. # However, the next step is comparing the two dictionaries and if it finds a record that is in both dicts, # it is creating new sub-dictionaries to hold the various stages of the records. This is the step # that is taking the most time! Do you know of a better way I can do this? for opco in Cn.keys(): for service in Cn[opco].keys(): for status in Cn[opco][service].keys(): for jarid in Cn[opco][service][status].keys(): if jarid in Pr['13'].keys(): Cn[opco][service].setdefault('ACK', {})[jarid] = jarid elif jarid in Pr['14'].keys(): Cn[opco][service].setdefault('NACK', {})[jarid] = jarid else: if jarid in Pr['504'].keys() or jarid in Pr['505'].keys(): Cn[opco][service].setdefault('RETRY', {})[jarid] = jarid # Once the new sub-dictionaries are created, I am just counting the number of records in # each one and writing the output to the log. timestamp = (datetime.now()).strftime('%y%m%d %H:%M') for opco in sorted(Cn.keys()): for service in sorted(Cn[opco].keys()): if 'RECV' in Cn[opco][service].keys(): recvcount = len(Cn[opco][service]['RECV']) else: recvcount = '' if 'NACK' in Cn[opco][service].keys(): nackcount = len(Cn[opco][service]['NACK']) else: nackcount = '' if 'ACK' in Cn[opco][service].keys(): ackcount = len(Cn[opco][service]['ACK']) else: ackcount = '' if 'RETRY' in Cn[opco][service].keys(): retrycount = len(Cn[opco][service]['RETRY']) else: retrycount = '' log.write('%s\t%s\t%s\t%s\t%s\t%s\t%s\n' % (timestamp, opco, service, recvcount, ackcount, nackcount, retrycount)) log.close() </code></pre> <p><strong>UPDATE</strong></p> <p>I have updated my script using most of the suggestions posted here. I am now using regexes. I am not using <code>dict.keys()</code> to iterate through the dicts anymore and I have shortened my statements, etc. However, my script is still running very slowly.</p> <pre><code> for opco in Cn: for service in Cn[opco]: for jarid in Cn[opco][service]['RECV']: if jarid in Pr['13']: Cn[opco][service].setdefault('ACK', []).append(jarid) elif jarid in Pr['14']: Cn[opco][service].setdefault('NACK', []).append(jarid) else: if jarid in Pr['504'] or jarid in Pr['505']: Cn[opco][service].setdefault('RETRY', []).append(jarid) </code></pre> <p>I have run my script with a profiler and I can see that this step in the script is taking the most time (1368 CPU secs last time I executed it!). Please note that I am new to Python and I still don't have a good grasp on everything that can be done with it.</p> <p><strong>UPDATE</strong></p> <p>I have managed to get my whole script to execute in under 10 seconds by changing the 'for loop' I posted above to the following:</p> <pre><code> for opco in Cn: for service in Cn[opco]: ack = set(Cn[opco][service]['RECV']) &amp; set(Pr['13']) for jarid in ack: Cn[opco][service].setdefault('ACK', set()).add(jarid) nack = set(Cn[opco][service]['RECV']) &amp; set(Pr['14']) for jarid in nack: Cn[opco][service].setdefault('NACK', set()).add(jarid) retry = set(Cn[opco][service]['RECV']) &amp; set(Pr['504']) for jarid in retry: Cn[opco][service].setdefault('RETRY', set()).add(jarid) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T18:17:58.000", "Id": "5184", "Score": "0", "body": "I just noticed the part you said is problematic. Can you specify what you're trying to do and what are the datastructures. For example, what is `opco`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T22:21:38.017", "Id": "5185", "Score": "0", "body": "Hi @Guy, What I try to do at that point is look through my two dictionaries and try to match the jarid on both. If the jarid is found, then I take the stage value where the jarid is found and create a new dictionary with this info. In this case, opco is a two letter country code.\n\nMy log files look like this...\n\nReceiver log file:-\n\n>timestamp,machine,opco,service,status,jarid\n>2011-07-04 11:15:02,152 ICMFCn01 EG SERV1 RECV 191a7971\n\nfor the 'stages' log, the entries are like:-\n\n>timestamp,machine,jarid,stage\n>2011-07-04 11:16:35,482 ICMFPr01 0cb6c851 14" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T23:34:16.070", "Id": "5186", "Score": "2", "body": "That is quite a shebang line. You ever consider `#!/usr/bin/env python`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T18:40:49.917", "Id": "58728", "Score": "0", "body": "Look at [my answer](http://codereview.stackexchange.com/questions/3393/im-trying-to-understand-how-to-make-my-application-more-efficient/3424#3424) to \"[I'm trying to understand how to make my application more efficient](http://codereview.stackexchange.com/questions/3393/im-trying-to-understand-how-to-make-my-application-more-efficient)\". Profiling Python code is pretty easy and painless." } ]
[ { "body": "<p>Suggestions:</p>\n\n<ul>\n<li>compile your regex-es once and use the compiled version</li>\n<li>go over the log files <strong>once</strong> instead of three times.</li>\n<li>find the lines in the log using a regex - I don't know the exact syntax but it should say: \"starts with a newline, ends with a newline and has ...\". Then compile it and use <code>re.findall()</code></li>\n<li>try and avoid the <code>line = line.replace(..)</code>'s you have. Since string is immutable, each replace creates a new line string. Maybe use indices <code>opco = line[x:y]</code>. I don't know how complicated the logs are but, I think that having a few <code>if</code>s instead of all those replacements should speed things up.</li>\n<li><p>If I understand your comment correctly, basically what you have is two giant lists. One for \"Receiver Log\" and one for \"stages\" log. As I see it (correct me if I'm wrong), what you're doing is (first, reducing the lists), and then going entry by entry on one list and checking if the entry appears in the second list. Maybe, (don't shoot me if this is ridiculous ;) sort one of the lists and go entry by entry on the second list while using binary search. I.e:</p>\n\n<p><code>l1 = open(\"Receiver Log\").readlines()</code></p>\n\n<p><code>l2 = open(\"Stages log\").readlines()</code></p>\n\n<p><code>sort(l2) # on jarid</code></p>\n\n<p><code>for entry in l1:</code></p>\n\n<pre><code> if binarySearch(l2, entry['jarid']) # again, on jarid\n # analyze the l2\n</code></pre>\n\n<p>Theoretically speaking, you're making a tremendous speed-up. Practically, I don't know if it'll work. python has a builtin <code>list.sort()</code> and according to <a href=\"https://stackoverflow.com/questions/212358/binary-search-in-python\">https://stackoverflow.com/questions/212358/binary-search-in-python</a> it's easy to implement binary search.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T03:14:19.393", "Id": "5284", "Score": "0", "body": "Hi @Guy, I have no knowledge of binary search. Please see my original post above. I have updated it to ask for help implementing a solution using binary search." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T08:12:37.010", "Id": "5289", "Score": "0", "body": "The link I pointed to has an implementation of binary search in python." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T18:12:01.923", "Id": "3455", "ParentId": "3454", "Score": "5" } }, { "body": "<p>First, is your process I/O bound or CPU bound? Look at your CPU meter when it's running. If it's I/O bound, the CPU will be at less than 100% and there might not be much you can do about it except get better hardware.</p>\n\n<p>If you're CPU bound, a number of things could help. It's not a huge savings, but it will help to pre-compile your regular expressions. Instead \n line = regex.sub('&lt;._', '', line)</p>\n\n<p>Start with</p>\n\n<pre><code>regex1 = regex.compile('&lt;._')\n</code></pre>\n\n<p>outside your loop, and inside the loop do</p>\n\n<pre><code>line = regex1.sub('',line)\n</code></pre>\n\n<p>Also the long if tests will run faster as regular expressions. Instead of </p>\n\n<pre><code>if 'SERV1' in line and 'RECV' in line or 'SERV2' in line and 'RECV' in line or 'SERV3' in line and 'RECV' in line:\n</code></pre>\n\n<p>Do</p>\n\n<pre><code>regex2 = regex.compile('SERV[1-3].*RECV') # Outside of loop\nif regex2.search(line):\n</code></pre>\n\n<p>The regular expression engine is very smart and highly optimized. Since that line is running on every log entry, it should be real savings.</p>\n\n<p>Similarly, a regex that only captures the 5th, 6th, 7th and 11th fields will save you from allocating memory for the strings for all the others that you aren't using. For example to capture the third and fifth words in a line use this regex (understanding that <code>\\s</code> matches whitespace and <code>\\S</code> matches non-whitespace and parentheses determine what gets captured and stored in the match object's <code>group</code>):</p>\n\n<pre><code>regex3 = regex.compile(\"^\\S+\\s+\\S+\\s+(\\S+)\\s+\\S+\\s+(\\S+)\")\nm = regex3.search(line)\nword3 = m.group(1)\nword5 = m.group(2)\n</code></pre>\n\n<p>A lot harder to read, but it will run a lot faster. (Comment your code!) In fact, if you just just replace that whole series of <code>line.replace</code> and <code>split</code> with one big fancy regex, that would be best. Without an example of what the input looks like it's not practical to construct that regex.</p>\n\n<p>Also, you could try running a <a href=\"http://docs.python.org/library/profile.html\" rel=\"noreferrer\">profiler</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T00:15:39.203", "Id": "5187", "Score": "0", "body": "Hi Leopd, can you please tell me what would be the regex to capture only certain fields from a line?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-14T21:24:27.720", "Id": "5188", "Score": "0", "body": "Edited my answer with an example regex." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T18:20:20.320", "Id": "3456", "ParentId": "3454", "Score": "5" } }, { "body": "<p>This:</p>\n\n<pre><code>jarid in Pr['13'].keys()\n</code></pre>\n\n<p>gets the keys of the dict as a list and then searches the list, which loses the speed advantage of a dict. Searching a list is O(n), whereas searching a dict is O(1). It's faster to do this:</p>\n\n<pre><code>jarid in Pr['13']\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>if 'SERV1' in line and 'RECV' in line or 'SERV2' in line and 'RECV' in line or 'SERV3' in line and 'RECV' in line:\n</code></pre>\n\n<p>is equivalent to this:</p>\n\n<pre><code>if ('SERV1' in line or 'SERV2' in line or 'SERV3' in line) and 'RECV' in line:\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>line = line.replace('&lt;', '')\nline = line.replace('&gt;', '')\nline = line.replace('.', ' ')\nline = line.replace(r'|', ' ')\n</code></pre>\n\n<p>can be shortened to this:</p>\n\n<pre><code>line = regex.sub('&lt;._', '', line)\nline = regex.sub('[&lt;&gt;,|]', '', line)\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>line = line.replace('&lt;', '')\nline = line.replace('&gt;', '')\nline = line.replace('.', ' ')\n</code></pre>\n\n<p>can be shortened to this:</p>\n\n<pre><code>line = regex.sub('[&lt;&gt;.]', '', line)\n</code></pre>\n\n<p>Pre-compiling the regexes may give a little speed improvement, but not much, because the regexes are cached by the re module.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T19:29:56.653", "Id": "5189", "Score": "0", "body": "Wow! Thanks MRAB, this are really good suggestions! I will definitely use them in my script" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T20:13:32.940", "Id": "5190", "Score": "1", "body": "as for keys() (which I didn't mention in my answer because already mentioned here): I believe it gets even worse: it's not only the list vs. dict lookup: a new list must be created first, (and at first sight, this is happening a lot, even multiple times for the same dict)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T19:17:00.577", "Id": "3458", "ParentId": "3454", "Score": "8" } }, { "body": "<p>Some other suggestions in addition to what has already been mentioned:</p>\n\n<ul>\n<li>stuff like <code>some_dict[jarid] = jarid</code> suggests that you actually want a <a href=\"http://docs.python.org/library/stdtypes.html#set-types-set-frozenset\" rel=\"nofollow\">set</a> instead of a dictionary?</li>\n<li>you're using the <code>setdefault</code> method quite a lot: maybe have a look at <a href=\"http://docs.python.org/dev/library/collections.html#defaultdict-objects\" rel=\"nofollow\">collections.defaultdict</a></li>\n<li>in the case of <code>Cn[opco][service]['RECV']</code> and so on... you seem to use that only to get the number of occurrences? You don't even have to use a set for that: have a look at <a href=\"http://docs.python.org/dev/library/collections.html#collections.Counter\" rel=\"nofollow\">collections.Counter</a> or use a <code>defaultdict(int)</code>. (you could just do something like <code>service_counter['RECV'] += 1</code>, you don't even have to check whether you've seen the key before or not) </li>\n<li><p>you're doing a whole lot of lookups again and again, for example you first ask for <code>Cn[opco].keys()</code>, then you do <code>Cn[opco][service].keys()</code>: you're looking up <code>Cn[opco]</code> <em>again</em>, and then you lookup the service (with the key you have just retrieved), and then you do the whole thing again, but with an extra level, and <em>again</em>... Use the dictionary's <code>items()</code> or <code>iteritems()</code> method to iterate over keys and values at the same time. For example:</p>\n\n<pre><code>for opco, opco_val in Cn.items():\n for service, service_val in opco_val.items():\n</code></pre>\n\n<p>etc.... That way, you don't have to look it up again (and certainly not the whole chain!)</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T03:10:11.720", "Id": "5283", "Score": "0", "body": "Hello @Steven, I have tried using your suggestion above by iterating through the keys, values in pair using dict.items(), however, when I then try to use 'service' as my value, I am getting the dictionary held at this value (e.j: opco is giving me 'UK' which is correct, however service is giving me '{SERV1:{RECV:{eai123ea:2011-07-18 21:09:13.251}}}' which is a sub-dict.\n\nCan you please give me another example of how I can use your approach to iterate through my dicts?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T20:09:52.733", "Id": "3459", "ParentId": "3454", "Score": "1" } }, { "body": "<p>You didn't complain about this part of the code, but I got some nitpicks:</p>\n\n<pre><code>with open(logfile) as logfile:\n filecontent = logfile.xreadlines()\n for line in filecontent:\n\n# The call to xreadlines() is wasteful; You can iterate over the file descriptor directly.\n# I also wouldn't use the same name for the filename and the file descriptor.\n\nwith open(logfile) as f:\n for line in f:\n</code></pre>\n\n<p>Two more suggestions:</p>\n\n<ul>\n<li><p>Make use of the <a href=\"http://docs.python.org/howto/logging.html#logging-basic-tutorial\" rel=\"nofollow\">logging module</a>. That way you won't have to do the kind of (buggy and unpretty) custom implementation here:</p>\n\n<pre><code>log = file('/logs/split_logs/processed_data.log', 'w')\nlog.write('%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\n' % (timestamp, opco, service, recvcount, ackcount, nackcount, retrycount))\nlog.close()\n</code></pre></li>\n<li>Have a look at <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a>. It has something to say about your overlong lines.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T21:39:12.163", "Id": "3471", "ParentId": "3454", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-13T18:00:45.737", "Id": "3454", "Score": "7", "Tags": [ "python", "optimization", "hash-map" ], "Title": "Holding records using dictionary" }
3454
<p>In your opinion what is the best way to construct an object given the two examples below:</p> <p><strong>Option 1:</strong> Lots of parameters</p> <pre><code>private string firstname; private string surname; private Address homeAddress; private PhoneNumber homeNumber; public Person(string firstname, string surname, Address homeAddress, PhoneNumber homeNumber) { _firstname = firstname; _surname = surname; _homeAddress = homeAddress; _homeNumber = homeNumber; } public string getFirstname() { return firstname; } public string getSurname() { return surname; } public Address getAddress() { return address; } public PhoneNumber getHomeNumber() { return _homeNumber; } </code></pre> <p><strong>Option 2:</strong> no parameters and use of set methods</p> <pre><code>private string firstname; private string surname; private Address homeAddress; private PhoneNumber homeNumber; public Person() { } public string getFirstname() { return firstname; } public void setFirstname(String value) { firstname = value; } public string getSurname() { return surname; } public void setSurname(String value) { surname = value; } public Address getAddress() { return address; } public void setAddress(Address value) { address = value; } public PhoneNumber getHomeNumber() { return _homeNumber; } public void setHomeNumber(PhoneNumber value) { _homeNumber = value; } </code></pre> <p>Which method do you prefer? In my mind, option 1 is better because you know that the state of your object cannot be changed. I believe this is called immutability and is something that should be desired? On the other hand, it can quickly get out of hand and ugly if you have more than a handful of parameters.</p> <p>I am aware that some languages such as C# have nice features that would probably make option 1 more appealing such as named and optional parameters however this question was prompted while dealing with Java code.</p> <p><strong>Update:</strong> Thank you for all of your suggestions. I will comment on each answer individually but a few answers suggested using a factory method instead of having the constructor do all of the work. This was actually the pattern I was using because it is a standard at work but I've never really seen the advantage of it as opposed to using the constructor to do the work. This is more how the code looked:</p> <pre><code>private string firstname; private string surname; private Address homeAddress; private PhoneNumber homeNumber; private Person() { } public Person factoryCreate(string firstname, string surname, Address homeAddress, PhoneNumber homeNumber) { Person person = new Person(); person.setFirstname(firstname); person.setSurname(surname); person.setHomeAddress(homeAddress); person.setHomeNumber(homeNumber); return person; } public string getFirstname() { return firstname; } public void setFirstname(String value) { firstname = value; } public string getSurname() { return surname; } public void setSurname(String value) { surname = value; } public Address getAddress() { return address; } public void setAddress(Address value) { address = value; } public PhoneNumber getHomeNumber() { return _homeNumber; } public void setHomeNumber(PhoneNumber value) { _homeNumber = value; } </code></pre> <p>From the discussion about having constructors do little work and using builders, I can see why having the factory method is a good one. My understanding of factory methods was that they were used to create a class given a few options. For example, if you have an <code>Employee</code> class and that is sub-classed by <code>FullTimeEmployee</code> and <code>PartTimeEmployee</code>, you would have a <code>factory()</code> method on <code>Employee</code> to deal with creating the more concrete class.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T09:32:55.910", "Id": "5211", "Score": "0", "body": "Good question! An answer to the downside of option 1 is to require programmers to properly comment their long constructor calls (one comment per parameter). Something that can be enforced only by peer review... I believe modern trend is to use builders instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-30T14:31:07.053", "Id": "231646", "Score": "0", "body": "As stated in Clean Code, a comment is a failure to express by the programming language. Luckily for C#programmers there are named parameters that it is the language way to do this. Aditional benefit is that the IDE can detect the change during refactors and prevents bugs if the signature changes" } ]
[ { "body": "<p>Starting out with immutable classes is typically a good idea. (according to Effective Java). I like to do things that way when I can.</p>\n\n<p>You should also check out the <a href=\"http://en.wikipedia.org/wiki/Builder_pattern\" rel=\"nofollow\">builder pattern</a>.</p>\n\n<p>As it encapsulates your initialization and allows you to add more parameters without affecting the constructors signature.</p>\n\n<p>EDIT: Here is an example based on your code, It might be a cross between C# and java but I think you will get the idea...</p>\n\n<pre><code>public class Person {\n private string firstname;\n private string surname;\n private Address homeAddress;\n private PhoneNumber homeNumber;\n\n public Person( Builder builder ) {\n super();\n this.firstname = builider.firstname;\n this.surname = builder.surname;\n this.homeAddress = builder.homeAddress;\n this.homeNumber = builder.homeNumber;\n }\n\n pubilc static class Builder {\n private integer id;//required field.\n private string firstname;//optional field.\n private string surname;//optional field.\n private Address homeAddress;// optional field.\n private PhoneNumber homeNumber;// optional field.\n\n public Builder( integer id ) {\n super();\n if ( id == null ) {\n //deal with it.\n }\n this.id = id;\n }\n public Builder setFirstname( string firstName ) {\n this.firstname = firstname;\n return this;\n }\n public Builder setSurname ( string surname ) {\n this.surname = surname;\n return this;\n }\n public Builder setHomeAddress( Address homeAddress ) {\n this.homeAddress = homeAddress;\n return this;\n }\n public Builder setHomeNumber( PhoneNumber homeNumber ) {\n this.homeNumber = homeNumber;\n return this;\n }\n }\n // Person.getXXX() goes here.\n\n public static void main( String...args ) {\n\n Person.Builder builder = new Person.Builder( new integer( 123 ) );\n builder.setFirstname( \"foo\" ).setSurname( \"bar\" ).setHomeAddress( new HomeAddress() ).setHomeNumber( new PhoneNumber() );\n\n // always the same\n Person person = new Person( builder );\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T10:24:29.873", "Id": "5468", "Score": "0", "body": "I'm not so sure that I can see the benefits of a builder class. I suppose you are making the `Person` class immutable which is good, especially if it's a database class but then you have another class which is immutable. It seems over-architected to me but do you think that is mostly because of the fairly simplistic example? Also, what about the problem of a little used code path that doesn't set all of the necessary fields? How do you spot that? Unit tests?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T13:19:38.367", "Id": "5471", "Score": "0", "body": "YMMV. I tend to go immutable by default since I can always expose properties and functionality as I needed. When I do expose it I know for what specific reasons I expose it (comment that) and I have intimate knowledge of that change.It's the builder's responsibility to ensure all required fields are populated. That's why the builder's constructor takes the required fields and the optional fields are setter injected. The builder can contain more involved validation logic if needed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T17:59:23.130", "Id": "3463", "ParentId": "3462", "Score": "0" } }, { "body": "<p>I also recommend the Builder pattern, however I prefer to do it this way:</p>\n\n<pre><code>public class Person {\n private int id;\n private String firstname;\n private String surname;\n private Address homeAddress;\n // etc.\n\n private Person() {// IMPORTANT, private constructor\n }\n\n public static class Builder {\n private Person person;\n\n public Builder(int id) {\n if (id == 0) {\n //fuck it\n }\n person = new Person();\n }\n\n public Builder setFirstname(String firstName) {\n person.firstname = firstName;\n return this;\n }\n\n public Builder setSurname(String surname) {\n person.surname = surname;\n return this;\n }\n // etc.\n\n public Person build() {\n // don't return the object if it was not created correctly... for instance:\n if (person.firstname == null) {\n throw new IllegalStateException(\"You are a fool\");\n }\n return person;\n }\n }\n\n public static void main(String... args) {\n Person person = new Person.Builder(666)\n .setFirstname(\"foo\")\n .setSurname(\"bar\")\n .build();\n }\n}\n</code></pre>\n\n<p>Main difference with regards to the previous response is that:</p>\n\n<ul>\n<li>You can't create a Person unless you use a Builder</li>\n<li>The builder knows when a person is ready, otherwise it won't return anything.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T10:16:43.977", "Id": "5466", "Score": "0", "body": "As far as the builder pattern goes, I prefer this one as it is more complete. However, how do you deal with @jimreed's suggestion that the builder pattern can cause exceptions in production if there is a little used code path that doesn't fully create a person? Is it simply having confidence in your unit tests?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-29T20:45:19.833", "Id": "267855", "Score": "0", "body": "This code does not even compile. How has it been upvoted? You can't have a non-static constructor nor methods in a static class." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T19:07:49.437", "Id": "3467", "ParentId": "3462", "Score": "2" } }, { "body": "<p>It depends on whether the data elements are required for the object to be well defined or if they are completely optional.</p>\n\n<p>My personal preference is for the constructor to have parameters for all the required data elements and use set methods for everything else. I also declare the default (parameterless) constructor to be private. That way the compiler guarantees that no one will create an incompletely defined object.</p>\n\n<p>If firstname and lastname are required but address and phone number are optional, I would do the following:</p>\n\n<pre><code>private string _firstname;\nprivate string _surname;\nprivate Address _homeAddress;\nprivate PhoneNumber _homeNumber;\n\nprivate Person()\n{\n // Ensure unitialized Person cannot be created\n}\n\npublic Person(string firstname, string surname)\n{\n _firstname = firstname;\n _surname = surname;\n}\n\n// getters and setters omitted for brevity\n</code></pre>\n\n<p>The disadvantage of using the Builder pattern as recommended in other answers is that the completeness check is deferred to runtime. If you have a code path that is very rarely executed and you change Person so that more data is required, then you could deliver code that will fail in the field. With my approach, you will know about the problem the next time you try to compile your code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T10:14:44.680", "Id": "5465", "Score": "0", "body": "Thank you for pointing out the problem with the builder pattern. It also seems a bit over-architected to me but maybe that is because of the simplicity of the example here.I have updated the original question with code that utilises a factory method to shift the work away from the constructor." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T20:39:43.720", "Id": "3469", "ParentId": "3462", "Score": "10" } }, { "body": "<p>When building objects, having a constructor that does very little is ideal. This becomes especially true once you are testing your objects with unit tests.</p>\n\n<p>Like other suggestions, I would leave the proper construction of the object to a builder or factory method. I would emphasize that you should only include parameters that are required for it to be a proper object, and that generally you want no more than 7 (give or take 2) parameters. If you have more parameters than that, your class may be trying to do too much.</p>\n\n<p>However, things like an ID that relates to a database field (or other storage mechanism) are better left to be set by the Data Mapper, Repository, etc. that you are using.</p>\n\n<p>In my native programming language, it would look something like this:</p>\n\n<pre><code>class Person\n{\n private $_id; // optional (not necessary for a Person... set once stored)\n private $_name; // required\n private $_address; // optional\n\n /**\n * @param $name - In this example, I'm just going to pretend like this is required.\n * It probably doesn't make sense for there to be an instance of a \n * Person without a name.\n * @return Person\n */\n public static function factory( $name )\n {\n $Person = new Person();\n $Person-&gt;setName($name);\n\n return $Person;\n }\n\n public function setId($id)\n {\n $this-&gt;_id = $id;\n }\n\n public function getId()\n {\n return $id;\n }\n\n public function setName($name)\n {\n $this-&gt;_name = $name;\n }\n\n public function getName()\n {\n return $this-&gt;_name;\n }\n\n public function setAddress($address)\n {\n $this-&gt;_address = $address;\n }\n\n public function getAddress()\n {\n return $this-&gt;_address;\n }\n}\n</code></pre>\n\n<p>When creating a Person:</p>\n\n<pre><code>$PersonRepository = new PersonRepository();\n$Person = Person::factory('Sarah');\n$PersonRepository-&gt;save($Person); // This generates an ID for $Person before saving\n</code></pre>\n\n<p>When retrieving a Person:</p>\n\n<pre><code>$PersonRepository = new PersonRepository();\n$Person = $PersonRepository-&gt;getById($id); \n</code></pre>\n\n<p>and the Repository in this case would be responsible for doing something like...</p>\n\n<pre><code>$Person = new Person();\n$Person-&gt;setId($storageResult['id']);\n$Person-&gt;setName($storageResult['name']);\n$Person-&gt;setAddress($storageResult['address']);\nreturn $Person;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T10:28:39.903", "Id": "5469", "Score": "0", "body": "I have updated my original question now to use a factory method and it does look very similar to your answer now. I am marking this as the answer because I like the idea of devolving the creation of an object to a factory method rather than using another class to build a person." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T21:04:09.283", "Id": "3470", "ParentId": "3462", "Score": "4" } }, { "body": "<p>The answer isn't necessarily language agnostic, because it would be silly not to use the facilities of your language to address this issue...<br>\nSo your question is valid in Java and other intermediate language, but is more pointless in some higher level languages.</p>\n\n<p>I am thinking of Scala, where you have indeed named and default parameters, allowing to have constructors with lot of parameters while keeping readability: you name the parameters on the call site, which similar to the chaining of sets, but safer as mandatory parameters (without default) must be present.</p>\n\n<p>On the other hand, you can also use type tricks (called phantom types, if I understood correctly the articles I have read, but not totally assimilated...) to force a builder to get all the required elements. When I write \"force\", I mean \"enforced by the compiler\", ie. your code must be correct at compile time, it isn't just checked at run time. Powerful.</p>\n\n<p>I won't address your specific question (solution working for all languages), the answers I see are much better than the one I could make, but I thought I should mention interesting alternatives to your question.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T10:20:09.327", "Id": "5467", "Score": "0", "body": "Thank you for pointing out that this isn't really a language agnostic question. I did intend it to be that way but as I was composing it, I was beginning to realise that it wasn't at all. Your answer did make me think a bit more carefully about different ways to accomplish this in C# (which is my preferred language) and named and default parameters are a much bigger help than I gave credit for in my original question." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T09:30:58.300", "Id": "3479", "ParentId": "3462", "Score": "2" } }, { "body": "<ul>\n<li>Making a constructor do as less work as possible is good. To me, simply assigning parameters to local fields is not work. That to me, is zero work - No logic is involved.</li>\n<li>Depending on your programming language, marking the fields as final is good, if you are not modifying them. My big reason for this is for readability - its immediately clear that the final fields are the easy bits - can't be modified and less hanging threads to keep in my thread as I read the rest of the code. This doesn't seem like a big deal for your current class, but I am guessing that the your code snippet is part of a much bigger class, and even if it wasn't, its pretty much something I always do.</li>\n<li>Exposing the setters just to use them by the builder and not anywhere else introduces more complexity(see point 2).</li>\n<li>Using the builder brings more verbosity. I wouldn't use it just for optional fields - constructor overloading/passing in null is much cleaner for this. In general, I use the builder pattern when the construction process is more laborious then just setting some fields.</li>\n<li>Too many paramters is a code smell but 4 parameters seems okay. Especially, if they actually seem like they belong to this class, and they have different types amongst them(not all are strings for e.g.).</li>\n</ul>\n\n<p>My conclusion: I would just mark the fields final and stick with your option 1. :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T08:17:18.850", "Id": "8052", "ParentId": "3462", "Score": "0" } } ]
{ "AcceptedAnswerId": "3470", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T17:54:58.383", "Id": "3462", "Score": "7", "Tags": [ "c#", "constructor" ], "Title": "Constructors - lots of paramters or none and use of set methods" }
3462