body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have a bit of code that came from <a href="http://www.eggheadcafe.com/tutorials/aspnet/aa5ff306-16a1-4014-a51d-6ffde0894a0d/aspnet-request-logging-with-asynchronous-fire-and-forget-pattern.aspx">Egg Head Cafe</a> a long while ago and it's been working great. But I ran the entire site through Redgate's Profiler. and it came up as the biggest hot spot in my code. (Honestly it ran so hot the rest of my site hardly spiked.) The point of it is to capture traffic into my site and filter out crawler traffic if it's needing to be blocked. It's worked greatly for years and I'm wanting to reuse it, but hoping it can be optimized a bit. </p> <p>Starts out in the Global.asax:</p> <pre><code>protected void Application_PreRequestHandlerExecute(object sender, EventArgs e) { Logger.LogRequest(sender as HttpApplication); } </code></pre> <p>This moves into the Logger class. Not the real name, just changed for the post.</p> <pre><code>public class Logger { private static string _conn = ConfigurationManager.AppSettings["MyDatabase"]; private static bool _denyBots = false; private static void DenyAccess(HttpApplication app) { app.Response.StatusCode = 0x191; app.Response.StatusDescription = "Access Denied"; app.Response.Write("401 Access Denied"); app.CompleteRequest(); } public static bool IsCrawler(HttpRequest request) { bool isCrawler = request.Browser.Crawler; if (!isCrawler) { Regex regEx = new Regex("Slurp|slurp|ask|Ask|Teoma|teoma");//shortened isCrawler = regEx.Match(request.UserAgent).Success; } return isCrawler; } public static void LogRequest(HttpApplication app) { HttpRequest request = app.Request; bool isCrawler = IsCrawler(request); string userAgent = request.UserAgent; string requestPath = request.Url.AbsoluteUri; string referer = (request.UrlReferrer != null) ? request.UrlReferrer.AbsoluteUri : ""; string userIp = request.UserHostAddress; string isCrawlerStr = isCrawler.ToString(); object[] parms = new object[] { userIp, userAgent, requestPath, referer, isCrawlerStr }; try { ThreadUtil.FireAndForget(new ThreadUtil.InsertOrUpdateDelegate(ThreadUtil.InsertLog), new object[] { _conn, "insertRequest", parms }); } catch (Exception ex) { app.Response.Write(ex.Message); } if (isCrawler &amp;&amp; _denyBots) DenyAccess(app); } } </code></pre> <p>And the actual threading code:</p> <pre><code>public class ThreadUtil { private static AsyncCallback callback = new AsyncCallback(ThreadUtil.EndWrapperInvoke); private static DelegateWrapper wrapperInstance = new DelegateWrapper(ThreadUtil.InvokeWrappedDelegate); private static void EndWrapperInvoke(IAsyncResult ar) { wrapperInstance.EndInvoke(ar); ar.AsyncWaitHandle.Close(); } public static void FireAndForget(Delegate d, params object[] args) { wrapperInstance.BeginInvoke(d, args, callback, null); } private static void InvokeWrappedDelegate(Delegate d, object[] args) { d.DynamicInvoke(args); } public static void InsertLog(string conn, string proc, object[] parms) { SqlHelper.ExecuteNonQuery(conn, proc, parms); } private delegate void DelegateWrapper(Delegate d, object[] args); public delegate void InsertOrUpdateDelegate(string conn, string proc, object[] parms); } </code></pre> <p>The stored procedure is going to be replaced with just a parameterized SQL insert. Maybe this is fine and it's just the profiler having issues with it as it was a couple years ago. Liek I said it's worked fine for me this long, but it just seems like it can be better. Also the title might be terrible, I suck at titling. </p> <p>Edit: Thinking about it this morning I'm thinking maybe the <code>Application_PreRequestHandlerExecute</code> is blocking causing a wait before the new thread is fired off which might be why the profilier had such an issue with it? Maybe someone could chime in on that. Also note that the code that was profilied was running under a URL rewriter so all requests are being handled by ASP.NET so each actual page being loaded could cause this code to execute anywhere from once to 30 times or more if there are many images or scripts loading on the page. </p> <p>Edit: Ran it through ANTS again and found the following hot spots:</p> <pre><code>public static void LogRequest(HttpApplication app) { ... bool isCrawler = IsCrawler(request); string requestPath = request.Url.AbsoluteUri; ... string userIp = request.UserHostAddress; ... ThreadUtil.FireAndForget(new ThreadUtil.InsertOrUpdateDelegate(ThreadUtil.InsertLog), new object[] { _conn, "insertRequest", parms }); ... } public static void FireAndForget(Delegate d, params object[] args) { wrapperInstance.BeginInvoke(d, args, callback, null); } </code></pre> <p>The two main offenders are <code>string requestPath = request.Url.AbsoluteUri;</code> and <code>wrapperInstance.BeginInvoke(d, args, callback, null);</code></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T08:17:31.510", "Id": "6986", "Score": "1", "body": "`StatusCode = 0x191`? You think in HEX?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T10:45:18.580", "Id": "6996", "Score": "0", "body": "Haha. No that was part of the original code. I know nothing of hex in all honesty, I've just never had something that needed it. I'm sure I will at some point." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T13:43:26.653", "Id": "7177", "Score": "1", "body": "Is the profiler eluding to the hot spot being within the ThreadUtil, the LogRequest or the regex within IsCrawler? Hopefully it gives you more granular detail." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T19:28:42.843", "Id": "7182", "Score": "0", "body": "It was pointing to `LogRequest(HttpApplication app)`. Thats as far as it dug into it from what I remember." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T09:39:48.320", "Id": "7296", "Score": "0", "body": "What's your priority? Overall CPU load or time in the main page render thread?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-18T14:44:03.617", "Id": "7314", "Score": "0", "body": "In the end, page rendering time." } ]
[ { "body": "<p>The BeginInvoke() call is a hotspot because it will need a thread from the thread pool (and when there are too many used, it will wait for one to be available). </p>\n\n<p>As a micro-optimization, try replacing that with ThreadPool.QueueUserWorkItem and measuring again, but in the end you're starting one (or more) sql insert query per request, that will use some resources no matter what is the async approach you use.</p>\n\n<p>You could also use SqlCommand's BeginExecuteNonQuery / EndExecuteNonQuery to do your inserts async (instead of BeginInvoke / EndInvoke or the ThreadPool), but in the end the fastest solution involves <em>not</em> doing the insert to db per request, just write the needed stuff to some kind of queue (preferably one faster than the db) and insert to the db at a later time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T23:03:06.683", "Id": "10936", "Score": "1", "body": "I push messages to MSMQ and then I have a task that runs every 1 minute and does a bulk insert into the data base. This has worked very well for us. MSMQ pushes are extremly fast. I'm very fond of this approach when it's silly things like logging/tracking/analytics, especially when every ms counts." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T17:34:07.230", "Id": "7000", "ParentId": "4659", "Score": "5" } }, { "body": "<p>Looks sharp to me. I'd do a little bit of declarative intent:</p>\n\n<pre><code>public static class Logger\n{\n private static readonly string _conn = ConfigurationManager.AppSettings[\"MyDatabase\"];\n private const bool _denyBots = false;\n\n private static void DenyAccess(HttpApplication app)\n {\n app.Response.StatusCode = 0x191;\n app.Response.StatusDescription = \"Access Denied\";\n app.Response.Write(\"401 Access Denied\");\n app.CompleteRequest();\n }\n\n\n public static bool IsCrawler(HttpRequest request)\n {\n bool isCrawler = request.Browser.Crawler;\n if (!isCrawler)\n {\n Regex regEx = new Regex(\"Slurp|slurp|ask|Ask|Teoma|teoma\");//shortened\n isCrawler = regEx.Match(request.UserAgent).Success;\n }\n return isCrawler;\n }\n\n public static void LogRequest(HttpApplication app)\n {\n HttpRequest request = app.Request;\n\n bool isCrawler = IsCrawler(request);\n string userAgent = request.UserAgent;\n string requestPath = request.Url.AbsoluteUri;\n string referer = (request.UrlReferrer != null) ? request.UrlReferrer.AbsoluteUri : string.Empty;\n string userIp = request.UserHostAddress;\n string isCrawlerStr = isCrawler.ToString();\n\n object[] parms = new object[] { userIp, userAgent, requestPath, referer, isCrawlerStr };\n try\n {\n ThreadUtil.FireAndForget(\n new ThreadUtil.InsertOrUpdateDelegate(ThreadUtil.InsertLog),\n new object[] { _conn, \"insertRequest\", parms });\n }\n catch (Exception ex)\n {\n app.Response.Write(ex.Message);\n }\n\n if (isCrawler &amp;&amp; _denyBots)\n DenyAccess(app);\n }\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>public static class ThreadUtil\n{\n private static readonly AsyncCallback callback = EndWrapperInvoke;\n private static readonly DelegateWrapper wrapperInstance = InvokeWrappedDelegate;\n\n public delegate void InsertOrUpdateDelegate(string conn, string proc, object[] parms);\n\n private delegate void DelegateWrapper(Delegate d, object[] args);\n\n public static void FireAndForget(Delegate d, params object[] args)\n {\n wrapperInstance.BeginInvoke(d, args, callback, null);\n }\n\n public static void InsertLog(string conn, string proc, object[] parms)\n {\n SqlHelper.VinManager.ExecuteNonQuery(conn, proc, parms);\n }\n\n private static void EndWrapperInvoke(IAsyncResult ar)\n {\n wrapperInstance.EndInvoke(ar);\n ar.AsyncWaitHandle.Close();\n }\n\n private static void InvokeWrappedDelegate(Delegate d, object[] args)\n {\n d.DynamicInvoke(args);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T23:08:05.277", "Id": "7008", "ParentId": "4659", "Score": "3" } } ]
{ "AcceptedAnswerId": "7000", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T01:16:48.500", "Id": "4659", "Score": "5", "Tags": [ "c#", "asp.net", "multithreading" ], "Title": "Optimizing a Fire and Forget page tracker" }
4659
<p>My code keeps some <code>int</code> value about the date range, and there is a method to check if all of it is zero. Is there a better way to do it than doing this?</p> <pre><code>public bool IsAllDayZero { get { return Today == 0 &amp;&amp; Days1_2 == 0 &amp;&amp; Days3_6 == 0 &amp;&amp; Days7_10 == 0 &amp;&amp; Days11_15 == 0 &amp;&amp; Days16_30 == 0 &amp;&amp; Days31_45 == 0 &amp;&amp; Days46_60 == 0 &amp;&amp; Days60Plus == 0 ; } } </code></pre>
[]
[ { "body": "<p>I see 3 alternative solutions:</p>\n\n<ol>\n<li>Use array of <code>days</code>, and then: <code>days.All(d =&gt; d == 0)</code></li>\n<li>You can define boolean variable <code>areAllDayZero</code> or something else :-) and change it when you set values to properties</li>\n<li>Use reflection</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T06:34:47.503", "Id": "4662", "ParentId": "4661", "Score": "2" } }, { "body": "<p>The question is: <em>Why do you want to change it</em>?</p>\n\n<p>I bet you can get a shorter form with some use of <em>xor</em>, <em>and</em>, <em>or</em> etc. functions but I believe it's not worth it. For example: </p>\n\n<pre><code>public bool IsAllDayZero\n{\n get\n {\n return\n (Today | Days1_2 | Days3_6| Days7_10 | Days11_15 |\n Days16_30 | Days31_45 | Days46_60 | Days60Plus) == 0; \n }\n}\n</code></pre>\n\n<p>It's indeed shorter but no way that it's more clear for some other person about what this code tries to achieve. </p>\n\n<p>Or you can get a faster version that will revert the conditions and then execute only few conditions without a need to check them all but again I doubt that clarity of the code will worth such a changes.</p>\n\n<p>However your current implementation is clear, complete and does exactly what it has to do without some extra noise and I just recommend not to change it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T11:11:05.957", "Id": "7037", "Score": "1", "body": "Maybe having `return (Today + Days1_2 + Days3_6 + Days7_10 + Days11_15 + Days16_30 + Days31_45 + Days46_60 + Days60Plus) == 0;` would make it a little more clear to other people." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T11:26:50.780", "Id": "7041", "Score": "0", "body": "@Piers. It would be clear but not correct - we need to think about overflow in this case. If I try to write the sum of two bytes (1 and 255) into byte field the result will be 0;" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T12:09:18.700", "Id": "7042", "Score": "0", "body": "yeah, you're probably right. As you stated, the current implementation is fine and is probably how I would have done it, plus `&&` is a short-circuit operator in C# and will stop evaluating subsequent conditions as soon as one becomes false." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T06:49:10.350", "Id": "4663", "ParentId": "4661", "Score": "4" } } ]
{ "AcceptedAnswerId": "4663", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T06:27:01.080", "Id": "4661", "Score": "2", "Tags": [ "c#", "datetime", "interval" ], "Title": "Comparing each property to the same value" }
4661
<p>Is this an efficient way to do this?</p> <p>the code is designed to find the nearest friday, without passing Sunday. If it is already past Friday, the start date should equal now.</p> <pre><code>function get_weekend(){ $start = time(); $day = date('w',$now); //find friday, without going past Sunday while ($day &lt; 5 &amp;&amp; $day &gt; 0){ $start = $start + 86400; $day = date('w',$start); } //find nearest sunday to start date $end = $start; while ($day != 0){ $end = $end + 86400; $day = date('w',$end); } $weekend['StartDate']=date("d-F-Y",$start); $weekend['EndDate'] = date("d-F-Y",$end); return $weekend; } </code></pre>
[]
[ { "body": "<p>No need for <code>while</code> loops - just some math:</p>\n\n<pre><code>function get_weekend()\n{\n $start = time();\n $end = $start;\n $day = date('w', $start);\n\n if ($day &gt; 0 &amp;&amp; $day &lt; 5)\n {\n $start = $time()+ ((5 - $day) * 86400);\n }\n\n if ($day != 0)\n {\n $end = time() + (7 - $day) * 86400;\n }\n\n $weekend['StartDate'] = date('d-F-Y', $start);\n $weekend['EndDate'] = date('d-F-Y', $end);\n\n return $weekend;\n}\n</code></pre>\n\n<p>Edit: Found there was a better way to calculate $end;</p>\n\n<p>Edit: Keep finding better code:</p>\n\n<pre><code>function get_weekend()\n{\n $start = time();\n $end = $start;\n $day = date('w', $start);\n\n if ($day &gt; 0)\n {\n if ($day &lt; 5)\n {\n $start += ((5 - $day) * 86400);\n }\n\n $end += (7 - $day) * 86400;\n }\n\n $weekend['StartDate'] = date('d-F-Y', $start);\n $weekend['EndDate'] = date('d-F-Y', $end);\n\n return $weekend;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T12:16:19.357", "Id": "4672", "ParentId": "4668", "Score": "1" } }, { "body": "<p>Short, short version:</p>\n\n<pre><code>function get_weekend()\n{\n $fri = strtotime('friday');\n $sun = strtotime('sunday');\n // strtotime('friday') will be after strtotime('sunday') if it is after 0:00 Friday\n // and before 0:00 on Sunday\n $start = $sun &lt; $fri? now():$fri;\n $weekend = array();\n $weekend['StartDate'] = date('d-F-Y', $start);\n $weekend['EndDate'] = date('d-F-Y', $end);\n return $weekend;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T13:02:34.723", "Id": "4677", "ParentId": "4668", "Score": "2" } } ]
{ "AcceptedAnswerId": "4672", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T09:14:35.350", "Id": "4668", "Score": "1", "Tags": [ "php" ], "Title": "Efficiently working out the nearest weekend" }
4668
<p>Any ideas?</p> <pre><code>public override string ToString() { string returnValue; if (!string.IsNullOrWhiteSpace(Country)) returnValue = string.Format("{0}", Country); else return returnValue; if (!string.IsNullOrWhiteSpace(City)) returnValue += string.Format(", city {0}", City); else return returnValue; if (!string.IsNullOrWhiteSpace(Street)) returnValue += string.Format(", street {0}", Street); else return returnValue; if (!string.IsNullOrWhiteSpace(Block)) returnValue += string.Format(", block {0}", Block); else return returnValue; if (!string.IsNullOrWhiteSpace(Building)) returnValue += string.Format(", building {0}", Building); if (!string.IsNullOrWhiteSpace(Latitude) &amp;&amp; !string.IsNullOrWhiteSpace(Longitude)) returnValue += string.Format(", coordinates {0}:{1}", Latitude, Longitude); return returnValue; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T15:28:57.357", "Id": "7011", "Score": "2", "body": "You did notice that in all but the first case you are returning strings. But the first case `return Country` you are always returning a NULL or an empty string. In which case you may want to make that explicit `return string.empty` just to show that it is nothing that is being returned." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T06:53:36.007", "Id": "7034", "Score": "0", "body": "I'm sorry for the typo. It must be \"return returnValue;\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T00:02:32.107", "Id": "7155", "Score": "0", "body": "@Alex About your Update: There are ways to simplify it, just depends on what you put a higher priority, readability/maintainability or performance etc etc. Your code looks easy to maintain but it could definitely be shorter Or run quicker ... did that make sense? So what exactly did you want simpler?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T07:06:47.553", "Id": "7164", "Score": "0", "body": "I do not know what is a higher priority. It's and a readbility and a perfomance." } ]
[ { "body": "<p>Using \"&amp;&amp;\" it will stop the evaluation at the first false, so something like this should work for you:</p>\n\n<pre><code>public class MyClass\n{\n public string Item1 { get; set; }\n public string Item2 { get; set; }\n public string Item3 { get; set; }\n public string Long { get; set; }\n public string Lat { get; set; }\n public override string ToString()\n {\n var sb = new StringBuilder();\n var tempVar =\n (AddPropertyData(sb, \"{0}\", Item1) &amp;&amp;\n AddPropertyData(sb, \", item2 {0}\", Item2) &amp;&amp;\n AddPropertyData(sb, \", item3 {0}\", Item3)) &amp;&amp;\n AddPropertyData(sb, \", long: {0}, lat: {1}\", Long, Lat);\n\n return sb.Length &gt; 0 ? sb.ToString() : Item1;\n }\n\n private static bool AddPropertyData(StringBuilder sb, string format, params string[] data)\n {\n if (data.All(x =&gt; !String.IsNullOrWhiteSpace(x)))\n {\n sb.AppendFormat(format, data);\n return true;\n }\n return false;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T13:34:45.333", "Id": "7006", "Score": "0", "body": "First question is, why isn't your `AddPropertyData` static? Then, what do you do with \"coordinates\" where the *single value* consists of *2 members* (latitude, longitude)?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T12:56:08.043", "Id": "4676", "ParentId": "4669", "Score": "1" } }, { "body": "<p>I would do something like this:</p>\n\n<pre><code> public override string ToString()\n {\n string returnValue = string.empty;\n\n if (string.IsNullOrWhiteSpace(Country))\n return returnValue; // Note: this is a change from the original code\n // That could have returned NULL. But I think the\n // intent of the function is to always return some\n // form of string.\n\n\n returnValue = string.Format(\"{0}\", Country);\n\n if (string.IsNullOrWhiteSpace(City))\n return returnValue;\n\n returnValue += string.Format(\", city {0}\", City);\n\n if (string.IsNullOrWhiteSpace(Street))\n return returnValue;\n\n returnValue += string.Format(\", street {0}\", Street);\n\n if (string.IsNullOrWhiteSpace(Block))\n return returnValue;\n\n returnValue += string.Format(\", block {0}\", Block);\n\n if (!string.IsNullOrWhiteSpace(Building))\n returnValue += string.Format(\", building {0}\", Building);\n\n if (!string.IsNullOrWhiteSpace(Latitude) &amp;&amp; !string.IsNullOrWhiteSpace(Longitude))\n returnValue += string.Format(\", coordinates {0}:{1}\", Latitude, Longitude);\n\n return returnValue;\n }\n</code></pre>\n\n<p>If you want to compress this slightly. Though I am in two minds weather this is worth it or not:</p>\n\n<pre><code>public class Pair\n{\n public Pair(string v, string f) { this.Value =v; this.Format = f;} \n public string Value { get; private set; }\n public string Format { get; private set; }\n};\n\n public override string ToString()\n {\n string returnValue = string.empty;\n\n string[] address = {new Pair(Country, \"{0}\"),\n new Pair(City, \", city {0}\"),\n new Pair(Street, \", street {0}\"),\n new Pair(Block, \", block {0}\")\n };\n\n foreach(Pair loop in address)\n {\n if (string.IsNullOrWhiteSpace(loop.Value))\n return returnValue;\n\n returnValue += string.Format(loop.Format, loop.Value);\n }\n\n if (!string.IsNullOrWhiteSpace(Building))\n returnValue += string.Format(\", building {0}\", Building);\n\n if (!string.IsNullOrWhiteSpace(Latitude) &amp;&amp; !string.IsNullOrWhiteSpace(Longitude))\n returnValue += string.Format(\", coordinates {0}:{1}\", Latitude, Longitude);\n\n return returnValue;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T16:40:09.597", "Id": "7012", "Score": "0", "body": "-1: I posted 2 answers in this topic and your answer is **exact** duplicate of what I recommend." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T16:46:13.797", "Id": "7013", "Score": "1", "body": "Moreover, using `string` for appending is a bad practice - it's way slower than `StringBuilder`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T20:06:22.567", "Id": "7016", "Score": "0", "body": "@loki2302: I'll take the -1 for not using StringBuilder. But don't vote people down because they have the same idea as you. Anyway this code is superior to yours in the maintainability field. Yours fails on the front that you are trying to hard to be clever and it makes the code less readable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T20:33:33.583", "Id": "7017", "Score": "2", "body": "The idea of this site is to have questions and answers. I see no reason in having the same answer for the same question twice. Read before you post - it's about 3 hours between mine and yours: you had a chance to see that everything you wanted to say has already been said. Not also sure why you think your code is more maintainable: redundant class, redundant logic. My approach is short, stupid and it works. It's really easy to understand and modify. I see no reason why someone might want to have extra `if`s when the problem is easily solvable with less code and less logic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T20:37:26.417", "Id": "7018", "Score": "0", "body": "I can add 10 more comments like: why is your 'Pair' not `sealed`? and even why is it `public`? why do you use bad names like `v` and `f`? Why do you use that strange formatting? why there are 2 returns in your `ToString()`? I don't think your code is *really* better by any mean." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T20:40:41.387", "Id": "7019", "Score": "0", "body": "Just a brief summary: in my solution, there's 1 explicit loop and 1 explicit `if`. What's about yours? Less logic, less problems." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T20:47:37.400", "Id": "7020", "Score": "0", "body": "@loki2302: If you think yours is so much better than why go to the effort of burrying mine. Just allow the general reader to vote on them as appropriate. Now that I re-read yours I see that mine is nowhere near the same so you have nothing to complain about. It is still a worse solution. Yours would not pass a decent code review. By failing the too clever by half rule and is thus not maintainable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T20:58:11.810", "Id": "7021", "Score": "2", "body": "I'm not trying to say mine is better, I just see complexity and redundancies in yours. Re-read your code." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T15:49:46.760", "Id": "4681", "ParentId": "4669", "Score": "0" } }, { "body": "<p>I find that writing it this way makes it more maintainable and relatively efficient.</p>\n\n<pre><code>public class Information\n{\n public string Country { get; set; }\n public string City { get; set; }\n public string Street { get; set; }\n public string Block { get; set; }\n public string Building { get; set; }\n public string Latitude { get; set; }\n public string Longitude { get; set; }\n\n private IEnumerable&lt;Tuple&lt;string[], string&gt;&gt; DataFormatPairs()\n {\n yield return Tuple.Create(new[] { Country }, \"{0}\");\n yield return Tuple.Create(new[] { City }, \"city {0}\");\n yield return Tuple.Create(new[] { Street }, \"street {0}\");\n yield return Tuple.Create(new[] { Block }, \"block {0}\");\n yield return Tuple.Create(new[] { Building }, \"building {0}\");\n yield return Tuple.Create(new[] { Latitude, Longitude }, \"coordinates {0}:{1}\");\n }\n public override string ToString()\n {\n var data = DataFormatPairs()\n .TakeWhile(p =&gt; p.Item1.All(s =&gt; !String.IsNullOrWhiteSpace(s)))\n .Select(p =&gt; String.Format(p.Item2, p.Item1));\n return String.Join(\", \", data);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T18:57:54.493", "Id": "4683", "ParentId": "4669", "Score": "2" } }, { "body": "<p>Here's another variation:</p>\n\n<pre><code>public override string ToString() { \n var list = new List&lt;string&gt;();\n\n if (!string.IsNullOrWhiteSpace(Country)) \n list.Add(string.Format(\"{0}\", Country));\n\n if (!string.IsNullOrWhiteSpace(City)) \n list.Add(string.Format(\"city {0}\", City));\n\n if (!string.IsNullOrWhiteSpace(Street)) \n list.Add(string.Format(\"street {0}\", Street));\n\n if (!string.IsNullOrWhiteSpace(Block)) \n list.Add(string.Format(\"block {0}\", Block));\n\n if (!string.IsNullOrWhiteSpace(Building)) \n list.Add(string.Format(\"building {0}\", Building));\n\n if (!string.IsNullOrWhiteSpace(Latitude) \n &amp;&amp; !string.IsNullOrWhiteSpace(Longitude)) \n list.Add(string.Format(\"coordinates {0}:{1}\", Latitude, Longitude));\n\n return list.Count &gt; 0 ? String.Join(\", \", list.ToArray()) : string.Empty;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T06:51:02.763", "Id": "7033", "Score": "1", "body": "What is the difference between your code and my code?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T03:20:31.797", "Id": "4693", "ParentId": "4669", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T11:11:06.047", "Id": "4669", "Score": "6", "Tags": [ "c#", "strings" ], "Title": "Simplifying ToString() implementation" }
4669
<p>I have the following code, which replaces " " &lt;-- Spaces with "-" &lt;-- Dash.<br> Because some of the title text will be returned with more spaces, it converts it into 3 dashes. </p> <p>Examples of Possible Titles:</p> <ul> <li>"Hello&nbsp;&nbsp;World&nbsp;&nbsp;From&nbsp;&nbsp;Jquery" &lt;--- Notice 2 Spaces between the words, not 1</li> <li>"Main Title - Sub-Title or description here" </li> </ul> <p>I would like the above titles to be turned into: </p> <ul> <li>"Hello-World-From-Jquery" &lt;---- (Not "Hello--World--From--Jquery")</li> <li>"Main-Title-Sub-Title-or-description-here" &lt;--- (Not "Main-Title---Sub-Title-or-desc...")</li> </ul> <p>This is what I got so far, but its not ideal as you can see. Example:</p> <pre><code>var dirty_url = ui.item.label; var url = dirty_url.replace(/\s+/g,"-"); var url = url.replace(/---/g,"-"); </code></pre> <p>So basically, I want to convert all spaces and illegal characters (Its for a url) to "-" to be used in a url. I only want a maximum of 1 dash between charactors.</p>
[]
[ { "body": "<p>Easy enough - regular expressions have an \"alternation\" operator, which works a lot like an \"or\".</p>\n\n<pre><code>var dirty_url = ui.item.label;\nvar url = dirty_url.replace(/(\\s+|-{2,})/g,\"-\");\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T11:50:11.460", "Id": "6997", "Score": "0", "body": "God bless you!.. thats what I was looking for!!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T11:51:27.060", "Id": "6998", "Score": "0", "body": "just testing, and it doesnt really solve my problem tho, still get 3 (---) when I only want 1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T12:02:44.310", "Id": "6999", "Score": "0", "body": "It looks to be working in my testing. Still, I've edited the regex to be slightly better - it will no longer replace a single dash with a single dash." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T11:48:57.187", "Id": "4671", "ParentId": "4670", "Score": "1" } }, { "body": "<p>Shouldn't this work:</p>\n\n<pre><code>var dirty_url = ui.item.label;\nvar url = dirty_url.replace(/[-\\s]+/g,'-')\n</code></pre>\n\n<p>Or, for more thorough: </p>\n\n<pre><code>var url = dirty_url.replace(/[-\\s@#$%^&amp;*]+/g,'-') // etc...\n</code></pre>\n\n<p>Though at this point, you might just want to remove all non word characters:</p>\n\n<pre><code>var url = dirty_url.replace(/\\W+/g,'-')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T13:31:23.073", "Id": "7005", "Score": "0", "body": "Good call using character sets. That should actually work better than my answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T13:16:18.523", "Id": "4678", "ParentId": "4670", "Score": "3" } } ]
{ "AcceptedAnswerId": "4678", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T11:27:22.557", "Id": "4670", "Score": "1", "Tags": [ "javascript", "regex" ], "Title": "Refactor 2 regular expressions in Javascript into 1 statement" }
4670
<p>Even in the presence of <code>&lt;fstream&gt;</code>, there may be reason for using the <code>&lt;cstdio&gt;</code> file interface. I was wondering if wrapping a <code>FILE*</code> into a <code>shared_ptr</code> would be a useful construction, or if it has any dangerous pitfalls:</p> <pre><code>#include &lt;cstdio&gt; #include &lt;memory&gt; std::shared_ptr&lt;std::FILE&gt; make_file(const char * filename, const char * flags) { std::FILE * const fp = std::fopen(filename, flags); return fp ? std::shared_ptr&lt;std::FILE&gt;(fp, std::fclose) : std::shared_ptr&lt;std::FILE&gt;(); } int main() { auto fp = make_file("hello.txt", "wb"); fprintf(fp.get(), "Hello world."); } </code></pre> <p><strong>Update:</strong> I just realized that it is <em>not</em> allowed to <code>fclose</code> a null pointer. I modified <code>make_file</code> accordingly so that in the event of failure there won't be a special deleter.</p> <hr> <p><strong>Second update:</strong> I also realized that a <code>unique_ptr</code> might be a more suitable than <code>shared_ptr</code>. Here is a more general approach:</p> <pre><code>typedef std::unique_ptr&lt;std::FILE, int (*)(std::FILE *)&gt; unique_file_ptr; typedef std::shared_ptr&lt;std::FILE&gt; shared_file_ptr; static shared_file_ptr make_shared_file(const char * filename, const char * flags) { std::FILE * const fp = std::fopen(filename, flags); return fp ? shared_file_ptr(fp, std::fclose) : shared_file_ptr(); } static unique_file_ptr make_file(const char * filename, const char * flags) { return unique_file_ptr(std::fopen(filename, flags), std::fclose); } </code></pre> <p><em>Edit.</em> Unlike <code>shared_ptr</code>, <code>unique_ptr</code> only invokes the deleter if the pointer is non-zero, so we can simplify the implementation of <code>make_file</code>.</p> <p><strong>Third Update:</strong> It is possible to construct a shared pointer from a unique pointer:</p> <pre><code>unique_file_ptr up = make_file("thefile.txt", "r"); shared_file_ptr fp(up ? std::move(up) : nullptr); // don't forget to check </code></pre> <hr> <p><strong>Fourth Update:</strong> A similar construction can be used for <code>dlopen()</code>/<code>dlclose()</code>:</p> <pre><code>#include &lt;dlfcn.h&gt; #include &lt;memory&gt; typedef std::unique_ptr&lt;void, int (*)(void *)&gt; unique_library_ptr; static unique_library_ptr make_library(const char * filename, int flags) { return unique_library_ptr(dlopen(filename, flags), dlclose); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T13:45:13.047", "Id": "7007", "Score": "0", "body": "That should work fine. Just out of curiosity, what reasons may there be to prefer cstdio over fstream?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T13:48:11.470", "Id": "7008", "Score": "3", "body": "To be brutally honest, I have several programs to dissect binary files, so I frequently want to print out some blocks of data in fixed-width hex, and others in decimals, and others in floats, and I'm very happy with `printf` for that purpose. Attempts to do that in `iostreams` lead to dramatic amounts of boilerplate code and it's never clear whether something will come out decimal or hex. So `fprintf` it is :-) But I was just sort of curious in general whether this would be a useful and correct idiom." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T15:21:15.600", "Id": "7009", "Score": "2", "body": "Would `unique_ptr` not be a better choice? Are you really going to share it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T15:23:02.843", "Id": "7010", "Score": "1", "body": "Wouldn't being able to share it be cool? Yeah, `unique_ptr` is certainly an alternative... I just thought of another application: You can put those guys into a standard container and thus manage a collection of open files easily." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-27T02:24:53.770", "Id": "9815", "Score": "1", "body": "I discovered that `unique_ptr` is better in the sense that it only invokes the deleter if the pointer is not null. Also, you can create a shared pointer from a unique one, but that opens up the problem of null pointer deletion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T00:07:39.473", "Id": "67859", "Score": "0", "body": "You may also want to use a custom deleter for your shared pointer, which will call fclose" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-01T11:12:42.207", "Id": "67860", "Score": "0", "body": "one of the disadvantage of unique_ptr - the need for the use of the C++0x. the possibility of using a boost equivalent instead it - discussed at [stackoverflow](http://stackoverflow.com/questions/2953530/unique-ptr-boost-equivalent)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-08T16:28:50.747", "Id": "222173", "Score": "0", "body": "About making `shared_ptr` from a null `unique_ptr` - `Since c++17 ...If r.get() is a null pointer, this overload is equivalent to the default constructor (1).`[link](http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-08T16:44:30.340", "Id": "222177", "Score": "0", "body": "@user362515: Yes, thank god. It was finally addressed by [LWG 2415](http://cplusplus.github.io/LWG/lwg-defects.html#2415)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-30T03:38:41.273", "Id": "335489", "Score": "0", "body": "typedef std::unique_ptr<std::FILE, decltype(fclose) > unique_file_ptr;\n\ncould be slightly easier to eye." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-30T07:30:05.077", "Id": "335490", "Score": "0", "body": "Even further:\n\ntemplate<class CloseFunc, class OpenFunc, class... Args >\nauto\nmake_unique_ptr(CloseFunc close_func, OpenFunc open_func, Args&&... args ) \n -> typename std::unique_ptr< typename remove_pointer<\n typename result_of<OpenFunc&&(Args&&...)>::type\n >::type\n , decltype(close_func)> \n{\n return std::unique_ptr<FILE, decltype(close_func) > ( open_func(std::forward<Args>(args)...), &fclose);\n}\n\n\n\nsee https://wandbox.org/permlink/5NJuAV7u1hnPLu2j" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-30T15:06:32.417", "Id": "335523", "Score": "0", "body": "@zhaorufei: Actually, it would be better to have a (default-constructible) class, since that one's call operator could be inlined." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-30T15:11:47.713", "Id": "335525", "Score": "0", "body": "@zhaorufei: (Also, `decltype(fclose)` doesn't actually work: [demo](https://wandbox.org/permlink/0sKaVNtTUhQN9gvf). I know it could be fixed, just saying.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-10-02T13:22:46.690", "Id": "335749", "Score": "0", "body": "@KerrekSB the decltype(fclose) doesn't work in your demo because in the context unique_ptr<FILE, decltype(fclose)> it's a function type, while the second fclose is decayed to a function pointer, which is mismatch.\n\nsimply add a & to explicitly get the function pointer fixed that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-10-02T13:28:18.460", "Id": "335754", "Score": "0", "body": "@zhaorufei: As I said, I understand that..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-01T15:55:57.370", "Id": "366562", "Score": "1", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Post a follow-up question with both old and new question linking to each other instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-01T19:59:41.923", "Id": "366605", "Score": "0", "body": "@Mast: I understand, but please know that I didn't do such a thing. I've updated the post with my own new information. Would you rather I post that as an answer?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-02T06:58:03.173", "Id": "366639", "Score": "0", "body": "It partly reads like a review, so I'd imagine posting it as an answer would be fitting. However, if you want to put the new code up for review, a follow-up question would be the way to go." } ]
[ { "body": "<p>Honestly, I was thinking very hard to come up with any real disadvantage this might have, but I cannot come up with anything. It certainly look strange to wrap a C structure into a shared_ptr, but the custom deleter takes care of that problem, so it is just a subjective dislike, and only at first. Actually now, I think it is quite clever.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T15:24:04.983", "Id": "5305", "ParentId": "4679", "Score": "23" } }, { "body": "<p>I should start with the fact that I don't entirely agree with the widespread belief that \"explicit is better than implicit\". I think in this case, it's probably at least as good to have a class that just implicitly converts to the right type:</p>\n\n<pre><code>class file { \n typedef FILE *ptr;\n\n ptr wrapped_file;\npublic:\n file(std::string const &amp;name, std::string const &amp;mode = std::string(\"r\")) : \n wrapped_file(fopen(name.c_str(), mode.c_str())) \n { }\n\n operator ptr() const { return wrapped_file; }\n\n ~file() { if (wrapped_file) fclose(wrapped_file); }\n};\n</code></pre>\n\n<p>I haven't tried to make this movable, but the same general idea would apply if you did. This has (among other things) the advantage that you work with a <code>file</code> directly as a file, rather than having the ugly (and mostly pointless) <code>.get()</code> wart, so code would be something like:</p>\n\n<pre><code>file f(\"myfile.txt\", \"w\");\n\nif (!f) {\n fprintf(stderr, \"Unable to open file\\n\");\n return 0;\n}\n\nfprintf(f, \"Hello world\");\n</code></pre>\n\n<p>This has a couple of advantages. The aforementioned cleanliness is a fairly important one. Another is the fact that the user now has a fairly normal object type, so if they want to use overloading roughly like they would with an ostream, that's pretty easy as well:</p>\n\n<pre><code>file &amp;operator&lt;&lt;(file &amp;f, my_type const &amp;data) { \n return data.write(f);\n}\n\n// ...\n\nfile f(\"whatever\", \"w\");\nf &lt;&lt; someObject;\n</code></pre>\n\n<p>In short, if the user wants to do C-style I/O, that works fine. If s/he prefers to do I/O more like iostreams use, a lot of that is pretty easy to support as well. Most of it is still just syntactic sugar though, so it generally won't impose any overhead compare to using a <code>FILE *</code> directly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-17T16:04:55.110", "Id": "9466", "Score": "1", "body": "That's a nice design. Thanks! (`operator ptr()` should be `const`, though, non?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-17T16:08:58.513", "Id": "9467", "Score": "0", "body": "@KerrekSB: Yes, probably." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-09T12:38:43.713", "Id": "99628", "Score": "2", "body": "Since the original answer goes to great pains to manage the lifetime of the `FILE*` correctly it seems odd to propose an alternative solution that fails to deal with copying correctly. I might build something like your `file` on top of the OP's `unique_file_ptr` or `shared_file_ptr`, not instead of them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-06T11:41:09.897", "Id": "221812", "Score": "0", "body": "Shouldn't the overloaded `operator<<` be something that includes `iostream` object as a first parameter and returning value (by reference), and the class `file` object as a second parameter?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-06T16:58:13.037", "Id": "221853", "Score": "0", "body": "@simplicisveritatis: Um...what? No, the idea here is that the `file` type basically acts as a substitute for an iostream, so there's no `iostream` involved in using it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-06T17:24:52.257", "Id": "221858", "Score": "0", "body": "@JerryCoffin you are right! I just couldn't understand how is the `operator<<` / `>>` overloaded to write to / read from `FILE*`. I'm using almost the same class implementation for file handling and had a problem providing insertion & extraction." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-17T15:58:15.810", "Id": "6122", "ParentId": "4679", "Score": "28" } }, { "body": "<p>Using a function pointer of function reference as a deleter has two major disadvantages:</p>\n\n<ol>\n<li><p>The deleter has <em>state</em> and thus requires storage, even though it is always the same, and the maker function is artificially used to create this \"constant\" state even though there is no choice to make here.</p></li>\n<li><p>Taking the address of a standard-library function is highly problematic. C++20 has started outright outlawing this practice, and it generally creates brittle code. Functions are first and foremost designed to be <em>called</em> in a certain way. The details of whether a function has overloads, default arguments, etc. are generally not meant to be observable, and liable to change at the whim of the implementer. Standard library functions should therefore always be <em>called</em>.</p></li>\n</ol>\n\n<p>Putting those two observations together immediately leads to an improved solution: Define your own custom deleter class. This class can be default-constructible, making the smart pointer construction straight-forward.</p>\n\n<p>Example (using <code>dlopen</code>/<code>dlclose</code>):</p>\n\n<pre><code>struct DlCloser\n{\n void operator()(void * dlhandle) const noexcept { dlclose(dlhandle); } \n};\n\nusing dl_ptr = std::unique_ptr&lt;void, DlCloser&gt;;\n\ndl_ptr make_loaded_dso(const string &amp; filename)\n{\n return dl_ptr(dlopen(filename.c_str()));\n}\n</code></pre>\n\n<p>Note that the maker function is now almost useless; I might as well just write <code>dl_ptr p(dlopen(filename))</code> instead of <code>auto p = make_loaded_dso(filename.c_str())</code>.</p>\n\n<p>Finally, here is a small aside on lambdas: The usual way to use library functions as callbacks and abide by the aforementioned \"call-only\" interface is to use a lambda expression, such as <code>[](void * h) { dlclose(h); }</code>. However, lambda expressions don't make for good deleter types. Even though C++20 made stateless lambdas default-constructible and allowed lambdas to appear in unevaluated contexts, we cannot generally use something like</p>\n\n<pre><code>std::unique_ptr&lt;void, decltype([](void * h) { dlclose(h); })&gt;\n</code></pre>\n\n<p>as a library type, since (if the above is contained in a header file) the lambda expression has a unique type in every translation unit and we would therefore have ODR violations. Unevaluated and default-construcible lambdas are only useful in a local setting, but not for libraries and interface types.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T14:26:44.887", "Id": "468272", "Score": "0", "body": "`inline` should fix the last problem with ODR violation" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-12T14:29:25.270", "Id": "468273", "Score": "0", "body": "or `static auto deleter = [](void * h) { dlclose(h); }; using ptr = std::unique_ptr<void, decltype(deleter)>;`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-04-02T20:52:22.107", "Id": "191096", "ParentId": "4679", "Score": "7" } } ]
{ "AcceptedAnswerId": "5305", "CommentCount": "18", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T13:30:33.340", "Id": "4679", "Score": "48", "Tags": [ "c++", "c++11" ], "Title": "shared_ptr and FILE for wrapping cstdio (update: also dlfcn.h)" }
4679
<p>I have the following function:</p> <pre><code>from collections import Counter import itertools def combinationsWithMaximumCombinedIntervals(data, windowWidth, maximumCombinedIntervals): for indices in itertools.combinations(range(len(data)),windowWidth): previous = indices[0] combinedIntervals = 0 for i in indices[1:]: combinedIntervals = combinedIntervals + i-previous-1 if combinedIntervals &gt; maximumCombinedIntervals: break previous = i else: yield(tuple(data[i] for i in indices)) test = ["a","b","c","d","e","f","g","h","i","j","k","l"] combinations = combinationsWithMaximumCombinedIntervals(test, 5, 2) for i in combinations: pass </code></pre> <p>The function is associated with a set of combinations for the data supplied to it. Each element in the list represents a combination with the length of each of these combinations equal to windowLength. </p> <p>If we take the flowing combination ("a","b","c","d","f"), then the combined interval is 1 since "d" to "f" is a hop of 1. If we take the flowing combination ("a","b","c","e","g"), then the combined interval is 2 since "c" to "e" and "e" to "g" are hops of 1 each. Finally, combination ("a","b","c","d","g") has a combined interval of 2 since "d" to "g" is a hop of 2. The maximumCombinedIntervals argument limits the number of combinations based on the combined interval. In other words, this combination is not available when maximumCombinedIntervals is 2: ("a","c","e","f","h") since the combination of hops is now greater than 2.</p> <p>I wish to run this function on data with a length of many thousands, a windowWidth in the order of 10 and a maximumCombinedIntervals under 10. However this takes forever to execute.</p> <p>Can anyone suggest how I might refactor this function so that it will run much more quickly in Python. itertools.combinations is implemented in C.</p> <p>Here is a similar function which I'm also interested in using:</p> <pre><code>def combinationsWithMaximumIntervalSize(data, windowWidth, maximumIntervalSize): maximumIntervalSizePlusOne = maximumIntervalSize+1 for indices in itertools.combinations(range(len(data)),windowWidth): previous = indices[0] for i in indices[1:]: if i-previous&gt;maximumIntervalSizePlusOne: break previous = i else: yield(tuple(data[i] for i in indices)) </code></pre> <p>I'm working in python 3. </p> <hr> <p>Edit: Here's my latest attempt. Any comments?</p> <pre><code>def combinationsWithMaximumCombinedIntervals2(data, combinationWidth, maximumCombinedIntervals): windowWidth = combinationWidth + maximumCombinedIntervals combinations = [] for startingIndex in range(len(data)-windowWidth+1): for indices in itertools.combinations(range(startingIndex, startingIndex+windowWidth), combinationWidth): if not indices in combinations: yield(tuple(data[j] for j in indices)) combinations.append(indices) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-17T12:29:23.873", "Id": "348187", "Score": "0", "body": "Just wondering what on earth `for i in combinations: pass` is actually adding to the code as it seems to be doing nothing." } ]
[ { "body": "<p>As for your actual algorithm, you need to change it. Filtering down python's generating makes things relatively simple. However, in this case you are going throw away way more items then you keep. As a result, this isn't going to be an efficient method.</p>\n\n<p>What I'd try is iterating over all possible starting positions. For each starting position I'd take the next windowWidth+maximumIntervalSize items. Then I'd use itertools.combinations to grab each possible set of maximumIntervalSize items to remove from the list. </p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Review of new code:</p>\n\n<pre><code>def combinationsWithMaximumCombinedIntervals2(data, combinationWidth, maximumCombinedIntervals):\n</code></pre>\n\n<p>The python style guide recommends lowercase_with_underscores for function and parameter names. The name are also just a bit on the longish side. (Which is way better then being too short or cryptic)</p>\n\n<pre><code> windowWidth = combinationWidth + maximumCombinedIntervals\n\n combinations = []\n\n for startingIndex in range(len(data)-windowWidth+1):\n for indices in itertools.combinations(range(startingIndex, startingIndex+windowWidth), combinationWidth):\n</code></pre>\n\n<p>If possible, try to avoid looping over indexes. Code is cleaner if it loops over the data elements.</p>\n\n<pre><code> if not indices in combinations: \n</code></pre>\n\n<p>You use <code>if indices not in combinations</code> for a slightly cleaner expression</p>\n\n<pre><code> yield(tuple(data[j] for j in indices))\n</code></pre>\n\n<p>You don't need the parenthesis for yield, it is a statement not a function.</p>\n\n<pre><code> combinations.append(indices)\n</code></pre>\n\n<p>Combinations would be faster to check if it were a set rather then a list.</p>\n\n<p>But the real question here is how to avoid the duplicates being generated in the first place. We simple restrict the combinations generated to include the startingIndex. This prevents duplicates because no later window can produce the same combinations. (They don't have the startingIndex in them). But it still produces all values because all combinations without the startingIndex will still be contained in the next window. (The next window is the current window except without startingIndex and with an additional value) The only tricky part is the end, when there are no more windows. This is most easily handled by continuing to generate just with a smaller window size for as long as possible.</p>\n\n<p>My solution (tested to make sure it produces the same results as yours, so I don't make any more silly mistakes):</p>\n\n<pre><code>def combinationsWithMaximumCombinedIntervals3(data, combinationWidth, maximumCombinedIntervals):\n windowWidth = combinationWidth + maximumCombinedIntervals\n\n for startingIndex in range(len(data)-combinationWidth+1):\n window = data[startingIndex + 1: startingIndex + windowWidth]\n for indices in itertools.combinations(window, combinationWidth - 1):\n yield (data[startingIndex],) + indices\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T20:35:31.877", "Id": "7273", "Score": "0", "body": "Thanks for your suggestion, I will investigate it. I will get duplicates with your approach - what would be a good way to deal with these? yield(tuple(data[i] for i in indices)) is not equal yield tuple(data). Thanks again!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T22:38:49.173", "Id": "7282", "Score": "0", "body": "@Baz, sorry about the tuple code, I misread that" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T21:25:38.273", "Id": "4687", "ParentId": "4682", "Score": "4" } } ]
{ "AcceptedAnswerId": "4687", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T16:57:40.790", "Id": "4682", "Score": "3", "Tags": [ "python", "optimization" ], "Title": "Very slow Python Combination Generator" }
4682
<p>I've created a custom timer to satisfy the following requirements:</p> <ul> <li>Millisecond accuracy</li> <li>I want the tick event handler to only be called once the current tick handler has completed (much like the winforms timer)</li> <li>I want exceptions on the main UI thread not to be swallowed up by the thread timer so this requires Invoke/Send instead of BeginInvoke/Post</li> </ul> <p>Note: I call timeBeginPeriod(1)/ timeEndPeriod(1) in order to achieve the millisecond accuracy.</p> <p>I've put in a check if the timer is deleted to make sure that the deletion is complete before the timer can be created again. Does that look ok?</p> <p>For the <i>IsRunning</i> property, is it possible that racing conditions could occur?</p> <p>...or is the code a disaster waiting to happen and I should try (again) to get CreateTimerQueueTimer to work? </p> <p>The code has been tested with a small interval of 1 millisecond and a large interval of 300 milliseconds with frequent start/stops, and I've had no problems so far. </p> <p><b>ETA: I've found a problem with it. If the timer is running at an interval of 1 millisecond, and I call, say, Change(300), it locks up @ while (this.DeleteRequest). This must be because the TimerLoop is in the this.CallbackDelegate.Invoke(null) call.</b></p> <pre><code>public class MyTimer : IDisposable { private System.Threading.TimerCallback CallbackDelegate; private bool DeleteRequest; private System.Threading.Thread MainThread; public MyTimer(System.Threading.TimerCallback callBack) { this.CallbackDelegate = callBack; } public void Create(int interval) { while (this.DeleteRequest) { System.Threading.Thread.Sleep(0); } if (this.MainThread != null) { throw new Exception(""); } this.MainThread = new System.Threading.Thread(TimerLoop); // Make sure the thread is automatically killed when the app is closed. this.MainThread.IsBackground = true; this.MainThread.Start(interval); } public void Change(int interval) { // A lock required here? if (!this.IsRunning()) { throw new Exception(""); } this.Delete(); this.Create(interval); } public void Delete() { this.DeleteRequest = true; } public bool IsRunning() { return (this.MainThread != null) &amp;&amp; this.MainThread.IsAlive; } private void TimerLoop(object args) { int interval = (int)args; Stopwatch sw = new Stopwatch(); sw.Start(); do { if (this.DeleteRequest) { this.MainThread = null; this.DeleteRequest = false; return; } long t1 = sw.ElapsedMilliseconds; // I want to wait until the operation completes, so I use Invoke. this.CallbackDelegate.Invoke(null); if (this.DeleteRequest) { this.MainThread = null; this.DeleteRequest = false; return; } long t2 = sw.ElapsedMilliseconds; int temp = Convert.ToInt32(Math.Max(interval - (t2 - t1), 0)); sw.Reset(); if (temp &gt; 0) { System.Threading.Thread.Sleep(temp); } sw.Start(); } while (true); } // dispose calls this.Delete(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T17:45:09.827", "Id": "7138", "Score": "0", "body": "If you found a solution, please post an answer with it and accept it instead of editing your post. That way future visitors can easily see what your solution was." } ]
[ { "body": "<p>System.Threading.Thread.Sleep() has an accuracy (resolution) of around 15 milliseconds, and so I would stay far away from using that in your code if you need millisecond accuracy. Can you use <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx\" rel=\"nofollow noreferrer\">Stopwatch</a> instead? - this uses a high resolution timer where available, by default. You might find this post on StackOverflow <a href=\"https://stackoverflow.com/questions/1631501/need-microsecond-delay-in-net-app-for-throttling-udp-multicast-transmission-rate\">here</a> useful as well.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T05:11:53.797", "Id": "4755", "ParentId": "4684", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T18:59:44.940", "Id": "4684", "Score": "1", "Tags": [ "c#", ".net" ], "Title": "Custom timer code needs reviewing for thread safety" }
4684
<p>Please provide positive and not-so-positive feedback on style, clarity, or any other additional feedback you would like to provide.</p> <pre><code>#ifndef MATRIX_H_ #define MATRIX_H_ #include &lt;string&gt; struct Matrix_error { Matrix_error(std::string error) { m_error = error; } std::string m_error; }; class Matrix { public: Matrix(std::string name, std::pair&lt;int, int&gt; dim, int mult); Matrix operator* (Matrix &amp;m) throw (Matrix_error) { if (m_dim.second != m.m_dim.first) { throw Matrix_error(std::string("ERROR:" "Matrix Multiplication Dimension Error") + m_name + m.m_name + std::string("\n")); } Matrix M(std::string("("+m_name + m.m_name+")"), std::pair&lt;int, int&gt;(m_dim.first, m.m_dim.second), m.m_mult + m_mult + m_dim.first*m_dim.second*m.m_dim.second); return M; } int getMultiplications() const {return m_mult;} std::string getName() const {return m_name;} std::pair&lt;int,int&gt; getDimensions() const {return m_dim;} private: std::string m_name; std::pair&lt;int,int&gt; m_dim; int m_mult; friend std::ostream&amp; operator&lt;&lt; (std::ostream &amp;out, Matrix &amp;m) { return out &lt;&lt; m.m_name &lt;&lt; "(" &lt;&lt; m.m_dim.first &lt;&lt; ", " &lt;&lt; m.m_dim.second &lt;&lt; ")"; } }; #endif /* MATRIX_H_ */ </code></pre> <p></p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include "matrix.h" Matrix::Matrix(std::string name, std::pair&lt;int, int&gt; dim, int mult = 0) { m_name = name; m_dim = dim; m_mult = mult; } </code></pre> <p></p> <pre><code>#include &lt;iostream&gt; #include &lt;list&gt; #include &lt;iterator&gt; #include &lt;cstdlib&gt; #include "matrix.h" /* * Declare typedefs up front. Keep them to a minimal * to help readability and reduce amount of scrolling */ typedef std::list&lt;Matrix&gt;::iterator matrix_it; typedef std::list&lt;Matrix&gt; matrix_chain; /* * This function prints out the final results of * the computations. */ void print_matrix_chain(matrix_it left, matrix_it right) { while (left != right) { std::cout &lt;&lt; (*left) &lt;&lt; " = " &lt;&lt; (*left).getMultiplications() &lt;&lt; std::endl; left++; } } /* * This function finds the optimal way to multiply * N matrices together when provided a list of N * matrices */ matrix_chain optimal_matrix_chain_multiplication(matrix_chain &amp;chain) { matrix_chain ret; if (chain.size() == 1) { ret.push_back(chain.front()); chain.pop_front(); } else if (chain.size() == 2) { Matrix A = chain.front(); chain.pop_front(); Matrix B = chain.front(); chain.pop_front(); Matrix C = (A*B); ret.push_back(A*B); } else { matrix_it pos = chain.begin(); pos++; //Start pos 1 from the left matrix_it end = chain.end(); for (; pos != end; pos++) { matrix_chain left; matrix_chain right; copy(chain.begin(), pos, back_inserter(left)); copy(pos, chain.end(), back_inserter(right)); left = optimal_matrix_chain_multiplication(left); right = optimal_matrix_chain_multiplication(right); matrix_it lbegin = left.begin(); matrix_it rbegin = right.begin(); matrix_it lend = left.end(); matrix_it rend = right.end(); for (; lbegin != lend; lbegin++) { for(; rbegin != rend; rbegin++) { try { ret.push_back((*lbegin)*(*rbegin)); } catch (Matrix_error e) { std::cout &lt;&lt; e.m_error; } } } } } return ret; } int main(int argc, char *argv[]) { std::list&lt;Matrix&gt; chain; Matrix A(std::string("A"), std::pair&lt;int, int&gt;(5, 10), 0); chain.push_back(A); Matrix B(std::string("B"), std::pair&lt;int, int&gt;(10, 7), 0); chain.push_back(B); Matrix C(std::string("C"), std::pair&lt;int, int&gt;(7, 11), 0); chain.push_back(C); Matrix D(std::string("D"), std::pair&lt;int, int&gt;(11, 2), 0); chain.push_back(D); Matrix E(std::string("E"), std::pair&lt;int, int&gt;(2, 5), 0); chain.push_back(E); std::list&lt;Matrix&gt; ret = optimal_matrix_chain_multiplication(chain); print_matrix_chain(ret.begin(), ret.end()); return 0; } </code></pre>
[]
[ { "body": "<p>Few remarks about the exception handling in your code - <code>struct Matrix_error</code>. \nConsider the following document - <a href=\"http://www.boost.org/community/error_handling.html\" rel=\"nofollow\">Error and Exception Handling</a> - for a proper design of exception classes in C++:</p>\n\n<blockquote>\n <ol>\n <li><p>Derive your exception class from <code>std::exception</code>. Except in\n <em>very</em> rare circumstances where you can't afford the cost of a virtual\n table, <code>std::exception</code> makes a reasonable exception base class, and\n when used universally, allows programmers to catch \"everything\"\n without resorting to catch(...). </p></li>\n <li><p>Don't embed a <code>std::string</code> object or any other data member or\n base class whose copy constructor could throw an exception. That could\n lead directly to <code>std::terminate()</code> at the throw point. Similarly,\n it's a bad idea to use a base or member whose ordinary constructor(s)\n might throw, because, though not necessarily fatal to your program</p></li>\n <li><p>There are various ways to avoid copying string objects when\n exceptions are copied, including embedding a fixed-length buffer in\n the exception object, or managing strings via reference-counting.\n However, consider the next point before pursuing either of these\n approaches.</p></li>\n <li><p>Format the what() message on demand, if you feel you really must\n format the message. Formatting an exception error message is typically\n a memory-intensive operation that could potentially throw an\n exception. This is an operation best delayed until after stack\n unwinding has occurred, and presumably, released some resources. It's\n a good idea in this case to protect your what() function with a\n catch(...) block so that you have a fallback in case the formatting\n code throws</p></li>\n </ol>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T06:13:45.073", "Id": "7032", "Score": "0", "body": "Thanks for the link. I appreciate the additional information. I would like to know if there is anything else I could improve on." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T05:59:14.490", "Id": "4696", "ParentId": "4690", "Score": "2" } }, { "body": "<p>Andrei knows way more than me, so aside from his advice about using std::exception and not making your own error class, even if that were ok, you're passing the error message in by value, not by reference, which causes an unnecessary copy to be made.</p>\n\n<pre><code>struct Matrix_error\n{\n Matrix_error(std::string error)\n {\n\n// you probably would want \n Matrix_error( std::string const &amp; error)\n\n// and since it's passed to the c'tor, you could use the member initialization list, which // is ever-so-slightly more correct\n\n Matrix_error( std::string &amp; error) : m_error( error ) {}\n\n// the reason that's considered more correct is that in your code, the default c'tor is \n// called first, then you are assigning it, which is a wasted call to the default c'tor. // If you supply it on the mem initialization list, then the c'tor is called directly with // the argument, so it saves a step. This can add up when initializing objects that are\n// more complex than just strings.\n\n// you might even be able to go a step futher, and declare m_error a const string, since // in principle, the error object should never need to *modify* the error message it\n// takes, only print it out or log it somewhere. This is more correct because the more you\n// use const, the less stuff can get changed, which means in the long run, fewer bugs and\n// more correct designs.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T00:54:34.493", "Id": "7053", "Score": "0", "body": "sorry I didn't add semicolons to the ctor and end of struct, this is only a sketch." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T00:53:38.047", "Id": "4720", "ParentId": "4690", "Score": "1" } }, { "body": "<p>The other approach is to make matrix dimensions as a template parameters, so you can make checks at compile time. It will heavily differ from your code, but i'll have some advantage in error checking.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T15:15:59.743", "Id": "58174", "Score": "0", "body": "The other advantage of templates is that they can have better performance through optimizations if they're coded correctly." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T23:58:12.967", "Id": "4732", "ParentId": "4690", "Score": "0" } }, { "body": "<p>I am not as thorough as lint++ but here are some coding issues.</p>\n\n<pre><code>Matrix(std::string name, std::pair&lt;int, int&gt; dim, int mult);\n</code></pre>\n\n<p>should really be</p>\n\n<pre><code>Matrix(std::string const&amp; name, std::pair&lt;int, int&gt; const&amp; dim, int const mult);\n</code></pre>\n\n<p>Yes \"int const mult\" is pedantic but also clearly indicates your intent i.e. to copy the value only.</p>\n\n<p>Unnecessary parentheses bug me.\n &lt;&lt; (*left)\nshould be</p>\n\n<pre><code>&lt;&lt; *left\n\n(*left).getMultiplications()\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>left-&gt;getMultiplications()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T13:10:59.797", "Id": "4795", "ParentId": "4690", "Score": "1" } } ]
{ "AcceptedAnswerId": "4696", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-08T23:48:56.667", "Id": "4690", "Score": "1", "Tags": [ "c++", "matrix", "stl" ], "Title": "STL matrix chain multiplication" }
4690
<pre><code>$.fn.linkNestedCheckboxes = function () { var childCheckboxes = $(this).find('input[type=checkbox] ~ ul li input[type=checkbox]'); childCheckboxes.change(function () { var checked = $(this).attr('checked'); checked = checked || ($(this).closest('li').siblings('li').find('input:checked').length &gt; 0) childCheckboxes.parent().closest('ul').siblings('input[type=checkbox]').attr('checked', checked); }); var parentCheckboxs = childCheckboxes.parent().closest('ul').siblings('input[type=checkbox]') parentCheckboxs.change(function () { $(this).siblings('ul').find('input[type=checkbox]').attr('checked', $(this).attr('checked')) }) return $(this); }; </code></pre> <p>Example of use:</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function () { $('form').linkNestedCheckboxes(); }); &lt;/script&gt; &lt;form&gt; &lt;input type="checkbox" name="parent" /&gt; &lt;ul&gt; &lt;li&gt;&lt;input type="checkbox" name="child1" /&gt;&lt;/li&gt; &lt;li&gt;&lt;input type="checkbox" name="child2" /&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/form&gt; </code></pre> <p>The result of this is:</p> <ul> <li>When <code>parent</code> is checked/unchecked all the child checkboxes will be out into the same state</li> <li>If nothing is checked &amp; one of the children are then checked, the parent will be checked</li> <li>When the last child is unchecked the parent will be unchecked</li> </ul> <p>What I'd like to know is:</p> <ul> <li>Have I just re-invented the wheel?</li> <li>If not, is there a more efficient way of doing this? The selectors above seem a bit convoluted.</li> <li>This works on my machine, but I haven't tested it beyond my limited requirements for one form, will this break anything other than my simplistic example HTML?</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T04:07:17.477", "Id": "7029", "Score": "0", "body": "Actually this doesn't work properly even in your example. When you click the parent then uncheck both the children then uncheck the oarent it will then mark the children checked." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T13:11:21.330", "Id": "7044", "Score": "0", "body": "I'm not seeing that behaviour, when I uncheck both the children, the parent is unchecked. Clicking on the parent after that checks both the children, which is the expected behaviour. What browser are you using?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T11:02:43.390", "Id": "7059", "Score": "0", "body": "i'm using chrome." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T11:13:30.110", "Id": "7060", "Score": "0", "body": "http://jsfiddle.net/skjY9/ try checking them all then unchecking them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T22:59:54.333", "Id": "7098", "Score": "0", "body": "Ok, I know what the problem is, I'm still using jQuery 1.4.4, something has changed in the latest version" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T23:25:03.560", "Id": "7100", "Score": "0", "body": "Ah ... my apologies yeah the `.attr()` has changed. I'd suggest you switch them for `.prop()` if you are moving to 1.6. (1.5 should still work fine.)" } ]
[ { "body": "<p>Firstly use <a href=\"http://api.jquery.com/prop/\" rel=\"nofollow\"><code>.prop</code></a> not <a href=\"http://api.jquery.com/attr/\" rel=\"nofollow\"><code>.attr</code></a> if you are using jQuery v1.6+.</p>\n\n<p>Secondly your code has a bug in it. When you click the parent then uncheck both the children then uncheck the parent it will then mark the children checked even though the parent is unchecked.</p>\n\n<p>If you mean that the parent is \"checked\" when any of the children are \"checked\":</p>\n\n<p><a href=\"http://jsfiddle.net/FS3CC/1/\" rel=\"nofollow\">http://jsfiddle.net/FS3CC/1/</a></p>\n\n<pre><code>$.fn.linkNestedCheckboxes = function () {\n var childCheckboxes = $(this).find('input[type=checkbox] ~ ul li input[type=checkbox]');\n\n childCheckboxes.change(function(){\n var parent = $(this).closest(\"ul\").prevAll(\"input[type=checkbox]\").first();\n var anyChildrenChecked = $(this).closest(\"ul\").find(\"li input[type=checkbox]\").is(\":checked\");\n $(parent).prop(\"checked\", anyChildrenChecked);\n });\n\n // Parents\n childCheckboxes.closest(\"ul\").prevAll(\"input[type=checkbox]\").first()\n .change(function(){\n $(this).nextAll(\"ul\").first().find(\"li input[type=checkbox]\")\n .prop(\"checked\", $(this).prop(\"checked\")); \n });\n\n return $(this);\n};\n</code></pre>\n\n<p>Firstly in the <code>//Parents</code> change event you want to set the children to what ever the value of the parent no matter what.</p>\n\n<p>This is the parent element:</p>\n\n<pre><code>// Parents\nchildCheckboxes.closest(\"ul\").prevAll(\"input[type=checkbox]\").first()\n</code></pre>\n\n<p>its change event means set all the child check boxes to the same value</p>\n\n<pre><code>.prop(\"checked\", $(this).prop(\"checked\"));\n</code></pre>\n\n<p>The child check box change event is slightly more complicated but basically it finds any child check boxes that are checked and sets the parent accordingly.</p>\n\n<p><em>(if you meant that the parent should be check ONLY when all the check boxes are checked its slightly different so please comment as such.)</em></p>\n\n<p>A different approach would be to specify who the parent is on the element:</p>\n\n<pre><code>&lt;form&gt;\n &lt;input type=\"checkbox\" name=\"parent\" id=\"parent\" /&gt;\n &lt;ul&gt;\n &lt;li&gt;&lt;input type=\"checkbox\" name=\"child1\" data-parent=\"parent\" /&gt;\n &lt;li&gt;&lt;input type=\"checkbox\" name=\"child2\" data-parent=\"parent\" /&gt;\n &lt;/ul&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>Which would make the selectors easier:</p>\n\n<p><em>(from child)</em> </p>\n\n<pre><code>var parent = $(\"#\" + $(this).data(\"parent\"));\n</code></pre>\n\n<p><em>(from parent)</em></p>\n\n<pre><code>var children = $(\"input[data-parent=\" + $(this).attr(\"id\") + \"]\");\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T04:20:33.727", "Id": "4695", "ParentId": "4691", "Score": "3" } } ]
{ "AcceptedAnswerId": "4695", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T00:16:18.930", "Id": "4691", "Score": "2", "Tags": [ "javascript", "jquery", "html" ], "Title": "jQuery function to link nested checkboxes" }
4691
<p>How can I rework the code up that <code>ema(x, 5)</code> returns the data now in <code>emaout</code>? I'm trying to enclose everything in one def.</p> <p>Right now its in a for loop and a def.</p> <pre><code>x = [32.47, 32.70, 32.77, 33.11, 33.25, 33.23, 33.23, 33.0, 33.04, 33.21] def ema(series, period, prevma): smoothing = 2.0 / (period + 1.0) return prevma + smoothing * (series[bar] - prevma) prevema = x[0] emaout =[] for bar, close in enumerate(x): curema = ema(x, 5, prevema) prevema = curema emaout.append(curema) print print emaout </code></pre> <p><code>x</code> could be a NumPy array.</p>
[]
[ { "body": "<ol>\n<li>ema uses series in one place, where it references <code>series[bar]</code>. But bar is a global variable which is frowned upon. Let's pass series[bar] instead of series to ema.</li>\n<li>That would be series[bar] in the for loop, but series[bar] is the same thing as close, so let's pass that instead.</li>\n<li>ema's period is only used to calculate smoothing. Let's calculate smoothing outside and pass it in.</li>\n<li>But now ema's a single line, so let's inline it</li>\n<li>Let's put all of that logic inside a function</li>\n<li>We use enumerate in the for loop, but we don't use bar</li>\n</ol>\n\n<p>Result:</p>\n\n<pre><code>x = [32.47, 32.70, 32.77, 33.11, 33.25, 33.23, 33.23, 33.0, 33.04, 33.21]\n\ndef function(x, period):\n prevema = x[0] \n emaout =[]\n\n smoothing = 2.0 / (period + 1.0) \n for close in x:\n curema = prevma + smoothing * (close - prevma) \n prevema = curema\n emaout.append(curema)\n\n return prevema\nprint \nprint function(x, 5)\n</code></pre>\n\n<p>We can better by using numpy. </p>\n\n<pre><code>def function(x, period):\n smoothing = 2.0 / (period + 1.0) \n current = numpy.array(x) # take the current value as a numpy array\n\n previous = numpy.roll(x,1) # create a new array with all the values shifted forward\n previous[0] = x[0] # start with this exact value\n # roll will have moved the end into the beginning not what we want\n\n return previous + smoothing * (current - previous)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T15:42:32.517", "Id": "7082", "Score": "0", "body": "@ winston the answers dont match." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T17:38:56.520", "Id": "7085", "Score": "0", "body": "@Merlin, I didn't test what I wrote. But hopefully it gives you some idea of how to improve your existing code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T18:15:58.800", "Id": "7090", "Score": "0", "body": "@merlin, `numpy.roll([1,2,3,4], 1) == numpy.array(4,1,2,3)` It shifts all of the elements in the array by one. That way when I subtract the original and rolled arrays I get the difference from one to the next." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T18:16:55.913", "Id": "7091", "Score": "0", "body": "@merlin, you are supposed to @ username of person you are talking to, not @ yourself. You don't need to when commenting on my questions because I am automatically alerted about those" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T18:28:50.050", "Id": "7092", "Score": "0", "body": "@winston...the on numpy.roll, how can you 'roll' only one column in array? tIA" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T18:47:35.533", "Id": "7093", "Score": "0", "body": "@Merlin, I've never needed to. Perhaps you should ask another question with the complete context of what you are now trying to accomplish." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T01:17:00.560", "Id": "10407", "Score": "0", "body": "The numpy version here doesn't implement the same algorithm and I don't think it's possible with the constructs shown. The problem is an EMA at index T is calculated based on the EMA at index T-1 (except for T=0 where the EMA must be hard-wired somehow). This explains the usage of the `prevema` value in the non-numpy example. Rolling the input values by 1 doesn't achieve this desired effect. Essentially EMA is a low-pass filter which I'm guessing can be implemented concisely using numpy/scipy, but I haven't found a good example yet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T01:35:58.630", "Id": "10408", "Score": "0", "body": "@JoeHolloway, you are right. Apparently I was suffering from brain fog when I wrote this." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T03:29:39.380", "Id": "4694", "ParentId": "4692", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T02:24:57.203", "Id": "4692", "Score": "0", "Tags": [ "python", "numpy" ], "Title": "Moving average of a data series" }
4692
<p>All colors can be represented by an <code>int</code>, and often you want to get the individual red, green and blue values from that <code>int</code>.</p> <p>I have a method <code>int2rgb</code> (and another called <code>rgb2int</code>) that does this. Is this a clear/good name?</p> <pre><code>public static int[] int2rgb(final int color) { return new int[] { (color &gt;&gt; 16) &amp; 0xFF, (color &gt;&gt; 8) &amp; 0xFF, color &amp; 0xFF }; } public static int rgb2int(final int red, final int green, final int blue) { return (red &lt;&lt; 16) + (green &lt;&lt; 8) + blue; } public static int rgb2int(final int[] color) { return (color[0] &lt;&lt; 16) + (color[1] &lt;&lt; 8) + color[2]; } </code></pre> <p>And in case you are interested, the rest of the class is <a href="https://bitbucket.org/alienmegacorp/alien-megacorp-utils/src/f613eae008be/src/com/alienmegacorp/utils/ColorUtils.java" rel="nofollow">here</a>.</p>
[]
[ { "body": "<p>As far as naming is concerned: Using 2 instead of <code>to</code> is pretty much a no-no - \"to\" is spelled out everywhere in the Java standard library. Further Java's naming convention is to capitalize every word, but the first in method names - except for acronyms which are all-caps no matter where they appear in the name. So the methods should be called <code>intToRGB</code> and <code>RGBtoInt</code> (<code>to</code> is lower case because it directly follows an acronym - compare for example <code>Color.RGBtoHSB</code> in the java standard library).</p>\n\n<p>In regards to the code: I'd recommend representing your colors as <code>Color</code> objects rather than 3-element arrays. If you choose to do that, you don't have to define any of your methods, because that functionality already exists in the <code>Color</code> class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T12:49:10.040", "Id": "7043", "Score": "4", "body": "see http://stackoverflow.com/questions/2236807/java-naming-convention-with-acronyms for a discussion about acronyms naming (I would personnly use `intToRgb` and `rgbToInt`)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T09:49:36.760", "Id": "4701", "ParentId": "4698", "Score": "10" } }, { "body": "<p>Make a RGB class with properties Red, Green and Blue and add a static <code>FromInt()</code> method, or a <code>RGB(int color)</code> constructor.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T10:36:27.327", "Id": "4702", "ParentId": "4698", "Score": "1" } }, { "body": "<p>Capitalization:</p>\n\n<p>I would use something in the form <code>rgbToInt</code> or <code>intToRgb</code>. I know, Javadoc tells that acronyms should be capitalized, but that leads to some weird results (v.g., <code>RGB rGBVariable;</code>)</p>\n\n<p>1) Joel Spolsky recommends to use \"form\" instead of \"to\", so code is easier to read. \nCompare</p>\n\n<pre><code>Rgb rgbVariable = intToRgb(intVariable); // mix of `rgb` an `int` in the line\n</code></pre>\n\n<p>to</p>\n\n<pre><code>Rgb rgbVariable = rgbFromInt(intVariable); // `rgb` to the right, `int` to the left; mistakes are easier to spot\n</code></pre>\n\n<p>More info here <a href=\"http://www.joelonsoftware.com/articles/Wrong.html\" rel=\"nofollow\">http://www.joelonsoftware.com/articles/Wrong.html</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-10T21:52:30.657", "Id": "46854", "ParentId": "4698", "Score": "1" } } ]
{ "AcceptedAnswerId": "4701", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T08:30:11.633", "Id": "4698", "Score": "2", "Tags": [ "java" ], "Title": "Is \"int2rgb\" an OK method name?" }
4698
<p>i will give a list of urls, and want to make multi processes to fetch certain url's web content, and quit if all the urls are all fetched.</p> <p>here is my implementation, and not sure if it's the right way to do the stuff:</p> <pre><code>#coding=utf8 import multiprocessing from multiprocessing import JoinableQueue import urllib2 import logging import os logging.basicConfig(level=logging.DEBUG) URLS = [ 'http://stackoverflow.com/q/2243542/94962', 'http://docs.python.org/library/logging.html', 'http://www.python.org/dev/peps/pep-3101/', 'http://news.ycombinator.com/', 'http://www.evernote.com/about/learn_more/', 'http://news.php.net/php.internals/55293', ] POOL_SIZE = multiprocessing.cpu_count() DEST_DIR = '/tmp/pytest/' url_q = JoinableQueue() class Worker(multiprocessing.Process): def run(self): while True: try: url = url_q.get() logging.info('%(process_name)s processing %(url)s' % { 'process_name': multiprocessing.current_process().name, 'url':url, }) web_cnt = urllib2.urlopen(url).read() url_filename = url[7:].replace('/', '-').strip('.html') + '.html' with open(os.path.join(DEST_DIR, url_filename), 'w') as f: f.write(web_cnt) url_q.task_done() except Exception: logging.exception('error') workers = [] for i in range(POOL_SIZE): worker = Worker() worker.name = 'worker%s'%i workers.append(worker) worker.start() for url in URLS: url_q.put(url) url_q.join() print 'workers have done stuff' for worker in workers: worker.terminate() </code></pre>
[]
[ { "body": "<p>You should pass the <code>url_q</code> queue to the constructor instead of using it as a global variable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T10:38:53.240", "Id": "4703", "ParentId": "4699", "Score": "2" } }, { "body": "<p>When you catch the exception, I suggest logging the complete exception so you can tell what went wrong.</p>\n\n<p>I suggest not using abbreviation like web_cnt. Code is easier to read when you spell things out. </p>\n\n<p>There isn't really a reason to use multiprocessing here since your tasks are IO not CPU bound. I'd probably use the eventlet library for this.</p>\n\n<p>Multiprocessing has a Pool class, about half of your code is duplicating the behavior of that. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T13:01:10.660", "Id": "4707", "ParentId": "4699", "Score": "2" } } ]
{ "AcceptedAnswerId": "4707", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T09:00:00.083", "Id": "4699", "Score": "5", "Tags": [ "python" ], "Title": "just implemented multiprocessing and queue demo, wonder if there are any improvements?" }
4699
<p>I've been looking for a solution to the ABA problem for a lock-free stack. Searching the Web revealed patented and complicated hazard pointers and tagged pointers using double compare-and-swap (DCAS, CAS2). I would settle for the DCAS, but it's not available on some older AMD CPUs. So I came up with this helper class:</p> <pre><code>class TaggedPtrBase { typedef unsigned int tag_t; static const tag_t INVALIDATED = 1; public: TaggedPtrBase() { tag.store(0, std::memory_order_relaxed); ptr = 0; } TaggedPtrBase &amp; operator=(const TaggedPtrBase &amp; other) { tag.store(other.tag.load(std::memory_order_acquire), std::memory_order_relaxed); ptr = other.ptr; return *this; } operator void *() const { return get(); } void * get() const { return ptr; } bool compare_and_swap(const TaggedPtrBase &amp; oldval, void * newptr) { uintptr_t old_tag = oldval.tag.load(std::memory_order_relaxed); if (old_tag &amp; INVALIDATED) { return false; } if (tag.compare_exchange_strong(old_tag, old_tag | INVALIDATED, std::memory_order_acquire)) { ptr = newptr; tag.store(old_tag + 2, std::memory_order_release); return true; } else { return false; } } private: std::atomic&lt;tag_t&gt; tag; void * ptr; }; ... void push(Node * node) { void * newptr = reinterpret_cast&lt;void *&gt;(node); TaggedPtrBase old; do { old = ptr; node-&gt;next = static_cast&lt;Node *&gt;(old.get()); } while (!ptr.compare_and_swap(old, newptr)); } </code></pre> <p>It appears to be working, but it's simplicity suggests that I'm missing something. So I wonder if this is a proper solution, or is it just a glorified spin-lock? Any issues on non-x86 platforms?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-22T14:36:50.897", "Id": "24258", "Score": "0", "body": "How important is portability? On current x86-64 platforms, pointers only have 48-significant bits. You can play bit tricks to store a tag in the remaining (upper) 16 bits, and so use only a 64-bit (single word) compare-and-swap. 16 bits of tag don't give quite the safety against ABA that 64 bits of tag do, as it's possible to quickly overflow a 16 bit tag. But it's still not particularly likely." } ]
[ { "body": "<p>It's just a spin lock. If the thread that invalidated of the tag got suspended right after, no other thread can make progress till the thread is resumed and releases the tag.</p>\n\n<pre><code>if (old_tag &amp; INVALIDATED) {\n return false; // no thread can go further if ...\n}\nif (tag.compare_exchange_strong(old_tag, old_tag | INVALIDATED, \n std::memory_order_acquire)) {\n ptr = newptr; // &lt;-- ... a thread is preempted here\n tag.store(old_tag + 2, std::memory_order_release);\n return true;\n}\n</code></pre>\n\n<p>So the solution is not lock-free.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-23T09:54:58.647", "Id": "9317", "ParentId": "4706", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T12:39:58.050", "Id": "4706", "Score": "4", "Tags": [ "c++", "multithreading", "locking", "thread-safety" ], "Title": "Single word CAS tagged pointer for algorithms susceptible to the ABA problem" }
4706
<p>I am writing a wrapper around the <code>GeUserArea</code> class of <a href="http://maxon.de" rel="nofollow">Cinema 4D</a>'s Python API to enable creating user interfaces using an object orientated interface.</p> <p>I've already written 2 prototypes, but I am <strong>not</strong> satisfied with my class-design. They <em>do</em> work very well, but I decided to start over to make it even more efficient, more clean and better commented, etc.</p> <p>The <code>GeUserArea</code> class provides drawing on it as it was a field of pixels, so it's a highly dynamic class to enable almost any type of interface you want, when you have the skills.</p> <p>The baseclass for all objects being rendered is the <code>Renderable</code> class. Two of the subclasses are <code>View</code> and <code>Lable</code>. The difference between these is, that <code>View</code> does hold a <code>frame</code> attribute that defines a rectangular area while <code>Lable</code> does only hold a <em>position</em> attribute that defines the position of the text being rendered.</p> <p>The <code>Renderable</code> class implements a tree-like design, so you can add a <code>Renderable</code> instance below another, etc. When an input event (mouse/keyboard) appears, a chain starts that tells the full tree that this event occured. Any <code>Renderable</code> instance should be able to react on an input event. But the view-subclass should also call a method when the mouse clicked into it's area.</p> <p>(Theese methods are to let the user override them while subclassing, enabling to react on those input events.)</p> <p>The event itself comes from <code>GeUserArea.InputEvent(self, msg)</code>. From the <code>msg</code> parameter, I can read out if and where a mouse event took place. After doing so, the event chain starts.</p> <pre><code>class Renderable: def InputEvent(self, msg): pass class View(Renderable): def MouseEvent(self, msg, mouse): pass </code></pre> <p>Using the above layout, I'd need to implement a method that manages calling of theese methods, like this:</p> <pre><code>class Renderable: # .. def _private_ManageInput(self, msg): self.InputEvent(msg) for sub in self.subs: sub._private_ManageInput(msg) class View(Renderable): # .. def _private_ManageInput(self, msg): if IsMouseEvent(msg): mouse = GetMouse(msg) if mouse in self.frame: self.MouseEvent(self, msg, mouse) Renderable._private_ManageInput(self, msg) </code></pre> <p>This does already seem a bit dirty to me.</p> <p>As the mouse position doesn't change within the recursive chain, it makes more sense to give the mouse position as an argument to the <code>Renderable._private_ManageInput()</code> method, which gives a speedup of about 30%.</p> <pre><code>class Renderable: # .. def _private_ManageInput(self, msg, mouse): self.InputEvent(msg) for sub in self.subs: sub._private_ManageInput(msg) class View(Renderable): # .. def _private_ManageInput(self, msg, mouse): if mouse is not None: if mouse in self.frame: self.MouseEvent(msg, mouse) Renderable._private_ManageInput(self, msg, mouse) </code></pre> <p>The <code>Renderable</code> class does not implement reacting on <code>MouseEvents</code> (as it does not define any area where the mouse could "hit" it), but a method does need arguments for this purpose? It seems quite dirty to me.</p> <p>Can you tell me how I can improve this design?</p>
[]
[ { "body": "<p>One thing you could do is ensure that events only reach those who are interested in that particular type of event. Right now you seem to be sending out a generic events that you then check to see what type they are.</p>\n\n<p>I wrote a similar answer some time ago to another question on Stack Overflow. You can read it here:<br>\n&#9658; <a href=\"https://stackoverflow.com/questions/7249388/7294148#7294148\">https://stackoverflow.com/questions/7249388/7294148#7294148</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T12:26:02.970", "Id": "7297", "Score": "0", "body": "The idea with the EventManager is a pretty good one and I think is easy to implement in this case. I will try it out, thank you so far !" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T22:54:20.720", "Id": "4717", "ParentId": "4708", "Score": "3" } } ]
{ "AcceptedAnswerId": "4717", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-05T16:44:17.963", "Id": "4708", "Score": "5", "Tags": [ "python", "user-interface" ], "Title": "Wrapper around a Python API for creating user interfaces" }
4708
<p>I know this is a lot of code, but I'm <strong>not</strong> looking for any kind of detailed review of the code. I'm just hoping some nice Javascript guru can give it a once over and offer any needed advice for using OOP in Javascript better than I am. </p> <p>Here are a few areas of concern that I have, that don't quite <em>seem</em> like they're ideal.</p> <ul> <li><p>The page has 4 objects that interact with each other, <strong>just floating in the middle of nowhere</strong>.</p></li> <li><p>The objects are all created by invoking anonymous constructors, since I didn't want named functions that are only used once hanging around.</p></li> <li><p>Most of the constructors have as the first line <code>var me = this;</code> since this changes context.</p></li> <li><p>There are about 4 or 5 global fields and functions that didn't really fit into any objects, so I just left them hanging in the global context.</p></li> </ul> <p>Any pointers on utilizing object oriented programming in JavaScript would be much appreciated.</p> <pre><code> var mode = "dev"; var currentSrc = []; var initialTitleValue = " [Title] "; var initialSelectedSubject = { id: -1, txt: "Books' Subjects" }; var currentDisplay = ""; $(function () { $("#header h1").text("Knockout / jQuery Book Demo"); $("#tbTitleSearch").blur(function () { if (!$(this).val().trim()) { viewModel.titleValue(initialTitleValue); $(this).addClass("watermark"); } }); $("#tbTitleSearch").click(function () { if ($(this).val() == initialTitleValue) { viewModel.titleValue(""); $(this).removeClass("watermark"); } }); $("#tbGenreSearch").click(function () { if (viewModel.selectedSubjects().length == 1 &amp;&amp; viewModel.selectedSubjects()[0] == initialSelectedSubject) { $(this).removeClass("watermark"); viewModel.selectedSubjects.removeAll(); } openSubjectWindow(); }); viewModel.selectedSubjects.subscribe(function () { if (viewModel.selectedSubjects().length == 1 &amp;&amp; viewModel.selectedSubjects()[0] == initialSelectedSubject) $("#tbGenreSearch").addClass("watermark"); }); $(window).bind('resize', function () { gridManager.sizeGrid(); }).trigger('resize'); $(".bookItem").live("mouseover", function () { $(this).addClass("highlight"); }); $(".bookItem").live("mouseout", function () { $(this).removeClass("highlight"); }); $(".smCovTempl").live("mouseover", function () { $(this).addClass("highlight"); }); $(".smCovTempl").live("mouseout", function () { $(this).removeClass("highlight"); }); $(".bookItem").live("click", function () { $(this).toggleClass("selected"); }); $(".smCovTempl &gt; img").live("click", function () { bookDetailsPopup($(this).data("id")); }); theme("grid"); ko.applyBindings(viewModel); dataLoader.loadSubjects(); }); var viewModel = new (function () { var me = this; this.rows = ko.observableArray([]); this.currentTemplate = ko.observable("bookTemplate1"); this.displayTemplate = function () { return me.currentTemplate(); }; this.subjects = ko.observableArray([]); this.selectedSubjects = ko.observableArray([initialSelectedSubject]); this.selectedSubjectNames = function () { return $(me.selectedSubjects()).map(function (i, o) { return o.txt; }).get(); }; this.selectedSubjectIds = function () { return $(me.selectedSubjects()).map(function (i, o) { return o.id; }).get(); }; this.manageSingleSelectedSubject = function () { if (me.selectedSubjects().length == 0) me.selectedSubjects.push(initialSelectedSubject); }; this.readStatus = ko.observable(-1); this.includeChildSubjects = ko.observable(true); this.titleValue = ko.observable(initialTitleValue); this.animateOnEntry = true; this.templateItemRendered = function (element) { if (me.animateOnEntry) $(element).fadeIn(); }; })(); var dataLoader = new (function () { var me = this; this.loadAllBooks = function () { dataManager.clearCurrentData(); if (mode == 'dev') me.loadTestData(); else post("../PublicServices/KnockoutService.asmx/ReadAll", '{}', function (d) { currentSrc = d.d; dataManager.refreshCurrentData(); }); }; this.searchForBooks = function () { alert(viewModel.titleValue()); }; this.loadSubjects = function () { viewModel.subjects([{ name: "Sub1", id: 1, children: [] }, { name: "Sub2", id: 2, children: [{ name: "Sub2a", id: 4, children: [{ name: "Sub2a1", id: 6, children: []}] }, { name: "Sub2b", id: 5, children: []}] }, { name: "Sub3", id: 3, children: []}]); $("#jsTreeTarget").jstree({ "themes": { "theme": "default", "dots": false, "icons": false }, "checkbox": { "two_state": true }, "plugins": ["themes", "html_data", "checkbox", "ui"] }); $("#jsTreeTarget").bind("change_state.jstree", function () { viewModel.selectedSubjects( $("li.jstree-checked &gt; a", "#jsTreeTarget").map(function (i, o) { return { txt: $(o).text(), id: $(o).data("id") }; }).get()); }); }; this.loadTestData = function () { currentSrc = [{ id: 1, title: "Mr. Jefferson's Hammer. William Henry Harrison and the foundation of Indian Policy", authors: ["a1", "a2"], subjects: ["sub1", "sub2"], smImg: 1, medImg: 1, pub: "Oxford", pubYear: 2004, pages: 250, asin: "a", isRead: false }, { id: 1, title: "Founding Brothers", authors: ["a1", "a2"], subjects: ["sub1", "sub2"], smImg: 1, medImg: 1, pub: "Oxford", pubYear: 2004, pages: 250, asin: "a", isRead: false }, { id: 1, title: "American Creation", authors: ["a1", "a2"], subjects: ["sub1", "sub2"], smImg: 1, medImg: 1, pub: "Oxford", pubYear: 2004, pages: 250, asin: "a", isRead: false}]; for (var i = 0; i &lt; 50; i++) currentSrc.push({ id: 1, title: "American Creation", authors: ["a1", "a2"], subjects: ["sub1", "sub2"], smImg: 1, medImg: 1, pub: "Oxford", pubYear: 2004, pages: 250, asin: "a", isRead: false }); dataManager.refreshCurrentData(); }; })(); var dataManager = new (function () { var me = this; this.templateDataNotLoaded = false; this.refreshCurrentData = function () { if (currentDisplay == "grid") gridManager.reloadGrid(); else { me.templateDataNotLoaded = false; me.cascadeData(); } }; this.cascadeData = function (index) { me.animateOnEntry = true; if (!index) index = 0; if (index == currentSrc.length - 1) return; if (index &gt;= 30) { viewModel.animateOnEntry = false; for (var i = index; i &lt; currentSrc.length; i++) viewModel.rows.push(currentSrc[i]); } else { viewModel.rows.push(currentSrc[index]); setTimeout(function () { me.cascadeData(index + 1); }, 60); } }; this.dumpDataWithoutCascade = function () { me.templateDataNotLoaded = false; viewModel.rows(currentSrc); }; this.clearCurrentData = function () { currentSrc.length = 0; viewModel.rows.removeAll(); gridManager.unloadGrid(); me.templateDataNotLoaded = true; }; })(); var gridManager = new (function () { var me = this; this.gridDataNotLoaded = false; this.reloadGrid = function () { me.gridDataNotLoaded = false; $("#jqGridElement").jqGrid({ datastr: { rows: currentSrc }, jsonReader: { repeatitems: false }, datatype: "jsonstring", colNames: ['', 'Title', 'Pages', 'Publisher', 'Authors', "Subjects"], colModel: [ { name: 'smImg', index: 'smImg', width: 65, fixed: true, sortable: false, formatter: gridCoverFormatter, title: false }, { name: 'title', width: 250, formatter: titleFormatter, title: false }, { name: 'pages', width: 80, fixed: true, align: 'center', title: false }, { name: 'pub', index: 'pub', width: 100, formatter: publisherFormatter, title: false }, { name: 'authors', width: 100, formatter: authorFormatter, sortable: false, title: false }, { name: 'subjects', width: 100, formatter: subjectFormatter, sortable: false, title: false}], height: 'auto', gridview: true, rowNum: -1 }); me.sizeGrid(); }; this.unloadGrid = function () { me.gridDataNotLoaded = true; $("#jqGridElement").jqGrid('GridUnload'); }; this.sizeGrid = function () { var targetContainer = "#contentParent"; var gridID = "#jqGridElement"; var width = $(targetContainer).width(); var height = $(targetContainer).height(); width = width - 20; // Fudge factor to prevent horizontal scrollbars height = height - 40; if (width &gt; 0) //&amp;&amp; Math.abs(width - $(gridID).width()) &gt; 5) { $(gridID).jqGrid('setGridWidth', width); if (height &gt; 0) // &amp;&amp; Math.abs(height - jQuery(gridID).height()) &gt; 5) $(gridID).jqGrid('setGridHeight', height); }; function gridCoverFormatter(cellvalue, options, rowObject) { return "&lt;div style='height:85px;'&gt;&lt;img src='../Books/Covers/Small/" + cellvalue + ".jpg' style='margin-top:5px;' /&gt;&lt;/div&gt;"; } function titleFormatter(cellvalue, options, rowObject) { return "&lt;div title='" + cellvalue.toString().replace("'", "") + "'&gt;" + cellvalue + "&lt;/div&gt;&lt;a href='http://www.google.com?a=" + rowObject.asin + "' target='_blank'&gt;&lt;img src='../Img/Misc/Amazon.png'&lt;/a&gt;"; } function publisherFormatter(cellvalue, options, rowObject) { var formattedVal = cellvalue.toString().replace("'", ""); if ((formattedVal != "") &amp;&amp; (rowObject.pubYear)) formattedVal += " - " + rowObject.pubYear; return "&lt;div title='" + formattedVal + "'&gt;" + formattedVal + "&lt;/div&gt;"; } function authorFormatter(cellvalue, options, rowObject) { var result = ""; for (var i = 0; i &lt; cellvalue.length; i++) result += "&lt;li&gt;&lt;span&gt;" + cellvalue[i] + "&lt;/span&gt;&lt;/li&gt;"; return "&lt;ul class='grAUL'&gt;" + result + "&lt;/ul&gt;"; } function subjectFormatter(cellvalue, options, rowObject) { var result = ""; for (var i = 0; i &lt; cellvalue.length; i++) result += "&lt;li title='" + cellvalue[i] + "'&gt;" + "Oxford - 2004" + "&lt;/li&gt;"; return "&lt;ul class='grSUL'&gt;" + result + "&lt;/ul&gt;"; } })(); function theme(value) { if (value == "grid") { manageDisplay("#gridParent", "#templateElement", 'emptyBookTemplate'); if (gridManager.gridDataNotLoaded) gridManager.reloadGrid(); } else { manageDisplay("#templateElement", "#gridParent", value); if (dataManager.templateDataNotLoaded) dataManager.dumpDataWithoutCascade(); } currentDisplay = value; } function manageDisplay(showID, hideID, newTemplate) { $(showID).show(); $(hideID).hide(); viewModel.currentTemplate(newTemplate); } function bookDetailsPopup(id) { var divToPopup = $("#bookInfoPopup").clone(); $(divToPopup).dialog({ width: 400, height: 400 }); $.get("PartialBookInfo.aspx?id=" + id, function (response) { $(".popupContent", divToPopup).html(response); $(".tabDiv", divToPopup).tabs(); $(".loadingMsg", divToPopup).remove(); }); } function openSubjectWindow() { $("#treeWrapper").dialog({ title: "Header", close: function () { viewModel.manageSingleSelectedSubject(); } }); } function post(targetURL, dataInput, success) { $.ajax({ url: targetURL, type: "POST", contentType: "application/json; charset=utf-8", data: dataInput, dataType: "json", success: success, async: true }); } </code></pre>
[]
[ { "body": "<p>If you want to be safer, wrap the whole thing in a executed closure <code>(function () { /* code goes here */ })()</code>.</p>\n\n<p>I don't think you need <code>var me = this</code> since at quick glance all the functions are called on the instances, which would make the keyword <code>this</code> the instance object.</p>\n\n<p>There is nothing wrong with using anonymous constructors, as far as I know, but it would probably be better to use <code>{}</code> to create your objects and drop the <code>new</code> keyword. It will save you a reference lookup, like</p>\n\n<pre><code>var gridManager = (function () {\n\n function gridCoverFormatter(cellvalue, options, rowObject) {\n return \"&lt;div style='height:85px;'&gt;&lt;img src='../Books/Covers/Small/\" + cellvalue + \".jpg' style='margin-top:5px;' /&gt;&lt;/div&gt;\";\n }\n\n function titleFormatter(cellvalue, options, rowObject) {\n return \"&lt;div title='\" + cellvalue.toString().replace(\"'\", \"\") + \"'&gt;\" + cellvalue + \"&lt;/div&gt;&lt;a href='http://www.google.com?a=\" + rowObject.asin + \"' target='_blank'&gt;&lt;img src='../Img/Misc/Amazon.png'&lt;/a&gt;\";\n }\n\n function publisherFormatter(cellvalue, options, rowObject) {\n var formattedVal = cellvalue.toString().replace(\"'\", \"\");\n if ((formattedVal != \"\") &amp;&amp; (rowObject.pubYear))\n formattedVal += \" - \" + rowObject.pubYear;\n\n return \"&lt;div title='\" + formattedVal + \"'&gt;\" + formattedVal + \"&lt;/div&gt;\";\n }\n\n function authorFormatter(cellvalue, options, rowObject) {\n var result = \"\";\n for (var i = 0; i &lt; cellvalue.length; i++)\n result += \"&lt;li&gt;&lt;span&gt;\" + cellvalue[i] + \"&lt;/span&gt;&lt;/li&gt;\";\n return \"&lt;ul class='grAUL'&gt;\" + result + \"&lt;/ul&gt;\";\n }\n\n function subjectFormatter(cellvalue, options, rowObject) {\n var result = \"\";\n for (var i = 0; i &lt; cellvalue.length; i++)\n result += \"&lt;li title='\" + cellvalue[i] + \"'&gt;\" + \"Oxford - 2004\" + \"&lt;/li&gt;\";\n return \"&lt;ul class='grSUL'&gt;\" + result + \"&lt;/ul&gt;\";\n }\n\n return {\n \"gridDataNotLoaded\": falsse,\n\n \"reloadGrid\": function () {\n me.gridDataNotLoaded = false;\n\n $(\"#jqGridElement\").jqGrid({\n datastr: { rows: currentSrc },\n jsonReader: { repeatitems: false },\n datatype: \"jsonstring\",\n colNames: ['', 'Title', 'Pages', 'Publisher', 'Authors', \"Subjects\"],\n colModel: [\n { name: 'smImg', index: 'smImg', width: 65, fixed: true, sortable: false, formatter: gridCoverFormatter, title: false },\n { name: 'title', width: 250, formatter: titleFormatter, title: false },\n { name: 'pages', width: 80, fixed: true, align: 'center', title: false },\n { name: 'pub', index: 'pub', width: 100, formatter: publisherFormatter, title: false },\n { name: 'authors', width: 100, formatter: authorFormatter, sortable: false, title: false },\n { name: 'subjects', width: 100, formatter: subjectFormatter, sortable: false, title: false}],\n height: 'auto',\n gridview: true,\n\n rowNum: -1\n });\n\n this.sizeGrid();\n },\n\n \"unloadGrid\": function () {\n this.gridDataNotLoaded = true;\n $(\"#jqGridElement\").jqGrid('GridUnload');\n },\n\n \"sizeGrid\": function () {\n var targetContainer = \"#contentParent\";\n var gridID = \"#jqGridElement\";\n\n var width = $(targetContainer).width();\n var height = $(targetContainer).height();\n\n width = width - 20; // Fudge factor to prevent horizontal scrollbars\n height = height - 40;\n\n if (width &gt; 0) //&amp;&amp; Math.abs(width - $(gridID).width()) &gt; 5) {\n $(gridID).jqGrid('setGridWidth', width);\n\n if (height &gt; 0) // &amp;&amp; Math.abs(height - jQuery(gridID).height()) &gt; 5)\n $(gridID).jqGrid('setGridHeight', height);\n }\n };\n})();\n</code></pre>\n\n<p>But all in all, JavaScript is a very flexible language when it comes to objects. You can force a class based structure, or use the prototyping delegation. It goes further with module patterns and just extending objects. The choice is up to you.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T02:34:04.133", "Id": "4735", "ParentId": "4709", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T14:40:58.007", "Id": "4709", "Score": "1", "Tags": [ "javascript", "jquery", "object-oriented", "json", "knockout.js" ], "Title": "Book catalog demo using Knockout, jQuery, and JSON" }
4709
<p>This is a plugin for inserting content, which is for fallback for CSS generated content for IE</p> <p>Please review and suggest optimization tips and or improvement of code. See the TODO in code and offer advice.</p> <pre><code>//jQuery plugin for generating content (function( $ ){ $.fn.genContent = function($$options) { //;;;_debug(this); var $settings = $.extend({}, $.fn.genContent.defaults, $$options); return this.each(function() { $this = $(this); //If metadata plugin present, use it http://plugins.jquery.com/project/metadata var o = $.meta ? $.extend({}, $settings, $this.data()) : $settings; //update element styles $this.css({ margin : o.elStyles.margin, padding : o.elStyles.padding }); //TODO: Build in support for custom conditions if ( this.previousSibling != null ) { switch(o.placement){ case 'prepend': var $markup = $.fn.genContent.format(o); $($markup) .prependTo($this); break; case 'append': var $markup = $.fn.genContent.format(o); $($markup) .appendTo($this); break; case 'before': var $markup = $.fn.genContent.format(o); $($markup) .insertBefore($this); break; case 'after': var $markup = $.fn.genContent.format(o); $($markup) .insertAfter($this); break; default: var $markup = $.fn.genContent.format(o); $($markup) .prependTo($this); } } }); }; // // private function for debugging // function _debug($obj) { alert( 'elements affected count: ' + $obj.size() ); }; // //Expose the format function //We expose this function to customization for other uses. //May re-factor for use with jQuery Template Plugin. //NOTE: We could use a css class to style this element // however I like the flexibility of controlling style // with the plugin options and this exposed function. // $.fn.genContent.format = function(o) { return '&lt;' + o.wrap + ' style="' + o.wrapStyles.margin + '' + o.wrapStyles.padding + '"&gt;' + o.content + '&lt;/' + o.wrap + '&gt;'; }; // //Plugin Defaults // $.fn.genContent.defaults = { 'placement' : 'prepend', //{before,after,prepend,append} 'elStyles' : { 'margin' : '0', 'padding' : '0' }, 'wrap' : 'span', 'wrapStyles' : { 'margin' : ' margin: .8em;', 'padding' : ' padding: 0;' }, 'content' : '&amp;#149' }; })( jQuery ); </code></pre>
[]
[ { "body": "<pre><code>//jQuery plugin for generating content\n(function( $ ){\nvar $_func = $.fn.genContent = function($$options) {\n //;;;_debug(this);\n var $settings = $.extend({}, $_func.defaults, $$options);\n return this.each(function() {\n ///If metadata plugin present, use it http://plugins.jquery.com/project/metadata/update element styles \n var $this = $(this),\n o = $.meta ? $.extend({}, $settings, $this.data()) : $settings,\n o_elStyles,\n $markup;\n\n $this.css({\n margin : o_elStyles.margin,\n padding : o_elStyles.padding \n });\n //TODO: Build in support for custom conditions\n if ( this.previousSibling != null ) {\n $markup = $.fn.genContent.format(o);\n switch(o.placement){\n case 'append':\n $($markup)\n .appendTo($this);\n break;\n case 'before':\n $($markup)\n .insertBefore($this);\n break;\n case 'after':\n $($markup)\n .insertAfter($this);\n break;\n case 'prepend':\n default:\n $($markup)\n .prependTo($this); \n }\n }\n\n });\n};\n//\n// private function for debugging\n//\nfunction _debug($obj) {\n alert( 'elements affected count: ' + $obj.size() );\n};\n//\n//Expose the format function\n//We expose this function to customization for other uses.\n//May re-factor for use with jQuery Template Plugin.\n//NOTE: We could use a css class to style this element\n// however I like the flexibility of controlling style\n// with the plugin options and this exposed function.\n//\n$_func.format = function(o) {\n var o_wrap = o.wrap,\n o_wrapStyles = o.wrapStyles;\n return '&lt;' + o_wrap + \n ' style=\"' + o_wrapStyles.margin + \n '' + o_wrapStyles.padding + \n '\"&gt;' + o.content + '&lt;/' + o_wrap + '&gt;';\n}; \n//\n//Plugin Defaults\n//\n$_func.defaults = {\n 'placement' : 'prepend', //{before,after,prepend,append}\n 'elStyles' : {\n 'margin' : '0',\n 'padding' : '0'\n },\n 'wrap' : 'span',\n 'wrapStyles' : {\n 'margin' : ' margin: .8em;',\n 'padding' : ' padding: 0;'\n },\n 'content' : '&amp;#149'\n };\n})( jQuery );\n</code></pre>\n\n<p>What I've done is, collected your variables to top of the scope, created new variables to reduce property lookup and reduced a few lines of code because of repetition. Also, I've found, running through the <a href=\"http://code.google.com/closure/compiler/docs/gettingstarted_app.html\" rel=\"nofollow\">Google Closure</a> compiler with <code>--compilation_level SIMPLE_OPTIMIZATIONS</code> doesn't hurt ;) </p>\n\n<p>On your <code>TODO</code>, the custom conditions can be stored as closures, which can be contained in an object or array - array maybe better. Then loop through the array - yeap, array is better - calling the closures to see if conditions succeed, and then do what you want with it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T16:45:44.807", "Id": "7132", "Score": "0", "body": "thank you for the review and comments. You used an underscore for the var $_func=... I understand this to be used on private functions, please share with me why an underscore was used in your optimization. Thank you again!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T17:05:41.213", "Id": "7133", "Score": "0", "body": "I use underscores to write variable names. However it only becomes considered private if it starts with `_` ot `__`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T01:55:31.293", "Id": "4734", "ParentId": "4710", "Score": "1" } } ]
{ "AcceptedAnswerId": "4734", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T16:42:46.873", "Id": "4710", "Score": "2", "Tags": [ "javascript", "jquery", "plugin" ], "Title": "genContent plugin" }
4710
<p>The encryption script:</p> <pre><code>import random splitArray = [] def takeInput(): rawText = raw_input("Type something to be encrypted: \n") password = raw_input("Please type a numerical password: \n") encrypt(rawText, int(password)) def encrypt(rawText, password): for c in rawText: divide(c, password) def divide(charToDivide, password): asciiValue = ord(charToDivide) a = 0 b = 0 c = 0 passa = 0 passb = 0 passc = 0 a = random.randrange(a, asciiValue) b = random.randrange(b, asciiValue - a) c = asciiValue - (a+b) passa = random.randrange(passa, password) passb = random.randrange(passb, password-passa) passc = password - (passa+passb) if isinstance(password, str): print "Please enter a number" takeInput() else: a += passa b += passb c += passc splitArray.append(str(a)) splitArray.append(str(b)) splitArray.append(str(c)) takeInput() f = open("myEncryptorTest", 'w') arrayDelimiterString = "." encryptedString = arrayDelimiterString.join(splitArray) encryptedString = "." + encryptedString f.write(encryptedString) f.close </code></pre> <p>Decryption:</p> <pre><code>#XECryption decryption program #Each character is a set of three numbers delimited by dots #Decryption works by adding these three numbers together, subtracting the ASCII for a space and using that number to decypher #the rest of the array. #User is prompted to see if the message makes sense f = open('myEncryptorTest') encryptedString = f.read() f.close() #separate sets of three numbers into an array def sort(): sortedCharArray = [] charBuffer = "" for c in encryptedString: if c == '.' and charBuffer != "": sortedCharArray.append(charBuffer) charBuffer = "" elif c != '.': charBuffer += c #if the buffer is not empty (e.g. last number), put it on the end if charBuffer != "": sortedCharArray.append(charBuffer) charBuffer = "" crack(sortedCharArray) #add sets of three numbers together and insert into an array decryption def crack(charArray): charBuffer = 0 arrayCount = 1 decypheredArray = [] for c in charArray: if arrayCount % 3 == 0: arrayCount = arrayCount + 1 charBuffer = charBuffer + int(c) decypheredArray.append(charBuffer) charBuffer = 0 else: arrayCount = arrayCount + 1 charBuffer = charBuffer + int(c) decypher(decypheredArray) #subtract ASCII value of a space, use this subtracted value as a temporary password def decypher(decypheredArray): space = 32 subtractedValue = 0 arrayBuffer = [] try: for c in decypheredArray: subtractedValue = c - space for c in decypheredArray: asciicharacter = c - subtractedValue arrayBuffer.append(asciicharacter) answerFromCheck = check(arrayBuffer) if answerFromCheck == "y": #print value of password if user states correct decryption print "Password: " print subtractedValue raise StopIteration() else: arrayBuffer = [] except StopIteration: pass #does the temporary password above produce an output that makes sense? def check(arrayBuffer): decypheredText = "" stringArray = [] try: for c in arrayBuffer: try: stringArray.append(chr(c)) except ValueError: pass print decypheredText.join(stringArray) inputAnswer = raw_input("Is this correct?") if inputAnswer == "y": return inputAnswer else: stringArray = [] return inputAnswer except StopIteration: return sort() f.close() </code></pre> <p>As I say, I'm looking for advice on how to improve my code and writing code in general. I'm aware that my code is probably an affront against programmers everywhere but I want to improve. These two scripts are for the hackthissite.org Realistic 6 mission. I won't be using them for encrypting anything of great importance. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T19:11:49.330", "Id": "7048", "Score": "0", "body": "Unless you have a specific and very good reason for writing your own encryption algorithm, you most likely shouldn't do it. http://diovo.com/2009/02/wrote-your-own-encryption-algorithm-duh/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T20:21:09.540", "Id": "7049", "Score": "0", "body": "I wrote this for the hackthissite.org Realistic 6 mission." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T05:12:14.580", "Id": "7055", "Score": "0", "body": "http://codereview.stackexchange.com/faq#make-sure-you-include-your-code-in-your-question" } ]
[ { "body": "<pre><code>import random\nsplitArray = []\n</code></pre>\n\n<p>It is best not to store data in global variables. Instead, you should have functions take all the input they need and return the result</p>\n\n<pre><code>def takeInput():\n\n rawText = raw_input(\"Type something to be encrypted: \\n\")\n</code></pre>\n\n<p>The python style guide recommends lowercase_with_underscores for local variable names</p>\n\n<pre><code> password = raw_input(\"Please type a numerical password: \\n\")\n encrypt(rawText, int(password))\n</code></pre>\n\n<p>If the user enters something not a number, you'll get an exception. Its best to catch the exception and ask the user to try again</p>\n\n<pre><code>def encrypt(rawText, password):\n for c in rawText:\n divide(c, password)\n print c \n</code></pre>\n\n<p>Why are you printing c? If its just debug output you should remove when you've finished debugging.</p>\n\n<pre><code>def divide(charToDivide, password):\n asciiValue = ord(charToDivide)\n a = 0\n b = 0\n c = 0\n</code></pre>\n\n<p>Consider storing these as a tuple</p>\n\n<pre><code> passa = 0\n passb = 0\n passc = 0\n</code></pre>\n\n<p>And here as well</p>\n\n<pre><code> a = random.randrange(a, asciiValue)\n</code></pre>\n\n<p>Ok, why did you assign zero to a earlier rather then just putting 0 as the argument here</p>\n\n<pre><code> b = random.randrange(b, asciiValue - a)\n</code></pre>\n\n<p>Same here</p>\n\n<pre><code> c = asciiValue - (a+b)\n passa = random.randrange(passa, password)\n passb = random.randrange(passb, password-passa)\n passc = password - (passa+passb)\n</code></pre>\n\n<p>And again here, the earlier assignments seemed to have no purpose. Additionally, the same logic was applied to both asciiValue and password. Make a function that produces the a,b,c from the input and call it for each of those values instead.</p>\n\n<pre><code> if isinstance(password, str): \n print \"Please enter a number\"\n takeInput()\n</code></pre>\n\n<p>Given your code how could password possibly be a string? If it were you would have already gotten an exception. You also shouldn't really mix function that perform logic and ones that take input.\n else:\n a += passa<br>\n b += passb\n c += passc<br>\n splitArray.append(str(a))\n splitArray.append(str(b))\n splitArray.append(str(c))</p>\n\n<p>If you take my advice and put a,b,c in a tuple, then you could done this in one line.</p>\n\n<pre><code>takeInput()\nf = open(\"myEncryptorTest\", 'w')\narrayDelimiterString = \".\"\nencryptedString = arrayDelimiterString.join(splitArray)\n</code></pre>\n\n<p>There isn't a whole lot of point in assigning a variable in one line and then using it only on the next.</p>\n\n<pre><code>encryptedString = \".\" + encryptedString\n</code></pre>\n\n<p>Instead of that:</p>\n\n<pre><code>encryptedString = ''.join('.' + data for data in splitArray)\n\n\nf.write(encryptedString)\nf.close\n</code></pre>\n\n<p>You are missing the (), so the file won't actually be closed.</p>\n\n<pre><code>#XECryption decryption program\n\n#Each character is a set of three numbers delimited by dots\n\n#Decryption works by adding these three numbers together, subtracting the ASCII for a space and using that number to decypher \n#the rest of the array.\n\n#User is prompted to see if the message makes sense\n</code></pre>\n\n<p>Python has a feature called docstrings. If the first thing in a module or function is a string, it it considered the documentation for that object. You would do something like </p>\n\n<pre><code>\"\"\"\nXEcryption decryption program\n\nyada yada yada\n\"\"\"\n</code></pre>\n\n<p>Rather then all those comments</p>\n\n<pre><code>f = open('myEncryptorTest')\n</code></pre>\n\n<p>I recommend against single-letter variable names</p>\n\n<pre><code>encryptedString = f.read()\nf.close()\n\n\n#separate sets of three numbers into an array\n</code></pre>\n\n<p>This comment should be a docstring in the function like I described. Also, the function doesn't do anything with sets of three numbers.</p>\n\n<pre><code>def sort():\n sortedCharArray = []\n charBuffer = \"\" \n for c in encryptedString:\n if c == '.' and charBuffer != \"\":\n sortedCharArray.append(charBuffer)\n charBuffer = \"\"\n elif c != '.':\n charBuffer += c\n #if the buffer is not empty (e.g. last number), put it on the end\n if charBuffer != \"\":\n sortedCharArray.append(charBuffer)\n charBuffer = \"\"\n</code></pre>\n\n<p>This entire function can be replaced by <code>sortedCharArray = encryptedString.split('.')</code> Also, the function doesn't do any sorting. </p>\n\n<pre><code> crack(sortedCharArray)\n\n#add sets of three numbers together and insert into an array decryption\ndef crack(charArray):\n charBuffer = 0\n arrayCount = 1\n decypheredArray = []\n for c in charArray:\n if arrayCount % 3 == 0:\n</code></pre>\n\n<p>Don't iterate over what you have, iterate over what you want. Do something like:</p>\n\n<pre><code> for index in xrange(0, len(charArray), 3):\n triplet = charArray[index:index+3]\n</code></pre>\n\n<p>That way triplet will have the three elements and you can operate on those without having to keep track of charBuffer or arrayCount</p>\n\n<pre><code> arrayCount = arrayCount + 1\n charBuffer = charBuffer + int(c)\n decypheredArray.append(charBuffer)\n charBuffer = 0\n else:\n arrayCount = arrayCount + 1\n charBuffer = charBuffer + int(c)\n decypher(decypheredArray)\n</code></pre>\n\n<p>Rather then calling the next function in a chain like this. I suggest that you return at the end of each function and then have a master function pass that onto the next function. That way the master function will have a list of all of the steps in the algorithm. But bonus points for actually splitting it up into multiple functions</p>\n\n<pre><code>#subtract ASCII value of a space, use this subtracted value as a temporary password\ndef decypher(decypheredArray):\n space = 32\n</code></pre>\n\n<p>Why don't you use <code>space = ord(' ')</code></p>\n\n<pre><code> subtractedValue = 0\n arrayBuffer = []\n try:\n for c in decypheredArray:\n subtractedValue = c - space\n for c in decypheredArray:\n</code></pre>\n\n<p>Careful! your inner loop has the same variable as the outer loop\n asciicharacter = c - subtractedValue\n arrayBuffer.append(asciicharacter)\n answerFromCheck = check(arrayBuffer)\n if answerFromCheck == \"y\":</p>\n\n<p>Use the python values True and False, not strings.</p>\n\n<pre><code> #print value of password if user states correct decryption\n print \"Password: \"\n print subtractedValue \n raise StopIteration()\n</code></pre>\n\n<p>Use <code>break</code> or <code>return</code>. You almost never need to <code>raise StopIteration</code>\n else:\n arrayBuffer = []</p>\n\n<p>Rather then clearing the arrayBuffer here, create a new arrayBuffer \n except StopIteration:\n pass\nSee this is problematic because something else could raise a StopIteration and you might accidently catch it.</p>\n\n<pre><code>#does the temporary password above produce an output that makes sense?\ndef check(arrayBuffer):\n decypheredText = \"\"\n stringArray = []\n try:\n for c in arrayBuffer:\n try:\n stringArray.append(chr(c))\n except ValueError:\n pass\n</code></pre>\n\n<p>If you get a ValueError, its because the character in question wasn't ascii. Shouldn't you just assume that the password was incorrect in that case?</p>\n\n<p>Try <code>stringArray = map(chr, arrayBuffer)</code> instead of that loop.</p>\n\n<pre><code> print decypheredText.join(stringArray)\n inputAnswer = raw_input(\"Is this correct?\")\n</code></pre>\n\n<p>You are mixing input and logic. I recommend reworking your code so they are seperate.</p>\n\n<pre><code> if inputAnswer == \"y\":\n return inputAnswer\n else:\n stringArray = []\n</code></pre>\n\n<p>This has no effect outside this function, why are you doing it?</p>\n\n<pre><code> return inputAnswer\n except StopIteration:\n return \nsort()\nf.close()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T07:18:59.887", "Id": "7072", "Score": "0", "body": "This is exactly what I was after. Thanks for taking the time to reply." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T07:28:59.753", "Id": "7073", "Score": "0", "body": "The password can be an ASCII character now, the encryption script basically adds the ASCII values of the characters together and uses that as a password. I'll go over the rest of the code with your advice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T06:30:36.803", "Id": "7107", "Score": "1", "body": "@user331296 if you agree the answer please tag it as accepted in front of answer" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T14:54:32.417", "Id": "4726", "ParentId": "4712", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T15:48:47.300", "Id": "4712", "Score": "2", "Tags": [ "python", "cryptography" ], "Title": "XECryption encryption and decryption script" }
4712
<p>How can I improve this?</p> <pre><code>#include "stdafx.h" #include &lt;iostream&gt; /*A program that accepts input of an employees' base salaries and years of service. Then it also calculates their bonus based on the years of service. - 20 or more years of service, bonus = salary * 0.1 - 10 or more years of service, bonus = salary * 0.05 - 5 or more years of service, bonus = salary * 0.025 Also the program should let the user to enter data until they want to stop. */ using namespace std; int main() { int iSalary; int iService; float fBonus; int counter = 1; bool okcontinue = true; char idontchar; while (okcontinue) { cout &lt;&lt; "You are employee #" &lt;&lt; counter &lt;&lt; " to use this.\n"; cout &lt;&lt; "Enter your base salary: \n"; cin &gt;&gt; iSalary; cout &lt;&lt; "Enter total # of years serviced: \n"; cin &gt;&gt; iService; if (iService &gt;= 20) fBonus = iSalary * 0.1; if ((iService &lt; 20) &amp;&amp; (iService &gt;= 10)) fBonus = iSalary * 0.05; if ((iService &lt; 10) &amp;&amp; (iService &gt;= 5)) fBonus = iSalary * 0.025; cout &lt;&lt; "Your bonus is: " &lt;&lt; fBonus &lt;&lt; ". Enter 'e' to exit or 'c' to continue.\n"; cin &gt;&gt; idontchar; if (idontchar == 'e') return 0; counter++; system("CLS"); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T22:40:45.083", "Id": "7050", "Score": "3", "body": "At the very least you could copy the formatting that was done for you over on stack overflow so somebody doesn't have to do it for you *again*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T21:39:03.560", "Id": "7142", "Score": "1", "body": "Don't use Windows-specific stuff like `#include \"stdafx.h\"` and `system(\"CLS\");` unless you want your code to be totally non-portable i.e. limited to running under Windows only." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T12:54:53.537", "Id": "7175", "Score": "0", "body": "Read this stackoverflow question too\r\nhttp://stackoverflow.com/questions/1798511/how-to-avoid-press-enter-with-any-getchar" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T12:57:15.747", "Id": "60693", "Score": "0", "body": "Read this stackoverflow question too for information about using an alternative to cin >> idontchar;\nhttp://stackoverflow.com/questions/1798511/how-to-avoid-press-enter-with-any-getchar\nTo remove a character that has been printed on the current line you can use putch('\\b'); // backspace" } ]
[ { "body": "<ol>\n<li><p>Don't declare variables before you need them:</p>\n\n<pre><code>int iSalary;\nint iService;\nfloat fBonus;\nint counter = 1;\nbool okcontinue = true;\nchar idontchar; \n</code></pre>\n\n<p>By declaring them at the point of first use you also see that they are correctly initialized. Rather than having to scan all the way up the function to the top.</p></li>\n<li><p>Sure if this works for you:</p>\n\n<pre><code>system(\"CLS\");\n</code></pre>\n\n<p>But it's not portable. Don't worry too much a bout clearing the screen (or learn to use a platform agnostic library like ncurses or equivalent).</p></li>\n<li><p>Tidy up your condition: (Nornagest nearly has it correct he needs to reverse the order and put in the else condition otherwise somebody with <code>iService</code> of >= 20 is going to be very happy with multiple bonus.)</p>\n\n<pre><code>if (iService &gt;= 20) { fBonus = iSalary * 0.1; }\nelse if (iService &gt;= 10) { fBonus = iSalary * 0.05; }\nelse if (iService &gt;= 5) { fBonus = iSalary * 0.025; }\n</code></pre></li>\n<li><p>Floating point has rounding problems. Businesses do not like this. They would prefer things stay exact. So you may want to use integers instead of floats. But track the salary in pennies rather than dollars.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T23:42:40.283", "Id": "4719", "ParentId": "4715", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T22:23:12.243", "Id": "4715", "Score": "-1", "Tags": [ "c++", "finance" ], "Title": "Calculating an employee's bonus" }
4715
<p>Can anyone check this code of mine for improvements? This was coded using Java with OOP concepts.</p> <p><strong><code>Game</code> Class</strong></p> <pre><code>import java.util.Random; public class Game { Player player = new Player(); Banker banker = new Banker(); private int a = 0; private int b = 6; private double myAmount = 0; private double offer = 0; private int turn = 1; private int cases = 26; private double amounts[] = { 23, 1, 5, 10, 25, 50, 75, 100, 200, 300, 400, 500, 750, 1000, 5000, 10000, 25000, 50000, 75000, 100000, 300000, 400000, 500000, 750000, 1000000, 250000, 800 }; private String models[] = { "Nayer", "Michelle", "Obama", "Rosey", "Miney", "Ashley", "Maria", "Ozawa", "Audrey", "Kristen", "Kim", "Kardashian", "Kourtney", "Ann", "Macy", "Tori", "Sam", "Monica", "Jin", "Koi", "jill", "Usher", "Justin Bieber", "Lindsay Lohan", "Hazell", "Buttercup", "Don Amalia", "Kojic!" }; Briefcase briefcase[] = new Briefcase[27]; Model lady[] = new Model[27]; public void setladies() { for (int i = 0; i &lt; lady.length; i++) { lady[i] = new Model(); String name = models[i]; lady[i].setName(name); } } public void Shuffle() { Random rgen = new Random(); for (int i = 0; i &lt; amounts.length - 1; i++) { int Position = rgen.nextInt(amounts.length); double temp = amounts[i]; amounts[i] = amounts[Position]; amounts[Position] = temp; } } public void casesSetup() { Shuffle(); for (int i = 0; i &lt; briefcase.length; i++) { if (i == 0) { } else { } briefcase[i] = new Briefcase(); double value = amounts[i]; briefcase[i].setAmount(value); briefcase[i].setFace(i); } } public void showCases() { for (int a = 0; a &lt; briefcase.length; a++) { if (a == 0) { } else if (briefcase[a] == null) { System.out.print("\t[X]"); } else { System.out.print("\t[" + briefcase[a].getFace() + "]"); } if (a % 5 == 0) { System.out.println(); } } System.out.println(); } public void Welcome() { System.out.println("\t~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*"); System.out.println("\t~* Welcome ! ~*"); System.out.println("\t~*~*~*~*~* Hosted by Kyel David ~*~*~*~*~*~*"); System.out.println("\t~* Please Select from the Following Cases!~*"); System.out.println("\t~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*"); } public void starGame() { boolean gamestatus = true; casesSetup(); Welcome(); showCases(); setladies(); int choice = player.nUser(); myAmount = briefcase[choice].getAmount(); briefcase[choice] = null; cases--; while (gamestatus == true) { showCases(); if (cases == 25 || cases == 19 || cases == 14 || cases == 10 || cases == 7) { for (a = b; a &gt; 0; a--) { int r = player.Remove(a, briefcase, models); briefcase[r] = null; cases--; } b--; turn++; banker.setOffer(turn,briefcase,myAmount); offer = banker.getOffer(turn, briefcase, myAmount); gamestatus = player.gamestatus(); } else if (cases == 1) { int r = player.Remove(1, briefcase, models); briefcase[r] = null; gamestatus = false; } else { int r = player.Remove(1, briefcase, models); briefcase[r] = null; cases--; banker.setOffer(turn,briefcase,myAmount); offer = banker.getOffer(turn, briefcase, myAmount); gamestatus = player.gamestatus(); } } finishgame(); } public void finishgame() { if (cases == 1) { System.out.println("\tYou Rejected the Offer of Banker"); System.out .printf("\tYour case contains $%.2f and the bankers offer is $%.2f\n", myAmount, offer); System.out.printf("\tYou've won your case with an amount of: %.2f", myAmount); } else { System.out.println("\tYou Accepted the offer of Banker"); System.out .printf("\tYour case contains $%.2f and the bankers offer is $%.2f\n", myAmount, offer); System.out.printf("\tYou've won the offer of Banker: $%.2f", offer); } } } </code></pre> <p><strong><code>Player</code> Class</strong></p> <pre><code>import java.util.Scanner; public class Player { Scanner input = new Scanner(System.in); Banker banker = new Banker(); public boolean gamestatus() { System.out.print("\tAccept or Reject! [1]Accept [2]reject: "); int temp = input.nextInt(); System.out.println(); if (temp == 1) { return false; } else { return true; } } public int nUser() { boolean isOkay = false; int nUser = 0; while (isOkay == false) { System.out.print("\n\tPlease Select Your Case!: "); nUser = input.nextInt(); if (nUser &lt; 0 || nUser &gt;= 27) { System.out.println("\tInvalid input Try again"); } else { isOkay = true; } } return nUser; } public int Remove(int i, Briefcase c[], String[] m) { int nChoice = 0; boolean inputisok = false; while (inputisok == false) { System.out.print("\tPlease remove " + i + " case/s: "); nChoice = input.nextInt(); if (nChoice &lt; 0 || nChoice &gt;= c.length || c[nChoice] == null) { System.out.println(); System.out.println("\tInvalid Input please Try again\n"); } else { System.out.println("\tI'm " + m[nChoice] + " You just removed case # " + nChoice); System.out.println("\t|" + nChoice + "| contains $" + c[nChoice].getAmount() + "\n"); inputisok = true; } } return nChoice; } } </code></pre> <p><strong><code>Banker</code> Class</strong></p> <pre><code>public class Banker { private double total = 0; private int a = 0; private double amount =0; double Average = 0; public void setOffer(int turn, Briefcase[] cases, double myAmount) { for (int i = 0; i &lt; cases.length; i++) { if (cases[i] == null) { } else { total = total + cases[i].getAmount(); a++; } } Average = myAmount+total / a; amount = Average*turn/ 10; } public double getOffer(int turn, Briefcase[] cases, double myAmount) { setOffer(turn, cases, myAmount); System.out.printf("\tThe Bankers Offer is: %.2f \n\n", amount); return amount; } } </code></pre> <p><strong><code>Model</code> Class</strong></p> <pre><code>public class Model { private String mName; public void setName(String mName) { this.mName = mName; } public String getName() { return mName; } } </code></pre> <p><strong><code>Briefcase</code> Class</strong></p> <pre><code>public class Briefcase { private double amount; private int face; public void setAmount(double amount) { this.amount = amount; } public double getAmount() { return this.amount; } public void setFace(int face) { this.face = face; } public int getFace() { return face; } } </code></pre> <p><strong>Main class</strong></p> <pre><code>public class Play { public static void main(String[] args) { Game dnd = new Game(); dnd.starGame(); } } </code></pre>
[]
[ { "body": "<p>There are a few things, I'll expand on this over time. First, always write method and variable names in <strong>lowerCamelCase</strong>. Everything starting with an uppercase letter wil be considered a class or a constant by other programmers.</p>\n\n<p>Then, don't use mechanically getters and setters. E.g. consider</p>\n\n<pre><code>public class Model {\n\n private String mName;\n\n public void setName(String mName) {\n\n this.mName = mName;\n }\n\n public String getName() {\n return mName;\n }\n\n}\n</code></pre>\n\n<p>Do you ever change the name of a <code>Model</code> afterwards? No? Is it okay to have a <code>Model</code> without name? No? Then a correct implementation is:</p>\n\n<pre><code>public class Model {\n\n private final String mName;\n\n public Model(String mName) {\n this.mName = mName;\n }\n\n public String getName() {\n return mName;\n }\n\n}\n</code></pre>\n\n<p>You could opt for implementing <code>toString</code> instead of <code>getName</code>, or even for making the member variable public (because it's final, and <code>String</code> is immutable). </p>\n\n<p><strong>[Some Random Thoughts]</strong></p>\n\n<p>Try to simplify logical expressions as much as possible:</p>\n\n<pre><code>if (temp == 1) {\n return false;\n} else {\n return true;\n}\n</code></pre>\n\n<p>is the same as simply <code>return temp != 1;</code>.</p>\n\n<p>Use API functions where possible. E.g. there is <code>java.util.Collections.shuffle</code> for <code>List</code>s.</p>\n\n<p>What is with the empty {} in <code>casesSetup</code> and <code>showCases</code>?</p>\n\n<p><strong>[Suggestion]</strong></p>\n\n<pre><code>public class Banker {\n\n private double total = 0;\n private int a = 0;\n private double amount =0;\n double average = 0;\n\n public void setOffer(int turn, Briefcase[] cases, double myAmount) {\n\n for (int i = 0; i &lt; cases.length; i++) {\n if (! cases[i].isRemoved()) {\n total += cases[i].getAmount();\n a++;\n }\n }\n average = myAmount + total / a;\n amount = average*turn/ 10;\n }\n\n public double getOffer(int turn, Briefcase[] cases, double myAmount) {\n setOffer(turn, cases, myAmount);\n System.out.printf(\"\\tThe Bankers Offer is: %.2f \\n\\n\", amount);\n return amount;\n }\n}\n</code></pre>\n\n<p>.</p>\n\n<pre><code>public class Briefcase {\n private final double amount;\n private final String model;\n private boolean removed = false;\n private String face;\n\n public Briefcase(double amount, int face, String model) {\n this.face = Integer.toString(face);\n this.amount = amount;\n this.model = model;\n }\n\n public double getAmount() {\n return amount;\n }\n\n @Override\n public String toString() {\n return face;\n }\n\n public String getModel() {\n return model;\n }\n\n public void remove() {\n removed = true;\n face = \"X\";\n }\n\n public boolean isRemoved() {\n return removed;\n }\n}\n</code></pre>\n\n<p>.</p>\n\n<pre><code>import java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Game {\n private Player player = new Player();\n private Banker banker = new Banker();\n private int a = 0;\n private int b = 6;\n private double myAmount = 0;\n private double offer = 0;\n private int turn = 1;\n private int cases = 26;\n private Briefcase briefcases[];\n\n public void casesSetup() {\n String[] modelNames = {\"Michelle\", \"Obama\", \"Rosey\", \"Miney\",\n \"Ashley\", \"Maria\", \"Ozawa\", \"Audrey\", \"Kristen\", \"Kim\",\n \"Kardashian\", \"Kourtney\", \"Ann\", \"Macy\", \"Tori\", \"Sam\", \"Monica\",\n \"Jin\", \"Koi\", \"jill\", \"Usher\", \"Justin Bieber\", \"Lindsay Lohan\",\n \"Hazell\", \"Buttercup\", \"Don Amalia\", \"Kojic!\"};\n\n List&lt;Integer&gt; amounts = Arrays.asList(1, 5, 10, 25, 50, 75, 100,\n 200, 300, 400, 500, 750, 1000, 5000, 10000, 25000, 50000, 75000,\n 100000, 300000, 400000, 500000, 750000, 1000000, 250000, 800);\n\n Collections.shuffle(amounts);\n\n briefcases = new Briefcase[amounts.size()];\n\n for (int i = 0; i &lt; briefcases.length; i++) {\n double value = amounts.get(i);\n briefcases[i] = new Briefcase(value, i + 1, modelNames[i]);\n }\n }\n\n public void showCases() {\n for (int i = 0; i &lt; briefcases.length; i++) {\n System.out.print(\"\\t[\" + briefcases[i] + \"]\");\n if (i % 5 == 4) {\n System.out.println();\n }\n }\n System.out.println();\n }\n\n public void welcomeMessage() {\n System.out.println(\"\\t~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\");\n System.out.println(\"\\t~* Welcome ! ~*\");\n System.out.println(\"\\t~*~*~*~*~* Hosted by Kyel David ~*~*~*~*~*~*\");\n System.out.println(\"\\t~* Please Select from the Following Cases!~*\");\n System.out.println(\"\\t~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*\");\n }\n\n public void startGame() {\n\n boolean gamestatus = true;\n casesSetup();\n welcomeMessage();\n showCases();\n\n int choice = player.nUser();\n myAmount = briefcases[choice].getAmount();\n briefcases[choice].remove();\n cases--;\n\n while (gamestatus == true) {\n showCases();\n if (cases == 25 || cases == 19 || cases == 14 || cases == 10\n || cases == 7) {\n for (a = b; a &gt; 0; a--) {\n player.remove(a, briefcases);\n cases--;\n }\n b--;\n turn++;\n banker.setOffer(turn, briefcases, myAmount);\n offer = banker.getOffer(turn, briefcases, myAmount);\n gamestatus = player.gamestatus();\n } else if (cases == 1) {\n player.remove(1, briefcases);\n gamestatus = false;\n } else {\n player.remove(1, briefcases);\n cases--;\n banker.setOffer(turn, briefcases, myAmount);\n offer = banker.getOffer(turn, briefcases, myAmount);\n gamestatus = player.gamestatus();\n }\n }\n finishgame();\n }\n\n public void finishgame() {\n if (cases == 1) {\n System.out.println(\"\\tYou Rejected the Offer of Banker\");\n System.out.printf(\"\\tYour case contains $%.2f and the bankers offer is $%.2f\\n\",\n myAmount, offer);\n System.out.printf(\"\\tYou've won your case with an amount of: %.2f\",\n myAmount);\n } else {\n System.out.println(\"\\tYou Accepted the offer of Banker\");\n System.out.printf(\"\\tYour case contains $%.2f and the bankers offer is $%.2f\\n\",\n myAmount, offer);\n System.out.printf(\"\\tYou've won the offer of Banker: $%.2f\", offer);\n }\n }\n}\n</code></pre>\n\n<p>.</p>\n\n<pre><code>public class Play {\n\n public static void main(String[] args) {\n Game dnd = new Game();\n dnd.startGame();\n }\n}\n</code></pre>\n\n<p>.</p>\n\n<pre><code>import java.util.Scanner;\n\npublic class Player {\n\n Scanner input = new Scanner(System.in);\n Banker banker = new Banker();\n\n public boolean gamestatus() {\n System.out.print(\"\\tAccept or Reject! [1]Accept [2]Reject: \");\n int temp = input.nextInt();\n System.out.println();\n return temp != 1;\n }\n\n public int nUser() {\n while (true) {\n System.out.print(\"\\n\\tPlease Select Your Case!: \");\n int nUser = input.nextInt() - 1;\n if (nUser &lt; 0 || nUser &gt;= 26) {\n System.out.println(\"\\tInvalid input Try again\");\n } else {\n return nUser;\n }\n }\n }\n\n public int remove(int index, Briefcase[] briefCases) {\n while (true) {\n System.out.print(\"\\tPlease remove \" + index + \" case/s: \"); \n int nChoice = input.nextInt() - 1;\n if (nChoice &lt; 0 || nChoice &gt;= briefCases.length || briefCases[nChoice].isRemoved()) {\n System.out.println();\n System.out.println(\"\\tInvalid Input please Try again\\n\");\n } else {\n System.out.println(\"\\tI'm \" + briefCases[nChoice].getModel()\n + \". You just removed case # \" + (nChoice+1));\n System.out.println(\"\\t|\" + nChoice + \"| contains $\"\n + briefCases[nChoice].getAmount() + \"\\n\");\n briefCases[nChoice].remove();\n return nChoice;\n }\n }\n }\n}\n</code></pre>\n\n<p><code>Model</code> is gone. <code>Briefcase</code> is more useful, especially you don't have to use null values to encode a removed briefcase. I changed the alignment of briefcase, so there is no more dummy value. Then I tried to simplify everything a little bit. </p>\n\n<p>This is far from perfect, there is still room for improvements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T15:13:09.023", "Id": "7064", "Score": "0", "body": "what more could I improve?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T18:43:22.390", "Id": "7067", "Score": "0", "body": "@Andrew Asmer: updated" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T02:03:15.340", "Id": "7070", "Score": "0", "body": "what it's does this do? if (! cases[i].isRemoved()" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T02:26:33.497", "Id": "7071", "Score": "0", "body": "and also, I just noticed that each while loop has this while (true\n\nI don't get that, and within that block of code it doesn't contain a boolean that retusn false :|" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T07:47:39.033", "Id": "7074", "Score": "0", "body": "1) a `Briefcase` holds a boolean `removed value (instead of setting it to `null`), and this expression just checks that this particular `Briefcase` isn't removed yet. 2) I just translated your code: The loop asks \"forever\" as long as it has no correct answer. You can leave a loop in 4 ways: By not fulfilling the loop condition, by throwing an exception, by using `break` and - as I did here - by calling `return`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T09:56:12.543", "Id": "7075", "Score": "0", "body": "sooo if I call return, the loop will break? is that correct? and the \"if (! cases[i].isRemoved())\" means that if the value is still false,? it will continue? am I getting it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T09:59:25.927", "Id": "7076", "Score": "0", "body": "and lastly !cases.isRemoved() means that !=not removed? am I right? sorry I am kinda having this confusion having this case" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T14:02:06.193", "Id": "7077", "Score": "0", "body": "A `return` will leave the method where ever you are (except in some crazy edge cases with `finally`). For the statement: You can really simply read it like English \"if (! cases[i].isRemoved())\" -> \"if not briefcase is removed\" -> \"if the briefcase isn't removed, then...\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T15:27:32.967", "Id": "7079", "Score": "0", "body": "okay let me get this straight the keyword return will break the while loop right ? and lastly can you provide me another example of the \"if (! cases[i].isRemoved())\" ? with simpler terms kinda getting confused because of that" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T15:29:26.600", "Id": "7080", "Score": "0", "body": "and what does this meaning? this is kinda getting complexed XD while(true) what does that do? ._. there's no boolean conditon?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T16:50:06.203", "Id": "7084", "Score": "0", "body": "`while(true)` is a loop that runs forever, conceptually the same as `while(1==1)`. The keyword `return` leaves a method, where ever it stands (even in a loop in a loop in a loop...). The keyword that leaves the innermost loop is `break`. BTW: I have a lot of patience and have no problem to explain every detail, but why don't you try it out yourself for such easy cases? And the meaning of keywords is described here: http://java.sun.com/docs/books/jls/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T08:15:24.417", "Id": "7166", "Score": "0", "body": "One last thing why did you declare the amounts as final? why?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T09:44:38.603", "Id": "7168", "Score": "0", "body": "They don't change, and shouldn't change in this context. I found that I sometimes forget to initialize member variables in the constructor. If I make them `final` (when possible), this can't happen, as the compiler yells at me. Generally `final` documents your intentions, e.g. if someone thinks you might have forgotten a setter, it signals that you left it out intentionally." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T09:46:10.720", "Id": "7169", "Score": "0", "body": "and BTW at Landel can you use logical operators on object? specifically \"!\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T12:40:36.057", "Id": "7174", "Score": "0", "body": "No, only on `boolean`s. But a dot binds closer than !, so if you see something like `! myList.isEmpty()`, it means `! (myList.isEmpty())`, so you first get a `boolean` value from the object, and then you apply ! on it." } ], "meta_data": { "CommentCount": "15", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T10:51:58.247", "Id": "4724", "ParentId": "4723", "Score": "11" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T08:23:53.637", "Id": "4723", "Score": "5", "Tags": [ "java", "object-oriented", "game" ], "Title": "\"Deal or No Deal\" console game" }
4723
<p>I wrote a search script, now I want a more efficient way of finding the keywords used for the search and make them bold. I used this code but it I feel it could be greatly improved on. Thanks for any suggestion.</p> <pre><code>// I use this code to select the lines to display $lines = explode('.', trim($search_result)); // Break up the result into sentences $j = 0; $line = ''; for($i = 0; $i &lt; sizeof($lines); $i++) { // Look for the keywords in each of the line if (strstr($lines[$i], $keywords[0]) || strstr($lines[$i], $keywords[1]) || strstr($lines[$i], $keywords[2]) || strstr($lines[$i], $keywords[3]) ) { $j++; $line .= trim($lines[$i])."..."; } if ($j == 2) return $line; // If no keyword is found in first 100 lines/sentences, just display the first 3 lines if ($i == 100) return $lines[0]."...".$lines[1]."...".$lines[2]; } </code></pre> <p>I use this code to make the keywords bold</p> <pre><code>function findAndReplace($keywords, $sentence) { for ($i=0; $i&lt;sizeof($keywords); $i++) $words[] = "&lt;b&gt;".ucfirst($keywords[$i])."&lt;/b&gt;"; return str_ireplace($keywords, $words, $sentence); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T08:25:10.893", "Id": "7061", "Score": "0", "body": "Please pardon how bad the code looks. I'm using a mobile device for this" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T08:25:51.490", "Id": "7062", "Score": "0", "body": "Next time format your code, keep the indentation consistent if you want others to help. Now, where exactly do you feel it can be greatly improved on? What is not working the way you expect it to?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T08:55:21.593", "Id": "7063", "Score": "0", "body": "The script is kind of inconsistent - it searches articles using the entered keywords, if it retrieves results, it may display topic, part of the body (of which I included the code for) and the article url, for some articles and only display the topic and url alone for the unlucky articles." } ]
[ { "body": "<p>A couple of small things...</p>\n\n<p>I would replace this:</p>\n\n<pre><code>if (strstr($lines[$i], $keywords[0]) || strstr($lines[$i], $keywords[1]) || \n strstr($lines[$i], $keywords[2]) || strstr($lines[$i], $keywords[3])\n</code></pre>\n\n<p>with something like:</p>\n\n<pre><code>foreach($keyword in $keywords) {\n if (strstr($lines[$i]) {\n $j++;\n $line .= trim($lines[$i]).\"...\";\n break;\n }\n }\n</code></pre>\n\n<p>Also, this line:</p>\n\n<pre><code> $line .= trim($lines[$i]).\"...\";\n</code></pre>\n\n<p>will result in an extra trailing \"...\" when $j gets to 2. I'm presuming you want something like \"line1...lineN\", but instead you'll get \"line1...lineN...\". You probably want to chop off those extra dots, or only add them when needed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-17T06:18:18.620", "Id": "6112", "ParentId": "4725", "Score": "2" } }, { "body": "<p>Just one note:</p>\n\n<pre><code>for($i = 0; $i &lt; sizeof($lines); $i++) { ... }\n</code></pre>\n\n<p>Calling <code>sizeof()</code> in every iteration could be slow. I'd write the following:</p>\n\n<pre><code>$size = count($lines);\nfor($i = 0; $i &lt; $size; $i++) { ... }\n</code></pre>\n\n<p>Note that <code>sizeof</code> was changed to <code>count</code> as <em>@Yannis Rizos</em> suggested in the comments.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-17T13:07:49.100", "Id": "6116", "ParentId": "4725", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T08:20:58.180", "Id": "4725", "Score": "3", "Tags": [ "php" ], "Title": "Please help and improve this script for displaying search results" }
4725
<p>I have classes representing gates (OR, XOR, AND etc) with the following method that is called whenever a property changes.</p> <p>Here is the XORGate code:</p> <pre><code>public void computeOutput() { if (this.input1 != null &amp;&amp; this.input0 != null) { if (this.input0.getValue() || this.input1.getValue()) { if (this.input0.getValue() &amp;&amp; this.input1.getValue()) { this.output.setValue(false); } else { this.output.setValue(true); } } else { this.output.setValue(false); } } else { this.output.Value = false; } } </code></pre> <p>It's horrible, but I can't think of a nicer way. It works as follows:</p> <p>If any of the inputs are null, treat the output as false. If any of the inputs are true BUT not all of the outputs are true (i.e just one is true), set the output to true. If BOTH input terminals are true, output is false. And finally, if none of the input is true, output is false.</p> <p>Very basic stuff.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T23:13:19.077", "Id": "108887", "Score": "0", "body": "Java has bitwise operators for this. Have a look at this link: [Java bitwise operators](http://download.oracle.com/javase/tutorial/java/nutsandbolts/op3.html) Hope this helps." } ]
[ { "body": "<pre><code>public void computeOutput() {\n output.setValue(\n (input1 == null || input0 == null)\n ? false\n : (input0.getValue() ^ input1.getValue()));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T09:06:12.633", "Id": "4739", "ParentId": "4729", "Score": "4" } } ]
{ "AcceptedAnswerId": "4739", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-10T23:01:03.890", "Id": "4729", "Score": "5", "Tags": [ "java" ], "Title": "Ternary gate handling - more succinct way then a bunch of if statements" }
4729
<p>I have a small class of 2D drawing utilities, <code>Draw2D</code> which is the global entry point for anything related to drawing. Currently, the class looks like this:</p> <pre><code>struct Draw2D { std::shared_ptr&lt;D2Label&gt; CreateLabel (...); std::shared_ptr&lt;D2Plot&gt; CreatePlot (...); void Draw (D2Element&amp; e); std::vector&lt;std::weak_ptr&lt;D2Element&gt;&gt; elements_; }; struct D2Element { ... }; struct D2Label : D2Element { ... }; </code></pre> <p>So far so good. The key point here is that Draw2D needs to know all it's elements so it can update them and for drawing, each element has to call back to its parent Draw2D instance. I.e. you cannot move elements between instances as all elements share resources provided by the parent. The solution I have right now is <code>weak_ptr</code> which get checked on each update of the <code>Draw2D</code> instance and if stale, the object is removed (meaning the user has deleted it in the meantime.)</p> <p>The problem is that after the Draw2D instance died, of course all still existing instances are dead, too. Even though they are technically valid objects, you cannot use them safely any more. Even queries could fail if they touch the shared resources, and keeping the shared resource alive via <code>shared_ptr</code> does not help either because that just postpones the problems until the drawing backend dies (in which case all resources are invalidated.)</p> <p>Is there some way to rewrite this code to make it clearer to the clients? I tried something like this, as I definitely want clients to be able to release resources early (i.e. before <code>Draw2D</code> dies.)</p> <pre><code>struct D2Element { ~D2Element () { deleter_ (this); } std::function&lt;void OnDelete (D2Element*)&gt; deleter_; } struct Draw2D { void Release (D2Element* element) { // Remove from list of registered elements } ~Draw2D () { // delete all remaining children } D2Label* CreateLabel (...) { auto label = ...; label-&gt;deleter_ = std::bind (&amp;Draw2D::Release, this, _1); return label; } } </code></pre> <p>This is ok but now the clients have to wrap it into smart pointers on their own by default.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T06:09:57.133", "Id": "7105", "Score": "0", "body": "I'm not sure if I understand the problem, but can't you overload `Draw2D::Release(std::shared_ptr<D2Element> element) { Release(element.get();) }` (with a cast if necessary) and then create `auto label` as a `shared_ptr`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T12:19:19.943", "Id": "7171", "Score": "0", "body": "Ok I have worked through your code several times now and it is becoming clear that you have not disclosed a key piece of information.\nWhat is this shared resource, the drawing back end as you call it?\nWhy is there a binding needed at all between the D2Element derived object types and the engine (Draw2D) that draws them?" } ]
[ { "body": "<p>Why not separate the 2D element into two parts.</p>\n\n<ul>\n<li>The interface that can be used</li>\n<li>The shared resource\n<ul>\n<li>Used by the Draw2D interface</li>\n<li>Used by the D2Elements.</li>\n</ul></li>\n</ul>\n\n<p>Then D2Elements does not need to depend on an object that can go out of scope, they have partial ownership of the shared resource (with any common data that they and the Draw2D needs.</p>\n\n<pre><code>class Draw2D\n{\n // interface as before\n // Weak pointers as before.\n\n std::shared_ptr&lt;SharedResource&gt; data;\n};\n\nclass D2Element\n{\n //... As before.\n\n std::shared_ptr&lt;SharedResource&gt; sharedData;\n};\n</code></pre>\n\n<p>Even of the Draw2D's lifetime ends, then the shared resource (because it is shared with any created children) will not die and thus not be destroyed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T07:58:43.313", "Id": "4738", "ParentId": "4737", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T06:37:06.427", "Id": "4737", "Score": "3", "Tags": [ "c++" ], "Title": "Ownership/Lifetime management issue" }
4737
<p>I recently wrote my first webapp and here is the code. I want to make it better, but I'm not exactly sure how. I believe the first place I should start is with the structure of it. Is this spaghetti code? If yes, how do I change that? You can view it at <a href="http://shiftfrog.com" rel="nofollow">http://shiftfrog.com</a></p> <p>I created a class called 'doer' that basically drives the program. Is that wrong? Should my class be called calendar and then manipulate in my post call to /calendar?</p> <pre><code>class Doer def makeDate(date) return Date.strptime(date, "%m/%d/%Y") end def buildArray(dateObj, on, off) array = frontpadding(dateObj, on, off) month = dateObj.month newMonth = month day = dateObj.mday date = dateObj while month == newMonth temp_array = [day,'day'] array.push(temp_array) day = day + 1 date = date + 1 newMonth = date.month end endpadding(date, array) array end def endpadding(dateObj, array) dofw = dateObj.wday filler = (dofw - 6).abs + 1 if filler == 7 #do nothing else until filler == 0 temp_array = ['','day'] array.push(temp_array) filler = filler - 1 end end end def frontpadding(dateObj, on, off) array = Array.new day = dateObj.mday firstOfMonth = Date.new(dateObj.year, dateObj.month) filler = firstOfMonth.wday on = on.to_i off = off.to_i mod = on + off if day != 1 @days = day @location = @days + filler until day &lt;= 1 off.times do if day &gt; 1 temp_array = ['','day'] array.unshift(temp_array) day = day - 1 end end on.times do if day &gt; 1 temp_array = ['','dayOn'] array.unshift(temp_array) day = day - 1 end end end end until filler == 0 temp_array = ['','day'] array.unshift(temp_array) filler = filler - 1 end array end def backFill(cal, on, off) @location = @location.to_i if @location &gt; 0 @location = @location - 1 until @days == 0 cal[0][1][@location][0] = @days @days = @days - 1 @location = @location - 1 end end cal end def makeCal(date, on, off) dateObj = makeDate(date) @cal = Array.new months = 0 while months &lt; 13 # #pass dateobj to build array array = buildArray(dateObj, on, off) # #save array to hash with month key monthName = Date::MONTHNAMES[dateObj.mon] monthYear = "#{monthName} " + dateObj.year.to_s holder = Array.new holder.push monthYear holder.push array @cal.push holder # #create new date object using month and set it to the first dateObj = Date.new(dateObj.year, dateObj.month) dateObj &gt;&gt;= 1 months = months + 1 end @cal = createCal(@cal, on, off) @cal = backFill(@cal, on, off) end def createCal(cal, on, off) on = on.to_i off = off.to_i @mod = on + off daycount = 0 cal.each do |month| month[1].each do |day| if day[0] == '' #do nothing else if daycount % @mod &lt; on day[1] = 'dayOn' end daycount = daycount + 1 end end end cal end end get '/' do haml :ask end post '/calendar' do @on = params["on"] @off = params["off"] @date = params["date"] a = Doer.new @cal = a.makeCal(@date, @on, @off) haml :feeling end </code></pre>
[]
[ { "body": "<p><code>Doer</code> is not a particularly <a href=\"http://en.wikipedia.org/wiki/Naming_convention_%28programming%29#Potential_benefits\">expressive</a> name. Sure, the class <em>does</em> something -- but what class doesn't? Your impulse to name the class <code>Calendar</code> is definitely on target. There are a few other naming things that are not according to Ruby style guidelines; you should avoid CamelCasing your method names -- for instance, <code>makeCal</code> should be <code>make_cal</code> and even better something like <code>make!</code> or <code>create!</code> (assuming the class itself is <em>named</em> calendar, saying <code>@calendar.make_calendar</code> is repeating yourself.)</p>\n\n<p>In general, with respect to 'spaghetti' code, the issue is usually that you are not really <em>separating</em> concerns. The problem that Objects are trying to solve is encapsulating responsibility. It destroys any advantage you stand to gain to put all your functionality into one place. Object-oriented programming involves modularity and encapsulation -- naming a class <code>Doer</code> might indicate some weaknesses in terms of really grokking the paradigm. Consider studying some actual web application source code and see how concerns are separated and handled at an appropriate level of abstraction.</p>\n\n<p>On that last point, one good rule of thumb is that code which is 'nearby' should be operating at roughly the same level of abstraction. Try to identify different concerns and modularize them -- make them 'loosely coupled' to one another. You might make a class which handles the business logic of padding and packing the string stuff, and separate the 'pure' calendar logic into a different class altogether; your application would then just have to 'glue' the two capabilities together.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-24T01:56:04.163", "Id": "4992", "ParentId": "4740", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T14:59:27.100", "Id": "4740", "Score": "4", "Tags": [ "ruby" ], "Title": "Is this Spaghetti code?" }
4740
<p>I need to draw a lot of multi-line text to the screen so I first used <code>DrawText</code> but it was getting a bit slow... So I've been looking at a few alternatives: save the drawn text in memory DC's, use Direct3D/Direct2D, write my own function. I don't want my program to be a memory hog so using memory DC's wasn't too great. I don't want to be dependent on D3D either so I was left with one option.</p> <p>Here is my routine to draw multi-line text using the standard Windows GDI. It splits up the text in lines (split by <code>\r\n</code>'s) and then calculates the length of the full line and estimates where it should break.</p> <p>Since speed is crucial, does anyone sees optimization I could perform to increase speed?</p> <pre><code>bool MLTextOut(HDC hDC, int x, int y, int cx, int cy, CString str, int nLineHeight = 0) { if (!hDC || cx &lt;= 0 || cy &lt;= 0) return false; if (str.IsEmpty() || x + cx &lt;= 0 || y + cy &lt;= 0) return true; const TCHAR *lpszEnd = (const TCHAR *)str + str.GetLength(); const TCHAR *p1 = str, *p2, *p3, *p4; SIZE sz; int yInc = 0, n; RECT rc = {x, y, x + cx, y + cy}; bool bContinue; while (true) { p2 = _tcsstr(p1, _T("\r\n")); if (!p2) p2 = lpszEnd; // check if we're already out of the rect if (y + yInc &gt;= rc.bottom) break; // calculate line length GetTextExtentPoint32(hDC, p1, p2 - p1, &amp;sz); // if line fits if (sz.cx &lt;= cx) { //TextOut(hDC, x, y + yInc, p1, p2 - p1); ExtTextOut(hDC, x, y + yInc, ETO_CLIPPED, &amp;rc, p1, p2 - p1, NULL); yInc += (nLineHeight ? nLineHeight : sz.cy); } // when line does not fit else { // estimate the line break point in characters n = ((p2 - p1) * cx) / sz.cx; if (n &lt; 0) n = 0; // reverse find nearest space for (p3 = p1 + n; p3 &gt; p1; p3--) if (*p3 == _T(' ')) break; // if it's one word spanning this line, but it doesn't fit... let's clip it if (p3 == p1) { // find first space on line for (p3 = p1; p3 &lt; p2; p3++) if (*p3 == _T(' ')) break; ExtTextOut(hDC, x, y + yInc, ETO_CLIPPED, &amp;rc, p1, p3 - p1, NULL); yInc += (nLineHeight ? nLineHeight : sz.cy); p1 = (p3 == p2 ? p2 + 2 : p3 + 1); continue; } // see if p3 as line end fits GetTextExtentPoint32(hDC, p1, p3 - p1, &amp;sz); if (sz.cx &lt;= cx) { // try to add another word until it doesn't fit anymore p4 = p3; do { p3 = p4; // save last position that was valid for (p4 = p4+1; p4 &lt; p2; p4++) if (*p4 == _T(' ')) break; if (p4 == p2) break; GetTextExtentPoint32(hDC, p1, p4 - p1, &amp;sz); } while (sz.cx &lt;= cx); ExtTextOut(hDC, x, y + yInc, ETO_CLIPPED, &amp;rc, p1, p3 - p1, NULL); yInc += (nLineHeight ? nLineHeight : sz.cy); p1 = p3 + 1; continue; } else { // try to strip another word until it fits bContinue = false; do { for (p4 = p3-1; p4 &gt; p1; p4--) if (*p4 == _T(' ')) break; // if it's one word spanning this line, but it doesn't fit... let's clip it if (p4 == p1) { // find first space on line for (p3 = p1; p3 &lt; p2; p3++) if (*p3 == _T(' ')) break; ExtTextOut(hDC, x, y + yInc, ETO_CLIPPED, &amp;rc, p1, p3 - p1, NULL); yInc += (nLineHeight ? nLineHeight : sz.cy); p1 = (p3 == p2 ? p2 + 2 : p3 + 1); bContinue = true; break; } p3 = p4; GetTextExtentPoint32(hDC, p1, p3 - p1, &amp;sz); } while (sz.cx &gt; cx); if (bContinue) continue; ExtTextOut(hDC, x, y + yInc, ETO_CLIPPED, &amp;rc, p1, p3 - p1, NULL); yInc += (nLineHeight ? nLineHeight : sz.cy); p1 = p3 + 1; continue; } } if (p2 == lpszEnd) break; p1 = p2 + 2; } return true; } </code></pre>
[]
[ { "body": "<p>I didn't take any time to try to figure out what you method is or does, but I would suggest, when drawing text it almost always (I say amost, because you could run into edge cases where resource limitations make the following untrue) faster to save your text up, and draw in big chunks, depending on your need, can be done synced to a framerate or based on a callback to your ui thread.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T15:36:03.660", "Id": "7081", "Score": "0", "body": "Thanks, you are right, it's definitely a good idea to do this in a separate thread that keeps the FPS in check. It'll require some effort but this suggestion is definitely going on my ToDo-list ;)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T15:27:26.220", "Id": "4742", "ParentId": "4741", "Score": "0" } }, { "body": "<p>I would split this function into two parts:</p>\n\n<ol>\n<li>Text layout part - find positions of text runs / lines of text. You\ncan use <code>GetTextExtentPoint32</code> as you did.</li>\n<li>And drawing using single call of <code>PolyTextOut</code></li>\n</ol>\n\n<p>That will allow to skip #1 if text position is not changing between WM_PAINTs - in this case you will get just single PolyTextOut call.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T15:58:48.960", "Id": "7083", "Score": "0", "body": "Hmm good call, maybe I can even split it up in two functions one that calculates the line breaks and simply fills an array with the positions. The other one just drawing the text using `PolyTextOut`. That way the caller can even cache the array when the rectangle does not change in size. Although it may require some allocation/de-allocation..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T15:42:28.030", "Id": "4743", "ParentId": "4741", "Score": "3" } }, { "body": "<ol>\n<li><p>Time your solution to see if it really is significantly faster than DrawText. I'd expect DrawText to be optimized pretty well.</p></li>\n<li><p>I've written code like this using a binary search on the length rather than estimating the length. It may not be as fast as estimating the number of characters, but it's hard to know without profiling.</p></li>\n<li><p>Since it looks like you don't care about complex scripts (you're doing simple breaks on spaces), check out GetCharacterPlacement. Although it does a lot of stuff you don't need, it may be faster since you can set a pixel width limit and it will stop as soon as that is exceeded. This can find a line's worth of text in one call (just back up to the last space). Also, if you do keep the extra info from this call, you can use a faster version of ExtTextOut which otherwise would have to recompute a bunch of the metrics.</p></li>\n<li><p>The PolyTextOut call is probably a good idea. Computing the breaks once and drawing in one go is likely to be a big win.</p></li>\n<li><p>When adding words until you overflow, consider measuring just the new word and add that on to a running total. Otherwise, you're measuring most of the line multiple times. (Again, this applies because you're not dealing with complex scripts.)</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-17T00:54:33.683", "Id": "6108", "ParentId": "4741", "Score": "0" } } ]
{ "AcceptedAnswerId": "4743", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T15:20:23.800", "Id": "4741", "Score": "9", "Tags": [ "c++" ], "Title": "Drawing multi-line text fast in C++, MLTextOut" }
4741
<p>I'm developing a publishing engine and trying to find better ways to optimize the code. The end result is to have an open-source alternative to publish content on mobile devices.</p> <p>For now, though, I have a touch-scroll-slide system I have created from a modified scroll system found elsewhere. There is a peculiar hesitation while doing slides (horizontally) on a mobile device (mostly iPad 1) while in portrait, yet the landscape version works very well. It is jQuery-based.</p> <p>I realize there are other portions of the larger project which may be dragging the behaviour down, but don't want to overwhelm people with code at this time. The end result (so far) is viewable <a href="http://stacks.acadnet.ca/reblend1/">here</a>.</p> <p>The code function for scroll-slide is here:</p> <pre><code> (function($){ $.fn.jScrollTouch = function () { return this.each(function() { // The two concepts for each page // scroller = text scrolling area // slider = full-screen page //previous = the page before the current // next = the page after the current var scroller = $(this).find('.article-scroller'); var slider = $(this); var previous = slider.prev(); var next = slider.next(); var slideOn = true; if (slider.attr('id')=='overlayed'){ slideOn = false; //console.log(slider.attr('id')) }; scroller.css({'overflow': 'auto','position':'relative'}); /* if (mobile) { //console.log('touch only'); scroller.css({'overflow': 'hidden','position':'relative'}); } else { //console.log('desk only'); scroller.css({'overflow': 'auto','position':'relative'}); }*/ var height = 0; var cpos = scroller.scrollTop() scroller.scrollTop(100000); height = scroller.scrollTop(); scroller.scrollTop(cpos); var fullheight = height + scroller.outerHeight(); var scrollbarV_length = scroller.innerHeight()*(scroller.innerHeight()/fullheight)+2; var width = 0; minWidth=($("body").width())*0.15; var lpos = scroller.scrollLeft(); scroller.scrollLeft(100000); width = scroller.scrollLeft(); scroller.scrollLeft(lpos); var fullwidth = width + scroller.outerWidth(); var scrollbarH_length = scroller.innerWidth()*(scroller.innerWidth()/fullwidth)+2; if(mobile){ var scrollbarV = $('&lt;div&gt;&lt;/div&gt;'); scrollbarV.css({ 'display':'none', 'position':'absolute', 'width':'5px', 'height':scrollbarV_length+'px', 'left':width-10+'px', 'top':0,'background':'black', 'border':'1px white solid', '-webkit-border-radius':'5px', 'opacity':'0.9' }); var scrollbarH = $('&lt;div&gt;&lt;/div&gt;'); //not used scrollbarH.css({ 'display':'none', 'position':'absolute', 'height':'5px', 'width':scrollbarH_length+'px', 'top':scroller.innerHeight()-7+'px', 'left':0,'background':'black', 'border':'1px white solid', '-webkit-border-radius':'5px', 'opacity':'0.9'}); if(height) scroller.append(scrollbarV); if(width) scroller.append(scrollbarH); } // these two chceks are to prevent sliding if // slider is animated or it is overlayed image currentPage = JSON.parse(localStorage.getItem('currentPage')); $remover = $('.article-wrapper:eq(' + currentPage + ')'); $remover.stop(); if (!$remover.is(':animated')) { slider.bind('mousedown touchstart',function(e){ width=$("body").width(); height=$("body").height(); if(mobile){ e = e.originalEvent.touches[0]; scrollbarV.show(); scrollbarH.show(); } if (slideOn==true){ $('.active').toggleClass('active'); slider.stop(false, true).addClass('active').removeClass('hidder'); } $('.article-wrapper').not('.active').addClass('hidder'); if(previous.is(':animated')){ previous.stop(true, true).removeClass('hidder'); } if (next.is(':animated')){ next.stop(true, true).removeClass('hidder'); } // previous.css('style',''); // next.css('style',''); var initX = e.pageX; var sX = e.pageX; var sWX = 0; var initY = e.pageY; var sY = e.pageY; var sWY = 0; var prevsWX = 0; //stores the previous sWX var scrollDirection = 0; var nextpage = 0; var display = false; var displayed = false; cpos = scroller.scrollTop(); slider.bind('mousemove touchmove ',function(ev){ if(mobile){ ev.preventDefault(); ev = ev.originalEvent.touches[0]; } // console.log('started'); // currentPage=parseInt(slider.attr("id")); var top = cpos-(ev.pageY-sY); var left = lpos-(ev.pageX-sX); sWX = sWX-(sX-ev.pageX); sX = ev.pageX; sWY = sWY-(sY-ev.pageY); sY = ev.pageY; var horDistance = Math.abs(sWX); var verDistance = Math.abs(sWY); if (scrollDirection ==0){ // haven't checked direction yet if ( verDistance &lt; horDistance) { scrollDirection = 1; // moving horizontally } else if ( verDistance &gt; horDistance) { scrollDirection = 2; // moving vertically } } if (scrollDirection == 2 ){ //set up the scrolling movement //set up the scroll bars scroller.scrollTop(top); cpos = scroller.scrollTop(); sY = ev.pageY; if(mobile){ scrollbarV.css({ 'left':Math.min(scroller.innerWidth()-7+lpos,fullwidth)+'px', 'top':Math.min(cpos+cpos*scroller.innerHeight()/fullheight,fullheight-scrollbarV_length)+'px'}); scrollbarH.css({ 'top':Math.min(scroller.innerHeight()-7+cpos,fullheight)+'px', 'left':Math.min(lpos+lpos*scroller.innerWidth()/fullwidth,fullwidth-scrollbarH_length)+'px'}); } } if (scrollDirection == 1 &amp;&amp; slideOn==true){ //set up the sideways movement // console.log('continuing'); slider.css('left',sWX+'px'); //page follows finger // unused for now // previous.css('left',(sWX-width)+'px'); //moves prev with the top // next.css('left',(sWX+width)+'px'); //moves next with the top if (!((Math.abs(prevsWX)/prevsWX) == (Math.abs(sWX)/sWX))) { // checking to see if we are going in the same direction still if (sWX&lt;0) { //moving right display = true; nextPage = currentPage + 1; if (nextPage &gt; maxPage+1){ //don't display any new pages nextPage = maxPage+1; display = false; } else { // display right page under the current page // hide the previous page, show the next page previous.addClass('hidder'); next.css('style','').removeClass('hidder'); display = true; } } if (sWX&gt;0) { //moving Left display = true; nextPage = currentPage - 1; if (nextPage&lt; 0 ){ nextPage = 0; display = false; } else{ // display left page under the current page // hide the next page, show the previous page next.addClass('hidder'); previous.css('style','').removeClass('hidder'); display = true; } } } prevsWX = sWX; } // end of same direction check }); //end of sideways scroll check slider.bind('mouseup touchend',function(ev){ slider.unbind('mousemove touchmove mouseup touchend'); display = false; // console.log('finished'); if(mobile){ ev = ev.originalEvent.touches[0]; scrollbarV.fadeOut(); scrollbarH.fadeOut(); } if (scrollDirection ==1 &amp;&amp; slideOn==true){ // only perform horizontal changes // sX = ev.pageX; // var ultimate = initX-sX; var distance = Math.abs(initX-sX); if (nextPage &lt; 1){ // can't go past beginning distance = 0; } if (nextPage &gt; maxPage){ // can't go past end distance = 0; } if (sWX == 0){ // do nothing } else if ( sWX&gt;0 ) { //are we moving the page to the left? if(distance&gt;minWidth){ // move to new page if we moved 25% of the width slider.stop(true,true).animate({'left':width+'px'},animTime/2,'easeOutBounce',function(){ previous.css('left','0').addClass('active'); next.addClass('hidder'); slider.removeClass('active').addClass('hidder').attr('style',''); currentPage = nextPage; localStorage.setItem('currentPage',JSON.stringify(currentPage)); }); }else{ //move back into place. Rehide the next/prev page afterwards slider.stop(true,true).animate({'left':0+'px'},100,'easeOutBounce',function(){ }); } // end of left check } else if ( sWX&lt;0 ){ //are we moving the page to the right? if(distance&gt;minWidth){ // move to new page if we moved more than 25% slider.stop(true,true).animate({'left':-width+'px'},animTime/2,'easeOutBounce',function(){ next.css('left','0').addClass('active'); slider.removeClass('active').addClass('hidder').attr('style',''); previous.addClass('hidder'); currentPage = nextPage; localStorage.setItem('currentPage',JSON.stringify(currentPage)); }); }else{ //move back into place. Rehide the next/prev page afterwards slider.stop(true,true).animate({'left':0+'px'},100,'easeOutBounce',function(){ }); } //end of right check }// finished horizontal checks } }); //end mouse/touch end }); //end mouse/touch start } // end of two checks (remover:animated &amp; slideOn) }); //end return each(?) function? } //end 'inner' function })(jQuery); // end it all… </code></pre> <p>Some simple caveats: </p> <p><code>currentPage</code> is a variable used to hold where a person was when they last opened the publication (the publication can be stored for offline reading).</p> <p>A typical page consists of a background graphic and scrollable region which contains content. The function is called in this manner, where article-wrapper is a class applied to a page. Each page is required to have a unique ID, article1-article'n':</p> <pre><code>$('.article-wrapper').jScrollTouch(); </code></pre> <p>There is also an overlay which behaves differently. It contains scrollable content but it shouldn't move horizontally.</p> <p>The end result for the project is an online publishing system that is free, similar to WordPress but dedicated to creating a more formal publication rather than a blog. The immediate next step is better layout options through CSS and inclusion of HTML5's canvas animations.</p>
[]
[ { "body": "<p>First off, if you have lines of code that are commented out, you should probably either uncomment them, or remove them. Commented out code is an eyesore.</p>\n\n<p>Secondly, some of your variable names are, not good. For example, I have no idea what the variable <code>sX</code>, <code>sWX</code>, or <code>lpos</code> do. Variable names should be not too long, but not too short, and be as descriptive as possible about the purpose of the variable.</p>\n\n<p>A lot of your spacing is odd as well. For example, the block of code from your code below:</p>\n\n<blockquote>\n<pre><code>scrollbarH.css({ 'display':'none',\n 'position':'absolute',\n 'height':'5px',\n 'width':scrollbarH_length+'px',\n 'top':scroller.innerHeight()-7+'px',\n 'left':0,'background':'black',\n 'border':'1px white solid',\n '-webkit-border-radius':'5px',\n 'opacity':'0.9'});\n</code></pre>\n</blockquote>\n\n<p>Would become the below block of code:</p>\n\n<pre><code>scrollbarH.css({ \n 'display': 'none',\n 'position': 'absolute',\n 'height': '5px',\n 'width': scrollbarH_length + 'px',\n 'top': scroller.innerHeight() - 7 + 'px',\n 'left': 0,\n 'background': 'black',\n 'border': '1px white solid',\n '-webkit-border-radius': '5px',\n 'opacity': '0.9'\n});\n</code></pre>\n\n<p>Generally, you should also have space between your operators. It usually makes expressions <em>much</em> easier to read as well. </p>\n\n<p>Finally, I'd recommend finding a code style, and then writing in that style. I usually follow <a href=\"http://google.github.io/styleguide/javascriptguide.xml\" rel=\"nofollow\">this style guide</a> for how I write my Javascript code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-05T02:21:33.323", "Id": "95827", "ParentId": "4745", "Score": "3" } }, { "body": "<h3>Style belongs to CSS</h3>\n\n<p>Avoid styling code in JavaScript, especially large blocks like this one:</p>\n\n<blockquote>\n<pre><code> scrollbarV.css({ 'display':'none',\n 'position':'absolute',\n 'width':'5px',\n 'height':scrollbarV_length+'px',\n 'left':width-10+'px',\n 'top':0,'background':'black',\n 'border':'1px white solid',\n '-webkit-border-radius':'5px',\n 'opacity':'0.9' });\n</code></pre>\n</blockquote>\n\n<p>Such styling details belong to a CSS file.\nIn JavaScript (and HTML) you should use appropriate <code>class</code> attributes instead.</p>\n\n<h3>Use consistent indentation</h3>\n\n<p>The indentation here is pretty nutty:</p>\n\n<blockquote>\n<pre><code> $('.article-wrapper').not('.active').addClass('hidder');\n if(previous.is(':animated')){\n previous.stop(true, true).removeClass('hidder');\n }\n if (next.is(':animated')){\n next.stop(true, true).removeClass('hidder');\n }\n</code></pre>\n</blockquote>\n\n<p>Should have been:</p>\n\n<pre><code> $('.article-wrapper').not('.active').addClass('hidder');\n if (previous.is(':animated')) {\n previous.stop(true, true).removeClass('hidder');\n }\n if (next.is(':animated')) {\n next.stop(true, true).removeClass('hidder');\n }\n</code></pre>\n\n<p>Btw the CSS class \"hidder\" looks odd too. Did you mean \"hidden\" instead?</p>\n\n<p>The messy indentation style is rampant in the posted code,\nmaking it extremely difficult to read.\nPlease review and correct everywhere.</p>\n\n<h3>Chaining with else-if</h3>\n\n<p>It seems these two condition cannot be true at the same time:</p>\n\n<blockquote>\n<pre><code> if (nextPage &lt; 1){ \n // can't go past beginning\n distance = 0; \n }\n if (nextPage &gt; maxPage){ \n // can't go past end\n distance = 0; \n }\n</code></pre>\n</blockquote>\n\n<p>... in which case it would be better to use <code>else if</code> for the second.</p>\n\n<h3>Open-sourcing</h3>\n\n<p>An open-source project should be impeccable, to attract users and contributors. This code looks really messy,\nwhich gives the impression as if you don't care,\nand if you don't care, why should contributors care?\nMessy code is unlikely to attract supporters,\nbut very easy to fix, so I urge you to do that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-05T01:03:41.503", "Id": "103836", "ParentId": "4745", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T16:32:02.347", "Id": "4745", "Score": "6", "Tags": [ "javascript", "jquery", "touch" ], "Title": "Simple touch-scroll-slide system for a magazine" }
4745
<p>As a personal habit I generally prefer to use string <code>replace</code> and <code>format</code> methods, along with string "patterns", in lieu of string concatenation and other methods in most languages I use (typically C# and Javascript).</p> <p>For example, if I want to generate a URL with parameters (C#), I use:</p> <pre><code>string url = "page.aspx?id={id}&amp;ref={ref}"; return url.Replace("{id}", id) .Replace("{referrer}", referrer); // could also be expressed as return "page.aspx?id={id}&amp;ref={ref}".Replace("{id}", id) .Replace("{referrer}", referrer); </code></pre> <p>Instead of:</p> <pre><code>return "page.aspx?id=" + id + "&amp;ref=" &amp; referrer; </code></pre> <p>Or:</p> <pre><code>// StringBuilder is typically more efficient than string concatenation StringBuiler sbUrl = new StringBuilder(); sbUrl.Append("page.aspx?"); sbUrl.AppendFormat("id={0}", id); sbUrl.AppendFormat("ref={0}", referrer); return sbUrl.ToString(); </code></pre> <hr> <p>I do the same in Javascript:</p> <pre><code>function generateUrl(p1, p2) { return "page.aspx?1={0}&amp;2={1}".replace("{0}", p1) .replace("{1}", p2); } </code></pre> <hr> <p>The reason is I prefer the readability of the code, especially when large amounts of textual data must be processed, such as in the case of a form letter or e-mail:</p> <pre><code>// this would typically be stored in an XML or other configuration file as a "pattern" string body = @"Dear {name}:&lt;br /&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec aliquam blandit risus, quis imperdiet nibh congue quis.&lt;/p&gt; &lt;p&gt;Pellentesque ullamcorper malesuada ante, ac auctor felis feugiat id. Etiam id eros convallis nisi feugiat tincidunt. Phasellus fringilla erat eu tortor egestas volutpat. Vestibulum in odio lorem, quis fringilla sapien.&lt;/p&gt; &lt;p&gt;Sincerely,&lt;/p&gt; &lt;p class='sig'&gt;{from-name}&lt;/p&gt;"; return body.Replace("{name}", name).Replace("{from-name}", fName); </code></pre> <hr> <p>My concern is, however, that my methods are <strong>generally inefficient</strong> and that there may be <strong>better, more standardized</strong> ways of doing this.</p> <p>Thoughts?</p>
[]
[ { "body": "<p>In C#, you could use the built-in <a href=\"http://msdn.microsoft.com/en-us/library/b1csw23d.aspx\" rel=\"noreferrer\"><code>string.Format</code></a> instead:</p>\n\n<pre><code>string parameterizedUrl = \"page.aspx?id={0}&amp;ref={1}\";\nreturn string.Format(parameterizedUrl, id, referrer);\n</code></pre>\n\n<p>I haven't profiled it, but I think it would at worst be not any less efficient than your double <code>Replace()</code> call.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T21:46:53.980", "Id": "7095", "Score": "0", "body": "This is true, however `String.Format` does not support named parameters, only index-based ones. Named parameters typically help prevent off-by-one errors in my experience." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T21:51:58.237", "Id": "7096", "Score": "1", "body": "@Paperjam That's a fair point, but I can honestly say I've never run into an off-by-one issue with string.Format that didn't quickly become apparent. I don't think it's any worse than having bugs due to typos in the named parameters (you even have to keep them synchronized between two places - the actual string and the arguments for `Replace()`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T06:28:40.843", "Id": "7106", "Score": "0", "body": "@Paperjam: If you asked me, I would much prefer to see the indexed parameters over named parameters in a format string. Since the BCL doesn't support names parameters, it's easier to identify as indexes than it is as names. The words too easily blends in with any surrounding text whereas indices are just numbers and stands out. Also their presence makes it obvious that it is a format string." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-17T23:53:56.510", "Id": "217742", "Score": "0", "body": "I like Paperjam's idea, and I also would love for the compiler to check format statements. Because this simple-to-fix mistake is too common." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T21:45:43.643", "Id": "4748", "ParentId": "4747", "Score": "5" } }, { "body": "<p>I'd tend towards format strings.</p>\n\n<p>You may not of come across having to do localization, but some of the tools understand format strings which makes life easier for translators. It's much more conventional C#.</p>\n\n<p>I do like the readability of named parameters though, and for localization, names would work a LOT better, but its not standard so its not supported.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-11T22:26:08.617", "Id": "4749", "ParentId": "4747", "Score": "3" } }, { "body": "<p>Efficiency-wise, you are already as fast as you can get without going to string concatenation or array joining as you are going to get without actually using them. (As you can see here: <a href=\"http://jsperf.com/string-test5\" rel=\"nofollow\">http://jsperf.com/string-test5</a>)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T03:54:45.997", "Id": "4753", "ParentId": "4747", "Score": "2" } }, { "body": "<p>Personally I would go with a String.Format() approach, but I think you should use whichever method is more readable. Trying to shave off a few microseconds here and there isn't worth the reduction in code readability and/or clarity for other people reading your code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T05:00:30.727", "Id": "4754", "ParentId": "4747", "Score": "3" } }, { "body": "<p>I'd use a format string instead. Any seasoned programmer will not find anything hard to read when using format strings. Though if you have multiple arguments for a multiple argument string (e.g., localization strings), it <em>might</em> be confusing with their orders or how much it requires, but they should be sufficiently documented anyway. It's a shame that the formatting features weren't a lot like python's. If you'd prefer not to use this approach for whatever reason, then I'm afraid you're catering to the wrong crowd for the wrong reasons IMHO.</p>\n\n<p>Alternatively, I know you said that you'd prefer not to use this but using <code>String.Concat()</code> would most likely be the fastest and most efficient of these approaches. There isn't anything to parse nor are there any intermediate strings you need to work with. You get your complete string in one shot. Now I've gotta admit, it isn't the prettiest of syntaxes and I too avoid them at times but there are ways to make it a bit more attractive. But at least the arguments should be immediately identifiable as they'd typically not be string constants but variables (which are highlighted differently in any decent IDE).</p>\n\n<p>First and foremost, your variable should <em>always</em> have the appropriate and descriptive names. This should be a given. Nothing kills readability as much as having crappy variable names, especially when you have a lot of them.</p>\n\n<p>And when dealing with large bodies of text, nothing's stopping you from moving that text into a separate method to encapsulate it. That way you can give your parameters better names when needed, you'd find the string all in one place and it isn't mixed in with your code as much. These could easily be tied in with your resource files to make it that much better. This also applies to with using the format strings as well.</p>\n\n<p>e.g.,</p>\n\n<pre><code>static string EmailText(string toName, string fromName)\n{\n return @\"Dear \" + toName + @\":&lt;br /&gt;\n &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec aliquam blandit risus, quis imperdiet nibh congue quis.&lt;/p&gt;\n &lt;p&gt;Pellentesque ullamcorper malesuada ante, ac auctor felis feugiat id. Etiam id eros convallis nisi feugiat tincidunt. Phasellus fringilla erat eu tortor egestas volutpat. Vestibulum in odio lorem, quis fringilla sapien.&lt;/p&gt;\n &lt;p&gt;Sincerely,&lt;/p&gt;\n &lt;p class='sig'&gt;\" + fromName + @\"&lt;/p&gt;\";\n}\n\n// then when you need it:\nreturn EmailText(toName: \"Bob\", fromName: \"Bill\"); // named parameters optional but useful\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T17:30:07.907", "Id": "7134", "Score": "0", "body": "Not in this case. The compiler will transform these \"additions\" to a single call to `String.Concat()` with each \"addend\" passed in as an argument. It will be exactly the same as if I called the method explicitly. It _would_ be like you described if I had multiple uses of the `+=` operator. _That_ would be terrible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T17:42:44.400", "Id": "7136", "Score": "0", "body": "You're absolutely right. I should refrain from reading SE pre-coffee. :) I'll remove my original comment. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T18:00:10.020", "Id": "7139", "Score": "0", "body": "It's an important point though and is worth mentioning as it might be a motivation for people avoiding it for the wrong reasons." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T07:27:53.353", "Id": "4756", "ParentId": "4747", "Score": "3" } }, { "body": "<blockquote>\n<pre><code>return \"page.aspx?id={id}&amp;ref={ref}\".Replace(\"{id}\", id)\n .Replace(\"{referrer}\", referrer);\n</code></pre>\n</blockquote>\n\n<p>The above can be written since C# 6 and ECMAScript 6 as..</p>\n\n<h1>C#</h1>\n\n<pre class=\"lang-cs prettyprint-override\"><code>return $\"page.aspx?id={id}&amp;ref={referrer}\";\n</code></pre>\n\n<h1>Javascript</h1>\n\n<pre class=\"lang-js prettyprint-override\"><code>return `page.aspx?id=${id}&amp;ref=${referrer}`;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T22:13:34.810", "Id": "435479", "Score": "0", "body": "the `$` within the C# string is not necessary. It should be `return $\"page.aspx?id={id}&ref={referrer}\";`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T05:31:57.540", "Id": "435493", "Score": "0", "body": "@ChadLevy You are absolutely right, I've edited the string to be even more compact." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T16:12:56.520", "Id": "435593", "Score": "2", "body": "You got the green tick after almost 8 years! I'll wait another 8 for the next groundbreaking C# improvement and steal it from you :-P" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T16:22:35.933", "Id": "435594", "Score": "0", "body": "I would be honoured if you'd be the one to steal it from me ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-24T21:28:06.483", "Id": "436251", "Score": "1", "body": "I mulled over whether it made sense to mark it as the answer, but it seems that template literals were invented just for this reason. So now an 8 year old question can still be relevant (though it seems this activity made it get caught in the \"on hold as off-topic\" singularity). Maybe I'll fix the question in 8 years to make it on topic ;)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T16:06:16.573", "Id": "224226", "ParentId": "4747", "Score": "3" } } ]
{ "AcceptedAnswerId": "224226", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-09-11T21:20:12.397", "Id": "4747", "Score": "6", "Tags": [ "c#", "javascript", "formatting" ], "Title": "Best practice and alternatives for string manipulation with an emphasis on readability" }
4747
<p>Well I just finished my first go at my own form validation (I always used validate plugin) for simple front end. It's definitely small potatoes as it's only meant for a form with 4 fields; 3 required text and one required e-mail. </p> <p>I'm new to Jquery so I am doing little exercises like these to help me learn and I was hoping someone could take a look and see if what I did was ok. Did I make any newbie mistakes? Can I improve this? Perhaps I should use js objects (new to those too) to organize code? I know there is no one answer, in fact I'm sure there are countless ways to validate a form...But I was just hoping some JS expert could offer a little insight on better coding practices.</p> <p>*<em>EDIT - forgot to mention...I'm aware that I should probably use regex for better email validation, however, just threw the indexOf() method for the time being *</em></p> <pre><code>$(function() { var err = "&lt;span class='error'&gt;Required field.&lt;/span&gt;"; var errEmail = "&lt;span class='error'&gt;Please enter valid email.&lt;/span&gt;"; var errors = false; $('.submit').click(function() { $('.error').remove(); $('.req').each(function() { if($(this).val() == '') { $(this).after(err); errors = true; } }); if ($('.reqe').val().indexOf('@') === -1) { $('.reqe').after(errEmail); errors = true; } if (errors == true) { return false; } else { var errors = false; alert("Submitted"); return true; } }); }); </code></pre> <p>Any feedback would be greatly appreciated. Thanks</p>
[]
[ { "body": "<p>A couple of small changes:</p>\n\n<ol>\n<li><p>near the end:</p>\n\n<pre><code>if (errors == true) {\n return false;\n}\nelse {\n var errors = false;\n alert(\"Submitted\");\n return true;\n}\n</code></pre>\n\n<p>Could be:</p>\n\n<pre><code>if(!errors)\n{\n alert(\"Submitted\");\n}\nreturn !errors; \n</code></pre></li>\n<li><p>the <code>.req</code> </p>\n\n<pre><code>if($(this).val() == ''){\n</code></pre>\n\n<p>could be:</p>\n\n<pre><code>if(!$(this).val()){\n</code></pre>\n\n<p>This would actually be a problem because</p>\n\n<pre><code> \" \" != \"\"\n</code></pre>\n\n<p>so a space would validate <em>(if that's what you intended then ignore this one ;) )</em></p></li>\n<li><p><code>var errors= false;</code> needs to be inside the click event:</p>\n\n<pre><code> $('.submit').click(function() {\n var errors = false;\n</code></pre>\n\n<p>otherwise when you click the submit a second time after an invalid attempt it won't reset the value.</p></li>\n</ol>\n\n<p><strong>Alternatively:-</strong></p>\n\n<p><a href=\"http://jsfiddle.net/ssTPm/\" rel=\"nofollow\">http://jsfiddle.net/ssTPm/</a></p>\n\n<pre><code>var validationConfig = [\n{\n \"selector\": \".req\",\n \"hasErrors\": function() {\n return !$(this).val()\n },\n \"errorMessage\": \"&lt;span class='error'&gt;Required field.&lt;/span&gt;\"},\n{\n \"selector\": '.reqe',\n \"hasErrors\": function() {\n return $('.reqe').val().indexOf('@') === -1\n },\n \"errorMessage\": \"&lt;span class='error'&gt;Please enter valid email.&lt;/span&gt;\"\n}];\n</code></pre>\n\n<p>then a nice loop like:</p>\n\n<pre><code>for (var i = 0, validation = null; validation = validationConfig[i]; i++) {\n $(validation.selector).each(validateEach);\n}\n</code></pre>\n\n<p>and validateEach would look like:</p>\n\n<pre><code> function validateEach () {\n var hasErrors = validation.hasErrors.call(this);\n errors |= hasErrors;\n if (hasErrors) {\n $(this).after(validation.errorMessage);\n }\n};\n</code></pre>\n\n<p>This would mean you could have the validation function in you js files and then when you initialise the page from the server you just output the validationConfig:</p>\n\n<pre><code>validationConfig = validationConfig || [];\nvalidationConfig.concat([\n {\n \"selector\": ... \n }\n];\n</code></pre>\n\n<p>as many times as you like. Although from the looks of things it might be over-engineering things a bit.</p>\n\n<p><strong>Explanations:-</strong></p>\n\n<p>so the <code>||</code> is a coalesce or OR operator. </p>\n\n<pre><code>myVariable = myVariable || [];\n</code></pre>\n\n<p>means if <code>myVariable</code> results in a true value <em>(not <code>false</code>, <code>undefined</code>, <code>null</code> etc etc)</em> then it does nothing otherwise it assigns it a defualt value.</p>\n\n<p>so if I had the following:</p>\n\n<pre><code>myList = myList|| [];\nmyList.push(1);\nmyList = myList|| [];\nmyList.push(2);\nmyList = myList|| [];\nmyList.push(3);\n</code></pre>\n\n<p>it would result in <code>[1,2,3]</code>. The first time it sets the value as <code>[]</code> the next times they just assign itself to itself. This way it doesn't need to know if it has been initialised or not.</p>\n\n<p>the <code>|=</code> is a bitwise <code>|</code> <em>(BITWISE OR)</em> and an <code>=</code> so</p>\n\n<pre><code>value |= otherValue;\n</code></pre>\n\n<p>is the equivalent to </p>\n\n<pre><code>value = value | otherValue;\n</code></pre>\n\n<p>In this example</p>\n\n<pre><code>errors |= hasErrors;\n</code></pre>\n\n<p>is the exact same as </p>\n\n<pre><code>errors = errors || hasErrors;\n</code></pre>\n\n<p>Errors is assigned <code>true</code> as long as either it was already <code>true</code> or <code>hasErrors</code> is <code>true</code>;</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T03:00:41.600", "Id": "4752", "ParentId": "4751", "Score": "1" } } ]
{ "AcceptedAnswerId": "4752", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T02:48:41.900", "Id": "4751", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "First go at my own form validation, and suggestions?" }
4751
<p>The idea is to apply some function on each element in each list, then compare two lists by the value returned by the function.</p> <p>My current solution works but is not fast enough. running "python -m cProfile" gives sth. like:</p> <pre><code> ncalls tottime percall cumtime percall filename:lineno(function) 2412505 13.335 0.000 23.633 0.000 common.py:38(&lt;genexpr&gt;) 285000 5.434 0.000 29.067 0.000 common.py:37(to_dict) 142500 3.392 0.000 35.948 0.000 common.py:3(compare_lists) </code></pre> <p>Here is my code, I would like to know how to optimize it to run faster.</p> <pre><code>import itertools def compare_lists(li1, li2, value_func1=None, value_func2=None): """ Compare *li1* and *li2*, return the results as a list in the following form: [[data seen in both lists], [data only seen in li1], [data only seen in li2]] and [data seen in both lists] contains 2 tuple: [(actual items in li1), (actual items in li2)] * *value_func1* callback function to li1, applied to each item in the list, returning the **logical** value for comparison * *value_func2* callback function to li2, similarly If not supplied, lists will be compared as it is. Usage:: &gt;&gt;&gt; compare_lists([1, 2, 3], [1, 3, 5]) &gt;&gt;&gt; ([(1, 3), (1, 3)], [2], [5]) Or with callback functions specified:: &gt;&gt;&gt; f = lambda x: x['v'] &gt;&gt;&gt; &gt;&gt;&gt; li1 = [{'v': 1}, {'v': 2}, {'v': 3}] &gt;&gt;&gt; li2 = [1, 3, 5] &gt;&gt;&gt; &gt;&gt;&gt; compare_lists(li1, li2, value_func1=f) &gt;&gt;&gt; ([({'v': 1}, {'v': 3}), (1, 3)], [{'v': 2}], [5]) """ if not value_func1: value_func1 = (lambda x:x) if not value_func2: value_func2 = (lambda x:x) def to_dict(li, vfunc): return dict((k, list(g)) for k, g in itertools.groupby(li, vfunc)) def flatten(li): return reduce(list.__add__, li) if li else [] d1 = to_dict(li1, value_func1) d2 = to_dict(li2, value_func2) if d1 == d2: return (li1, li2), [], [] k1 = set(d1.keys()) k2 = set(d2.keys()) elems_left = flatten([d1[k] for k in k1 - k2]) elems_right = flatten([d2[k] for k in k2 - k1]) common_keys = k1 &amp; k2 elems_both = flatten([d1[k] for k in common_keys]), flatten([d2[k] for k in common_keys]) return elems_both, elems_left, elems_right </code></pre> <p>Edit:</p> <p>zeekay suggests using set, which is also what I was doing, except that I make a dict for each list first, then compare the keys using set, finally return the original elements using the dict. I realized that the speed actually depends on which one will take more time -- the callback function, or the groupby. In my case, the possible callback functions are mostly dot access on objects, and the length of lists can be large causing groupby on lists takes more time.</p> <p>In the improved version each callback function is executed more than once on every single element, which I considered is a waste and has been trying to avoid in the first place, but it's still much faster than my original approach, and much simpler.</p> <pre><code>def compare_lists(li1, li2, vf1=None, vf2=None): l1 = map(vf1, li1) if vf1 else li1 l2 = map(vf2, li2) if vf2 else li2 s1, s2 = set(l1), set(l2) both, left, right = s1 &amp; s2, s1 - s2, s2 - s1 orig_both = list((x for x in li1 if vf1(x) in both) if vf1 else both), list((x for x in li2 if vf2(x) in both) if vf2 else both) orig_left = list((x for x in li1 if vf1(x) in left) if vf1 else left) orig_right = list((x for x in li2 if vf2(x) in right) if vf2 else right) return orig_both, orig_left, orig_right </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T08:58:51.990", "Id": "7109", "Score": "0", "body": "there are smarter ways to flatten a list, using `sum`, for other comparison approaches see http://stackoverflow.com/questions/1388818/how-can-i-compare-two-lists-in-python-and-return-matches" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T09:26:54.090", "Id": "7110", "Score": "0", "body": "@Fredrik Thanks. sum does not work for list of lists though... sum([1, 2], [3]) raises TypeError." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T09:39:35.390", "Id": "7111", "Score": "1", "body": "@Shaung it does if you use it like `sum([[],[1],[2,3]], [])`, note the 2nd argument `[]`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T09:39:40.940", "Id": "7112", "Score": "0", "body": "he would be referring to `sum([[1, 2], [3]], [])`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T09:40:08.317", "Id": "7113", "Score": "0", "body": "@Dan D... snap!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T09:45:49.183", "Id": "7114", "Score": "0", "body": "Oh I see now. Cool! Wish I knew that earlier" } ]
[ { "body": "<p>So it seems you primarily want to use your callback functions to pull the value to compare out of an object, if you don't mind simplifying how compared items are returned, a faster and simpler approach would be:</p>\n\n<pre><code>def simple_compare(li1, li2, value_func1=None, value_func2=None):\n s1, s2 = set(map(value_func1, li1)), set(map(value_func2, li2))\n common = s1.intersection(s2)\n s1_diff, s2_diff = s1.difference(s2), s2.difference(s1)\n return common, s1_diff, s2_diff\n\n&gt;&gt;&gt; simple_compare(li1, li2, value_func1=f)\n&lt;&lt;&lt; (set([1, 3]), set([2]), set([5]))\n\n&gt;&gt;&gt; compare_lists(li1, li2, value_func1=f)\n&lt;&lt;&lt; (([{'v': 1}, {'v': 3}], [1, 3]), [{'v': 2}], [5])\n</code></pre>\n\n<p>Which depending on actual use case, might be something you could live with. It's definitely a lot faster:</p>\n\n<pre><code>&gt;&gt;&gt; timeit x = simple_compare(xrange(10000), xrange(10000))\n100 loops, best of 3: 2.3 ms per loop\n\n&gt;&gt;&gt; timeit x = compare_lists(xrange(10000), xrange(10000))\n10 loops, best of 3: 53.1 ms per loop\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T09:28:15.807", "Id": "7115", "Score": "0", "body": "You did not read my question, dude :) What I am trying to do is compare lists by the value after applied to some function, and return the original elements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T09:42:08.650", "Id": "7116", "Score": "1", "body": "You can of course use my answer to modify your original function and support applying functions to values. As is, it merely demonstrates how much faster using the `set` methods would be." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T09:45:02.483", "Id": "7117", "Score": "1", "body": "yes, quite simply by for example using `s1, s2 = set(map(func1, l1)), set(map(func2, l2))`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T10:18:42.907", "Id": "7118", "Score": "0", "body": "Yeah I suppose I'll update with an alternate approach using `map`, actually. Format of return is a bit different, but I think this makes more sense honestly. Might not work for you, but if you can make it work it'd be a lot simpler and faster." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T09:06:59.140", "Id": "4758", "ParentId": "4757", "Score": "3" } }, { "body": "<p>If you are really trying to do sets, rather than using a list as a bag look at this code</p>\n\n<pre><code>a = [1,2,3]\nb = [2,3,4]\n\nprint list (set(a) - set(b))\nprint list (set(b) - set(a))\nprint list (set(a) &amp; set(b))\nprint list (set(a) | set(b))\nprint list (set(a) ^ set(b))\n</code></pre>\n\n<p>=========</p>\n\n<p>Output</p>\n\n<pre><code>[1]\n[4]\n[2, 3]\n[1, 2, 3, 4]\n[1, 4]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T10:23:58.393", "Id": "4759", "ParentId": "4757", "Score": "1" } }, { "body": "<p>If counts matter, then you need to use the Counter class from collections</p>\n\n<pre><code>from collections import Counter\n\na = [1,1,2,3,3]\nb = [1,3,4,4]\n\nprint \"a \",a\nprint \"b \",b \nprint \"union \", list ((Counter(a) | Counter(b)).elements())\nprint \"a not b\", list ((Counter(a) - Counter(b)).elements())\nprint \"b not a\", list ((Counter(b) - Counter(a)).elements())\nprint \"b and a\", list ((Counter(b) &amp; Counter(a)).elements())\n</code></pre>\n\n<p>which gives this answer</p>\n\n<pre><code>a [1, 1, 2, 3, 3]\nb [1, 3, 4, 4]\nunion [1, 1, 2, 3, 3, 4, 4]\na not b [1, 2, 3]\nb not a [4, 4]\nb and a [1, 3]\n</code></pre>\n\n<p>Always better to use the inbuilt, rather than write your own</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T08:02:40.903", "Id": "4809", "ParentId": "4757", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T08:46:15.343", "Id": "4757", "Score": "6", "Tags": [ "python", "performance", "optimization" ], "Title": "Python list comparison: Can this code run faster?" }
4757
<p>I want to fill a <code>DataSet</code> with 20,0000 records using a <code>SqlDataAdapter</code> by using this code:</p> <pre><code>adapter.Fill(dataset); </code></pre> <p>If I fill a <code>DataSet</code> this way it takes a long time. Is there anything wrong with this?</p> <p>This is my code:</p> <pre><code>connection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]); connection.Open(); SqlCommand command = new SqlCommand("sp_DMS_Report_Generate", connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@XML", reportCriteria.XML); command.CommandTimeout = 1000; SqlDataAdapter adapter = new SqlDataAdapter(command); adapter.Fill(resultSet); return resultSet.Tables[0]; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T10:08:06.897", "Id": "7119", "Score": "0", "body": "Please, post the complete code which you have tried. Then only we come to know whats your problem is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T10:08:31.467", "Id": "7120", "Score": "2", "body": "Please, review your question. Don't get it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T10:22:01.780", "Id": "7121", "Score": "1", "body": "Yes it will take some time to load. Please, write what is your point, what problems you have?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T10:32:22.143", "Id": "7122", "Score": "1", "body": "20 thousand or 200 thousand?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T10:32:59.640", "Id": "7123", "Score": "1", "body": "What is *too long* ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T10:40:53.140", "Id": "7124", "Score": "0", "body": "Off-topic: This is a matter of style and won't have any influence the speed of `adapter.Fill`, but do use `ConfigurationManager.ConnectionStrings` instead of `ConfigurationSettings.AppSettings` for accessing connection strings from `App.config`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T10:46:32.620", "Id": "7125", "Score": "1", "body": "First, if the above code is exactly what you're doing, how do you know that it's the call to `adapter.Fill` that's taking a long time? Have you measured the time taken for this one particular call? How long exactly did it take? What factors could influence DB speed (slow network connection to DB server, command timeout not being honored, etc.)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T14:34:50.967", "Id": "7130", "Score": "0", "body": "adapter.Fill opens and closes the DB connection automatically so connection.Open() is redundant. Also if you're returning a datatable vs dataset why not fill a datatable instead" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T17:44:05.007", "Id": "7137", "Score": "2", "body": "Is this 20,000 or 200,000 records?" } ]
[ { "body": "<p>I would say the C# is fine, it's your database that is the issue. Is the Stored procedure optimized? Are the tables in the proper normalization? Are your primary keys &amp; foreign keys set up properly? (you should get the point by now) </p>\n\n<p>Start there first since really everything is there. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T11:44:24.123", "Id": "7126", "Score": "0", "body": "+1: right, there isn't much more you can change with this sort of operation." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T10:59:43.740", "Id": "4761", "ParentId": "4760", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T10:05:40.253", "Id": "4760", "Score": "4", "Tags": [ "c#", "performance" ], "Title": "Fill a DataSet with nearly 20,0000 records using SqlDataAdapter" }
4760
<p>I've got a form, for which the "Send" button should only be available, upon each form field being validated. For most of my check, I call a function <code>checkFormValue()</code> which is a function gathering all the simple checks, give warning where check failed, and if at least one of the check fail, disable the button. The call are made on the <code>blur</code> event for each field of the form.</p> <pre><code>function checkFormValue(){ var form = document.myform; //initializing a few variable with check, amongst them the following //Those are example of check which are pure javascript function var checkIDField = checkField(form.myids) &amp;&amp; checkIDs(); //... //This is an example of AJAX function if(checkIDField){ checkIDValidity(); } //Checks variables are gathered under one variable var validform = checkIDField &amp;&amp; CheckContactField &amp;&amp; CheckPathsField; var warnings = document.getElementsByClassName('warning'); var i; var count = 0; //Loop to check the number of warnings for (i = 0; i &lt; warnings.length; i++){ // Check that current character is number. if(warnings[i].style.display===""){ count++ } } validform = validform &amp;&amp; (count === 0); document.form.send.disabled = !(validform); } </code></pre> <p>A few check needs to be done on the server (SELECT query, check if some file exists,etc.). For those check,, I do AJAX calls, and I added in the <code>checkFormValue()</code> a loop which count the number of warning displayed. If none are displayed, then the button is not disable anymore.</p> <p>One of my field should contain a series of ID, in the form of a space separated list. After checking that the list is correctly formatted (list of integer separated by space, no duplicate), I want to see if those ID exist in the database. The following function set the AJAX call:</p> <pre><code>function checkIDValidity(){ var xmlhttp; if (window.XMLHttpRequest){ //code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); }else{ // code for IE6, IE5 xmlhttp=new ActiveXObject('Microsoft.XMLHTTP'); } xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState===4 &amp;&amp; xmlhttp.status===200){ var existingIDs = xmlhttp.responseText; var idcomponent = document.myform.myids; var idwarningdiv = document.getElementById('nonexistingid'); if(existingIDs==="Existing"){ idcomponent.setAttribute('class', 'valid'); if(idwarningdiv.style.display !== 'none'){ idwarningdiv.style.display='none'; idwarningdiv.innerHTML=''; } }else{ idcomponent.setAttribute('class', 'invalid'); if(idwarningdiv.style.display !== ''){ idwarningdiv.style.display=''; } if(idwarningdiv.innerHTML.substr(51,existingIDs.length)!==existingIDs){ idwarningdiv.innerHTML='&lt;br /&gt;&lt;img src="img/warning2.png" alt="Warning!" /&gt;'+existingIDs+' is not an existing id.'; } } } }; var idnumbers = document.myform.myids.value; var d=new Date(); //d.toUTCString() is used so the result never get cached xmlhttp.open('GET', 'checkidvalidity.php?id='+idnumbers+'&amp;rand='+d.toUTCString(), true); xmlhttp.send(); } </code></pre> <p>When I enter an ID, which doesn't exist in the database, I got a warning, and if the ID is valid, the warning disappear. But the enabled/disabled status of the "Send button" is not immediately updated, on the contrary, I need to click twice on other field in the form before I can see any change on the button.</p> <p>Adding a listener on the warning div for non existent IDs, triggering on <code>propertyChanged</code> event and calling <code>checkFormValue</code> did at first the trick, but the event is only supported on IE, and as such it didn't work on other browser. Using the mutation event <code>"DOMAttrModified"</code> when it was supported, helped for Firefox and Opera.</p> <pre><code>function formLink(objectid){ var xmlhttp; if (window.XMLHttpRequest){ //code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); }else{ // code for IE6, IE5 xmlhttp=new ActiveXObject('Microsoft.XMLHTTP'); } xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState===4 &amp;&amp; xmlhttp.status===200){ document.getElementById('terminal').innerHTML=xmlhttp.responseText; if(isDOMAttrModifiedSupported()){ document.getElementById("nonexistingid").addEventListener("DOMAttrModified", checkFormValue, false); } checkFormValue(); } }; xmlhttp.open('GET', 'myform.php?id='+objectid, true); xmlhttp.send(); } </code></pre> <p>Details on the isDomAttrModifiedSupported function can be found on <a href="https://stackoverflow.com/questions/4562354/javascript-detect-if-event-lister-is-supported/4562426#4562426">this post about detecting if the DomAttrModified event listener is supported</a>.</p> <p>But using that approach leaves my with <a href="https://stackoverflow.com/questions/919428/onpropertychange-for-a-textbox-in-firefox/919470#919470">no solution for the WebKit browsers</a> (Chrome, Safari). Is there a way to refactor my code so I can do my AJAX call, and it would result on an update of the disabled status of the "Send" button, without discounting the result of my other simple checks? In other word, is my validation approach correct?</p> <p>PS: I get some restraints on this project, and I am not allowed to use jQuery.</p>
[]
[ { "body": "<p>I would approach it slightly differntly.</p>\n\n<p>Have functions to change when the field has been validated or not:</p>\n\n<pre><code>function checkFormValues(){\n\n var invalidFields = 0;\n\n function updateValidFields(isValidField)\n {\n\n invalidFields += isValidField ? -1 : 1;\n if(!invalidFields)\n {\n // Enable Submit Button\n // ???\n // Profit\n }\n else\n {\n // Disable submit Button\n // Fail!\n }\n }\n\n // etc\n}\n</code></pre>\n\n<p>then your validation functions look something like:</p>\n\n<pre><code>function validateMe()\n{\n //Always assume invalid to startwith\n updateValidFields(false);\n\n // do awesome field checking.\n\n if(thisFieldIsValid)\n {\n updateValidFields(true);\n }\n}\n</code></pre>\n\n<p>then your checkValidID function would look like:</p>\n\n<pre><code>function checkIDValidity(){\n updateValidFields(false);\n</code></pre>\n\n<p>and the readyState change function:</p>\n\n<pre><code>xmlhttp.onreadystatechange=function(){ \n if (xmlhttp.readyState===4 &amp;&amp; xmlhttp.status===200){ \n var existingIDs = xmlhttp.responseText;\n var idcomponent = document.myform.myids;\n var idwarningdiv = document.getElementById('nonexistingid');\n if(existingIDs===\"Existing\"){\n // Do valid stuff\n updateValidFields(true);\n }else{\n //do invalid stuff.\n } \n } \n };\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T06:55:30.930", "Id": "7163", "Score": "0", "body": "Didn't you mean for `invalidField` to be a global variable, as well as for `updateValidField()` to be a publich function?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T23:36:24.050", "Id": "7185", "Score": "0", "body": "@Eldros Nope. This way it creates the variable and function in the same scope and a new one each time. You coould make it Global if you wanted but i think its better this way as each new time it starts fresh. [yoda] Think it is a matter of preference I do.[/yoda]" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T06:15:54.307", "Id": "7192", "Score": "0", "body": "Then I don't understand why the variable is in `checkIDValidity`, I mean it is only one check for one field (where there could be already many check on a field). It might be that I still think as a PHP developer, but wouldn't it be better to put it in the `validateMe()`(Which I take is your form validation function)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T06:34:00.190", "Id": "7193", "Score": "0", "body": "@eldros Sorry That first one was supposed to be `CheckFormValue`. oops! Fixed now. Then `validateme` would either check its validity for required and if that pass it would then check its ID (if needed)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T06:38:14.533", "Id": "7194", "Score": "0", "body": "@Eldros also if you would like to see someone else's crack at something similar check out: http://codereview.stackexchange.com/questions/4751/first-go-at-my-own-form-validation-and-suggestions/4752#4752" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T07:04:45.903", "Id": "7195", "Score": "0", "body": "Would `validateMe` be a part of `checkFormValue`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T07:08:11.443", "Id": "7196", "Score": "0", "body": "@Eldros `validateMe` represents the logic for validating one field." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T09:39:44.260", "Id": "7884", "Score": "0", "body": "Ok, I took time to do it, and now it breaks at my first check function, telling me that `updateValidFields()` is not defined. Shouldn't I declare the function globally?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T13:01:06.747", "Id": "7888", "Score": "0", "body": "@Eldros it depends on its usage. this way you always get a different scope. Globally you can use it wherever you want." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T13:23:39.247", "Id": "7889", "Score": "0", "body": "But it seems like I can't use it wherever I want, because it doesn't recognize that the function is defined when I call it from my first field validation check function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T07:28:46.793", "Id": "7928", "Score": "0", "body": "Oh sorry, I think I misunderstood you, you meant that it could be used globally if I want to use it on each of my validation check function. If I do that, I'll declare the `invalidField` variable globally, and reinitialize it with the value 0 at the beginning of `checkFormValues()`. I'll tell you how it turns out on monday." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T11:06:08.820", "Id": "7983", "Score": "1", "body": "Now, with a few adaptation from my side, it works perfectly. I may edit my post with the refactored code at a later time." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T02:42:41.047", "Id": "4778", "ParentId": "4763", "Score": "2" } } ]
{ "AcceptedAnswerId": "4778", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T12:06:54.713", "Id": "4763", "Score": "2", "Tags": [ "php", "javascript", "ajax" ], "Title": "mixed AJAX/Javascript form validation check" }
4763
<p>I've implemented a polling function with a timer in C, that every 10s checks a given condition (I've just replaced it for a log to stdout for testing purposes only) but I would like to know your opinion on this code, namely if there is a simpler way to achieve the same result, what issues may arise concerning performance, thread-safety, memory footprint. I'm interested in writing the most simple, correct and fast code for this. Suggestions are, as always, welcome.</p> <pre><code>/* includes removed for clarity */ void signalAlarmHandler(int signum) { switch(signum) { case SIGINT: fprintf(stdout, "received interrupt. going to exit.\n"); exit(0); break; case SIGALRM: fprintf(stdout, "received signal alarm.\n"); /* checking for condition here */ break; default: break; } } int main(int argc, char* argv[]) { if(initializeEnvironment(argc, argv) == -1) { return -1; } else { signal(SIGINT, signalAlarmHandler); /* for testing purposes */ signal(SIGALRM, signalAlarmHandler); fprintf(stdout, "starting the signal alarm stuff\n"); while(1) { alarm(10); sleep(20); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T14:32:37.610", "Id": "7129", "Score": "0", "body": "Which system is this for? C has no function called sleep() and my answer would be quite different if this was intended for Windows or Linux or something else." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T21:57:51.483", "Id": "7143", "Score": "0", "body": "@Lundin: sleep() is part of the Posix standard (and thus in nearly every C-stdlib) so it is implemented in every C-stdlib implemented on OS that conform to the Posix standard." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T06:50:52.447", "Id": "7162", "Score": "0", "body": "@Tux There are plenty of functions called sleep() in all kinds of systems. Since there are no includes in the code posted, nor any tags, we can't really make any assumptions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T08:51:41.743", "Id": "7199", "Score": "0", "body": "I've ommited the includes, but if you want to know it's for a Linux system and these are the includes:\n`code`\n#include <stdio.h>\n#include <signal.h>\n#include <unistd.h>\n`code`" } ]
[ { "body": "<p>What is a reason for using alarm() with sleep()? Why not just</p>\n\n<pre><code>void sigIntHandler(int signum) {\n fprintf(stdout, \"received interrupt. going to exit.\\n\");\n exit(0);\n}\n\nint main(int argc, char* argv[]) {\n if(initializeEnvironment(argc, argv) == -1) {\n return -1;\n }\n signal(SIGINT, signalAlarmHandler); /* for testing purposes */\n\n while(1) {\n sleep(10);\n /* checking for condition here */\n }\n}\n</code></pre>\n\n<p>Also:</p>\n\n<ul>\n<li>fprintf() is not signal-safe, better not to use it from signal handler</li>\n<li>signal() is obsolete and implementation-dependent, use sigaction() for consistent results.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T09:04:59.210", "Id": "7201", "Score": "0", "body": "Thank you for your answer. I need to check for a given condition at every 10s, so I use alarm() to receive a SIGALRM for this purpose. Then I use sleep() for the program to do nothing but wait. When the 10s have passed, the program receives a SIGALRM and handles it, e.g., checks for a given condition. Also, can you tell me how do you know that fprintf is not signal-safe? I've read the manpage for fprintf and there is nothing there pointing for this. Also, any books, articles you can point me for reading on this topic? Regards ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T10:07:54.943", "Id": "7204", "Score": "0", "body": "http://linux.die.net/man/2/signal - here you can find POSIX list of safe functions. By the way, your code will check for condition only once: alarm() causes single signal to be delivered. Call alarm() again in signal handler or use setitimer() for periodic signal delivery." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T13:28:40.473", "Id": "7259", "Score": "0", "body": "Thank you blaze. Are you sure my code will check only once for the condition? Because I can see that string on stdout every 10s... In the while loop I call alarm(), is this different from not calling alarm() in the while loop and calling it on the signalAlarmHandler function?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T14:07:12.490", "Id": "4765", "ParentId": "4764", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T13:05:59.203", "Id": "4764", "Score": "2", "Tags": [ "optimization", "c" ], "Title": "Polling timer function in C" }
4764
<p>I have these MySQL tables:</p> <pre><code>-- Create product table CREATE TABLE `product` ( `product_id` int NOT NULL auto_increment, `price` decimal(10,2) NOT NULL default '0.00', `discounted_price` decimal(10,2) NOT NULL default '0.00', `avail` enum('Y','N') NOT NULL default 'Y', `image` varchar(150) NOT NULL default '', `image_2` varchar(150) NOT NULL default '', `thumbnail` varchar(150) NOT NULL default '', `thumbnail_2` varchar(150) NOT NULL default '', `for_sale` enum('Y','N') NOT NULL default 'Y', `views_stats` int NOT NULL default '0', `sales_stats` int NOT NULL default '0', `amount_stats` decimal(12,2) NOT NULL default '0.00', PRIMARY KEY (`product_id`), KEY `idx_avail` (`avail`), KEY `idx_for_sale` (`for_sale`) ) ENGINE=MyISAM default charSET=utf8 COLLATE=utf8_unicode_ci; -- Create table for product languages CREATE TABLE `product_languages` ( `language_id_iso_639_1` char(2) NOT NULL default '', `product_id` int NOT NULL auto_increment, `name` varchar(100) NOT NULL default '', `description` varchar(1000) NOT NULL default '', `keywords` varchar(255) NOT NULL default '', `meta_description` text NOT NULL, `meta_keywords` text NOT NULL, `title_tag` text NOT NULL, PRIMARY KEY (`language_id_iso_639_1`, `product_id`), FULLTEXT KEY `idx_ft_product_name_description` (`name`, `description`, `keywords`) ) ENGINE=MyISAM DEFAULT charSET=utf8 COLLATE=utf8_unicode_ci; -- Create product_category table 'many to many relationship' between products and categories CREATE TABLE `product_category` ( `product_id` int NOT NULL default '0', `category_id` int NOT NULL default '0', PRIMARY KEY (`product_id`, `category_id`) ) ENGINE=MyISAM default charSET=utf8 COLLATE=utf8_unicode_ci; </code></pre> <p>Then I try to get all products from table <code>product</code> with the product details in English from table <code>product_languages</code>, and from a specific category looking at <code>product_category</code> table and where <code>avail</code> from table <code>product</code> is Y, something like this:</p> <pre><code>SELECT product.product_id, product.price, product.discounted_price, product.avail, product.image, product.image_2, product.thumbnail, product.thumbnail_2, product.for_sale, product.views_stats, product.sales_stats, product.amount_stats, product_languages.name, product_languages.description, product_languages.keywords, product_languages.meta_description, product_languages.meta_keywords, product_languages.title_tag FROM product INNER JOIN product_category ON product.product_id = product_category.product_id INNER JOIN product_languages ON product.product_id = product_languages.product_id WHERE product_category.category_id = 1 AND product.avail = 'Y' AND product_languages.language_id_iso_639_1 = 'en' ORDER BY product.product_id LIMIT 0 , 30; </code></pre> <p>It works (I tried it with PHPMyAdmin). I get all products from the product table that belong to a category that are avail='Y', and I get the names and descriptions from every product in English (en) from <code>product_languages</code> table.</p> <p>Could someone with experience with MySQL suggest any changes? I'm not really sure if what I do is correct. Should I change tables, fields, or types for better options, such as enums, or remove or add better indexes to improve speed?</p> <p>For example, maybe add another index at <code>product_id</code> from <code>product_languages</code> table because now I have <code>PRIMARY KEY ('language_id_iso_639_1', 'product_id')</code> and I use for the second <code>INNER JOIN ON product.product_id = product_languages.product_id</code>, is it correct the FULLTEXT KEY at <code>product_languages</code> table <code>FULLTEXT KEY 'idx_ft_product_name_description' ('name', 'description', 'keywords')</code> to use that feature to look at those 3 fields, change parts of the query with the INNER JOINS change the order of <code>INNER JOINS first INNER JOIN table product_languages</code> and second <code>INNER JOIN product_category</code>, etc.</p>
[]
[ { "body": "<p>I'm not an expert as say, but my only suggestions might be:</p>\n\n<p>1) If the enums are only ever going to be Y, N, you could look at changing these to the bit flag.</p>\n\n<p>2) I would perhaps look at removing the defaults from the fields that are defined as part of the primary key i.e. product_category. This would force the values to be always supplied from the application.</p>\n\n<p>3) product_languages.product_id. I don't understand the auto_increment setting here. The field appears to want to be a foreign_key to the products table but you have set it as a auto_increment field. I would perhaps remove the auto_increment and set an index on it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T23:27:53.793", "Id": "7158", "Score": "0", "body": "\"product_languages.product_id. I don't understand the auto_increment setting here\"\nyes you're totally right just a mistake with my copy paste,\nthanks for your response" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T20:12:31.007", "Id": "4769", "ParentId": "4768", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T13:48:23.690", "Id": "4768", "Score": "1", "Tags": [ "sql", "mysql" ], "Title": "Acquiring product details" }
4768
<p>I used to mostly do this:</p> <pre><code>class Person constructor : (@parent, @data)-&gt; @index = @parent.length class People constructor : -&gt; people = [] for data in database.people people.push new Person(people, data) </code></pre> <p>Lately I have been trying the following:</p> <pre><code>class Person constructor : (@data)-&gt; pushTo : (list)-&gt; this.index = list.length list.push this class People constructor : -&gt; people = [] for data in database.people person = new Person(data) person.pushTo people </code></pre> <p>So was wondering if there is any cons about doing it the second way. The reason I am asking is that it might not be the responsibility of Person to add himself to the list.</p>
[]
[ { "body": "<blockquote>\n <p>The reason I am asking is that it might not be the responsibility of Person to add himself to the list.</p>\n</blockquote>\n\n<p>I think you should ask youself a question \"Why am I doing this?\" Why do you need to keep the <code>@index</code> inside a <code>Person</code>? </p>\n\n<ul>\n<li><p>Is it just an id? If so why don't you use <code>_.uniqueId('person')</code> from <a href=\"http://documentcloud.github.com/underscore/#uniqueId\" rel=\"nofollow noreferrer\">Underscore JS</a>? That would be much cleaner.</p></li>\n<li><p>Do you use it for ordering so you could for example sort an array of people by it? If so <code>uniqueId</code> would still suit your needs well.</p></li>\n<li><p>Do you use it to search for person by it's index in the list later on? Basically I can envision two kinds of data processing.</p>\n\n<ol>\n<li><p>You iterate over a list of people. In this case you'll be fine with Underscore's <code>each</code> method:</p>\n\n<pre><code>_.each people, (person, index) -&gt;\n // your code here ^----- see that? ;)\n</code></pre></li>\n<li><p>You got a person data from some external source and you want to reuse the associated <code>Person</code> object. In this case you should still use an ID and search for your object with <code>find</code> or <code>select</code> methods.</p></li>\n</ol></li>\n</ul>\n\n<hr>\n\n<p>Some notes:</p>\n\n<ol>\n<li><p>Both your solutions are totally fine if you certain that they don't complicate the code of your application. They also apply in cases when your collection is very large and <code>find</code> takes too much time. <em>BUT</em> you can speed up selection on later invocations:</p>\n\n<pre><code>indexFor = (targetPerson) -&gt;\n unless person.index // we search for index once and then store it for later use\n _.find people, (person, index) -&gt;\n person.index = index if found = (person.id == targetPerson.id)\n found\n targetPerson.index\n</code></pre></li>\n<li><p><code>uniqueId</code> uses internal counter so the ID is always increasing. It cannot be reset which may not be always convenient. For example if you need to save your collection and reload it later you won't be able to tell the generator to increase the counter accordingly. In that case I would still go with <code>uniqueId</code> for presentation code but use some other ID generation scheme for persistence. I would go with <a href=\"https://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\">UUIDs</a>: but you can also try timestamps though I wouldn't recommend it since generally time is <em>way</em> too difficult to get right.</p></li>\n<li><p>You should definitely check out other methods in <a href=\"http://documentcloud.github.com/underscore/\" rel=\"nofollow noreferrer\">Underscore</a> library. Whenever you encounter a kind of low-level task you should ask if Underscore does it for you already. If it doesn't check jQuery or whatever library you use for UI. If you're still out of luck ask Google or StackOverflow. I'm sure you're great coder and you can solve many of those tasks yourself but why should you spend your time and effort reinventing stuff instead of creating something new? Know your libraries and use them. It's like a new language or a new text editor - at first it's painful but it pays off later on.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-19T08:40:12.747", "Id": "4902", "ParentId": "4776", "Score": "2" } }, { "body": "<p>Regarding @Andrew's answer: Best Coffeescript practice would be to use <code>is</code> instead of <code>==</code>. I.e., <code>person.id is targetPerson.id</code>. Coffeescript will substitute <code>===</code> in place of either AFAIK.</p>\n\n<p>Regarding @Pickels' question: List comprehension is a great tool here. Consider this:</p>\n\n<pre><code>people = (new Person(people, data) for data in database.people)\n</code></pre>\n\n<p>This compiles to:</p>\n\n<pre><code>var data, people;\n\npeople = (function() {\n var _i, _len, _ref, _results;\n _ref = database.people;\n _results = [];\n for (_i = 0, _len = _ref.length; _i &lt; _len; _i++) {\n data = _ref[_i];\n _results.push(new Person(people, data));\n }\n return _results;\n})();\n</code></pre>\n\n<p>which is, I believe, what you want.</p>\n\n<p>A great new reference is the <a href=\"https://github.com/polarmobile/coffeescript-style-guide\" rel=\"nofollow\">Coffeescript Style Guide</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-20T18:05:09.500", "Id": "7026", "ParentId": "4776", "Score": "1" } }, { "body": "<p>Here's a pattern I use all the time; for model/collections as in your example, or even for managing views and arbitrary objects. This is also how Spine.JS models work.</p>\n\n<p>You can declare static methods and properties on the class itself with @method. So calling Person.Fetch() here will instantiate new Person instances with the appropriate id (Array#push returns the new length) and add them to the collection array, a private static variable. </p>\n\n<p>So to answer the original question, I do think it is appropriate for instances to add themselves to the collection. What if a Person was created client-side by the user rather than through a call to the database? Shouldn't it also be a part of the collection, say for syncing back to the server? The cool thing here is that it's encapsulated within the class definition, rather than establishing a dependency with another class.</p>\n\n<pre><code>class Person\n collection = []\n\n @Fetch: -&gt; new Person data for data in database\n @Get: (id) -&gt; if id? then collection[id] else collection\n\n constructor: (@data) -&gt; @id = collection.push this\n\ndatabase = [\"Barry\", \"Other Barry\", \"Sterling\"]\nPerson.Fetch()\nalert Person.Get(1).data # alerts \"Other Barry\"\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-17T23:31:48.207", "Id": "22839", "ParentId": "4776", "Score": "0" } } ]
{ "AcceptedAnswerId": "4902", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-12T22:52:54.650", "Id": "4776", "Score": "4", "Tags": [ "design-patterns", "coffeescript" ], "Title": "Adding push to array inside the class that is being pushed" }
4776
<pre><code> package xml.impl; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; public class XMLCreator { private String parent; private String child; private Integer ctr = 0; private HashMap&lt;Integer, String&gt; xml; private String root; private HashMap&lt;Integer, String&gt; roots; private StringBuilder sB; private HashMap&lt;Integer, String&gt; getRoot() { this.roots.put(1, "&lt;" + root + "&gt;"); this.roots.put(2, "&lt;/" + root + "&gt;"); return roots; } public void setRoot(String root) { this.root = root; } public XMLCreator() { if (this.xml == null) { this.xml = new HashMap&lt;Integer, String&gt;(); } if (this.roots == null) { this.roots = new HashMap&lt;Integer, String&gt;(); } if (this.sB == null) { this.sB = new StringBuilder(); } } /* * private void startParentField(String parent) { this.parent = "&lt;" + parent * + "&gt;"; this.ctr++; addToXML(getParentField()); } * * private void endParentField(String parent) { this.parent = "&lt;/" + parent * + "&gt;"; this.ctr++; addToXML(getParentField()); } * * public void setParent(String parent) { startParentField(parent); * endParentField(parent); } */ public void addChildField(String child) { this.child = "&lt;" + child + "&gt;" + "&lt;/" + child + "&gt;"; this.ctr++; addToXML(getChildField()); } public void addChildField(String child, String value) { this.child = "&lt;" + child + "&gt;" + value + "&lt;/" + child + "&gt;"; this.ctr++; addToXML(getChildField()); } private String getParentField() { return parent; } private String getChildField() { return child; } private void addToXML(String element) { xml.put(ctr, element); } public void buildXMLPreview() { // Set&lt;Integer&gt; keys = xml.keySet(); getRoot(); System.out.println(roots.get(1)); sB.append(roots.get(1)); for (int x = 1; x &lt;= xml.size(); x++) { sB.append(xml.get(x)); } sB.append(roots.get(2)); System.out.println(sB.toString()); sB.delete(0, sB.length()); } public void buildXMLToFile() throws IOException { FileWriter writer = new FileWriter("try.xml"); getRoot(); writer.append(roots.get(1)); for (int x = 1; x &lt;= xml.size(); x++) { writer.append(xml.get(x)); } writer.append(roots.get(2)); writer.flush(); writer.close(); } } </code></pre> <p>Sample Implementation:</p> <pre><code>package xml.impl; import java.io.IOException; public class XMLCreatorTester { public static void main(String[] args) throws IOException { XMLCreator xmlCreator = new XMLCreator(); xmlCreator.setRoot("Art"); xmlCreator.addChildField("name", "Mona Lisa"); xmlCreator.addChildField("artist", "Leonardo Da Vinci"); xmlCreator.addChildField("adsa"); xmlCreator.buildXMLPreview(); xmlCreator.buildXMLToFile(); } } </code></pre> <p>Output:</p> <pre><code>&lt;Art&gt; &lt;name&gt;Mona Lisa&lt;/name&gt; &lt;artist&gt;Leonardo Da Vinci&lt;/artist&gt; &lt;adsa&gt;&lt;/adsa&gt; &lt;/Art&gt; </code></pre> <p>As you can see as of now I can only create the root element and child elements(note that the parent element implementation is commented out).</p> <p>Good enough? Suggestions? Violent reactions? Thanks. :)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-24T06:15:13.987", "Id": "53118", "Score": "0", "body": "how does your code work for nested to more than just a single level ?" } ]
[ { "body": "<p>What's this?</p>\n\n<pre><code>public XMLCreator() {\n if (this.xml == null) {\n this.xml = new HashMap&lt;Integer, String&gt;();\n }\n if (this.roots == null) {\n this.roots = new HashMap&lt;Integer, String&gt;();\n }\n if (this.sB == null) {\n this.sB = new StringBuilder();\n }\n}\n</code></pre>\n\n<p>The null checks are always true, where should a value come from?</p>\n\n<p>Why </p>\n\n<pre><code>this.child = \"&lt;\" + child + \"&gt;\" + \"&lt;/\" + child + \"&gt;\";\n</code></pre>\n\n<p>and not </p>\n\n<pre><code>this.child = \"&lt;\" + child + \"/&gt;\";\n</code></pre>\n\n<p>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T08:18:47.923", "Id": "7165", "Score": "0", "body": "As you can see in my sample implementation when XMLCreator is instanciated it checks if those values are null... But yeah I get your point I guess when I instanciate XMLCreator those values are null so no need to check. :) \n\nAnyway with the child yeah when I view the xml generated on IE it shows that if I use that statement it would give me only '</child>', what gives? If an xml element is empty the closing tag is the one only shown?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T07:18:07.503", "Id": "7229", "Score": "0", "body": "According to the XML standard, `<bla></bla>` is equivalent to `<bla/>` (note that the \"/\" is at the *end*)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T06:43:38.043", "Id": "4783", "ParentId": "4780", "Score": "1" } } ]
{ "AcceptedAnswerId": "4783", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T02:50:31.670", "Id": "4780", "Score": "2", "Tags": [ "java", "xml" ], "Title": "Simple XML Creator in Java" }
4780
<p>This is a simple login script. Thought I'm not sure when it's appropriate to use includes over just embedding the code. I'm also not sure if I should make cookies, but I guess I don't really need to right now. Also looking at my code would it be easy to create a 'Remember Me' function? </p> <pre><code>&lt;?php $validUser; $validPass; $win; if($_POST) { include('admin/functions.php'); // Database Connection AllYourBase(); if(CheckEmpty($_POST['username'])) { $username = $_POST['username']; $validUser = true; } else $validUser = false; if(CheckEmpty($_POST['password'])) { $password = $_POST['password']; $validPass = true; } else $validPass = false; $query = mysql_query(sprintf("SELECT * FROM Users WHERE username = '%s'", mysql_real_escape_string($username))) or die(exit()); $result = mysql_fetch_assoc($query); // Split the Salt $fs = substr($result['salt'], 0, 10); $ls = substr($result['salt'], -10); // Add The Salt $pass = md5($fs.$password.$ls); $name = $result['fname']. ' ' . $result['lname']; // Authenticate if($result['password'] == $pass) { session_start(); $_SESSION['name'] = $name; $_SESSION['auth'] = true; $win = true; // Javascript Redirect not Header() Redirect('index.php'); } else $win = false; } ?&gt; &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;form action="&lt;?php echo $_SERVER['PHP_SELF'] ?&gt;" method="POST"&gt; &lt;?php if($_POST &amp;&amp; $win == false): ?&gt; &lt;div class="error"&gt;Login Unsuccessful&lt;/div&gt; &lt;?php endif ?&gt; &lt;input type="text" size="10" name="username" /&gt;&lt;br /&gt; &lt;?php if($_POST &amp;&amp; $validUser == false): ?&gt; &lt;div class="error"&gt;Empty Username&lt;/div&gt; &lt;?php endif ?&gt; &lt;input type="password" size="10" name="password" /&gt;&lt;br /&gt; &lt;?php if($_POST &amp;&amp; $validPass == false): ?&gt; &lt;div class="error"&gt;Empty Password&lt;/div&gt; &lt;?php endif ?&gt; &lt;input type="submit" text="Submit" /&gt; &lt;/form&gt; &lt;a href="register.php"&gt;Registration Page&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T18:59:41.487", "Id": "7179", "Score": "1", "body": "I'd really recommend utilizing OpenID, where you would gain the security of the services you accept (i.e. Twitter, Facebook, Google). The Zend Framework has a module available to assist with this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T19:10:03.250", "Id": "7180", "Score": "1", "body": "Yeah people keep telling me to use the frameworks but I would like to really understand what I'm doing and how things work before jumping into a framework" } ]
[ { "body": "<p>Rather than an else statement to set false on invalid username/password why not just default to false and only set to true if it worked. Also do you care unless both are valid?</p>\n\n<pre><code>$validUserAndPassword = false;\n\nif (CheckEmpty($_POST['username']) &amp;&amp; CheckEmpty($_POST['password']))\n{\n $username = $_POST['username'];\n $password = $_POST['password'];\n $validUserAndPassword = true;\n}\n</code></pre>\n\n<p>The DB is an expensive resources. There is no point in connecting to the DB or even getting stuff from the DB unless you have a valid username and password.</p>\n\n<pre><code>$ result = array();\nif ($validUserAndPassword)\n{\n AllYourBase();\n\n $query = mysql_query(sprintf(\"SELECT * FROM Users WHERE username = '%s'\", \n mysql_real_escape_string($username))) or die(exit());\n $result = mysql_fetch_assoc($query);\n}\n</code></pre>\n\n<p>I am pretty sure that splitting the salt provides little extra entropy.</p>\n\n<pre><code>// Split the Salt\n$fs = substr($result['salt'], 0, 10);\n$ls = substr($result['salt'], -10);\n\n// Add The Salt\n$pass = md5($fs.$password.$ls); \n</code></pre>\n\n<p>I think doing authentication your self is a bad idea (this is a specialized field with lots of gotchas). Anway don't you want to spend time on your application rather than doing mundane tasks like authentication?</p>\n\n<p>I am not an expert on front-ends so I have no good recommendations on packages that can do it for you. But I did play around with <a href=\"http://code.google.com/p/openid-selector/\" rel=\"nofollow\"><code>openid-selector</code></a> (available via google source), which is the same authentication package that the stack exchange sites use. This allows the users to login-in to your site using the open-id credentials (google/open-id/facebook/yahoo/stack-exchange)). </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T15:20:36.723", "Id": "7178", "Score": "0", "body": "Thanks for your help. The reason I check if the username / pass is empty is because IF it's false - it displays an error message at the bottom in HTML that tells them the field is empty. If I set them both to false right out the gate it will display the message no matter what so I'm not sure any other way to do this." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T13:52:07.440", "Id": "4796", "ParentId": "4781", "Score": "2" } }, { "body": "<blockquote>\n <p>Thought I'm not sure when it's appropriate to use includes over just embedding the code.</p>\n</blockquote>\n\n<p>It's appropriate to use includes when you have reusable chunks of code that will be or could be used in more than one place in your application. This way, if you need to make a change to a certain chunk of code, you'll only need to make it once (in the included file) and not in every place that you embedded that code. It's always a great idea to keep your code <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY</a>. </p>\n\n<blockquote>\n <p>I'm also not sure if I should make cookies, but I guess I don't really need to right now. Also looking at my code would it be easy to create a 'Remember Me' function?</p>\n</blockquote>\n\n<p>You cannot have remember me functionality without using cookies. Basically, you need to add a checkbox to your form. Then, write two separate pieces of code. The first bit of code will create a cooke containing a unique token (obviously, only if the checkbox is in the post data) that is unique to his user account. The second bit will need to check for a known token (stored in your datebase perhaps) and automatically log him in. You can find many examples of this by searching for some php authentication scripts on Google.</p>\n\n<p>One thing that sticks out to me in your code is the <code>die(exit())</code>. Just <code>die()</code> or <code>exit()</code> is sufficient as they are exact equivalents. See <a href=\"http://php.net/manual/en/function.die.php\" rel=\"nofollow\">here</a>.</p>\n\n<p>As for further improvements, Google is your friend.</p>\n\n<p><strong>Update</strong> - Concerning the redirect question in comments</p>\n\n<p>For Redirection, there are pros and cons to each method. PHP's Header() is preferable because it handle's the redirect on the server side. However, if any output has been sent to the browser using Header() will throw an error. In such a case, the javascript method can still be leveraged to redirect the user. The downside to using Javascript for redirection is that javascript can be disabled therefor disabling your redirect.</p>\n\n<p>You could use a combination of the two redirect methods. Something like this perhaps:</p>\n\n<pre><code>&lt;?php\n\nfunction Redirect($url)\n{\n // if headers have been sent, use javascript\n if (headers_sent())\n {\n // write redirect\n echo '&lt;script&gt;window.location = \"' . $url . '\"&lt;/script&gt;';\n\n // fallback in case javascript is disabled\n echo '&lt;noscript&gt;Click &lt;a href=\"' . $url . '\"&gt;here&lt;/a&gt; to continue.&lt;/noscript&gt;';\n }\n\n // if header have not been sent, use php to redirect\n else\n {\n header('Location: ' . $url);\n exit;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T19:20:28.187", "Id": "7181", "Score": "0", "body": "So having a Javascript Redirect over a Header() Redirect is acceptable? This was a major concern; I started with Header() redirects but was told that it was better to use javascript." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T18:59:37.193", "Id": "7241", "Score": "0", "body": "@Howdy_McGee I've updated my answer to address your question. Hope that helps bro!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T14:07:22.653", "Id": "4797", "ParentId": "4781", "Score": "2" } }, { "body": "<p>You could retrieve only the fields you need from the database, namely <code>salt</code>, <code>fname</code>, <code>lname</code>, <code>password</code> - provided the current snippet of code. </p>\n\n<p>This way, you won't even have to worry about the extra-load coming along with the other columns of the table \"Users\" encompassed by the wildcard symbol.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-19T21:31:43.523", "Id": "4915", "ParentId": "4781", "Score": "1" } }, { "body": "<p>Take a look at the Stack Exchange questions:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/1581610/how-can-i-store-my-users-passwords-safely\">How can I store my user's passwords safely?</a></p>\n\n<p><a href=\"https://crypto.stackexchange.com/questions/24/what-password-hash-should-i-use\">What password hash should I use?</a></p>\n\n<p>Basically, <code>md5</code> isn't good enough. MD5 is designed to be fast, and that's bad. You really shouldn't write your own password hashing method. In PHP, you should be using <a href=\"http://us3.php.net/crypt\" rel=\"nofollow noreferrer\"><code>crypt</code></a>:</p>\n\n<pre><code>// Generate hash - This will also make a salt for you\n$hashed = crypt($password);\n\n// Check hash - This uses the salt from $hash_from_database as in the input salt\n$hashed = crypt($password, $hash_from_database);\nif($hashed == $hash_from_database) {\n // success, passwords match\n}\n</code></pre>\n\n<h1>Why you should do this</h1>\n\n<p>What you're looking for is a <a href=\"http://en.wikipedia.org/wiki/Key_derivation_function\" rel=\"nofollow noreferrer\">key derivation function</a>. Popular examples include <a href=\"http://en.wikipedia.org/wiki/PBKDF2\" rel=\"nofollow noreferrer\">PBKDF2</a>, <a href=\"http://en.wikipedia.org/wiki/Crypt_%28Unix%29#Library_Function\" rel=\"nofollow noreferrer\">crypt</a>, <a href=\"http://en.wikipedia.org/wiki/Bcrypt\" rel=\"nofollow noreferrer\">bcrypt</a>, and the ever-popular \"append a salt and hash\".</p>\n\n<p>Why is \"append a salt and hash\" the worst of these?</p>\n\n<ul>\n<li><p>What happens when the password format changes? In crypt and bcrypt, the salt <em>and</em> the hashing algorithm are stored with the hash, so if you change the hash function, you can still check old passwords (with no extra work).</p></li>\n<li><p>How fast is it? If someone gets a hold of your database with password + salt, how long would it take them to break one? The answer is not very long. MD5 is designed to be fast, and that's exactly what you don't want when you're hashing a password. So how many times should you loop? What happens when you need to do change that loop size? Store all old passwords? Keep doing that every time computers get faster?</p></li>\n</ul>\n\n<p><a href=\"http://chargen.matasano.com/chargen/2007/9/7/enough-with-the-rainbow-tables-what-you-need-to-know-about-s.html\" rel=\"nofollow noreferrer\">Use someone else's password system</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T01:17:32.783", "Id": "7346", "Score": "1", "body": "If nobody tried to write their own hashing methods then there would be no hashing methods ;p and what's the point of crypting if you can't decrypt." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T01:29:11.790", "Id": "7347", "Score": "1", "body": "@Howdy_McGee - Not being able to decrypt it is *the entire point*. You *can* compare a password to a hashed password though (see lines 5-8 of my post), which is what you want." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T01:31:55.250", "Id": "7348", "Score": "0", "body": "@Howdy_McGee - Obviously some people come up with their own hashing methods, but they know what they're doing and most people don't (you and me included). MD5 is a cryptographic hash function and you're trying to write your own key derivation function. Would you write your own hash function and expect it to be secure? No, you use one that someone who knows what they're doing came up with. With that in mind, what makes you think you know how to write a key derivation function? I'll give some examples of what you're missing in my answer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-19T23:59:33.460", "Id": "4916", "ParentId": "4781", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T05:55:24.983", "Id": "4781", "Score": "1", "Tags": [ "php", "html" ], "Title": "How Can I Improve/Secure My Login Script?" }
4781
<p>I'm using Winforms C# .NET 3.5. I'm getting frames, and this is how I handle them:</p> <pre><code> delegate void videoStream_NewFrameDelegate(object sender, NewFrameEventArgs eventArgs); public void videoStream_NewFrame(object sender, NewFrameEventArgs eventArgs) { if (ready) { if (this.InvokeRequired) { videoStream_NewFrameDelegate del = new videoStream_NewFrameDelegate(videoStream_NewFrame); this.Invoke(del, new object[] {sender, eventArgs} ); } else { Rectangle rc = ClientRectangle; Bitmap bmp = new Bitmap(rc.Width, rc.Height); Graphics g = Graphics.FromImage((Image)bmp); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear; g.DrawImage((Bitmap)eventArgs.Frame, rc.X+10, rc.Y+10, rc.Width-20, rc.Height-20); g.Dispose(); this.Image = (Image)bmp; } } } </code></pre> <p>Is there any way to optimize or improve performance?</p> <p>I'm getting low performance when my image is 320x240 and I'm stretching it to 1280x1024, But the same image on 640x480 and stretching to 1280x1024 wont get much loss in performance.</p> <p>I tried to use WPF and still same performance loss. That is weird because WPF is supposed to use DirectX and be fast in image processing.</p> <p>Here is my WPF code:</p> <pre><code> delegate void videoStream_NewFrameDelegate(object sender, NewFrameEventArgs eventArgs); public void videoStream_NewFrame(object sender, NewFrameEventArgs eventArgs) { if (ready) { if (!this.Frame.Dispatcher.CheckAccess()) { videoStream_NewFrameDelegate del = new videoStream_NewFrameDelegate(videoStream_NewFrame); this.Frame.Dispatcher.Invoke(del, new object[] { sender, eventArgs }); } else { Bitmap bmp = (Bitmap)eventArgs.Frame.Clone(); IntPtr hBitmap = bmp.GetHbitmap(); BitmapSource img = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); bmp.Dispose(); GC.Collect(); this.Frame.Source = img; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-21T04:33:56.157", "Id": "7380", "Score": "0", "body": "Use Managed D2D withing WPF window" } ]
[ { "body": "<blockquote>\n <p>I tried to use WPF and still same preformence lose.. that is weird because WPF suppose to use DirectX and be fast in image proccessing.</p>\n</blockquote>\n\n<p>Except, in the WPF version, you are cloning a <code>Bitmap</code> (which has nothing to do with WPF) and then calling <code>Imaging.CreateBitmapFromHBitmap</code>, which eventually resolves to a call to:</p>\n\n<pre><code>[DllImport(\"WindowsCodecs.dll\", EntryPoint=\"IWICImagingFactory_CreateBitmapFromHBITMAP_Proxy\")]\ninternal static extern int CreateBitmapFromHBITMAP(IntPtr THIS_PTR, IntPtr hBitmap, IntPtr hPalette, WICBitmapAlphaChannelOption options, out BitmapSourceSafeMILHandle ppIBitmap);\n</code></pre>\n\n<p>Now I don't know what that method is doing, but it may very well be copying the data <em>again</em>, but perhaps not. Either way, your WPF method is performing at least one clone of the entire image and your WinForms version is not.</p>\n\n<p>That's not really the meat of it though. You haven't even posted benchmark results, so you need to do that first before assuming any one part of code is \"slow\", and you will have a hard time optimizing until you have that answer. You're two versions aren't even identical in output; the WinForms version performs <code>HighQualityBilinear</code> interpolation, which is certainly going to take a significant amount of time.</p>\n\n<p>You need to tell us what you requirements are. I ran a quick test with the following code using a 320x240 size image, and then again at 640x480:</p>\n\n<pre><code>public Form1()\n{\n InitializeComponent();\n} \n\nprivate TimeSpan RunTest( int sampleSize )\n{\n var sw = Stopwatch.StartNew();\n var baseImg = new Bitmap( @\"C:\\TestImage.jpg\" );\n Bitmap bmp = null;\n for( int i = 0; i &lt; sampleSize; ++i )\n {\n var rect = picBox.ClientRectangle;\n bmp = new Bitmap( rect.Width, rect.Height );\n using( Graphics g = Graphics.FromImage( bmp ) )\n {\n g.InterpolationMode = InterpolationMode.HighQualityBilinear;\n g.DrawImage( baseImg, rect );\n }\n\n picBox.Image = bmp;\n // the call to Invalidate() that you have is not needed.\n }\n\n sw.Stop();\n return TimeSpan.FromMilliseconds( sw.ElapsedMilliseconds );\n}\n\nprivate void picBox_Click( object sender, EventArgs e )\n{\n int iterations = 100;\n var time = RunTest( iterations );\n MessageBox.Show( String.Format( \n \"Elapsed: {0}, Average: {1}\", \n time.TotalMilliseconds, \n time.TotalMilliseconds / iterations ) );\n}\n</code></pre>\n\n<p>I then performed another test using the default <code>InterpolationMode</code>. Under a release build that gave me the following results:</p>\n\n<p>320x240\n1. High quality interpolation: Total: 3122ms, Average: 31.22ms, FPS: 32\n2. Default interpolation: Total: 2165ms, Average: 21.65ms, FPS: 46</p>\n\n<p>640x480\n1. High quality interpolation: Total: 3963ms, Average: 39.63ms, FPS: 25\n2. Default interpolation: Total: 2256ms, Average: 22.56ms, FPS: 44</p>\n\n<p>Are you saying that 32 frames per second is not good enough for your application? Is 42 ok and is it alright to remove the high quality rendering? You need to provide more details. You can't expect us to optimize your code with no target requirement in mind. Also, as you can see, your claim that the performance is better with large images does not appear to be true, though the difference without high quality bilinear rendering is negligible.</p>\n\n<p>If you can forego the Bilinear interpolation you can simply set the <code>StretchMode</code> of the <code>PictureBox</code> to <code>Stretch</code> and just set the <code>Image</code> property to the <code>Frame</code> property of the event args object and be done with it. This will be significantly faster.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T18:41:31.350", "Id": "7216", "Score": "0", "body": "Hey! thx alot for the awosome answer ! i added some test to my questions.\nMy event is getting called when a WebCam frame is arrived.\nI tried what you said with the stretch mode but i get Empty Image..\n`this.Image = (Bitmap)eventArgs.Frame;`\n\nI dont know why but when i'm taking the 320x240 picture and stretching it in a full screen PictureBox i get Long delay, but the tests you you do shows only 4500ms on full screen, and 3300 on normal size.. but in the eye it looks like 3 seconds delay.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-19T20:38:20.870", "Id": "7342", "Score": "1", "body": "@Danpe: My timings may have been a bit misleading; they don't take into account the time that the PictureBox takes to redraw itself, which is bound to be significant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T01:44:23.533", "Id": "7350", "Score": "1", "body": "@Ed S.: your \"sample\" is not useful, and do not provide significant performance improvements compared to the original post. Is any case, it will have almost the same timings, because it usese the same managed function calls" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T21:23:52.983", "Id": "4801", "ParentId": "4785", "Score": "3" } } ]
{ "AcceptedAnswerId": "4801", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T09:22:22.550", "Id": "4785", "Score": "3", "Tags": [ "c#", ".net", "image", "winforms", "wpf" ], "Title": "Image processing optimization" }
4785
<p>I have simple code that just has to check if a checkbox is checked and if so enable some fields that, by default, should be disabled.</p> <p>I have written the next code which I know can be severely improved. Could anyone tell me how? I tried getting the siblings of the checkbox also but that just caused some trouble.</p> <pre><code>$(function(){ $('#amount').attr('disabled','disabled'); $('#period').attr('disabled','disabled'); $('#key').attr('disabled','disabled'); $('#api').change(function(){ if($('#apiEnabled').is(':checked')){ $('#amount').attr('disabled',''); $('#period').attr('disabled',''); $('#key').attr('disabled',''); }else{ $('#amount').attr('disabled','disabled'); $('#period').attr('disabled','disabled'); $('#key').attr('disabled','disabled'); } }); }); </code></pre>
[]
[ { "body": "<pre><code>$(function(){ \n var $els = $('#amount, #period, #key');\n $('#api').change(function(){\n var unchecked = !this.checked;\n $els.each(function(){\n $(this).prop('disabled', unchecked);\n });\n });\n});\n</code></pre>\n\n<p>And if applicable change:</p>\n\n<pre><code>var $els = $('#amount, #period, #key');\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>var $els = $('#api').siblings();\n</code></pre>\n\n<p><br/></p>\n\n<h1>Example Here:</h1>\n\n<p><a href=\"http://jsfiddle.net/BpVkw/\" rel=\"nofollow\"><h3>http://jsfiddle.net/BpVkw/</h3></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T10:19:14.067", "Id": "4789", "ParentId": "4787", "Score": "0" } }, { "body": "<p>This is my take at it, but if you won't be needing the separate elements all over the place, then take @Frédéric Hamidi's advice and create a single object.</p>\n\n<pre><code>$(function(){\n var $amount = $('#amount'), // cache jQuery objects\n $period = $('#period'), // to avoid overhad\n $key = $('#key'), // of fetching them\n $apiEnabled = $('#apiEnabled'); // all the time\n $amount.prop('disabled', true);\n $period.prop('disabled', true);\n $key.attr('disabled', true);\n $('#api').change(function(){\n if ($apiEnabled.is(':checked')) {\n $amount.prop('disabled', false);\n $period.prop('disabled', false);\n $key.prop('disabled', false);\n } else{\n $amount.prop('disabled', true);\n $period.prop('disabled', true);\n $key.attr('disabled', true);\n }\n });\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T10:19:58.380", "Id": "4790", "ParentId": "4787", "Score": "0" } }, { "body": "<p>You can cache your set of elements to prevent jQuery from looking them up every time you refer to them. You can also group them all into one set because you are applying the same code to all three of them.</p>\n\n<p><code>prop</code> can be used instead of <code>attr</code> which is new in jQuery 1.6+. <code>prop</code> is better suited to checkboxes and setting things as <code>disabled</code>.</p>\n\n<p>Now that all three elements are grouped, you have one place (the <code>checkboxes</code> variable) that you can add or remove new checkboxes. It also means more succinct code in your <code>change</code> event.</p>\n\n<pre><code>$(function(){\n\n // Cache the elements\n var checkboxes = $(\"#amount, #period, #key\");\n\n // Disable them using prop rather than attr (jquery 1.6+)\n checkboxes.prop('disabled', true);\n\n $(\"#api\").change(function(){\n\n if($('#apiEnabled').is(':checked')) checkboxes.prop('disabled', false);\n else checkboxes.prop('disabled', true);\n\n });\n\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T10:20:28.797", "Id": "4791", "ParentId": "4787", "Score": "0" } }, { "body": "<p>It's difficult to answer accurately without seeing your markup, but maybe you can use a <a href=\"http://api.jquery.com/multiple-selector/\" rel=\"nofollow\">multiple selector</a> to alleviate code redundancy. You can also use <a href=\"http://api.jquery.com/prop/\" rel=\"nofollow\">prop()</a> to enable or disable your elements more easily:</p>\n\n<pre><code>$(function() {\n var $elements = $(\"#amount, #period, #key\");\n $elements.prop(\"disabled\", true);\n $(\"#api\").change(function() {\n $elements.prop(\"disabled\", !$(\"#apiEnabled\").is(\":checked\"));\n });\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T10:21:52.600", "Id": "4792", "ParentId": "4787", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T10:14:08.317", "Id": "4787", "Score": "5", "Tags": [ "javascript", "jquery" ], "Title": "Function that enables fields based on checkbox state" }
4787
<p>How could I improve this algorithm? The goal is to organize matches between sport teams such that:</p> <ul> <li>Each team affront each other</li> <li>A minimum number of team should start a match after just finishing one</li> </ul> <p>The interesting part is here:</p> <pre><code>myPerm [] _ = [[]] myPerm xs threshold = [x:ys | x &lt;- xs, ys &lt;- take nbToKeep $ filter (\ts -&gt; price ts &lt;= threshold) (myPerm (delete x xs) threshold)] </code></pre> <p>It is a way to remove from the enumeration of permutations all sub-sequences not being good enough. Even with this, the problem for 6 teams is very long to resolve.</p> <p>Here is the complete program:</p> <pre><code>import System.Environment import Data.Ord import Data.List -- The number of items we keeps to only search -- from bests local results nbToKeep :: Int nbToKeep = 10 type Match = (Int,Int) type MatchSequence = [Match] -- Give all sport matches in the form -- (1,2) =&gt; match between Team 1 and Team 2 all_matches :: Int -&gt; MatchSequence all_matches n = [ (x,y) | x &lt;- [1..n], y &lt;- [1..n], x &lt; y ] -- A price function for sequence of matches -- 0 if no team make a match just after finishing one -- Possible with 5 teams not for 3 and 4 price :: MatchSequence -&gt; Int price ((x,y):((z,t):rest)) | x==z = 1 + price ((z,t):rest) | x==t = 1 + price ((z,t):rest) | y==z = 1 + price ((z,t):rest) | y==t = 1 + price ((z,t):rest) | otherwise = price ((z,t):rest) price _ = 0 -- Simple adjoin the price to a MatchSequence addPrices :: MatchSequence -&gt; (Int,MatchSequence) addPrices xs = (price xs, xs) -- Instead of listing _all_ permutations -- Just keep the one such that its subsequece price -- is under the threshold myPerm [] _ = [[]] myPerm xs threshold = [x:ys | x &lt;- xs, ys &lt;- take nbToKeep $ filter (\ts -&gt; price ts &lt;= threshold) (myPerm (delete x xs) threshold)] -- Keep the best one under some threshold find_best_under n threshold = take nbToKeep $ sortBy (comparing fst) $ map addPrices ( myPerm (all_matches n) threshold) isNonEmpty [] = False isNonEmpty _ = True -- Try to test with the minimal threshold (0) -- Then repeat until a solution is found for some threshold find_best n = head $ filter isNonEmpty $ map (find_best_under n) [0..] showMatchSequence :: MatchSequence -&gt; String showMatchSequence [] = [] showMatchSequence ((team1,team2):[]) = show team1 ++ "-" ++ show team2 showMatchSequence ((team1,team2):xs) = show team1 ++ "-" ++ show team2 ++ " " ++ showMatchSequence xs showResult :: (Int,MatchSequence) -&gt; String showResult (score,xs) = show score ++ " collisions: " ++ showMatchSequence xs main = do args &lt;- getArgs mapM_ (putStrLn . showResult) $ find_best (read (head args)::Int) </code></pre> <p>I know I do a linear number of computation using price, while, I shouldn't need it if I integrate the price computation inside the <code>myPerm</code> function.</p> <p>I take all advice, concerning not only style but also sytactic optimisations. For example, I am pretty sure I could have used a Monad to find the first <code>n</code> for which there is a solution.</p>
[]
[ { "body": "<p>No algorithmic improvement, just some cosmetics...</p>\n\n<pre><code>import System.Environment\nimport Data.Ord\nimport Data.List\n\n-- The number of items we keeps to only search\n-- from bests local results\nnbToKeep :: Int\nnbToKeep = 10\n\ntype Match = (Int,Int)\ntype MatchSequence = [Match]\n\n-- gives a different order, but I think this is okay\nall_matches :: Int -&gt; MatchSequence\nall_matches n = [ (x,y) | y &lt;- [2..n], x &lt;- [1..(y-1)]] \n\n-- A price function for sequence of matches\n-- 0 if no team make a match just after finishing one\n-- Possible with 5 teams not for 3 and 4\nprice :: MatchSequence -&gt; Int\nprice xs = sum $ zipWith comp xs $ tail xs where\n comp (x,y) (z,t) = fromEnum $ x==z || x==t || y==z || y==t \n\n-- Simple adjoin the price to a MatchSequence\naddPrices :: MatchSequence -&gt; (Int,MatchSequence)\naddPrices xs = (price xs, xs)\n\n-- Instead of listing _all_ permutations\n-- Just keep the one such that its subsequece price\n-- is under the threshold\nmyPerm [] _ = [[]]\nmyPerm xs threshold = [x:ys | x &lt;- xs,\n ys &lt;- take nbToKeep $\n filter\n ((&lt;= threshold).price)\n (myPerm (delete x xs) threshold)]\n\n\n-- Keep the best one under some threshold\nfind_best_under n threshold = take nbToKeep $\n sortBy (comparing fst) $\n map addPrices ( myPerm (all_matches n) threshold)\n\n-- Try to test with the minimal threshold (0)\n-- Then repeat until a solution is found for some threshold\nfind_best n = head $ filter (not.null) $ map (find_best_under n) [0..]\n\nshowMatchSequence :: MatchSequence -&gt; String\nshowMatchSequence [] = []\nshowMatchSequence ((team1,team2):[]) = show team1 ++ \"-\" ++ show team2 --is this case needed?\nshowMatchSequence ((team1,team2):xs) = show team1 ++ \"-\" ++ show team2 ++ \" \" ++ showMatchSequence xs\n\nshowResult :: (Int,MatchSequence) -&gt; String\nshowResult (score,xs) = show score ++ \" collisions: \" ++ showMatchSequence xs\n\nmain = do\n args &lt;- getArgs\n mapM_ (putStrLn . showResult) $ find_best (read (head args)::Int)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T07:33:11.287", "Id": "4837", "ParentId": "4793", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T12:57:12.493", "Id": "4793", "Score": "2", "Tags": [ "algorithm", "haskell", "combinatorics" ], "Title": "Organizing matches between sports teams" }
4793
<p>This game is explained <a href="http://en.wikipedia.org/wiki/Deal_or_No_Deal" rel="nofollow">here</a>.</p> <p>Could this code be more efficient?</p> <p><strong>The Game Class</strong></p> <pre><code>import java.util.List; import java.util.Arrays; import java.util.Collections; public class Game { private Case[] cases = new Case[26]; private Player player = new Player(); private Banker banker = new Banker(); private int myAmount = 0; private int turn = 1; private int briefCases = 26; private int casesToRemove = 6; private int offer = 0; private boolean gameContinue = true; public void caseSetup() { List&lt;Integer&gt; values = Arrays.asList(1, 5, 10, 100, 500, 750, 1000, 20000, 50000, 75000, 95000, 100000, 150000, 250000, 350000, 400000, 450000, 500000, 600000, 700000, 25, 900000, 1000000, 1500000, 300, 900000); Collections.shuffle(values); for (int i = 0; i &lt; cases.length; i++) { int amount = values.get(i); cases[i] = new Case(amount, i + 1); } } public void showCase(){ for (int j = 0; j &lt; cases.length; j++) { System.out.print("\t[" + cases[j].getFace() + "] "); if (j % 5 == 4) { System.out.println(); } } } public void game(){ caseSetup(); showCase(); myAmount = player.userCase(cases); briefCases--; while(gameContinue==true){ if(briefCases == 25||briefCases == 19 ||briefCases == 14 || briefCases == 10 ||briefCases == 7){ for(int counter = casesToRemove;counter&gt;0;counter--){ player.removeCase(counter,cases); briefCases--; showCase(); } offer = banker.getOffer(turn,cases,myAmount); gameContinue = player.dnd(); casesToRemove--; turn++; }else if(briefCases == 1){ player.removeCase(1,cases); offer = banker.getOffer(turn,cases,myAmount); gameContinue = player.dnd(); casesToRemove--; briefCases--; turn++; } else{ player.removeCase(1,cases); offer = banker.getOffer(turn,cases,myAmount); gameContinue = player.dnd(); casesToRemove--; briefCases--; turn++; } } finishGame(); } public void finishGame(){ if(briefCases == 0){ System.out.println("You've rejected the Offer of banker"); System.out.println("You've won "+myAmount+"And your Case is Larger Than Bankers Offer: "+offer); }else{ System.out.println("Your Accept the offer of banker"); System.out.println("You've won "+myAmount+" and the Bankers offer is :"+offer); } } } </code></pre> <p><strong>Banker Class</strong></p> <pre><code>public class Banker{ private int total = 0; private int numOfSamples = 0; private int average = 0; private int offer = 0; public void setOffer(int turn,Case[] cases,int myAmount){ for(int i = 0 ; i &lt; cases.length;i++){ if(!cases[i].Removed()){ total = myAmount+cases[i].getValue(); numOfSamples++; } } average = myAmount+total/numOfSamples; offer = average*turn/10; } public int getOffer(int turn,Case[] cases,int myAmount){ setOffer(turn,cases,myAmount); System.out.print("The Bankers Offer Is: "+offer); return offer; } } </code></pre> <p><strong>The Briefcase Class</strong></p> <pre><code>public class Case{ private int value = 0; private String face; private boolean removed = false; public Case(int nValue,int nFace){ this.value = nValue; this.face = Integer.toString(nFace); } public int getValue(){ return value; } public String getFace(){ return face; } public boolean Removed() { return removed; } public void remove(){ removed = true; face = "X"; } } </code></pre> <p><strong>Main class</strong></p> <pre><code>public class GameTest{ public static void main(String[] args){ Game DND = new Game(); DND.game(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T00:39:31.880", "Id": "21733", "Score": "0", "body": "You should google \"oo lecture\" or \"oo design\" [Here's](http://mmiika.wordpress.com/oo-design-principles/) an example of a link you get from it." } ]
[ { "body": "<p><code>gameContinue==true</code> can just be <code>gameContinue</code></p>\n\n<p>It looks like you could just get rid of:</p>\n\n<pre><code>else if(briefCases == 1){\n player.removeCase(1,cases); \n offer = banker.getOffer(turn,cases,myAmount);\n gameContinue = player.dnd();\n casesToRemove--;\n briefCases--;\n turn++; \n}\n</code></pre>\n\n<p>These lines can be moved out of the if and else blocks:</p>\n\n<pre><code>offer = banker.getOffer(turn,cases,myAmount);\ngameContinue = player.dnd();\ncasesToRemove--;\nturn++;\n</code></pre>\n\n<p>I would either rename the setOffer method or get rid of it completely. The name is deceptive, and it does not seem to be used outside of the class. Further, it requires an additional state variable. (Is the ever increasing <code>numOfSamples</code> a bug?).</p>\n\n<p>You may want to rename <code>void game</code> to <code>void startGame</code>. Also, those look like they should be the only public methods of that class.</p>\n\n<p>Strictly speaking, it looks like Case should be the only class which has any state variables (you do not give the code for <em><code>Player</code></em>) -- if you have the time, you may want to refactor that as it will make life <em>so</em> much better.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T05:02:18.093", "Id": "7190", "Score": "0", "body": "what do you mean refactor ? (posted the player class)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T08:59:27.870", "Id": "7200", "Score": "0", "body": "Sorry, got the German link... here is the English version: http://en.wikipedia.org/wiki/Code_refactoring" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T00:45:58.443", "Id": "4804", "ParentId": "4800", "Score": "4" } }, { "body": "<p>A few comments:</p>\n\n<ul>\n<li>Try to keep the scope of your variables as low as possible. Don't not be afraid of local variables.</li>\n<li>Consistently follow naming conventions. Sometimes your method names are in UpperCamelCase. That should be reserved for class and interface names only. Also method names should be verbs or verb phrases. <em>(EDIT: This used to say variable names should be verbs. That is completely wrong, and it was a sleep-deprived mistake on my part to include that. Variable names should be lowerCamelCase descriptive nouns.)</em></li>\n<li>Complicated if statement can almost always be refactored away. Sometimes they need to move to their own class, but most of the time you can get rid of them altogether. See <a href=\"http://blogs.microsoft.co.il/blogs/gilf/archive/2009/11/22/applying-strategy-pattern-instead-of-using-switch-statements.aspx\" rel=\"nofollow\">Strategy Pattern</a>, <a href=\"http://sourcemaking.com/refactoring/replace-type-code-with-subclasses\" rel=\"nofollow\">Replace Type Code with Subclasses</a>, <a href=\"http://en.wikipedia.org/wiki/Abstract_factory_pattern\" rel=\"nofollow\">Abstract Factory Pattern</a></li>\n<li>Whitespace is your friend. It makes your code prettier and easier to read.<br>\n<code>average = myAmount+total/numOfSamples</code> should be<br>\n<code>average = myAmount + total / numOfSamples</code></li>\n<li>Magic number suck. Firmly eschew them.</li>\n<li><p>Comments are your friend. A lot of the stuff you had was confusing the first couple go throughs because of a lack of comments. They can help you come up with better variable and function names, do better decomposition, and pay more attention to refactoring (all for the low, low price of $0.00!)</p>\n\n<p>For <strong>every</strong> line of code in your program:</p>\n\n<ul>\n<li>Think of a comment that explains both what you're doing and why you're doing it. You should only add comments regarding why your doing something to your actual code, but thinking about what your doing helps with the refactoring.</li>\n<li>If it's a comment on a field or constant and it's not already redundant, consider refactoring your variable name so that the comment becomes redundant. If there's still a why explanation needed, then add a comment, otherwise your code should <em>mostly</em> be self-documenting.</li>\n<li>Comments before functions should be considered <strong>required</strong> before your function is complete. There is always a why to each function. However, thinking about the what can help you refactor the names of your functions. Also if you can't think of a good short name for your function it may be a sign that it is doing too much. Decompose.</li>\n<li>Comments before classes are much like comments before functions; they are required, they can help you refactor the names of your classes, and they help get rid of <a href=\"http://en.wikipedia.org/wiki/God_object\" rel=\"nofollow\">God Classes</a>.</li>\n<li>Comments within functions that don't seem redundant are probably an indicator for more decomposition unless your doing a complicated algorithm. Decompose.</li>\n</ul></li>\n<li>This code is begging to be extendable. Text-based is fine to start with, but sometimes there's that nagging feeling that you should change it to a GUI (or change the text interface or w/e). Design with that in mind. Your code is so tightly coupled a few small changes to the UI would make you have to go through the whole thing. You probably want more classes to separate out the different functionalities. Consider <a href=\"http://www.oracle.com/technetwork/articles/javase/index-142890.html\" rel=\"nofollow\">MVC</a>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-20T06:03:08.130", "Id": "35233", "Score": "1", "body": "`variable` names should be verbs? Did you mean `function` names?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-20T06:20:35.580", "Id": "35235", "Score": "0", "body": "@JasonLarke You are totally right. I was very sleep-deprived when I wrote this answer. Messed that bit up. Edited now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-20T06:31:06.017", "Id": "35236", "Score": "0", "body": "No dramas, I think we've all been there :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T09:21:43.730", "Id": "13415", "ParentId": "4800", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T17:53:24.330", "Id": "4800", "Score": "7", "Tags": [ "java", "optimization", "object-oriented", "game" ], "Title": "\"Deal Or No Deal\"-style game in Java" }
4800
<p>I need to read records from a flat file, where each 128 bytes constitutes a logical record. The calling module of this below reader does just the following.</p> <blockquote> <pre><code>while(iterator.hasNext()){ iterator.next(); //do Something } </code></pre> </blockquote> <p>Means there will be a next() call after every hasNext() invocation.</p> <p>Now here goes the reader.</p> <pre><code>public class FlatFileiteratorReader implements Iterable&lt;String&gt; { FileChannel fileChannel; public FlatFileiteratorReader(FileInputStream fileInputStream) { fileChannel = fileInputStream.getChannel(); } private class SampleFileIterator implements Iterator&lt;String&gt; { Charset charset = Charset.forName("ISO-8859-1"); ByteBuffer byteBuffer = MappedByteBuffer.allocateDirect(128 * 100); LinkedList&lt;String&gt; recordCollection = new LinkedList&lt;String&gt;(); String record = null; @Override public boolean hasNext() { if (!recordCollection.isEmpty()) { record = recordCollection.poll(); return true; } else { try { int numberOfBytes = fileChannel.read(byteBuffer); if (numberOfBytes &gt; 0) { byteBuffer.rewind(); loadRecordsIntoCollection(charset.decode(byteBuffer) .toString().substring(0, numberOfBytes), numberOfBytes); byteBuffer.flip(); record = recordCollection.poll(); return true; } } catch (IOException e) { // Report Exception. Real exception logging code in place } } try { fileChannel.close(); } catch (IOException e) { // TODO Report Exception. Logging } return false; } @Override public String next() { return record; } @Override public void remove() { // NOT required } /** * * @param records * @param length */ private void loadRecordsIntoCollection(String records, int length) { int numberOfRecords = length / 128; for (int i = 0; i &lt; numberOfRecords; i++) { recordCollection.add(records.substring(i * 128, (i + 1) * 128)); } } } @Override public Iterator&lt;String&gt; iterator() { return new SampleFileIterator(); } } </code></pre> <p>The code reads 80 mb of data in 1.2 seconds on a machine with 7200 RPM HDD, with Sun JVM and running Windows XP OS. But I'm not that satisfied with the code I have written. Is there any other way to write this in a better way (especially the decoding to character set and taking only the bytes that has been read, I mean the <code>charset.decode(byteBuffer) .toString().substring(0, numberOfBytes)</code> part)?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T22:18:27.010", "Id": "7184", "Score": "0", "body": "If you can use Java 7, its ARM feature would be nice here." } ]
[ { "body": "<ol>\n<li><p>There is no particular advantage to using a direct buffer here. You have to get the data across the JNI boundary into Java-land, so you may as well use a normal ByteBuffer. Direct buffers are for copying data when you don't want to look at it yourself really.</p></li>\n<li><p>Use a ByteBuffer that is a multiple of 512, e.g. 8192, so you aren't driving the I/O system and disk controller mad with reads across sector boundaries. In this case I would think about using 128*512 to agree with your record length.</p></li>\n<li><p>The <code>.substring(0, numberOfBytes)</code> is unnecessary. After the read and rewind, the ByteBuffer's position is zero and its limit equals <code>numberOfBytes</code>, so the charset.decode() operation is already delivering the correct amount of data.</p></li>\n<li><p>You're assuming you didn't get a short read from FileChannel.read(). You can't assume that, there is nothing in the Javadoc to support that assumption. You need to read until the buffer is full or you get EOF.</p></li>\n</ol>\n\n<p>Having said all that, I would also experiment with a BufferedReader around an InputStreamReader around the FileInputStream, and just read 128 chars at a time. You might get a surprise as to which is faster.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T00:10:00.997", "Id": "4803", "ParentId": "4802", "Score": "2" } } ]
{ "AcceptedAnswerId": "4803", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-13T21:34:15.057", "Id": "4802", "Score": "1", "Tags": [ "java", "performance", "io", "iterator", "file-structure" ], "Title": "Iterating through 128-byte records in a file" }
4802
<p>I recently implemented a cache for a pet project of mine. The main objectives behind this implementation were:</p> <ol> <li><p><strong>Support move-only types for values</strong>: C++11 is here, and some of the objects that will be used with this template are movable but not copyable. Keys are fine with a copyable requirement because move-only keys make little sense in my opinion.</p></li> <li><p><strong>Fast key lookup</strong>.</p></li> <li><p><strong>Lazy evaluation</strong>: if the creation of the cached value type is an expensive operation, unnecessary creation is undesirable. Instead of creating the value directly and passing it along, I can simply pass a lambda or an existing factory function or function object, like this:</p> <pre><code>lru_cache&lt;int,int&gt; c; c.get_or_add(17, [&amp;blah]{ return long_calculation(blah); }); </code></pre></li> <li><p><strong>Simple syntax when lazy evaluation is not needed</strong>: sometimes if an instance is available, or its creation is "free", using a lambda can be cumbersome. I'd rather just pass it directly:</p> <pre><code>c.get_or_add(17, 42); // int literals are "free", no need for laziness </code></pre></li> </ol> <p>Points 1 and 2 are achieved with a hash map of nodes in a linked list. The hash map gives fast lookup, and the linked list tracks the order of use. I tried to use Boost.Intrusive for the internal linked list, but its hooks don't have move semantics, so I had to roll my own :)</p> <p>Points 3 and 4 are achieved through the <code>meta::lazy&lt;T&gt;::eval</code> function. It alone decides whether the argument is a function that is to be called or just a value to be returned.</p> <p>Here is the code:</p> <pre><code>// for wheels::meta::lazy #include "../meta/traits.hpp" #include &lt;functional&gt; #include &lt;cstddef&gt; #include &lt;type_traits&gt; #include &lt;unordered_map&gt; #include &lt;utility&gt; namespace wheels { //! A cache that evicts the least recently used item. template &lt;typename Key, typename T, typename Hash = std::hash&lt;Key&gt;, typename Pred = std::equal_to&lt;Key&gt;&gt; class lru_cache { public: //! Initializes an LRU cache with the given capacity. lru_cache(std::size_t capacity) : front(), back(), map(), capacity(capacity) {} //! Fetches an item from the cache, or adds one if it doesn't exist. /*! The value parameter can be passed directly, or lazily (i.e. as a factory function). */ template &lt;typename Lazy&gt; T&amp; get_or_add(Key const&amp; key, Lazy value) { auto it = map.find(key); if(it != map.end()) { touch(it); return it-&gt;second.value; } else { return add(key, meta::lazy&lt;T&gt;::eval(value)); } } //! Flushes the cache evicting all entries. void flush() { front = back = nullptr; map.clear(); } private: //! Moves a recently used entry to the front. template &lt;typename Iterator&gt; void touch(Iterator it) noexcept { auto&amp; entry = it-&gt;second; unplug(entry); push_front(entry); } //! Adds a new entry. template &lt;typename Tf&gt; T&amp; add(Key const&amp; key, Tf&amp;&amp; value) { cache_entry entry(key, std::forward&lt;Tf&gt;(value)); auto item = std::make_pair(key, std::move(entry)); auto it = map.insert(std::move(item)).first; push_front(it-&gt;second); if(map.size() &gt; capacity) evict(); return it-&gt;second.value; } //! Evicts the least recently used entry. void evict() { map.erase(back-&gt;key); unplug(*back); } //! An entry in the cache. Maintains a linked list to track the LRU. struct cache_entry { template &lt;typename Tf&gt; cache_entry(Key const&amp; key, Tf&amp;&amp; value) : key(key), value(std::forward&lt;Tf&gt;(value)), next(), prev() {} cache_entry(cache_entry&amp;&amp; that) : key(std::move(that.key)), value(std::move(that.value)) {} Key key; T value; cache_entry* next; cache_entry* prev; }; //! Unplugs an entry from the linked list. void unplug(cache_entry&amp; entry) { if(entry.prev) { entry.prev-&gt;next = entry.next; } else { front = entry.next; } if(entry.next) { entry.next-&gt;prev = entry.prev; } else { back = entry.prev; } } //! Pushes an entry to the front of the linked list. void push_front(cache_entry&amp; entry) { entry.prev = nullptr; entry.next = front; if(front) { front-&gt;prev = &amp;entry; } else { back = &amp;entry; } front = &amp;entry; } cache_entry* front; //! Front of the internal linked list. cache_entry* back; //! Back of the internal linked list. //! Hash table for quick lookup by key. std::unordered_map&lt;Key,cache_entry, Hash&gt; map; //! Maximum capacity. std::size_t capacity; }; } </code></pre> <p>I'm particularly concerned about exception safety (which I've been a bit lax about, and it's something I'm still assimilating), but any criticism is welcome.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-26T16:22:33.560", "Id": "67373", "Score": "0", "body": "Here's [a nice article](http://timday.bitbucket.org/lru.html) comparing two data structures: a) `std::list` and `std::unordered_map` and b) `boost::bimap`. Boost.MultiIndex also has [an MRU example](http://www.boost.org/doc/libs/1_55_0/libs/multi_index/example/serialization.cpp) that should be easy to transform to LRU." } ]
[ { "body": "<p>I think you can make the maintenance of the list a lot easier if the list is circular.<br>\nWith a circular list there are no test for NULL when inserting or removing an element (you just need a fake head node so that an empty list points back at itself).</p>\n\n<p>Also you are not using encapsulation enough, this makes your methods a little more complex than they need to be. For example the cache_entry should be able to add and move itself around in the list.</p>\n\n<p>Here is a simplified example of what I mean to try and show what I mean. Unfortunately there is no way I can implement the full template thing you have (way beyond me skill level).</p>\n\n<p>The only worry I have for this technique is exception safety. There are no problems with this simplified version but I can quite convince myself this is true for your more complex cache. I would need to write the unit tests to make myself convinced.</p>\n\n<pre><code>#include &lt;map&gt;\n\nclass simple_cache\n{\n // The node(s) used to maintain the circular list.\n struct Link\n {\n // Links are created into a list.\n Link(Link* n, Link* p)\n : next(n)\n , prev(p)\n {}\n\n // Remove a `this` from the list.\n void unlink()\n {\n // Unlink this from the chain\n prev-&gt;next = next;\n next-&gt;prev = prev;\n }\n\n // Move a link to `head` of the list.\n // But we do need to pass the head of the list.\n void move(Link&amp; head)\n {\n unlink();\n\n // Put this node back into the chain at the head node\n this-&gt;next = &amp;head;\n this-&gt;prev = head.prev;\n\n head.prev-&gt;next = this;\n head.prev = this;\n }\n\n Link* next;\n Link* prev;\n };\n // A cache_entry is a link\n // So we can add it to the circular list.\n struct cache_entry: public Link\n {\n // Create a link AND add it to the head of the list.\n cache_entry(int key, int value, Link&amp; head)\n : Link(&amp;head, head.prev)\n , key(key)\n , value(value)\n {\n head.prev-&gt;next = this;\n head.prev = this;\n }\n\n int key;\n int value;\n };\n typedef std::map&lt;int, cache_entry&gt; Data;\n Link head; // Circular linked list\n // If there are zero elements it points at itself\n Data data;\n public:\n simple_cache() \n : head(&amp;head, &amp;head)\n {}\n\n void add(int key, int value)\n {\n Data::iterator find = data.find(key);\n if (find != data.end())\n {\n find-&gt;second.value = value;\n find-&gt;second.move(head);\n }\n else\n {\n data.insert(std::make_pair(key,cache_entry(key, value,head)));\n if (data.size() &gt; 5)\n {\n evict();\n }\n }\n }\n private:\n void evict()\n {\n /* This function will explode if called when the list is empty\n * i.e. if the only link in the chain is the fake node.\n * Thus it is important to make sure that you only call this\n * when their is a real node in the list.\n *\n * Maybe a check and exception may be worth it (though if done \n * correctly it should be possible to make sure it does not happen)\n */\n\n\n // Get and remove the last element from the list\n Link* lastElement = head.prev;\n lastElement-&gt;unlink();\n\n // Now remove it from the map.\n data.erase(static_cast&lt;cache_entry*&gt;(lastElement)-&gt;key);\n }\n\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T08:49:54.913", "Id": "7198", "Score": "0", "body": "I think you have a good point about the encapsulation. Even though that API is completely private, it should have a place of its own. :) I'll have to give some more thought about the other stuff you mentioned :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T09:31:28.357", "Id": "7202", "Score": "0", "body": "I think that making a circular list with a sentinel would require one of: 1) require DefaultConstructible keys; 2) keep an extra pointer to the key per node. Note that I need to access the key from the back of the list to erase it from the map. I can't think of a way to avoid this :(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T11:23:20.577", "Id": "7206", "Score": "0", "body": "Oh silly me, I didn't notice/think of just using a downcast since I know it's safe here!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T07:11:24.743", "Id": "4807", "ParentId": "4806", "Score": "5" } } ]
{ "AcceptedAnswerId": "4807", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T01:13:32.067", "Id": "4806", "Score": "4", "Tags": [ "c++", "c++11", "cache" ], "Title": "An LRU cache template" }
4806
<p>I am making an Address Book like application . <br> I have a contactType enum.</p> <pre><code>public enum ContactType { //just a cut down version MOBILE,PHONE,FAX,EMAIL; } </code></pre> <p>Then I have a Contact class </p> <pre><code>public class Contact { private ContactType contactType; private String value;//e.g phone number or email private String areaCode;//does not apply to email or mobile //....getters and setters } </code></pre> <p>Then I have a Person class</p> <pre><code>public class Person { private List&lt;Contact&gt;contacts; //----Other attributes and getters and setters } </code></pre> <p>I thought I have nailed very well :) but as it turns out probably not:( Because<br></p> <p>I now needs to display a list of people(list of person) and in the table along with some other things (name etc)I have these columns:<br></p> <pre><code>Name|......|Phone|Mobile|Fax |Email </code></pre> <p>I now realised that I can not just loop through the list of people and display contact numbers since these contacts are in list inside every object in list of people.<br> In simple words as you might know by now already if I have a list of people e.g<br></p> <pre><code>List&lt;Person&gt;people ; </code></pre> <p>Then this is not a valid option</p> <pre><code>for(Person person: people) { //can not get phone number for example by going person.getPhone(); } </code></pre> <p>but this is</p> <pre><code>for(Person person: people) { //but will have to get it from the list of contacts e.g List&lt;Contact&gt;contacts = person.getContacts(); for(Contact contact:Contacts) { if (contact.getContactType.isPhone()) { contact.getValue(); } } } </code></pre> <p>So I have now introduced a Rowitem Class</p> <pre><code> public class Rowitem { private String phone; private String fax; private String mobile; private String email; .... } </code></pre> <p>and populating is like this</p> <pre><code>private void populateForDisplay(Rowitem item,List&lt;Contact&gt; contacts) { for (Contact contact : contacts) { if (contact.getType().isEmail()) { item.setEmail(contact.getValue()); } if (contact.getType().isFax()) { item.setFax(contact.getValue()); } if (contact.getType().isMobile()) { item.setMobile(contact.getValue()); } if (contact.getType().isPhone()) { item.setPhone(contact.getValue()); } } } </code></pre> <p>While this approach works I just do not think it is right. Firstly I do not like the fact that I have to introduce this RowItem class and then all these if statements do not look right. How can I improve this?<br> The front end framework that I am using is JSF2 but probably not relevant here. <br><br> I need someone to review my approach rather than line by line code.<br>I have read <a href="https://codereview.stackexchange.com/faq">https://codereview.stackexchange.com/faq</a> and I think my question is with the rules if not then please guide me and I will move this.<br>Because not code problem I did not think will go to StackOverFlow<br></p>
[]
[ { "body": "<p>At first I would suggest to get rid of the contact type enumeration and instead derive concrete contacts from your contact class. This will increase cohesion dramatically as this way you do not need to have fields like area code in your base contact class. </p>\n\n<p>Regarding your problem: You could use something like a <a href=\"http://en.wikipedia.org/wiki/Visitor_pattern\" rel=\"nofollow\">visitor pattern</a> to navigate the \"tree\" of data (Persons -> Person -> Contacts) with your Person and Contact acting as elements accepting the abstract visitor. This will give you the flexibility to walk the tree for different purposes. For your scenario you could write something like a TableVisitor that creates the table structure you want to generate.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T11:56:45.643", "Id": "7207", "Score": "0", "body": "+1 excellent answer. Depending on the context the visitor pattern might be overkill, though." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T10:16:06.100", "Id": "4813", "ParentId": "4811", "Score": "3" } }, { "body": "<p>If your data structure for storing a contact's value is simply a <code>String</code>, this code should help :-</p>\n\n<pre><code>public class Person {\n\n private Map&lt;ContactType, String&gt; contactMap;\n\n public Person() {\n contactMap = new HashMap&lt;ContactType, String&gt;();\n }\n\n public void addContact(ContactType type, String value) {\n contactMap.put(type, value);\n }\n\n public String getContact(ContactType type) {\n return contactMap.get(type);\n }\n}\n</code></pre>\n\n<p>Adding a new <code>ContactType</code> won't change the above code. Simply add the new type in enum <code>ContactType</code>.</p>\n\n<p>Iterating part is cleaner now. You can easily iterate over a <code>Person</code>'s contact using enums as the key. </p>\n\n<pre><code>ContactType[] contactTypes=ContactType.values();\nfor (Person p : personList) {\n // get other Person fields.\n for(ContactType t:contactTypes){\n p.getContact(t);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T17:39:09.337", "Id": "4823", "ParentId": "4811", "Score": "2" } } ]
{ "AcceptedAnswerId": "4813", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T09:48:37.290", "Id": "4811", "Score": "2", "Tags": [ "java", "object-oriented" ], "Title": "How can I improve this code to display contact numbers?" }
4811
<p>Here is my standard .htaccess file, any suggestions on how I can improve it with regards to page load speed? Would gZip instead of DEFLATE make any sort of difference?</p> <pre><code>ExpiresActive On RewriteEngine on RewriteBase / # compress text, html, javascript, css, xml: AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/javascript AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/xml AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/x-javascript # Expires 1 month after file is first accessed ExpiresByType image/jpeg A2592000 ExpiresByType image/jpg A2592000 ExpiresByType image/gif A2592000 ExpiresByType image/png A2592000 ExpiresByType image/x-icon A2592000 ExpiresByType text/plain A2592000 # Expires 1 month after file is modified ExpiresByType application/x-javascript M2592000 ExpiresByType text/css M2592000 ExpiresByType text/javascript M2592000 ExpiresByType text/html M2592000 </code></pre>
[]
[ { "body": "<p>Honestly, this looks OK, though you could clean it up a little bit. </p>\n\n<p>You have two ways to make this code better: </p>\n\n<ol>\n<li>group related mime types.</li>\n<li>use human-readable syntax</li>\n</ol>\n\n<p>Regarding point #2, here's part of the config I created after watching Illya Grigorik's presentation \"<a href=\"http://www.youtube.com/watch?v=Il4swGfTOSM\" rel=\"nofollow\">Breaking the 1000ms Time to Glass Mobile Barrier</a>\":</p>\n\n<pre><code>&lt;IfModule mod_deflate.c&gt;\n# these are known to be safe with MSIE 6\nAddOutputFilterByType DEFLATE text/html text/plain text/xml\n\n# everything else may cause problems with MSIE 6\nAddOutputFilterByType DEFLATE text/css\nAddOutputFilterByType DEFLATE application/x-javascript application/javascript application/ecmascript\nAddOutputFilterByType DEFLATE application/rss+xml\n\nExpiresActive On\nExpiresDefault \"access plus 15 minutes\"\n\nExpiresByType text/html \"access\"\nExpiresByType application/json \"access\"\n\nExpiresByType text/css \"access plus 1 week\"\nExpiresByType image/gif \"access plus 1 week\"\nExpiresByType image/png \"access plus 1 week\"\nExpiresByType image/jpeg \"access plus 1 week\"\nExpiresByType application/javascript \"access plus 1 week\"\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>You might also look into <a href=\"https://developers.google.com/speed/pagespeed/mod\" rel=\"nofollow\">Google's mod_pagespeed for Apache</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-15T08:05:49.743", "Id": "40537", "Score": "1", "body": "Hello John, and welcome to Code Review! I've stumbled upon (and upvoted) a few of your answers since yesterday, and they're usually very good! It's always great to see [new active members](http://codereview.stackexchange.com/users?tab=newusers) :). However, please avoid just posting a random dump of yours that seems related. In this case, you could simply have said \"You have two ways to make this code better: 1/ group related mime types 2/ use this human-readable syntax\". I believe such an answer would have been even more helpful than the current one. And again, thank you for your answers!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-15T03:14:31.767", "Id": "26189", "ParentId": "4812", "Score": "3" } }, { "body": "<p>You can improve this code by removing unnecessary repetition. If you put a trailing slash after each declaration, then you do not need to repeat the same code over and over again. I would also suggest wrapping all the similar statements inside of <code>IfModule</code> checks: it only takes the server a fraction of a second, maybe less, to check if a module is installed; if it is not, it will skip straight past that section of the code. </p>\n\n<pre><code>ExpiresActive On\nRewriteEngine on\nRewriteBase /\n\n&lt;IfModule mod_deflate.c&gt;\n# compress text, html, javascript, css, xml:\n &lt;IfModule mod_filter.c&gt;\n AddOutputFilterByType DEFLATE text/plain \\\n DEFLATE text/javascript \\\n DEFLATE text/html \\\n DEFLATE text/xml \\\n DEFLATE text/css \\\n DEFLATE application/xml \\\n DEFLATE application/xhtml+xml \\\n DEFLATE application/rss+xml \\\n DEFLATE application/javascript \\\n DEFLATE application/x-javascript \n &lt;/IfModule&gt;\n&lt;/IfModule&gt;\n\n&lt;IfModule mod_expires.c&gt;\n # Expires 1 month after file is first accessed\n ExpiresByType image/jpeg A2592000 \\\n image/jpg A2592000 \\\n image/gif A2592000 \\\n image/png A2592000 \\\n image/x-icon A2592000 \\\n text/plain A2592000 \\\n\n # Expires 1 month after file is modified\n ExpiresByType application/x-javascript M2592000 \\\n text/css M2592000 \\\n text/javascript M2592000 \\\n text/html M2592000 \\\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>There honestly wouldn't be a noticeable difference between GZip &amp; DEFLATE: the only difference is that GZip uses a checksum, header &amp; footer which are also included. Hence a tiny bit slower, but more reliable and secure. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T21:00:19.270", "Id": "237456", "ParentId": "4812", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T10:02:13.490", "Id": "4812", "Score": "6", "Tags": [ "optimization", ".htaccess" ], "Title": "Suggestions on how to improve this .htaccess file for page load speed" }
4812
<p>I am trying to create a function similar to Excel's <a href="http://office.microsoft.com/en-us/excel-help/eomonth-HP005209076.aspx" rel="nofollow"><code>EOMONTH</code></a> function in C#. I have written the following, however, I am not entirely sure if the it achieves the equivalent functionality. Is my equivalent of Excel's "Eomonth" function correct and are my tests sufficient?</p> <pre><code>public static DateTime EOMonth(this DateTime dateTime, int months = 0) { DateTime firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1); return firstDayOfTheMonth.AddMonths(1 + months).AddDays(-1); } </code></pre> <p><strong>Tests</strong></p> <pre><code>[Test] public void EOMonth_For5jan2011WithNoAddedMonths_ReturnsLastDayOfJan() { var expectedDate = DateTime.Parse("31-Jan-2011"); var currentDate = DateTime.Parse("5-Jan-2011"); var result = currentDate.EOMonth(); Assert.That(result, Is.EqualTo(expectedDate)); } [Test] public void EOMonth_For5jan2011With_1_AddedMonths_ReturnsLastDayOfFeb2011() { var expectedDate = DateTime.Parse("28-Feb-2011"); var currentDate = DateTime.Parse("5-Jan-2011"); var result = currentDate.EOMonth(1); Assert.That(result, Is.EqualTo(expectedDate)); } [Test] public void EOMonth_For5jan2011WithNegative_1_AddedMonths_ReturnsLastDayOfFeb() { var expectedDate = DateTime.Parse("31-Dec-2010"); var currentDate = DateTime.Parse("5-Jan-2011"); var result = currentDate.EOMonth(-1); Assert.That(result, Is.EqualTo(expectedDate)); } [Test] public void EOMonth_For28Feb2007_12_AddedMonths_ReturnsLastDayOfFeb2008() { var expectedDate = DateTime.Parse("29-Feb-2008"); var currentDate = DateTime.Parse("28-Feb-2007"); var result = currentDate.EOMonth(12); Assert.That(result, Is.EqualTo(expectedDate)); } </code></pre>
[]
[ { "body": "<p>For your implementation, why not use:</p>\n\n<pre><code>return ((new DateTime(dateTime.Year, dateTime.Month, 1)).AddMonths(1 + months).AddDays(-1));\n</code></pre>\n\n<p>To me, that's a little cleaner, but it might just be me. When I'm just creating an object to be returned, I'm not a fan of storing it in a variable. Instead, just return exactly what you mean to and be done with it.</p>\n\n<hr>\n\n<p>For your test cases:</p>\n\n<p>I'm not sure that it matters in this instance, since you are relying exclusively on built in methods, but I would create test cases around February and March for the various types of leap years. What if I specify February 29th on a non-leap year? Does it work for the different leap year conditions? I'd also create test cases around new years (December and January).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T13:20:56.047", "Id": "4815", "ParentId": "4814", "Score": "1" } }, { "body": "<p>Thomas Owens has covered most points, but I would like to add that you should use <code>var</code>when you are declaring a local variable and the right-hand side of the declaration makes the type obvious, so:</p>\n\n<pre><code>DateTime firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1);\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>var firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1);\n</code></pre>\n\n<p>The reason to do this is that if you decide to change the type of the variable later, you only have to do it in one place, and it simplifies the code a little for a new reader.</p>\n\n<p>You actually do this in your tests, which is good, but highlights the importance of <em>consistency</em>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-02T16:00:05.967", "Id": "71421", "ParentId": "4814", "Score": "0" } }, { "body": "<p>Some general observations:</p>\n\n<ul>\n<li>Your tests are locale dependent, <code>DateTime.Parse(\"31-Jan-2011\")</code> will not work on every locale. I'd use <code>new DateTime(2011, 01, 31)</code> instead, but you could also specify a specific culture when parsing.</li>\n<li>You never test the case where the input has a time part.</li>\n<li>Your code won't work for December 9999, but I assume you can live with that.</li>\n<li>The result always has <code>Kind = DateTimeKind.Unspecified</code> regardless of the <code>Kind</code> of the input. You should document your guarantees regarding <code>Kind</code> and perhaps add a test.</li>\n</ul>\n\n<p>An important design question is if you want to provide functionality similar to <code>EOMONTH</code> but following C# and .NET conventions, or if you want it to be identical to Excel.</p>\n\n<ul>\n<li><p>If you want to be identical to Excel, keep it like it is, but put it in a class and/or namespace that contains the word <code>Excel</code>.</p></li>\n<li><p>If you want to adapt it to C#, you should rename it to <code>EndOfMonth</code>. I'd also drop the <code>month</code> parameter overload in that case, in favour of the caller using <code>x.AddMonths(month).EndOfMonth()</code> since I consider adding months and finding the end of the month different concerns that shouldn't be mixed within a function.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-03T11:44:51.850", "Id": "71494", "ParentId": "4814", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T10:31:55.470", "Id": "4814", "Score": "1", "Tags": [ "c#", "unit-testing", "datetime" ], "Title": "Is my equivalent of Excel's \"EOMONTH\" function correct?" }
4814
<p>I have two text boxes and one combobox. I am retrieving the data based upon the text entered into the text boxes and combobox selection, by using the following method:</p> <pre><code> private void textboxfillnames() { if (txtlastname.Text != "") { var totalmembers = from tsgentity in eclipse.members join memtomships in eclipse.membertomships on tsgentity.member_Id equals memtomships.member_Id join mshipoptiions in eclipse.mshipoptions on memtomships.mshipOption_Id equals mshipoptiions.mshipOption_Id join mshiptypes in eclipse.mshiptypes on mshipoptiions.mshipType_Id equals mshiptypes.mshipType_Id join mshipstatus in eclipse.mshipstatustypes on memtomships.mshipStatusType_Id equals mshipstatus.mshipStatusType_Id where tsgentity.member_Lastname.StartsWith(txtlastname.Text) select new { tsgentity.member_Id, tsgentity.member_Lastname, tsgentity.member_Firstname, tsgentity.member_Postcode, tsgentity.member_Reference, tsgentity.member_CardNum, tsgentity.member_IsBiometric, tsgentity.member_Dob, mshiptypes.mshipType_Name, mshipstatus.mshipStatusType_Name, memtomships.memberToMship_EndDate }; dgvReportMembers.DataSource = totalmembers; } if (txtpostcode.Text != "") { var totalmembers = from tsgentity in eclipse.members join memtomships in eclipse.membertomships on tsgentity.member_Id equals memtomships.member_Id join mshipoptiions in eclipse.mshipoptions on memtomships.mshipOption_Id equals mshipoptiions.mshipOption_Id join mshiptypes in eclipse.mshiptypes on mshipoptiions.mshipType_Id equals mshiptypes.mshipType_Id join mshipstatus in eclipse.mshipstatustypes on memtomships.mshipStatusType_Id equals mshipstatus.mshipStatusType_Id where tsgentity.member_Postcode.StartsWith(txtpostcode.Text) select new { tsgentity.member_Id, tsgentity.member_Lastname, tsgentity.member_Firstname, tsgentity.member_Postcode, tsgentity.member_Reference, tsgentity.member_CardNum, tsgentity.member_IsBiometric, tsgentity.member_Dob, mshiptypes.mshipType_Name, mshipstatus.mshipStatusType_Name, memtomships.memberToMship_EndDate }; dgvReportMembers.DataSource = totalmembers; } if (cbGEStatustype.Text != null) { var totalmembers = from tsgentity in eclipse.members join memtomships in eclipse.membertomships on tsgentity.member_Id equals memtomships.member_Id join mshipoptiions in eclipse.mshipoptions on memtomships.mshipOption_Id equals mshipoptiions.mshipOption_Id join mshiptypes in eclipse.mshiptypes on mshipoptiions.mshipType_Id equals mshiptypes.mshipType_Id join mshipstatus in eclipse.mshipstatustypes on memtomships.mshipStatusType_Id equals mshipstatus.mshipStatusType_Id where mshipstatus.mshipStatusType_Name.StartsWith(cbGEStatustype.Text) select new { tsgentity.member_Id, tsgentity.member_Lastname, tsgentity.member_Firstname, tsgentity.member_Postcode, tsgentity.member_Reference, tsgentity.member_CardNum, tsgentity.member_IsBiometric, tsgentity.member_Dob, mshiptypes.mshipType_Name, mshipstatus.mshipStatusType_Name, memtomships.memberToMship_EndDate }; dgvReportMembers.DataSource = totalmembers; } } </code></pre>
[]
[ { "body": "<p>You should wrap each query into a function that takes in a string and returns your query result. You should not make direct reference to GUI objects in your business logic as you have done.</p>\n\n<p>You should have a controller negotiating the transfer of data between your model (eclipse.members) and your view (the various text and combo boxes you are populating).</p>\n\n<p>EDIT:</p>\n\n<p>I'm not sure what your level of knowledge is, but if all that went over your head let me know and I'll post a small example later today. ;)</p>\n\n<p>Promised Sample Code:</p>\n\n<p>To learn more about why I have structured the code like this, do some searching for Model View Presenter. The Presenter in this sample is the controller I referred to above. </p>\n\n<p>NOTE: You shouldn't name classes and interfaces like this in real life, but I've done it to emphasize which part of the MVP pattern I am implementing.</p>\n\n<p>NOTE: These are not fully defined classes or interfaces. I've only shown the relevant parts to your question.</p>\n\n<pre><code>//\n// Presenter\n//\npublic class Presenter\n{\n private IView _view;\n private IModel _model;\n\n public void FindAndDisplayMemberList\n {\n // I have made a few assumptions here. \n // First, I wasn't sure what dgvReportMembers was. I assumed that it was some\n // sort of view object being used to display the results on a form.\n //\n // Second, I noticed you were assigning it three times. I've assumed that\n // you really only want to assign it once. Therefore once this function finds\n // a valid field, it returns.\n //\n // Finally, the large amount of very similar code here should suggest that you\n // need to rethink your structure. But without more knowledge of what you are\n // building I can't give you much help with that.\n\n string lastName = _view.LastName;\n if (!String.IsNullOrEmpty(lastName))\n {\n var data = _model.GetMemberListFromLastName(lastName);\n _view.SetReportMembersDataSource(data);\n\n return;\n }\n\n string postalCode = _view.PostalCode;\n if (!String.IsNullOrEmpty(postalCode))\n {\n var data = _model.GetMemberListFromPostalCode(postalCode);\n _view.SetReportMembersDataSource(data);\n\n return;\n }\n\n string geStatus = _view.SelectedGeStatus;\n if (!String.IsNullOrEmpty(geStatus))\n {\n var data = _model.GetMemberListFromGeStatus(geStatus);\n _view.SetReportMembersDataSource(data);\n\n return;\n }\n }\n}\n\n\n//\n// View Interface - Your form that displays the relevant data should implement this.\n//\npublic interface IView\n{\n string LastName { get; set; }\n string PostalCode { get; set; }\n string SelectedGeStatus { get; }\n\n void SetReportMembersDataSource(object source);\n}\n\n//\n// Model Interface - Controller uses this to access the database. \n// Your model should not know anything about the\n// presenter or the view.\n//\npublic interface IModel\n{\n //\n // NOTE: MemberInfo is a class that should hold all of the fields you\n // you are selecting in the query. (Id, LastName, etc.)\n //\n List&lt;MemberInfo&gt; GetMemberListFromLastName(string lastName);\n List&lt;MemberInfo&gt; GetMemberListFromPostalCode(string postalCode);\n List&lt;MemberInfo&gt; GetMemberListFromGeStatus(string geStatus);\n}\n</code></pre>\n\n<p>There are a few improvements to note in this code.</p>\n\n<p>First code related to the view and the model is isolated.</p>\n\n<p>Second, the Presenter works with interfaces, so it never needs to know what the actual model or view object is.</p>\n\n<p>Third, in the view interface, I don't expose the actual GUI controls being used to display data. I use common types such as string to pass data back and forth, and let the view worry about displaying that with an appropriate GUI object.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T15:49:38.173", "Id": "7210", "Score": "0", "body": "Plus those queries can be compiled!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T20:10:37.513", "Id": "7217", "Score": "0", "body": "@errorcode105: I did see the joins. Those can be wrapped into the functions I suggested as well. I used the term 'query' to mean your entire request starting with `from`. (I'm not a SQL expert however so I won't presume to comment on how you could improve that portion of your code.) And yes, I'll put up some example code a little later tonight." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T15:46:52.887", "Id": "4820", "ParentId": "4817", "Score": "3" } }, { "body": "<p>I generaly don't use LINQ all that much because most of the time, it's not as performant. I use views instead (Database views, not to be mistaken with views from the previous answer ;D) which are created manually, instead of dynamicly at runtime (=LINQ).</p>\n\n<p>In this situation I'm sure it doesn't matter all that much, seeing how you're using \"Select new {...});\", which in my experience, means that the queries remain relatively \"clean\".</p>\n\n<p>If you're however using a lot of \"Contains()\" or other LINQ-commands, LINQ has a hard time creating a good query. If you use an SQL profiler (a tool, I like to use anjlab's) you can check which query gets sent to the database (really good way to see if you should write a query yourself or not).</p>\n\n<p>If you're using Entity Framework you can insert the view into your model, and call it like it's a tabel (from member in objectContext.vwblalbah select member), you can also still use WHERE statements on it if you'd please (where member.memberID == ID)...</p>\n\n<p>If you don't like writing views in your database, you can also pre-generate queries, so that LINQ doesn't have to dynamicly create it. I think (don't know for sure though) that views are still faster.</p>\n\n<p>I hope this helped</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-10T00:28:04.547", "Id": "32608", "Score": "0", "body": "Never forget to mention table valued functions (parametized views)! ; )" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T19:16:26.527", "Id": "4854", "ParentId": "4817", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T14:32:37.147", "Id": "4817", "Score": "5", "Tags": [ "c#", ".net", "linq", "winforms" ], "Title": "Retrieving data based upon text entered in a textbox" }
4817
<p>I am writing a JavaScript feature where by I need to make a call to a third-party library (pre-1.10 DataTables) depending upon whether or not the user provides an integer as an input to the function during initialization. I am pasting here the snippet. As you can see it has duplicate code in the if/else clauses, the only difference is the method signature for <code>*.fnFilter</code>. </p> <p>How can I optimize this code further? Also I dont want to test the condition during each key-up.</p> <pre><code>/* * By default this is a global search box events. Global being searchable across all columns. * But if an int is provided as an input then it will apply the search only on that column. * */ _bindSearchEvents: function(onColumnIndex) { var self = this; if (Math.ceil(onColumnIndex) === Math.floor(onColumnIndex)) { self.settings.search.input.live('keyup', function() { self.widget.fnFilter($(this).val(), onColumnIndex); }); self.settings.search.reset.live('click', function() { self.settings.search.input.val(""); self.widget.fnFilter("", onColumnIndex); }); } else { self.settings.search.input.live('keyup', function() { self.widget.fnFilter($(this).val()); }); self.settings.search.reset.live('click', function() { self.settings.search.input.val(""); self.widget.fnFilter(""); }); } }, </code></pre>
[]
[ { "body": "<p>Since all that is different about the two if/else bodies is the arguments to the fnFilter method, you can construct the difference in one if statement and then use that in one copy of the code rather than two.</p>\n\n<pre><code>/*\n * By default this is a global search box events. Global being searchable across all columns.\n * But if an int is provided as an input then it will apply the search only on that column.\n * */\n_bindSearchEvents: function (onColumnIndex) {\n\n var self = this;\n var args = [];\n if (Math.ceil(onColumnIndex) === Math.floor(onColumnIndex)) {\n args.push(onColumnIndex);\n }\n self.settings.search.input.live('keyup', function () {\n var argsCopy = [].concat(args); // make copy of args\n argsCopy.unshift($(this).val()); // push item onto front of args\n self.widget.fnFilter.apply(self.widget, argsCopy);\n });\n\n self.settings.search.reset.live('click', function () {\n self.settings.search.input.val(\"\");\n var argsCopy = [].concat(args);\n argsCopy.unshift(\"\"); // push item onto front of args\n self.widget.fnFilter.apply(self.widget, argsCopy);\n });\n},\n</code></pre>\n\n<p>If the fnFilter function is written to check to see if the second parameter is null (rather than checking the number of arguments passed), then this shorter version could work also, but we'd have to see what the fnFilter documentation says or how the fnFilter source code actually works to know if this shorter method would work:</p>\n\n<pre><code>/*\n * By default this is a global search box events. Global being searchable across all columns.\n * But if an int is provided as an input then it will apply the search only on that column.\n * */\n_bindSearchEvents: function (onColumnIndex) {\n\n var self = this;\n var index = null;\n if (Math.ceil(onColumnIndex) === Math.floor(onColumnIndex)) {\n index = onColumnIndex;\n }\n self.settings.search.input.live('keyup', function () {\n self.widget.fnFilter($(this).val(), index);\n });\n\n self.settings.search.reset.live('click', function () {\n self.settings.search.input.val(\"\");\n self.widget.fnFilter(\"\", index);\n });\n},\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T15:30:30.857", "Id": "4819", "ParentId": "4818", "Score": "3" } }, { "body": "<p>Based on <a href=\"http://legacy.datatables.net/api\" rel=\"nofollow\">http://legacy.datatables.net/api</a> definition, the default integer value for .fnfilter(int) is null. It is recommended to set it to null rather than let it be undefined.</p>\n\n<pre><code>/*\n * By default this is a global search box events. Global being searchable across all columns.\n * But if an int is provided as an input then it will apply the search only on that column.\n * */\n_bindSearchEvents: function (onColumnIndex) {\n\n var index = null; // defaults to undefined\n if (Math.ceil(onColumnIndex) === Math.floor(onColumnIndex)) {\n index = onColumnIndex;\n }\n\n var searchInput = this.setting.search.input;\n var searchReset = this.setting.search.reset;\n var fnFilter = this.setting.widget.fnFilter;\n searchInput.live('keyup', function () {\n fnFilter($(this).val(), index);\n });\n\n searchReset.live('click', function () {\n searchInput.val(\"\");\n fnFilter(\"\", index);\n });\n},\n</code></pre>\n\n<p>I use searchInput, searchReset, fnfilter to avoid repeat call to 'multi-layer functions' such as this.setting.search. This provide two benefits: \ni) More efficient in access input, reset and fnFilter. This could be a huge plus if the _bindSearchEvents is accessed multiple time.\nii) Provide more readable code. This could be my own personal taste.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T17:24:04.770", "Id": "4822", "ParentId": "4818", "Score": "2" } } ]
{ "AcceptedAnswerId": "4822", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T14:41:26.750", "Id": "4818", "Score": "1", "Tags": [ "javascript", "event-handling", "jquery-datatables" ], "Title": "DataTables search filter handler" }
4818
<p>I'm still fairly new with JavaScript, and wrote something to generate some social media links on my page. The idea was to have that script grab the necessary URL info and feed it to the social media APIs.</p> <pre><code>&lt;script type="text/javascript"&gt; // print links titleElement = urlencode(document.title); linkElement = urlencode(location.href); document.write ("&lt;a href='http://facebook.com/sharer.php?u=" + linkElement + "&amp;t=" + titleElement + "' target='_blank'&gt;&lt;img src='socialMedia/social_facebook.png' border='0' class='png tip' title='Facebook :: Post on your wall!' alt='Facebook' /&gt;&lt;/a&gt;"); document.write ("&lt;a href='http://stumbleupon.com/submit?url=" + location.href + "&amp;title=" + titleElement + "' target='_blank'&gt;&lt;img src='socialMedia/social_stumbleupon.png' border='0' class='png tip' title='Stumbleupon :: Share this page!' alt='Stumbleupon' /&gt;&lt;/a&gt;"); document.write ("&lt;a href='http://twitter.com/?status=" + titleElement + "%20-%20" + linkElement + "' target='_blank'&gt;&lt;img src='socialMedia/social_twitter.png' border='0' class='png tip' title='Twitter :: Tweet this page!' alt='Twitter' /&gt;&lt;/a&gt;"); document.write ("&lt;a href='http://digg.com/submit?phase=2&amp;url=" + linkElement + "' target='_blank'&gt;&lt;img src='socialMedia/social_digg.png' border='0' class='png tip' title='Digg :: Digg this page!' alt='Digg' /&gt;&lt;/a&gt;"); document.write ("&lt;a href='http://del.icio.us/post?url=" + linkElement + "&amp;title=" + titleElement + "' target='_blank'&gt;&lt;img src='socialMedia/social_delicious.png' border='0' class='png tip' title='Del.icio.us :: Bookmark this page!' alt='Del.icio.us' /&gt;&lt;/a&gt;"); &lt;/script&gt; </code></pre>
[]
[ { "body": "<p>I suppose a more valid and improved way is to put the JavaScript into an external file</p>\n\n<pre><code>&lt;script type=\"text/javascript\" src=\"path/to/script\"&gt;&lt;/script&gt;\n</code></pre>\n\n<p>rather than putting it inline into a html. In the same html have a <code>span</code> tag with an id</p>\n\n<pre><code>&lt;span id=\"social-links\"&gt;&lt;/span&gt;\n</code></pre>\n\n<p>Then in the script itself</p>\n\n<pre><code>var tags = \"\",\n titleLink = urlencode(document.title);,\n linkElement = urlencode(location.href);\n\ntitleElement = urlencode(document.title);\nlinkElement = urlencode(location.href);\n\n// String optimisation, which is really good for IE\ntags = tags + \"&lt;a href='http://facebook.com/sharer.php?u=\" + linkElement + \"&amp;t=\" + titleElement + \"' target='_blank'&gt;&lt;img src='socialMedia/social_facebook.png' border='0' class='png tip' title='Facebook :: Post on your wall!' alt='Facebook' /&gt;&lt;/a&gt;\";\ntags = tags + \"&lt;a href='http://stumbleupon.com/submit?url=\" + location.href + \"&amp;title=\" + titleElement + \"' target='_blank'&gt;&lt;img src='socialMedia/social_stumbleupon.png' border='0' class='png tip' title='Stumbleupon :: Share this page!' alt='Stumbleupon' /&gt;&lt;/a&gt;\";\ntags = tags + \"&lt;a href='http://twitter.com/?status=\" + titleElement + \"%20-%20\" + linkElement + \"' target='_blank'&gt;&lt;img src='socialMedia/social_twitter.png' border='0' class='png tip' title='Twitter :: Tweet this page!' alt='Twitter' /&gt;&lt;/a&gt;\";\ntags = tags + \"&lt;a href='http://digg.com/submit?phase=2&amp;url=\" + linkElement + \"' target='_blank'&gt;&lt;img src='socialMedia/social_digg.png' border='0' class='png tip' title='Digg :: Digg this page!' alt='Digg' /&gt;&lt;/a&gt;\";\ntags = tags + \"&lt;a href='http://del.icio.us/post?url=\" + linkElement + \"&amp;title=\" + titleElement + \"' target='_blank'&gt;&lt;img src='socialMedia/social_delicious.png' border='0' class='png tip' title='Del.icio.us :: Bookmark this page!' alt='Del.icio.us' /&gt;&lt;/a&gt;\";\n\ndocument.getElementById('social-links').innerHTML = tags;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T11:20:55.183", "Id": "4838", "ParentId": "4825", "Score": "1" } }, { "body": "<p>Use the <code>var</code> keyword to declare <code>titleElement</code> and <code>linkElement</code> in this scope, otherwise they will always be global variables and you'll have no choice about it.</p>\n\n<p>Using <code>var</code> will still put them in the global scope until you wrap this logic in a <em>closure</em>:</p>\n\n<pre><code>(function() {\n // var titleLink...\n})();\n</code></pre>\n\n<p>You should still take the advice of @NebulaFox - don't use <code>document.write</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-14T20:31:12.770", "Id": "113962", "ParentId": "4825", "Score": "2" } } ]
{ "AcceptedAnswerId": "4838", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T20:49:22.847", "Id": "4825", "Score": "3", "Tags": [ "javascript", "html", "api" ], "Title": "Generated social media links" }
4825
<p>I'm working with an XML structure that requires booleans to be represented as 1 or 0. </p> <p>So, suppose the XML output has to look like:</p> <pre><code>&lt;valid&gt;1&lt;/valid&gt; </code></pre> <p>Several nodes can be represented this way, so I made a struct to handle this. The solution I found works, but lacks <em>oomph</em>. OK, no, it doesn't just lack <em>oomph</em>, it <strong>sucks</strong>.</p> <p>(Implemented in .NET 4)</p> <pre><code>public struct MyCrappyBool : IXmlSerializable { private int _IntValue; private bool _BoolValue; public int IntValue { get { return _IntValue; } set { if (value &lt; 0 || value &gt; 1) throw new ArgumentOutOfRangeException(); _IntValue = value; _BoolValue = value == 1; } } public bool BoolValue { get { return _BoolValue; } set { _BoolValue = value; _IntValue = value ? 1 : 0; } } public MyCrappyBool(int intValue) : this() { IntValue = intValue; } public MyCrappyBool(bool boolValue): this() { BoolValue = boolValue; } #region IXmlSerializable Members public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { IntValue = int.Parse(reader.ReadString()); } public void WriteXml(XmlWriter writer) { writer.WriteString(IntValue.ToString()); } #endregion } </code></pre> <p>This is incredibly tedious, first and foremost because I need to instantiate every time:</p> <pre><code>MyCrappyBool isValid = new MyCrappyBool(true); </code></pre> <p>But even then, some nifty implicit overloading can address that:</p> <pre><code> public static implicit operator MyCrappyBool(bool boolValue) { return new MyCrappyBool(boolValue); } public static implicit operator MyCrappyBool(int intValue) { return new MyCrappyBool(intValue); } </code></pre> <p>That's still a lot of code for one... crappy boolean.</p> <p>Later, it can be (XML) serialized as part of any other class:</p> <pre><code>[XmlElement("valid")] public MyCrappyBool IsValid { get; set; } [XmlElement("active")] public MyCrappyBool IsActive { get; set; } </code></pre> <p>Is there a simpler way about this I'm not seeing?</p> <hr> <p>Update: Reverse implicit operator overloading!</p> <pre><code> public static implicit operator bool(MyCrappyBool myCrappyBool) { return myCrappyBool.BoolValue; } public static implicit operator int(MyCrappyBool myCrappyBool) { return myCrappyBool.IntValue; } </code></pre> <p>This means all my properties can be private.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T02:23:57.720", "Id": "7219", "Score": "0", "body": "Do you need the IntValue property? Could you get away with just having a bool Value property and do the appropiate read and writes in the serialization. Not much different but does away with the Int and Bool unless they are both required for some reason?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T02:28:39.490", "Id": "7220", "Score": "0", "body": "It's used in the constructor that receives a boolean and in ReadXml. I'd still need its code, I think. I *could* make it private, though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T03:25:33.737", "Id": "7221", "Score": "1", "body": "+1000 Ha, I was just wanting to do the exact review implicit operator overload in some code. Brilliant timing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T15:16:23.367", "Id": "7300", "Score": "0", "body": "Linking to [your related SO question](http://stackoverflow.com/questions/7455497/how-to-manage-xml-serialization-exceptions-for-enum)" } ]
[ { "body": "<p>Here's a possible answer although I'm not sure it goes far enough for you</p>\n\n<pre><code>public struct MyCrappyBool : IXmlSerializable\n{\npublic bool Value\n{\n get; private set;\n}\n\npublic MyCrappyBool(object v)\n{\n bool value = false;\n\n if(Boolean.TryParse(v, out value))\n Value = value;\n else\n throw new ArgumentException(\"Parameter not a valid boolean value\");\n}\n\n#region IXmlSerializable Members\npublic XmlSchema GetSchema() { return null; }\npublic void ReadXml(XmlReader reader)\n{\n Value = int.Parse(reader.ReadString()) == 1;\n}\npublic void WriteXml(XmlWriter writer)\n{\n writer.WriteString(Value ? \"1\" : \"0\");\n}\n#endregion\n}\n</code></pre>\n\n<p>I would constrain the type of the element in the xml by specifying it's allowed values in the XSD definition. Otherwise I'd just have another SetBoolean(int) method that through the exception if the int value was not 0.</p>\n\n<p>I'm sure there are other ways. I'm not sure if the System.Xml.Serialization.XmlElementAttribute attribute would already do this for you but may be worth looking into.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T03:26:11.783", "Id": "7222", "Score": "0", "body": "That makes me realize I could also have an overload of ToString. My oh my, does it ever end?!?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T03:55:19.957", "Id": "7223", "Score": "0", "body": "Changed to only one constructor. Might help make it end :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T03:58:08.690", "Id": "7225", "Score": "0", "body": "I don't know about that last change. I have to sleep on it." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T03:13:33.350", "Id": "4830", "ParentId": "4829", "Score": "1" } }, { "body": "<p>Based on dreza's ideas, I now have: (and somehow I see this better as an answer than an edit on the question):</p>\n\n<pre><code>public struct MyCrappyBool : IXmlSerializable\n{\n private bool Value;\n\n public MyCrappyBool(int intValue) : this(intValue == 1)\n { }\n public MyCrappyBool(bool boolValue) : this()\n {\n Value = boolValue;\n }\n\n public override string ToString()\n {\n //return ((int)this).ToString();\n return Value ? \"1\" : \"0\";\n }\n\n public static implicit operator MyCrappyBool(bool boolValue)\n {\n return new MyCrappyBool(boolValue);\n }\n public static implicit operator MyCrappyBool(int intValue)\n {\n return new MyCrappyBool(intValue);\n }\n public static implicit operator bool(MyCrappyBool myCrappyBool)\n {\n return myCrappyBool.Value;\n }\n public static implicit operator int(MyCrappyBool myCrappyBool)\n {\n return myCrappyBool ? 1 : 0;\n }\n\n #region IXmlSerializable Members\n public XmlSchema GetSchema() { return null; }\n public void ReadXml(XmlReader reader)\n {\n Value = int.Parse(reader.ReadString()) == 1;\n }\n public void WriteXml(XmlWriter writer)\n {\n writer.WriteString(ToString());\n }\n #endregion\n}\n</code></pre>\n\n<p>To be honest, <code>((int)this).ToString()</code> seems convoluted and evil.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T03:57:44.337", "Id": "7224", "Score": "1", "body": "hmm, I think your right. Not sure of a better answer but I personally would find the Value ? \"1\" : \"0\" notation easier to read inside the ToString() method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T04:01:33.880", "Id": "7226", "Score": "0", "body": "I just wanted to avoid having the logic (even if minimal) twice. But that can be backwards sometimes." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T03:51:34.440", "Id": "4831", "ParentId": "4829", "Score": "0" } }, { "body": "<p>I'd implement it like this:</p>\n\n<pre><code>public struct Bit : IEquatable&lt;Bit&gt;, IXmlSerializable\n{\n private int value;\n public Bit(bool value) { this.value = value ? 1 : 0; }\n public Bit(int value) : this(value != 0) { }\n\n public bool Equals(Bit other) { return this.value == other.value; }\n public override bool Equals(object obj) { return obj is Bit &amp;&amp; this.Equals((Bit)obj); }\n public override int GetHashCode() { return value.GetHashCode(); }\n public override string ToString() { return this.value.ToString(); }\n\n public static implicit operator int(Bit value) { return value.value; }\n public static explicit operator bool(Bit value) { return value.value != 0; }\n\n System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema() { throw new NotImplementedException(); }\n void IXmlSerializable.ReadXml(XmlReader reader) { this.value = reader.ReadElementContentAsInt(); }\n void IXmlSerializable.WriteXml(XmlWriter writer) { writer.WriteValue(this.value); }\n}\n</code></pre>\n\n<p>It would be better to store your value as an integer as that is the \"true\" value that you're interested in. It's value is normalized using C semantics (i.e., <code>false</code> if <code>0</code>, <code>true</code> otherwise as opposed to <code>true</code> if <code>1</code>, <code>false</code> otherwise). That would feel more natural to me but it's up to you.</p>\n\n<p>I'd be careful with the operator overloading. Don't do it just because you can, do it because it makes sense. I'd stop at implementing casting operators from the type explicitly (since that's the only way to get at the value), use the constructors otherwise. And make only one of them an implicit cast, otherwise you will run into ambiguity errors if you use this a lot in your code.</p>\n\n<p>Consider implementing the <code>IEquatable&lt;T&gt;</code> interface and other appropriate overrides. If you intend to use this in your code, this could be invaluable.</p>\n\n<p>Consider implementing the <code>IXmlSerializable</code> interface explicitly. If you intend to use this type as you would any other in your code, you probably wouldn't want to see the serialization methods all the time. Otherwise if you are only using this for serialization, implement it implicitly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T21:18:34.483", "Id": "7246", "Score": "0", "body": "\"I'd be careful with the operator overloading. Don't do it just because you can.\" Curses, you found me out! OK, I guess that's sensible. I will revise my struct. I think you're dead on with storing as int, that's pretty good." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T20:19:14.610", "Id": "4857", "ParentId": "4829", "Score": "6" } }, { "body": "<p>And now for something completely different. While this does not have the flexibility of implicit conversion to and from bool, I think it's the next best thing:</p>\n\n<pre><code>public enum BoolEnum\n{\n [XmlEnum(\"0\")]\n False = 0,\n [XmlEnum(\"1\")]\n True = 1\n}\n</code></pre>\n\n<p>And... that's it! It serializes <code>BoolEnum.True</code> as \"1\", and can deserialize from it too. Error catching is nonexistent, though. If the value in the file should be other than 1 or 0, an <code>InvalidOperationException</code> inside another is thrown. If there was a way to customize that exception, I'd like to know it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T04:47:53.720", "Id": "7294", "Score": "0", "body": "And yes, mods, I'm breaking a rule, I'm using a question almost as a forum thread. But this really is a different answer, not a followup." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T19:59:39.060", "Id": "7308", "Score": "0", "body": "+1 yes i like, and with method you could decorate the values with other attributes to achieve different information" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T22:23:52.593", "Id": "7309", "Score": "0", "body": "@dreza I wonder what attributes are available at this level, especially in terms of validation. The IDE kinda lists everything and anything." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T04:46:52.333", "Id": "4885", "ParentId": "4829", "Score": "3" } } ]
{ "AcceptedAnswerId": "4857", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T01:11:52.173", "Id": "4829", "Score": "5", "Tags": [ "c#", ".net", "xml" ], "Title": "Presenting a boolean as an int for XMLSerialization in C#" }
4829
<p>Inspired by the motivations expressed in <a href="https://stackoverflow.com/questions/932222/implementing-the-koch-curve">this question</a>.</p> <p>I created some code to generate the point list (and also display a pretty picture) using just analytic geometry (no Logo/Turtle, no trigonometry). Also, instead of recursively inserting new points to a growing list, I calculated the final length, and then assigned values to the already initialized positions.</p> <p>I would like to know if there is some obvious improvement to make it faster, cleaner, more pythonic and/or more canonical.</p> <pre><code>#!/bin/env python # coding: utf-8 def kochenize(a,b): HFACTOR = (3**0.5)/6 dx = b[0] - a[0] dy = b[1] - a[1] mid = ( (a[0]+b[0])/2, (a[1]+b[1])/2 ) p1 = ( a[0]+dx/3, a[1]+dy/3 ) p3 = ( b[0]-dx/3, b[1]-dy/3 ) p2 = ( mid[0]-dy*HFACTOR, mid[1]+dx*HFACTOR ) return p1, p2, p3 def koch(steps, width): arraysize = 4**steps + 1 points = [(0.0,0.0)]*arraysize points[0] = (-width/2., 0.0) points[-1] = (width/2., 0.0) stepwidth = arraysize - 1 for n in xrange(steps): segment = (arraysize-1)/stepwidth for s in xrange(segment): st = s*stepwidth a = (points[st][0], points[st][1]) b = (points[st+stepwidth][0], points[st+stepwidth][1]) index1 = st + (stepwidth)/4 index2 = st + (stepwidth)/2 index3 = st + ((stepwidth)/4)*3 result = kochenize(a,b) points[index1], points[index2], points[index3] = result stepwidth /= 4 return points if __name__ == '__main__': TOTALWIDTH = 1000. points = koch(7, TOTALWIDTH) # If you want a pretty picture (and have Cairo and PIL modules installed) if True: import cairo, Image width = int(TOTALWIDTH) height = int(TOTALWIDTH*0.32) surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) cr = cairo.Context(surface) cr.set_source_rgb(1,1,1) cr.rectangle(0, 0, width, height) cr.fill() cr.translate(width*0.5, height*0.95) cr.scale(1, -1) cr.set_source_rgb(0,0,0) cr.set_line_width(0.5) cr.move_to(*points[0]) for n in range(len(points)): cr.line_to(*points[n]) cr.stroke() im = Image.frombuffer("RGBA", (width, height), surface.get_data(), "raw", "BGRA", 0,1) im.show() </code></pre>
[]
[ { "body": "<pre><code>#!/bin/env python\n# coding: utf-8\n\ndef kochenize(a,b):\n HFACTOR = (3**0.5)/6\n</code></pre>\n\n<p>Stylistically, this would better as a global constant although there'll be some runtime cost to that.</p>\n\n<pre><code> dx = b[0] - a[0]\n dy = b[1] - a[1]\n mid = ( (a[0]+b[0])/2, (a[1]+b[1])/2 )\n p1 = ( a[0]+dx/3, a[1]+dy/3 )\n p3 = ( b[0]-dx/3, b[1]-dy/3 )\n p2 = ( mid[0]-dy*HFACTOR, mid[1]+dx*HFACTOR )\n</code></pre>\n\n<p>The [0] and [1] all over the place obscures your algorithm. Checkout collections.namedtuple</p>\n\n<pre><code> return p1, p2, p3\n\ndef koch(steps, width):\n arraysize = 4**steps + 1\n points = [(0.0,0.0)]*arraysize\n points[0] = (-width/2., 0.0)\n points[-1] = (width/2., 0.0)\n stepwidth = arraysize - 1\n for n in xrange(steps):\n segment = (arraysize-1)/stepwidth\n</code></pre>\n\n<p>This loop is slightly confusing to read. To understand the logic of what stepwidth, n and steps are all doing I have to look for it in several places. I'd probably write a generator which produces the decreasing values of stepwidth to encapsulate that</p>\n\n<pre><code> for s in xrange(segment):\n st = s*stepwidth\n a = (points[st][0], points[st][1])\n b = (points[st+stepwidth][0], points[st+stepwidth][1])\n index1 = st + (stepwidth)/4\n index2 = st + (stepwidth)/2\n index3 = st + ((stepwidth)/4)*3\n</code></pre>\n\n<p>They way you've coded that, the symmetry between the index is non-obvious. The code would be clearer if you hand't reduce the fractions. Also, index1, index2, index3 are begging to be in a list index</p>\n\n<pre><code> result = kochenize(a,b)\n points[index1], points[index2], points[index3] = result \n stepwidth /= 4\n return points\n\nif __name__ == '__main__':\n</code></pre>\n\n<p>I recommend putting the contents of this inside a function called main which you call from here</p>\n\n<pre><code> TOTALWIDTH = 1000.\n points = koch(7, TOTALWIDTH)\n\n # If you want a pretty picture (and have Cairo and PIL modules installed)\n if True: \n</code></pre>\n\n<p>If you want this to be optional check command line arguments or check whether the necessary modules are installed. Putting if True as anything other then a quick hack is frowned upon.</p>\n\n<pre><code> import cairo, Image\n\n width = int(TOTALWIDTH)\n height = int(TOTALWIDTH*0.32)\n surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)\n cr = cairo.Context(surface)\n</code></pre>\n\n<p>I dislike cr, it doesn't obviously stand for anything.</p>\n\n<pre><code> cr.set_source_rgb(1,1,1)\n cr.rectangle(0, 0, width, height)\n cr.fill()\n cr.translate(width*0.5, height*0.95)\n cr.scale(1, -1)\n\n cr.set_source_rgb(0,0,0)\n cr.set_line_width(0.5)\n cr.move_to(*points[0])\n for n in range(len(points)):\n cr.line_to(*points[n])\n cr.stroke()\n\n im = Image.frombuffer(\"RGBA\", (width, height), surface.get_data(), \"raw\", \"BGRA\", 0,1)\n im.show()\n</code></pre>\n\n<p>If you want more speed, you should look into numpy. It will allow you to do vector operations which will be faster then what you can do in straight python.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T19:21:28.857", "Id": "4855", "ParentId": "4832", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-14T17:11:03.023", "Id": "4832", "Score": "4", "Tags": [ "python", "performance", "algorithm", "computational-geometry" ], "Title": "Koch Curve algorithm in Python without using Turtle/Logo logic" }
4832
<p>Is it a bad idea for a model class hold the db handler as a property? Example code are as below. I think the second is better, but the first is not so bad in my opinion.</p> <p>First:</p> <pre><code>class ActiveModel { protected $db; public function __construct() { $this-&gt;db = DbFactory::get('Foo'); } public function save() { //use $this-&gt;db to do the job; .... } } </code></pre> <p>Second:</p> <pre><code>class ActiveModel { public function save($db = null) { if ($db === null) { $db = DbFactory::get('Foo'); } //then use $db to do the job; .... } } </code></pre>
[]
[ { "body": "<p>It is fine and very convenient to keep the database handler as a property. However, you should pass it in the constructor via <a href=\"http://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow\">dependency injection</a>, rather than call it's factory method inside the class. This can ease unit testing when you need to mock a database connection object.</p>\n\n<pre><code>public function __construct($db) {\n $this-&gt;db = $db;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T02:38:23.737", "Id": "7228", "Score": "0", "body": "Yes, you are right. But when dependency injection is not used, I need pass it to constructor every time. When by calling the factory method, I just need change the setting of DbFactory to let it give the mock db connection object." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T16:27:20.360", "Id": "7238", "Score": "1", "body": "Also, when doing automated testing, if DbFactory::get('Foo') becomes expensive your test suite will run much slower." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T02:26:14.917", "Id": "4834", "ParentId": "4833", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T02:20:05.097", "Id": "4833", "Score": "2", "Tags": [ "php", "object-oriented" ], "Title": "Which way is better for db handler?" }
4833
<p>Use this tag only when you're looking for <strong>constructive feedback</strong> for rewriting parts of your <strong>existing code</strong> into better, cleaner code. Questions that merely ask for newer versions of the code should <em>not</em> use this tag and are also <em>off-topic</em> in accordance with the <a href="http://codereview.stackexchange.com/help/on-topic">Help Center</a>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T07:03:20.720", "Id": "4835", "Score": "0", "Tags": null, "Title": null }
4835
Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior. Use this tag only when you're looking for constructive feedback for rewriting parts of your existing code into better, cleaner code.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T07:03:20.720", "Id": "4836", "Score": "0", "Tags": null, "Title": null }
4836
<p>I am a biologist. Some time ago, I wanted to learn to program, and since I am fascinated by the 4th dimension and I was fascinated by the rotatation of hypercubes and hypersphere, so I decided to understand it better, and thanks to the work of Steve Hollasch, I understood that humans cannot "see" the 4th dimension, only project it in the 3 dimensional world.</p> <p>Anyway, after finding the function to project the 4th dimension, I wanted to do something interactive with it, something where one can learn where and how the object moves in a 4 dimensional space. So I came up with the idea of a simple game: Snake.</p> <p><a href="http://www.youtube.com/watch?v=8IUnqm8j4BE" rel="nofollow">snake4d</a></p> <p>Can you please comment on the code here?</p> <pre><code>__author__ = "Mauro Pellanda" __credits__ = ["Mauro Pellanda"] __license__ = "GNU" __version__ = "1.1.0" __maintainer__ = "Mauro Pellanda" __email__ = "pmauro@ethz.ch" __status__ = "Devlopment" ''' In this file is contained the snake definition''' def get_random_color(): return "#%02x%02x%02x" % (random.randrange(0,255), random.randrange(0,255), random.randrange(0,255)) from vec import * import time class Snake: def __init__(self): self.head_pos = V4(0,0,0,0) #position of the head self.head_dir ="UP" #direction of the head self.p_list = [] #store the polygon of the snake self.score = 0 #score self.score2 = 0 #number of cube taken self.time = 0. #boh self.color = [0, 255, 0] #color self.color_var = "up" #Variable to circulary change color def create_cube(self,point): '''This function return the polygon coordinates in a determined postion defined by point''' #calculate coordinates v = V4(.4,.4,.4,.4) higher = sum4(point,v) lower = sub4(point,v) c = cube4d(lower,higher) #calculate the color if self.color_var == "up": self.color[0] += 20 if self.color[0] &gt; 255-21: self.color_var = "down" elif self.color_var == "down": self.color[0] -= 20 if self.color[0] &lt; 21: self.color_var = "up" color_tuple = (self.color[0],self.color[1],self.color[2]) c.color = "#%02x%02x%02x" % color_tuple #add the tag for the canvas (not used in this version) c.tag = "snake" return c def initialize_snake(self): '''it initialize the snake at the original position with 4 cubes''' self.__init__() size = 4 for x in range(size+1): point = V4(0,-(size-x),0,0) self.p_list.append(self.create_cube(point)) def move(self,dir): '''check if is a valid move in that direction, the snake cannot go in opposite direction''' no_move = False if dir == "UP" and self.head_dir != "DOWN": dir_v = V4(0,1,0,0) elif dir == "DOWN" and self.head_dir != "UP": dir_v = V4(0,-1,0,0) elif dir == "LEFT" and self.head_dir != "RIGHT": dir_v = V4(-1,0,0,0) elif dir == "RIGHT" and self.head_dir != "LEFT": dir_v = V4(1,0,0,0) elif dir == "FW" and self.head_dir != "RW": dir_v = V4(0,0,1,0) elif dir == "RW" and self.head_dir != "FW": dir_v = V4(0,0,-1,0) elif dir == "IN" and self.head_dir != "OUT": dir_v = V4(0,0,0,-1) elif dir == "OUT" and self.head_dir != "IN": dir_v = V4(0,0,0,1) else: no_move = True if not no_move: #move the snake, and append a new polygon in the new position, #take off the polygon from the tail, the snake is stored in the #list like this: [tail,-&gt;,head] self.head_pos = sum4(self.head_pos, dir_v) self.head_dir = dir self.p_list.pop(0) self.p_list.append(self.create_cube(self.head_pos)) </code></pre> <ol> <li>Are the comments useful to understand what I did? </li> <li>Do you have any suggestions about the programming style and/or the algorithms?</li> </ol> <p><a href="http://www.mediafire.com/?b8ocioxx80wnnxq" rel="nofollow">Here</a> is the download of the complete source.</p>
[]
[ { "body": "<pre><code>__author__ = \"Mauro Pellanda\"\n__credits__ = [\"Mauro Pellanda\"]\n__license__ = \"GNU\"\n__version__ = \"1.1.0\"\n__maintainer__ = \"Mauro Pellanda\"\n__email__ = \"pmauro@ethz.ch\"\n__status__ = \"Devlopment\"\n\n\n''' In this file is contained the snake definition'''\n</code></pre>\n\n<p>For this to be recognized as a docstring I think it needs to be the first thing in a file.</p>\n\n<pre><code>def get_random_color():\n return \"#%02x%02x%02x\" % (random.randrange(0,255), random.randrange(0,255), random.randrange(0,255))\n\nfrom vec import *\nimport time\n</code></pre>\n\n<p>imports are typically placed before function definitions</p>\n\n<pre><code>class Snake:\n</code></pre>\n\n<p>If you are working python 2.x, I recommend you make your classes inherit from object. That way they are new style classes.</p>\n\n<pre><code> def __init__(self):\n self.head_pos = V4(0,0,0,0) #position of the head\n self.head_dir =\"UP\" #direction of the head\n</code></pre>\n\n<p>Using a string for something like this is a little odd. I suggest a boolean value or an integer.</p>\n\n<pre><code> self.p_list = [] #store the polygon of the snake\n self.score = 0 #score\n self.score2 = 0 #number of cube taken\n self.time = 0. #boh\n self.color = [0, 255, 0] #color\n</code></pre>\n\n<p>I'd make color a tuple. Lists are for storing, well lists, not related items like colors. I know you do this so you can modify it. But I'd create new tuples everytime I changed the color.</p>\n\n<pre><code> self.color_var = \"up\" #Variable to circulary change color\n</code></pre>\n\n<p>Agains strings are odd unless its actually text. It'll take slightly longer to compare strings then say ints or bools. </p>\n\n<pre><code> def create_cube(self,point):\n '''This function return the polygon coordinates in a\n determined postion defined by point'''\n</code></pre>\n\n<p>Typically, the first ''' and final ''' are placed on a line by themselves\nfor multiline docstrings</p>\n\n<pre><code> #calculate coordinates\n v = V4(.4,.4,.4,.4)\n higher = sum4(point,v)\n lower = sub4(point,v)\n c = cube4d(lower,higher)\n #calculate the color\n if self.color_var == \"up\": \n self.color[0] += 20\n if self.color[0] &gt; 255-21:\n self.color_var = \"down\"\n elif self.color_var == \"down\":\n self.color[0] -= 20\n if self.color[0] &lt; 21:\n self.color_var = \"up\" \n color_tuple = (self.color[0],self.color[1],self.color[2])\n</code></pre>\n\n<p>You can just do <code>color_tuple = tuple(self.color)</code></p>\n\n<pre><code> c.color = \"#%02x%02x%02x\" % color_tuple\n</code></pre>\n\n<p>You've duplicated the tuple to string logic here and in the random color function. I suggest refactoring so they share it.</p>\n\n<pre><code> #add the tag for the canvas (not used in this version)\n c.tag = \"snake\"\n return c\n\n def initialize_snake(self):\n '''it initialize the snake at the original position with 4 cubes'''\n self.__init__()\n</code></pre>\n\n<p>Don't ever do that. <code>__init__</code> is called when the object is built. You shouldn't call it later. Python will let you, but nobody expects you to do it and you are liable to confuse people.</p>\n\n<pre><code> size = 4\n for x in range(size+1):\n point = V4(0,-(size-x),0,0)\n self.p_list.append(self.create_cube(point))\n\n def move(self,dir):\n '''check if is a valid move in that direction, the snake cannot go\n in opposite direction'''\n no_move = False\n if dir == \"UP\" and self.head_dir != \"DOWN\":\n dir_v = V4(0,1,0,0)\n elif dir == \"DOWN\" and self.head_dir != \"UP\":\n dir_v = V4(0,-1,0,0)\n elif dir == \"LEFT\" and self.head_dir != \"RIGHT\":\n dir_v = V4(-1,0,0,0)\n elif dir == \"RIGHT\" and self.head_dir != \"LEFT\":\n dir_v = V4(1,0,0,0)\n elif dir == \"FW\" and self.head_dir != \"RW\":\n dir_v = V4(0,0,1,0)\n elif dir == \"RW\" and self.head_dir != \"FW\":\n dir_v = V4(0,0,-1,0)\n elif dir == \"IN\" and self.head_dir != \"OUT\":\n dir_v = V4(0,0,0,-1)\n elif dir == \"OUT\" and self.head_dir != \"IN\":\n dir_v = V4(0,0,0,1)\n else:\n no_move = True\n</code></pre>\n\n<p>Chains of elifs are a sign to look for a better solution. For example, you could have a dictionary mapping directionts to opposites and vectors. Then you'd just have to fetch from the dictionary.</p>\n\n<pre><code> if not no_move:\n</code></pre>\n\n<p>Double negative, consider inverting the logic on no_move so it becomes moved.</p>\n\n<pre><code> #move the snake, and append a new polygon in the new position,\n #take off the polygon from the tail, the snake is stored in the\n #list like this: [tail,-&gt;,head]\n self.head_pos = sum4(self.head_pos, dir_v)\n self.head_dir = dir\n self.p_list.pop(0)\n self.p_list.append(self.create_cube(self.head_pos))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T09:34:06.447", "Id": "7252", "Score": "0", "body": "Thank you very much for the comments!! A specific question about the elif chain, can I define something like this dic_opp_dir = {\"UP\":\"DOWN\", ecc} then call def catch_dir(dir_x): for dir in dic: if dir_x == dic[x]: move = false ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T09:34:23.573", "Id": "7253", "Score": "0", "body": "And there are enum in python? in C++ I defined the directions as enum. And is better then a string, because giving an int decrease the readability of the code..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T12:18:17.223", "Id": "7256", "Score": "1", "body": "@Pella86, why are you wanting to put a loop in that example? Just check if dir_x == dic_opp_dir[head_x]. Python doesn't have enum, but I'd add global constants UP = 0 and DOWN = 1 and use those." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T12:25:45.823", "Id": "7257", "Score": "0", "body": "I didn't know such things can be done with a dictionary... I almost never use them (even though I know they are really useful). And about the global constat I thought it too, but maybe there was a better way. Thank you!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T16:26:34.013", "Id": "7304", "Score": "0", "body": "You wrote to never call self.__init__() I usually don't do this, but I need it to reset all varibles, there is a nicer way to do it instead of copying the init funtion in the initialize_snake?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T17:59:01.117", "Id": "7305", "Score": "0", "body": "@Pella86, probably all those assignments should be moved into initialize_snake. The constructor should either call initialize_snake itself, or set all the variables to None, or both." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T19:30:01.713", "Id": "4856", "ParentId": "4839", "Score": "10" } } ]
{ "AcceptedAnswerId": "4856", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T12:19:02.167", "Id": "4839", "Score": "6", "Tags": [ "python", "game", "snake-game" ], "Title": "Snake game in Python" }
4839
<p>Any suggestions on cleaning up this code:</p> <pre><code> public override bool Validate(Control control, object value) { bool res = false; string str = string.Empty; try { if (((string)value).Length &gt; 0) str = value.ToString(); } catch (Exception e) { res = false; this.ErrorText = "Bad values " + e.Message; this.ErrorType = ErrorType.Critical; } //Is it empty? if (String.IsNullOrEmpty(str)) { res = false; this.ErrorType = ErrorType.Critical; } Regex RegNrShortRegexDarm = new Regex(@"([F][A][D][-][Z]\d{3})"); Regex RegNrLongRegexDarm = new Regex(@"([F][A][D][-][Z]\d{3}[-][0-9]+$)"); Regex RegNrShortRegexBrust = new Regex(@"([F][A][B][-][Z]\d{3})"); Regex RegNrLongRegexBrust = new Regex(@"([F][A][B][-][Z]\d{3}[-][0-9]+$)"); if (selectedItem == Constants.Item1) { this.ErrorText = "The correct form is: FAD-Zxxx oder FAD-Zxxx-x !"; //has the form FAD-Zxxx if (RegNrShortRegexDarm.IsMatch(str) &amp;&amp; str.Length == 8) { // Number is valid res = true; } //has the form FAD-Zxxx-x if (RegNrLongRegexDarm.IsMatch(str) &amp;&amp; str.Length &gt;= 10 &amp;&amp; str.Length &lt;= 12) { // Number is valid res = true; } } else if (selectedItem == Constants.Item2) { this.ErrorText = "The correct form is: FAB-Zxxx oder FAB-Zxxx-x !"; //has the form FAB-Zxxx if (RegNrShortRegexBrust.IsMatch(str) &amp;&amp; str.Length == 8) { // Number is valid res = true; } //has the form FAB-Zxxx-x if (RegNrLongRegexBrust.IsMatch(str) &amp;&amp; str.Length &gt;= 10 &amp;&amp; str.Length &lt;= 12) { // Number is valid res = true; } } return res; } </code></pre> <p>Later Edit:</p> <p>I've reached the following solution:</p> <pre><code>public override bool Validate(Control control, object value) { var str = value as string; var letter = (selectedItem == Constants.Item1) ? "D" : "B"; var errText = String.Format("The correct form is: FA{0}-Zxxx or FA{0}-Zxxx-x !", letter); if (string.IsNullOrWhiteSpace(str)) { this.ErrorType = ErrorType.Critical; this.ErrorText = errText; return false; } string regExString = String.Format(@"FA{0}-Z\d{{3}}", letter); Regex shortRegEx = new Regex(regExString); Regex longRegEx = new Regex(regExString + @"-\d+$"); bool isMatch = ((shortRegEx.IsMatch(str) &amp;&amp; IsValidShortLength(str)) || (longRegEx.IsMatch(str) &amp;&amp; IsValidLongLength(str))); if (!isMatch) { this.ErrorText = errText; } return isMatch; } private static bool IsValidShortLength(string str) { return str.Length == 8; } private static bool IsValidLongLength(string str) { return (str.Length &gt;= 10 &amp;&amp; str.Length &lt;= 12); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T13:34:11.700", "Id": "7233", "Score": "0", "body": "Welcome to Code Review! It would help us if your post included at least a high-level description of what your method does or any specific concerns you have. Even if it's clear enough for us to figure out, realize that we are all volunteers and the more you can to do make it easier for us or more appealing to us, then more likely you are to get helpful answers." } ]
[ { "body": "<p>I can't believe I'm saying this, but you have too much error handling going on. The first 15 lines or so all deals with converting value to a string.</p>\n\n<p>just do something like...</p>\n\n<pre><code>string str = value as string;\nif(string.IsNullOrWhiteSpace(str))\n{ \n this.ErrorType = ErrorType.Critical;\n return false;\n}\n</code></pre>\n\n<p>Also, return false immediately when you encounter an error condition. You continue to attempt to process the string even though you know the string is in an invalid state.</p>\n\n<p>Name your variables according to the C# guidelines. All variables should be camel-cased, not Pascal-cased.</p>\n\n<p>Use the alias string rather than String.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T13:47:24.917", "Id": "7234", "Score": "2", "body": "Even that first line is overkill. `string str = value as string;`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T13:59:22.923", "Id": "7235", "Score": "0", "body": "You are absolutely right. But it doesn't look as cool. ;)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T13:32:03.887", "Id": "4841", "ParentId": "4840", "Score": "1" } }, { "body": "<p>The first check in the try block is not needed at all. It just checks if the value is string, and it's unlikely to be something else. If this validation is attached to a control, who's value is not a string, then this is an error, and I would throw an exception \"Bad values\", so the code is corrected.</p>\n\n<p>Then, if the value is null or empty, you have an error, why would you inspect all the other possibilities?</p>\n\n<p>Also - where you use the control itself? Why you pass it, if you do not use it?</p>\n\n<p>Anyway, if I was to check the string for valid formatting, I would do this:</p>\n\n<pre><code> var str = value as String;\n\n var letter = (selectedItem == Constants.Item1) ? \"D\" : \"B\";\n var errText = String.Format(\"The correct form is: FA{0}-Zxxx oder FA{0}-Zxxx-x !\", letter);\n\n if (str == null \n || str.Length &lt; 8 \n || !(str.Length &gt;= 10 &amp;&amp; str.Length &lt;=12))\n {\n this.ErrorType = ErrorType.Critical;\n this.ErrorText = errText;\n return false;\n }\n\n var regExString = @\"([F][A][\" + letter + @\"][-][Z]\\d{3})\";\n Regex shortRegEx = new Regex(regExString);\n Regex longRegEx = new Regex(regExString + @\"[-][0-9]+$)\");\n\n var isMatch = (shortRegEx.IsMatch(str) || longRegEx.IsMatch(str));\n if (!isMatch)\n {\n this.ErrorText = errText;\n }\n\n return isMatch;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T14:11:50.533", "Id": "7236", "Score": "1", "body": "Nice tips ;) ... I would extract a boolean method 'IsValidLength' with the first if condition... figure it would improve the readability, perhaps even some vars for the max, min length." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T11:25:19.057", "Id": "7255", "Score": "0", "body": "In my later edit I used two boolean methods 'IsValidShortLength' and 'IsValidLongLength' because otherwise the isMatch variable would be 'true' if the user enters 'FAD-Zddd-ccc' (d = digits, c = characters). It is desired to get a correct match only if the string has one of the following forms: 'FAD-Zddd' ; 'FAD-Zddd-d' ; 'FAD-Zddd-dd' ; 'FAD-Zddd-ddd';" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T13:48:58.003", "Id": "4844", "ParentId": "4840", "Score": "4" } }, { "body": "<p>Just to pick on the regexes (since other people are picking up some of the other stuff I'd have commented):</p>\n\n<pre><code> Regex RegNrShortRegexDarm = new Regex(@\"([F][A][D][-][Z]\\d{3})\");\n Regex RegNrLongRegexDarm = new Regex(@\"([F][A][D][-][Z]\\d{3}[-][0-9]+$)\");\n Regex RegNrShortRegexBrust = new Regex(@\"([F][A][B][-][Z]\\d{3})\");\n Regex RegNrLongRegexBrust = new Regex(@\"([F][A][B][-][Z]\\d{3}[-][0-9]+$)\");\n</code></pre>\n\n<p>Just ditch the classes for single characters: <code>[F]</code> is overkill. And be consistent about the class for digits. Also, there's no point using a group for the entire expression.</p>\n\n<pre><code> Regex RegNrShortRegexDarm = new Regex(@\"FAD-Z\\d{3}\");\n Regex RegNrLongRegexDarm = new Regex(@\"FAD-Z\\d{3}-\\d+$\");\n Regex RegNrShortRegexBrust = new Regex(@\"FAB-Z\\d{3}\");\n Regex RegNrLongRegexBrust = new Regex(@\"FAB-Z\\d{3}-\\d+$\");\n</code></pre>\n\n<p>And then given the way you actually use the things it would be more sensible to have</p>\n\n<pre><code> Regex RegNrDarm = new Regex(@\"FAD-Z\\d{3}(-\\d{1,3})?\");\n Regex RegNrBrust = new Regex(@\"FAB-Z\\d{3}(-\\d{1,3})?\");\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T13:53:22.147", "Id": "4845", "ParentId": "4840", "Score": "4" } }, { "body": "<p>After combining some of the other answers and some very minor stylistic tweaks we get:</p>\n\n<pre><code> public override bool Validate(Control control, object value)\n {\n var str = value as string;\n var letter = (selectedItem == Constants.Item1) ? \"D\" : \"B\";\n var errText = String.Format(\"The correct form is: FA{0}-Zxxx oder FA{0}-Zxxx-x !\", letter);\n\n if (string.IsNullOrEmpty(str))\n {\n this.ErrorType = ErrorType.Critical;\n this.ErrorText = errText;\n return false;\n }\n\n string pattern = @\"(FA\" + letter + @\"-Z\\d{3}(-\\d{1,3})?\";\n bool isMatch = Regex.IsMatch(str, pattern);\n\n if (!isMatch)\n {\n this.ErrorText = errText;\n }\n return isMatch;\n}\n</code></pre>\n\n<p>As part of the combining, I switched to using the static <code>Regex.IsMatch</code> method, because we got down to only one RegEx, and creating an object for it seemed like overkill. </p>\n\n<p>I might consider using a format string for <code>regExString</code>, although I think that would make readibility worse, so I would probably skip it.</p>\n\n<p>I would avoid mixing languages in my error message. The English word is \"or\", not \"oder\" which is German. It might be best to internationalize error messages, which implies fetching that format string from a resource file, rather than hardcoding it. </p>\n\n<p>The above is probably otherwise getting pretty close to optimal. This function is also not quite the same as the original though, since it makes the assumption that <code>selectedItem</code> is always either <code>Constants.Item1</code> or <code>Constants.Item2</code>. If that change is not acceptable, the method above should be changed appropriately.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T21:06:41.260", "Id": "7244", "Score": "0", "body": "The `IsValidLength` is unnecessary with the fixed regex. And, in fact, you've changed the logic by making it a critical error to be the wrong length, when in the original it was only a critical error is the string was null or empty. (Edit: oops, hadn't read the last paragraph)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T00:21:46.697", "Id": "7248", "Score": "0", "body": "@Peter, Good Point, I'll change the first test to be IsNullOrEmpty, and let the regex take care of the rest." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T17:20:06.483", "Id": "4852", "ParentId": "4840", "Score": "1" } }, { "body": "<p>Other people have commented on your try/catch and whether or not it is even applicable, but I don't believe it has been mentioned that you shouldn't catch <code>Exception</code>, but rather something you can actually handle and might expect. Given your code, I might expect to run into a <code>NullReferenceException</code> or an <code>InvalidCastException</code>. The fact is you can avoid both of those, but assuming you could not, those would be the types you would want to catch. Other exceptions should bubble up.</p>\n\n<p>Beyond that, I see a <em>long</em> method. Break that down into smaller, descriptive parts. </p>\n\n<p>Another thing I see is </p>\n\n<pre><code>if (selectedItem == x)\n{\n // several lines of code\n}\nelse if (selectedItem == y)\n{\n // several lines of code\n}\n</code></pre>\n\n<p>The bodies of these blocks at the very least are strong candidates to be refactored out. Perhaps <code>ValidateForItem1</code>, <code>ValidateForItem2</code>, or something along those lines. Just an idea to get you started. </p>\n\n<p>I see that in an upper section of code you set <code>res = false</code> when <code>str</code> is null or empty. But later you can set <code>res</code> to true. Whether or not it is even possible for later sections of code to override the initial value, I don't want to even have to think about it. If it's OK to override, that's one thing. If it isn't (even if it isn't even <em>possible</em>), don't make me have to perform the mental gymnastics to confirm to myself that the value will not change. </p>\n\n<p>My (hopefully) final observation is I see this in multiple places </p>\n\n<pre><code>// Number is valid\nres = true;\n</code></pre>\n\n<p>You know what this comment tells me? It tells me that <code>res</code> is a terrible name for the variable. <code>res</code> tells me nothing. Rename the variable to something that actually tells me what information it is supposed to convey, and then you can get rid of useless comments. </p>\n\n<pre><code>isValidNumber = true; \n</code></pre>\n\n<p>OK, so that directly leads me to another point.</p>\n\n<pre><code>//Is it empty? \nif (String.IsNullOrEmpty(str)) \n</code></pre>\n\n<p><em>Ya think?</em></p>\n\n<p>I don't need a comment to tell me what the line of code tells me. Save your comments for things that actually do need to be explained. Perhaps comments are useful for regular expressions, because who wants to think about those. Provide high level comments for tricky pieces of code, or say why you chose algorithm X over Y, if you feel the need. Don't provide comments for what the code already tells me (and refactor the code when the code <em>should</em> be able to tell me what I need to know, as in the case of <code>res</code>). </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T20:22:07.137", "Id": "4858", "ParentId": "4840", "Score": "1" } } ]
{ "AcceptedAnswerId": "4844", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T12:46:29.280", "Id": "4840", "Score": "2", "Tags": [ "c#" ], "Title": "Validation function code review" }
4840
<p>This is my general database connection class. I am using this class to execute my queries through website.</p> <p>What would your suggestions on how to improve performance be?</p> <p>(<em>Running MSSQL 2008 R2 SP1 - Microsoft Visual Studio 2010 SP1 , C# 4.0 - ASP.net 4.0</em>)</p> <p>Class:</p> <pre><code>using System; using System.Collections.Generic; using System.Collections; using System.Linq; using System.Web; using System.Data.Sql; using System.Data.SqlClient; using System.Data; using System.IO; /// &lt;summary&gt; /// Summary description for DbConnection /// &lt;/summary&gt; public class DbConnection { public static string srConnectionString = "server=localhost;database=myDB;uid=sa;pwd=MYPW;"; public DbConnection() { } public static DataSet db_Select_Query(string strQuery) { DataSet dSet = new DataSet(); try { using (SqlConnection connection = new SqlConnection(srConnectionString)) { connection.Open(); SqlDataAdapter DA = new SqlDataAdapter(strQuery, connection); DA.Fill(dSet); } return dSet; } catch (Exception) { using (SqlConnection connection = new SqlConnection(srConnectionString)) { if (srConnectionString.IndexOf("select Id from tblAspErrors") != -1) { connection.Open(); strQuery = strQuery.Replace("'", "''"); SqlCommand command = new SqlCommand("insert into tblSqlErrors values ('" + strQuery + "')", connection); command.ExecuteNonQuery(); } } return dSet; } } public static void db_Update_Delete_Query(string strQuery) { try { using (SqlConnection connection = new SqlConnection(srConnectionString)) { connection.Open(); SqlCommand command = new SqlCommand(strQuery, connection); command.ExecuteNonQuery(); } } catch (Exception) { strQuery = strQuery.Replace("'", "''"); using (SqlConnection connection = new SqlConnection(srConnectionString)) { connection.Open(); SqlCommand command = new SqlCommand("insert into tblSqlErrors values ('" + strQuery + "')", connection); command.ExecuteNonQuery(); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-18T17:51:50.207", "Id": "42854", "Score": "0", "body": "`SqlCommand` implements `IDisposable`, so those also should be wrapped in `using` (similar to what you're correctly doing with `SqlConnection`)." } ]
[ { "body": "<p>You are not using a DataContext, so presuming you don't want to for this, I'd suggest that you also consider a connection pool, that way you don't need to incur the connection cost for every select/delete.</p>\n\n<p>Additionally, your catches are very heavy, are you getting that many errors that you need to track? You may want to see this question as an alternative to logging the errors yourself: <a href=\"https://stackoverflow.com/questions/5076303/sql-server-error-messages\">https://stackoverflow.com/questions/5076303/sql-server-error-messages</a></p>\n\n<p>@kubal5003 - good point on automatic connection pooling, here is the <a href=\"http://msdn.microsoft.com/en-us/library/8xx3tyca(v=VS.100).aspx\" rel=\"nofollow noreferrer\">MSDN</a> that discusses it and its sibling that lists the <a href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx\" rel=\"nofollow noreferrer\">connection string</a> properties and defaults</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T22:07:36.380", "Id": "7435", "Score": "0", "body": "hello thanks for answers. actually i almost never get any error. this connection pool i am really interested in. can you provide me any good article tutorial about this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-24T22:50:05.833", "Id": "7464", "Score": "3", "body": "ADO.NET already uses connection pooling without the user knowing about it, so you don't have to do anything in here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-26T23:50:42.660", "Id": "7487", "Score": "0", "body": "ye i also asked on official forum and they said the latest version is fine. here the link : http://forums.asp.net/p/1723810/4612236.aspx/1?Re+Does+this+class+using+connection+pool+feature+right+now+MSSQL+2008+R2+ASP+net+4+0" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T20:28:09.577", "Id": "4964", "ParentId": "4843", "Score": "3" } }, { "body": "<p>I don't have a comment on your performance problem, but I wanted to comment on this...</p>\n\n<pre><code>public static void db_Update_Delete_Query(string strQuery)\n{\n try\n {\n using (SqlConnection connection = new SqlConnection(srConnectionString))\n {\n connection.Open();\n SqlCommand command = new SqlCommand(strQuery, connection);\n command.ExecuteNonQuery();\n }\n }\n catch (Exception)\n {\n strQuery = strQuery.Replace(\"'\", \"''\");\n using (SqlConnection connection = new SqlConnection(srConnectionString))\n {\n connection.Open();\n SqlCommand command = new SqlCommand(\"insert into tblSqlErrors values ('\" + strQuery + \"')\", connection);\n command.ExecuteNonQuery();\n }\n\n }\n}\n</code></pre>\n\n<p>First, DB calls in a catch block is probably a really bad idea. I'm not sure why you think the second call will work when the first call has failed, it makes absolutely no sense.</p>\n\n<p>As for your question, you need to include more information. I am not an ADO expert by any means, so I'm not going to guess as to where your problem lies, but you at least need to provide us with:</p>\n\n<ol>\n<li>Your performance requirements.</li>\n<li>Your benchmark results (you have run benchmark tests, right?)</li>\n<li>Your usage scenario. </li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-18T15:35:03.337", "Id": "42835", "Score": "0", "body": "+1. This corrupts and thwarts the whole reason for try/catch. If \"try/catching\" the first DB call is a good idea, why not that second.. And if that second \"try/catch\" is a good idea .... You get the idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-18T23:31:14.387", "Id": "42891", "Score": "0", "body": "try catch perfectly works. for example you are trying to insert data to non existing table. the catch block will catch and store it .)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-18T23:37:51.580", "Id": "42892", "Score": "0", "body": "@MonsterMMORPG: The problem is `catch(Exception)`. Anything could have gone wrong there. If that were the case then he should be catching `InvalidOperationException` instead. What if the error arose because the DB was unreachable? What if the connection string was bad?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-19T14:56:10.310", "Id": "42923", "Score": "0", "body": "@EdS. - I generally agree, but feel its worth noting that in most exceptional cases the 2nd db call will fail in the same way as the first. So its pretty much a wash - you'll still get the exception info, but will have lost some call stack and possible info from swallowing the first exception. Overall, it's a little less than well thought out - but I don't see it as a huge deal. FWIW." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-26T21:11:14.120", "Id": "5007", "ParentId": "4843", "Score": "3" } }, { "body": "<p>Sql Injection in your catch clause - just use a parameter for the <code>strQuery</code> value instead of trying to escape it.</p>\n\n<p>That said, I don't see any performance problems with this - it's basically raw ADO.NET, which is more or less the fastest you'll get. </p>\n\n<p><code>DataSet</code>s are a little heavy compared to <code>DataReader</code>s, but it's not likely to be the source of any performance problems.</p>\n\n<p>The main performance issue with any database is going to be the queries you send to it - not really the DB access code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-18T02:53:47.387", "Id": "27494", "ParentId": "4843", "Score": "1" } } ]
{ "AcceptedAnswerId": "4964", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T13:47:31.850", "Id": "4843", "Score": "2", "Tags": [ "c#", "object-oriented", "asp.net", "sql-server" ], "Title": "Database connection class performance" }
4843
<p>I am looking for best practices as they apply to constructor usage in common Java class construction.</p> <p><strong>Example 1</strong></p> <pre><code>import javax.swing.*; import java.awt.*; public class Painter extends JPanel{ public Painter(){ buildGUI(); } private void buildGUI(){ JFrame frame = new JFrame(); frame.setLayout(new BorderLayout()); frame.setTitle("Paint drawing demonstration"); new Center_frame(frame); JPanel headerPanel = new JPanel(); headerPanel.add(new JLabel("The drawing panel is below")); Drawing_panel dp = new Drawing_panel(); frame.add(BorderLayout.NORTH,headerPanel); frame.add(BorderLayout.SOUTH,dp); frame.pack(); frame.setVisible(true); } public static void main(String args[]){ new Painter(); } }//end class Painter </code></pre> <p><strong>Example2</strong></p> <pre><code>import javax.swing.*; import java.awt.*; public class Painter extends JPanel{ public Painter(){ JFrame frame = new JFrame(); frame.setLayout(new BorderLayout()); frame.setTitle("Paint drawing demonstration"); new Center_frame(frame); JPanel headerPanel = new JPanel(); headerPanel.add(new JLabel("The drawing panel is below")); Drawing_panel dp = new Drawing_panel(); frame.add(BorderLayout.NORTH,headerPanel); frame.add(BorderLayout.SOUTH,dp); frame.pack(); frame.setVisible(true); } public static void main(String args[]){ //create a Painter object new Painter(); } }//end class Painter </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T17:20:10.077", "Id": "7239", "Score": "1", "body": "Both of those have serious potential threading problems. You should be using `SwingUtilities.invokeAndWait` or `SwingUtilities.invokeLater` at the very least to wrap the `frame.setVisible(true)` calls." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T20:50:50.510", "Id": "7242", "Score": "0", "body": "@Peter. Not an expert so forgive the silly question. How can there be a threading problem. The object does not exist until after the constructor completes. So there is no way for another thread to have a reference to the object to call any methods (let alone the constructor)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T21:01:50.237", "Id": "7243", "Score": "2", "body": "@Tux-D, it's not a silly question. Lots of people (and even tutorial writers) don't understand the problem, and (threading being what it is) it's one of those bugs which doesn't trigger every time. The root issue is what's going on behind the scenes in the library, and in particular the interaction with the native widget library, which has to take place in the AWT thread to be safe. [Reference](http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html) (although it's out of date - from Java 6 the first exception is no longer applicable)." } ]
[ { "body": "<p>no one from them, this should be standard or base</p>\n\n<p>EDIT: added DefaultCloseOperation for Top-Level Container </p>\n\n<pre><code>import javax.swing.*;\nimport java.awt.*;\n\npublic class Painter {\n\n private JFrame frame;\n private JPanel headerPanel;\n private Drawing_panel ;\n\n public Painter() {\n frame = new JFrame();\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n frame.setLayout(new BorderLayout());\n frame.setTitle(\"Paint drawing demonstration\");\n\n //new Center_frame(frame); \n //no reason for create another new JFrame look for \n //JDialog instead of JFrame, if you needed multiplayed\n //view then check CardLayout, is very easy for use \n\n headerPanel = new JPanel();\n headerPanel.add(new JLabel(\"The drawing panel is below\"));\n\n dp = new Drawing_panel();\n\n frame.add(headerPanel, BorderLayout.NORTH);\n frame.add(dp, BorderLayout.SOUTH);\n\n frame.pack();\n frame.setVisible(true);\n }\n\n public static void main(String args[]) {\n SwingUtilities.invokeLater(new Runnable() {\n\n @Override\n public void run() {\n Painter p = new Painter();\n }\n });\n }\n} \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-18T19:15:02.520", "Id": "7323", "Score": "1", "body": "AWT and Swing-related code must happen in the EDT (the AWT event dispatch thread), you are right. But in practice, you won't run into troubles if initialization codes (like this code) happens in another thread." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-18T21:24:44.813", "Id": "7325", "Score": "0", "body": "@barjak exclent catch, +1" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T14:05:00.103", "Id": "4888", "ParentId": "4850", "Score": "4" } }, { "body": "<p>What is the purpose of your <code>Painter</code> class ? You are just using its constructor to run some code which is completely unrelated to <code>Painter</code> itself. You are doing the same thing with the two other objects you instanciate : <code>Center_frame</code> and <code>Drawing_panel</code>.</p>\n\n<p>When writing a GUI in Swing, you generally write classes that extend <code>JPanel</code>, and the constructors contains the code that initialize the inner components. It's a bad idea to let the constructor have a side effect (the display of a frame) like you have.</p>\n\n<p>Also, try to follow the <a href=\"http://www.oracle.com/technetwork/java/codeconventions-135099.html#367\" rel=\"nofollow\">Java naming conventions</a> : variables and types names use <a href=\"http://en.wikipedia.org/wiki/CamelCase\" rel=\"nofollow\">camel case</a>, and variables start with a lowercase.</p>\n\n<p>When initializing a <code>JFrame</code>, you might be interrested in calling the method <code>setDefaultCloseOperation</code> (generally with <code>JFrame.EXIT_ON_CLOSE</code> or <code>JFrame.DISPOSE_ON_CLOSE</code>) </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-18T19:19:48.220", "Id": "4900", "ParentId": "4850", "Score": "2" } } ]
{ "AcceptedAnswerId": "4888", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T16:44:44.363", "Id": "4850", "Score": "6", "Tags": [ "java" ], "Title": "What constructor implementaton follows best practice in Java" }
4850
<p>The following is a personal attempt at implementing the <a href="https://en.m.wikipedia.org/wiki/Composite_pattern" rel="nofollow">Composite design pattern</a> in Scala. <code>Observation</code> is abstract...</p> <pre><code>class CompositeObservation(obss: Observation*) extends Observation { val elements: MutableList[Observation] = new MutableList[Observation]() elements ++ obss def hasElement(o: Observation): Boolean = elements.contains(o); } </code></pre> <p><code>hasElement</code> fails to return if an element is contained in the composite. Questions:</p> <ol> <li>Am I misinterpreting the ++ operator? The Observation*?</li> <li>What is the most ideomatic way to implement this pattern in Scala?</li> </ol>
[]
[ { "body": "<ol>\n<li><code>++</code> returns a <em>new</em> collection, you need <code>++=</code> here</li>\n<li>Your attempt looks fine to me. Maybe you should additionally implement the <code>Traversable</code> trait or so, and delegate the calls to <code>elements</code> in order to make things a little bit more convenient.</li>\n</ol>\n\n<p><strong>[Edit]</strong></p>\n\n<pre><code>class CompositeObservation(obss: Observation*) \n extends Observation with Traversable[Observation] {\n\n val elements = new MutableList[Observation]()\n\n elements ++= obss\n\n def hasElement(o: Observation): Boolean = elements.contains(o);\n\n def foreach[U](f: (Observation) =&gt; U): Unit = elements.foreach(f)\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T21:08:36.097", "Id": "7245", "Score": "0", "body": "Thanks for the ++=. I like the idea of Traversable (akin to IEnumerable in C#). Could you provide me an example of how to do that \"elengatly\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T21:39:49.557", "Id": "7247", "Score": "0", "body": "@Hugo S Ferreira: It's really easy. I added the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T10:21:32.153", "Id": "7254", "Score": "0", "body": "thx. I realize the `: Unit = ...` can be replaced by `{ ... }` Any particular reason I'm not aware for you to have used it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T21:08:10.210", "Id": "7275", "Score": "0", "body": "I copied the definiton of foreach from somewhere :-) But for beginners I would recommend to write out always the return type for methods, as it is easy to forget the `=` between arg list and method body (especially as ist looks like Java), and you search for hours why your method doesn't work." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T18:39:02.300", "Id": "4853", "ParentId": "4851", "Score": "2" } } ]
{ "AcceptedAnswerId": "4853", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T16:49:42.627", "Id": "4851", "Score": "0", "Tags": [ "design-patterns", "scala" ], "Title": "Composite Design Pattern in Scala" }
4851
<p>I wrote one of my first classes in Actionscript 3 and I want someone versed in AS3 to help me fine tune my class. I am sure there are things that could really help with efficiency and I love learning about "Object Oriented Programming" so please take a look and let me know what you think.</p> <p>Project Background: This project is a card game that reads all the cards information from an XML file so the client can easily add, edit, or delete card information. The user will drag an Activity card from one of the six stacks and place it on top of the Event card. The six stacks will have a card face up so the user can see the information and match the best card to the Event card. <em>i.e.</em> If the Event Card is: "Burning auto wreck with a person inside"; the Activity Cards may read "Pull Victim", "Put out Flames" <em>etc.</em></p> <p>When the user makes drops the Activity card on the Event Card it goes through a point check to determine whether it was a good drop, and assigns points accordingly. </p> <p>After the drop, the next user clicks "Next >>", the deck re-shuffles, and the process starts all over again until a certain number of points have been gained in total.</p> <p>Hopefully that made sense and you can get some kind of idea on how it works. I can elaborate more if needed.</p> <pre><code>/* Document Class (CardGame.as) */ package library { import flash.display.*; import flash.events.*; import flash.net.*; public class CardGame extends Sprite { // Variables private var _xml:XML; private var _loader:URLLoader; private var _cardArray:Array; private var _activity:ActivityCard; private var _event:EventCard; private var _randomCardArray:Array; // Contructor public function CardGame():void { _loader = new URLLoader(); _loader.addEventListener(Event.COMPLETE,buildArray); _loader.load(new URLRequest("library/card.xml")); start_btn.addEventListener(MouseEvent.CLICK,buildDeck); restart_btn.addEventListener(MouseEvent.CLICK,removeDeck); } // Methods public function buildArray(e:Event):Array { _cardArray = new Array(); _xml = new XML(_loader.data); for(var i=0;i&lt;_xml.card.length();i++) { if(_xml.card.face[i]== "activity") { _cardArray.push({id:_xml.card.id[i],face:_xml.card.face[i],category:_xml.card.category[i],point:_xml.card.point[i],value:_xml.card.value[i]}); } else if(_xml.card.face[i] == "event") { _cardArray.push({id:_xml.card.id[i],face:_xml.card.face[i],category:_xml.card.category[i],point:_xml.card.point[i],value:_xml.card.value[i]}); } else { trace("no card found"); } } return _cardArray; } private function randomizeArray():Array { //trace(buildArray(null)); _randomCardArray = new Array(); do { var cardItem = int(Math.random()*_cardArray.length); _randomCardArray.push(_cardArray[cardItem]); _cardArray.splice(cardItem,1); } while (_cardArray.length &gt; 0); return _randomCardArray; } public function buildDeck(e:Event):void { var _finalCardArray = randomizeArray(); for(var i=0;i&lt;_finalCardArray.length;i++) { if(_finalCardArray[i].face == "activity") { _activity = new ActivityCard(); _activity.x = 200; _activity.y = 150; _activity.buttonMode = true; _activity.mouseChildren = false; _activity.name = "card"+i; _activity.id_txt.text = _finalCardArray[i].id; _activity.value_txt.text = _finalCardArray[i].value; _activity.addEventListener(MouseEvent.MOUSE_DOWN,dragStart); _activity.addEventListener(MouseEvent.MOUSE_UP,dragStop); addChild(_activity); } else if(_finalCardArray[i].face == "event") { _event = new EventCard(); _event.x = stage.stageWidth/2; _event.y = 550; _event.mouseChildren = false; _event.name = "card"+i; _event.id_txt.text = _finalCardArray[i].id; _event.value_txt.text = _finalCardArray[i].value; addChild(_event); } else { trace("no cards"); } } } public function dragStart(e:Event):void { _activity = e.target as ActivityCard; _activity.parent.setChildIndex(_activity, numChildren - 1); _activity.startDrag(false); } public function dragStop(e:Event):void { this.stopDrag(); } private function removeDeck(e:Event):void { if(_cardArray.length == 0) { for(var i=0;i&lt;106;i++) { removeChild(getChildByName("card"+i)); } buildArray(null); buildDeck(null); } } } </code></pre>
[]
[ { "body": "<p>There are a few areas that can be improved but I guess we need some more context as to how this is laid out. My comments and questions below:</p>\n\n<p>1 - In ActionScript, since you can modify the contents of a collection inside a loop querying the length of the collection at each iteration is a small performance hit. So:</p>\n\n<pre><code>for(var i=0;i&lt;_xml.card.length();i++)\n</code></pre>\n\n<p>should really be</p>\n\n<pre><code>var xmlLength:int = _xml.card.length();\nfor(var i=0;i&lt;xmlLength;i++)\n</code></pre>\n\n<p><br/><br/>\n2 - To help with clarity you want to use strongly typed objects wherever possible. For example when you are storing each event or activity in the _cardArray consider having a class which just holds the data for those objects. This helps with runtime performance as well as other developers understanding not only the contents of the array but the data type of each property in the object. For example:</p>\n\n<pre><code>_cardArray.push({id:_xml.card.id[i],face:_xml.card.face[i],category:_xml.card.category[i],point:_xml.card.point[i],value:_xml.card.value[i]});\n</code></pre>\n\n<p>could instead be</p>\n\n<pre><code>_cardArray.push(new ActivityVO(_xml.card.id[i], _xml.card.face[i], _xml.card.category[i], _xml.card.point[i], _xml.card.value[i]));\n</code></pre>\n\n<p>where ActivityVO is(I'm just assuming the type of these properties):</p>\n\n<pre><code>public class ActivityVO {\n\n public var id:int;\n public var face:String;\n public var category:String;\n public var point:int;\n public var value:int;\n\n public function ActivityVO(_id:int, _face:String, _category:String, _point:int, _value:int){\n id = _id;\n face = _face;\n category = _category;\n point = _point;\n value = _value;\n }\n}\n</code></pre>\n\n<p><br/><br/>\n3 - How does buildArray work right now? I see it is executed onComplete of the loader but it returns the array. If buildArray is called by something else(I see its public) then all of this logic will be executed twice.\nWhere does this get returned to? If this is the document class what is calling this public method?\nrandomizeArray seems to suffer from the same problem. I'm not sure where you are returning this array to.</p>\n\n<p><br/><br/>\n4 - Think about having a new class which manages the deck of cards. Methods like randomizeArray and buildDeck could be within this class and reduce the clutter of your current class.</p>\n\n<p><br/><br/>\n5 - The removeDeck method doesn't feel right. You should always try to avoid for loops with hard coded breaking values (106). Arguably a better way to go about the whole loop would be to maintain an array of all the cards on the table, then when it comes time to remove them they can all be cleaned up by looping through the array.</p>\n\n<p>These comments aren't really in any particular order, I put them together as I was reading through your code. Let me know if you have any questions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T16:29:57.870", "Id": "7267", "Score": "0", "body": "@ mbaker, this is GOLD! I really appreciate the feedback. I understand what you are saying about creating more classes and how that could improve many things. I am doing some reading and modifying of my code, but I will have questions. Thanks again .... stand by ...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T16:44:08.300", "Id": "7270", "Score": "0", "body": "And to answer your question about `buildArray()` it does get called again in `removeDeck()` and that is the only time. What it's doing is it's called from the `_loader` and it builds the `_cardArray` and is held in memory to be used in `randomizeArray()`. `buildDeck()` will then use the new random array as `_finalCardArray`. My thought behind this was to have most my tasks as methods for easy modification and or readablilty. I never thought of making multiple classes, seems a better approach after I think of it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T18:41:21.630", "Id": "7272", "Score": "0", "body": "Now you have opened a can of worms, lol. I am trying to add more classes to my package and I receive an error: **5006: An ActionScript file can not have more than one externally visible definition: library.Card, library.ActivityVO**. I have tried a few ways to instantiate the `ActivityVO` class and have no luck :-(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T20:50:37.320", "Id": "7274", "Score": "0", "body": "I just learned something that I thought was something to tell anyone who is new to AS3 Classes, I thought you had to `import` all external class files into the document class in order to have access to any of the external classes methods, but it turns out that if the external class file resides in the same folder all you have to do is instantiate it. VERY USEFUL knowledge :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T19:09:52.593", "Id": "7426", "Score": "0", "body": "Sorry I was MIA for a few days. Good to hear that my feedback was well received!\n\nWith regards to import statements they can become a royal pain if you get beyond a few simple classes.If you're going to continue doing a good deal of AS3 work I highly recommend looking into a proper IDE. Something like FDT (http://www.fdt.powerflasher.com/) or FlashDevelop (http://www.flashdevelop.org/wikidocs/index.php?title=Main_Page). They will handle all of the intellisense and import statements for you." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T14:52:07.350", "Id": "4870", "ParentId": "4859", "Score": "3" } } ]
{ "AcceptedAnswerId": "4870", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-15T23:25:18.077", "Id": "4859", "Score": "3", "Tags": [ "object-oriented", "actionscript-3" ], "Title": "More efficient way to write this Actionscript 3 class?" }
4859
<p>At the end of the <a href="http://go.googlecode.com/hg-history/release-branch.r60/doc/GoCourseDay1.pdf" rel="nofollow">Day 1 Go Course slides (pdf)</a> there is an exercise stated as follows (NOTE: the course in the linked presentation is considered obsolete. If you are looking to learn Go the suggested route is first via <a href="http://tour.golang.org" rel="nofollow">http://tour.golang.org</a>):</p> <blockquote> <p>You all know what the Fibonacci series is. Write a package to implement it. There should be a function to get the next value. (You don't have structs yet; can you find a way to save state without globals?) But instead of addition, make the operation settable by a function provided by the user. Integers? Floats? Strings? Up to you.</p> </blockquote> <p>How does the following solution rate with respect to its 'Go'-iness?</p> <pre><code>package fib type BinOp func (uint64, uint64) uint64 func fib_intern(a, b uint64, op BinOp) uint64 { Fib = func(opnew BinOp) uint64 { return fib_intern(b, op(a,b), opnew) } return a } var Fib = func(op BinOp) uint64 { return fib_intern(0,1,op) } </code></pre> <p>Which can then be called like:</p> <pre><code>package main import ( "./fib" "fmt" ) func add(a, b uint64) uint64 { return a+b } func main() { for i := 0; i &lt; 20; i++ { fmt.Println(fib.Fib(add)) } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T14:46:10.820", "Id": "7265", "Score": "0", "body": "Probably the wrong place to ask. Try asking on StackOverflow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T23:29:16.957", "Id": "7285", "Score": "0", "body": "OK, happy for it to be migrated if its more suitable over in StackOverflow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T18:45:09.247", "Id": "34106", "Score": "0", "body": "I don't know, it seems to meet the criteria for here. Biggest problem currently is that the link is dead. Presumably the course is obsolete and has been removed from the Go site." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-24T12:28:13.093", "Id": "35585", "Score": "0", "body": "Thanks for pointing out the broken link. I've updated it to point to an archived version of the course. However, you are correct in that the content is now considered obsolete and the recommended starting point is the Go Tour (http://tour.golang.org)." } ]
[ { "body": "<p>The link is dead and the code doesn't compile, but there is still an obvious issue to critique: Part of the challenge was to not save state with \"global variables.\" In Go, package variables of the package main are typically considered \"global variables\". However, only a single instance of any package ever exists at run time, so package variables of all packages are essentially global variables as well. The code here uses a package variable fib.Fib, thus the code is failing the exercise from the start, working or not.</p>\n\n<p>Edit: Thank you Anthony for tracking down the archived course and updating the question. It helps to have the full context. It also helps to have code working with a current version of Go, which is pretty easy:</p>\n\n<pre><code>package fib\n\ntype BinOp func(uint64, uint64) uint64\n\nvar Fib func(op BinOp) uint64\n\nfunc init() {\n Fib = func(op BinOp) uint64 {\n return fib_intern(0, 1, op)\n }\n}\n\nfunc fib_intern(a, b uint64, op BinOp) uint64 {\n Fib = func(opnew BinOp) uint64 {\n return fib_intern(b, op(a, b), opnew)\n }\n return a\n}\n</code></pre>\n\n<p>Go now has stricter checking of static dependencies and reports \"initialization loop\" with the old code. My update of your code works by moving the initial assignment of Fib to an init function, which runs at program startup.</p>\n\n<p>I'll abandon this answer now and add another answer where I try to stick to your request for a review of the 'Go'-iness.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-03T19:06:22.467", "Id": "21253", "ParentId": "4860", "Score": "6" } }, { "body": "<p>With working code it's fun to instrument it and watch it work. Each call to fib.Fib computes a new value in the sequence and also replaces itself with a new function literal to hold the new vaue. It's computationally efficient but it does keep allocating and discarding function literals, creating garbage on each call. A better solution would be one that avoided this memory churn. Having a sense for this isn't an idiom, but I think it counts for Go style, to be aware of your use of memory, and to find memory-efficient algorithms.</p>\n\n<p>A purely stylistic issue is the name of the function fib_intern. Go style is to use camel-case as in fibIntern. But even this is redundant. Lower case always means non-exported, so simply 'fib' is enough. There's nothing wrong with having both Fib and fib. Go programmers understand that one is exported, one isn't, and that they are two different things. Perhaps you wanted a more descriptive name than just fib, but fib_intern isn't it. That tells your reader nothing that isn't obvious already.</p>\n\n<p>Finally, the use of a relative import path, \"./fib\" is okay for a small exercise like this, but it's not a habit you want to form. Relative import paths have historically been problematic, and I think it's fine to do little experiments like this right on your GOPATH.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-25T18:19:49.867", "Id": "23121", "ParentId": "4860", "Score": "3" } }, { "body": "<p>How about using channels to do it?</p>\n\n<pre><code>func fib(f func(int, int) int) chan int {\n\n ch := make(chan int)\n a, b := 0, 1\n go func() {\n for {\n a, b = b, f(a, b)\n ch &lt;- a\n }\n }()\n return ch\n}\n</code></pre>\n\n<p>This takes a function which returns an integer given two others, and returns a channel which will supply each term.</p>\n\n<p>You can then run it by doing something like:</p>\n\n<pre><code>func add(a, b int) int {\n return a + b\n}\n\nfunc main() {\n\n ch := fib(add)\n for i := 0; i &lt; 10; i++ {\n fmt.Println(&lt;-ch)\n }\n}\n</code></pre>\n\n<p>I'm still just getting used to go, so not sure how idiomatic this solution is. You would certainly need to ensure you stopped the goroutine by passing it a 'done' channel or something, but for quick jobs, this is a quick and easy solution.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-16T13:06:15.783", "Id": "84204", "ParentId": "4860", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T06:00:58.850", "Id": "4860", "Score": "4", "Tags": [ "go", "fibonacci-sequence" ], "Title": "Fibonacci implementation in Go" }
4860
<p>I've got a foreach loop, going through each section of an XML document (an example of said XML document can be found in <a href="https://stackoverflow.com/q/4122955/500559">this SO question</a>) and only display them in divs with corresponding classes. </p> <pre><code>&lt;xsl:for-each select="sections/section"&gt; &lt;xsl:sort select="sc_index" /&gt; &lt;h2&gt; &lt;xsl:value-of select='name' /&gt; &lt;/h2&gt; &lt;div class="rel10r3"&gt; &lt;ul&gt; &lt;xsl:for-each select="instructions/instruction[releases//release='10r3']"&gt; &lt;xsl:sort select="index" /&gt; &lt;li&gt; &lt;xsl:value-of select="content" /&gt; &lt;/li&gt; &lt;/xsl:for-each&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="rel11r2" style="display:none"&gt; &lt;ul&gt; &lt;xsl:for-each select="instructions/instruction[releases//release='11r2']"&gt; &lt;xsl:sort select="index" /&gt; &lt;li&gt; &lt;xsl:value-of select="content" /&gt; &lt;/li&gt; &lt;/xsl:for-each&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="rel12r1" style="display:none"&gt; &lt;ul&gt; &lt;xsl:for-each select="instructions/instruction[releases//release='12r1']"&gt; &lt;xsl:sort select="index" /&gt; &lt;li&gt; &lt;xsl:value-of select="content" /&gt; &lt;/li&gt; &lt;/xsl:for-each&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="rel12r2" style="display:none"&gt; &lt;ul&gt; &lt;xsl:for-each select="instructions/instruction[releases//release='12r2']"&gt; &lt;xsl:sort select="index" /&gt; &lt;li&gt; &lt;xsl:value-of select="content" /&gt; &lt;/li&gt; &lt;/xsl:for-each&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="rel13r1" style="display:none"&gt; &lt;ul&gt; &lt;xsl:for-each select="instructions/instruction[releases//release='13r3']"&gt; &lt;xsl:sort select="index" /&gt; &lt;li&gt; &lt;xsl:value-of select="content" /&gt; &lt;/li&gt; &lt;/xsl:for-each&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/xsl:for-each&gt; </code></pre> <p>What I do after that is using a drop-down menu, and with the help of javascript switch the style.display property of the divs accordingly.</p> <p>Form:</p> <pre><code>&lt;form&gt; &lt;select name="release" onchange="return showHide(this);"&gt; &lt;option value="10r3" selected="selected"&gt;10r3&lt;/option&gt; &lt;option value="11r2"&gt;11r2&lt;/option&gt; &lt;option value="12r1"&gt;12r1&lt;/option&gt; &lt;option value="12r2"&gt;12r2&lt;/option&gt; &lt;option value="13r1"&gt;13r1&lt;/option&gt; &lt;/select&gt; &lt;/form&gt; </code></pre> <p>Javascript:</p> <pre><code>function showHide(selection) { var f = selection.form; // Retrieve the value of the option selected. var opt = selection.options[selection.selectedIndex].value; /* Retrieve all the div elements of the document and then parse them to * see if they have a classname corresponding with the selected release. * If it is the case, remove all display style, otherwise set the * display style to none. */ var divArray = document.getElementsByTagName("div"); for(var i=0; i&lt;divArray.length; i++){ var relArray = ["10r3","11r2","12r1","12r2","13r1"]; for(var j=0; j&lt;relArray.length; j++){ var relName = relArray[j]; if(divArray[i].className == "rel"+relName){ if(opt===relName){ divArray[i].style.display = ""; }else{ divArray[i].style.display = "none"; } } } } return false; } </code></pre> <p>I've already refactored my javascript code, but there is still plenty of repetitive code out there, and it can only grow the more releases there will be.</p> <p><strong>EDIT:</strong> One more thing, those instruction are shown in a CSS pop-up using a technique I found (<a href="http://www.pat-burt.com/web-development/how-to-do-a-css-popup-without-opening-a-new-window/" rel="nofollow noreferrer">reference</a>):</p> <p>HTML:</p> <pre><code>&lt;div&gt; &lt;a id="helplink" href="#" onclick="popup('popUpDiv')"&gt;Click Here to Open the Help&lt;/a&gt; &lt;/div&gt; </code></pre> <p>Javascript:</p> <pre><code>function toggle(div_id) { var el = document.getElementById(div_id); if ( el.style.display == 'none' ) { el.style.display = 'block';} else {el.style.display = 'none';} } function blanket_size(popUpDivVar) { if (typeof window.innerWidth != 'undefined') { viewportheight = window.innerHeight; } else { viewportheight = document.documentElement.clientHeight; } if ((viewportheight &gt; document.body.parentNode.scrollHeight) &amp;&amp; (viewportheight &gt; document.body.parentNode.clientHeight)) { blanket_height = viewportheight; } else { if (document.body.parentNode.clientHeight &gt; document.body.parentNode.scrollHeight) { blanket_height = document.body.parentNode.clientHeight; } else { blanket_height = document.body.parentNode.scrollHeight; } } var blanket = document.getElementById('blanket'); blanket.style.height = blanket_height + 'px'; var popUpDiv = document.getElementById(popUpDivVar); popUpDiv_height=50; popUpDiv.style.top = popUpDiv_height + 'px'; } function window_pos(popUpDivVar) { if (typeof window.innerWidth != 'undefined') { viewportwidth = window.innerHeight; } else { viewportwidth = document.documentElement.clientHeight; } if ((viewportwidth &gt; document.body.parentNode.scrollWidth) &amp;&amp; (viewportwidth &gt; document.body.parentNode.clientWidth)) { window_width = viewportwidth; } else { if (document.body.parentNode.clientWidth &gt; document.body.parentNode.scrollWidth) { window_width = document.body.parentNode.clientWidth; } else { window_width = document.body.parentNode.scrollWidth; } } var popUpDiv = document.getElementById(popUpDivVar); window_width=50; popUpDiv.style.left = window_width + 'px'; } function popup(windowname) { blanket_size(windowname); window_pos(windowname); toggle('blanket'); toggle(windowname); } </code></pre> <p>CSS:</p> <pre><code>#blanket { background-color:#111; opacity: 0.65; filter:alpha(opacity=65); position:absolute; z-index: 9001; top:0px; left:0px; width:100%; } #popUpDiv { position:absolute; background-color:#eeeeee; width:700px; height:700px; z-index: 9002; } </code></pre> <p>I mention this information, because the refactoring proposed seems to mess with my pop-up.</p> <p><strong>EDIT2:</strong> One of the shortcoming of the actual code I noticed is that I wouldn't be able to use <code>release</code> element of value All, which would make that the parent <code>instruction</code> keep its place relative to other elements of a specific release, whichever release is selected.</p>
[]
[ { "body": "<p>On the js side, I'm not convinced you need the double looping.\nHave you tried something like this:</p>\n\n<pre><code>var optClass = \"rel\" + selection.options[selection.selectedIndex].value;\nvar divArray = document.getElementsByTagName(\"div\");\nfor (var i = 0; i &lt; divArray.length; i++){\n divArray[i].style.display = optClass === divArray[i].className ? \"\" : \"none\"; \n}\n</code></pre>\n\n<p>On the xslt side, you will want to factor the div blocks in a separate template with parameters for the release number and the style.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T12:39:49.633", "Id": "7258", "Score": "0", "body": "Sorry, but your refactoring broke the function, so I had to come back to my code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T14:15:08.473", "Id": "7261", "Score": "0", "body": "Oops, messed up array iteration syntax :-). I updated the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T06:44:12.290", "Id": "7354", "Score": "0", "body": "Now, when I change an option in my drop down menu, the css pop-up disappears completely. I suspect that it hide also the div containing my help link." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T12:09:04.713", "Id": "4864", "ParentId": "4861", "Score": "0" } }, { "body": "<ol>\n<li><p>in your <code>showHide()</code> function:</p>\n\n<pre><code>var relArray = [\"rel10r3\",\"rel11r2\",\"rel12r1\",\"rel12r2\",\"rel13r1\"];\nfor(var i=0; i&lt;divArray.length; i++)\n{\n var currentDiv = divArray[i];\n if(currentDiv.className &amp;&amp; relArray.indexOf(currentDiv.className) != -1)\n {\n currentDiv.style.display = \"\"; \n }\n else\n {\n currentDiv.style.display = \"none\";\n }\n}\n</code></pre></li>\n<li><p>Don't be skimpy on the formatting as it makes a big difference on the readability. forexample:</p>\n\n<pre><code>function toggle(div_id) {\n var el = document.getElementById(div_id);\n if (el.style.display == 'none' )\n {\n el.style.display = 'block';\n }\n else \n {\n el.style.display = 'none';\n }\n}\n</code></pre></li>\n<li><p>Javascript is very nice with falsey values:</p>\n\n<pre><code>if (typeof window.innerWidth != 'undefined') {\n viewportheight = window.innerHeight;\n} else {\n viewportheight = document.documentElement.clientHeight;\n}\n</code></pre>\n\n<p>can be written:</p>\n\n<pre><code>if (window.innerWidth) {\n viewportheight = window.innerHeight;\n} else {\n viewportheight = document.documentElement.clientHeight;\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>viewportheight = window.innerHeight || document.documentElement.clientHeight;\n</code></pre></li>\n<li><p>patterns like:</p>\n\n<pre><code>if(){\n //\n}else{\n if(){\n //\n }else{\n //\n }\n}\n</code></pre>\n\n<p>can be written much easier and cleaner:</p>\n\n<pre><code>if(){\n //\n}else if(){\n //\n}else{\n //\n}\n</code></pre></li>\n<li><p>you have:</p>\n\n<pre><code>if ((viewportwidth &gt; document.body.parentNode.scrollWidth) &amp;&amp; (viewportwidth &gt; document.body.parentNode.clientWidth)) {\n //etc etc\n</code></pre>\n\n<p>can be:</p>\n\n<pre><code>window_width = Math.max(viewportwidth, document.body.parentNode.clientWidth, document.body.parentNode.scrollWidth); \n</code></pre></li>\n<li><p>you are using variables to hold a value for one line:</p>\n\n<pre><code>var popUpDiv = document.getElementById(popUpDivVar);\nwindow_width=50;\npopUpDiv.style.left = window_width + 'px';\n</code></pre>\n\n<p>instead:</p>\n\n<pre><code>var popUpDiv = document.getElementById(popUpDivVar);\nif(popUpDiv) // incase it couldn't find the div.\n{\n popUpDiv.style.left = \"50px\";\n}\n</code></pre></li>\n</ol>\n\n<p><strong>TL;DR?</strong> <a href=\"http://jsfiddle.net/37Uge/1/\" rel=\"nofollow\">http://jsfiddle.net/37Uge/1/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T14:07:55.293", "Id": "7847", "Score": "0", "body": "Thanks for all the tip. To be honest, the css pop-up code aren't from me, I added the source in my post. But about the first point, it doesn't really work. When the call the function showHide is triggered, all the contents inside divs disapear, included my drop-down menu. When I choose to move the `relArray.indexOf` check outside of the if else structure, so then, when the function is called, all the divs are displayed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T22:37:40.573", "Id": "7861", "Score": "0", "body": "@Eldros Thats because i didn't write the `relArray` properly I only put `'rel'` in the first element instead of all of them. I'll fix it and you can try it again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T22:45:06.053", "Id": "7862", "Score": "0", "body": "@Eldros about your **edit2** you could put a specific value *(e.g. 99)* and test for this before looping." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T06:53:21.233", "Id": "7874", "Score": "0", "body": "I already caught your mistake and put `rel` before each release ids before I made my last comment, so it is not the source of the problem. About using a specific value, I'll see what I can do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T07:43:15.653", "Id": "7875", "Score": "1", "body": "After a few fiddling I came to a working code: [link](http://jsfiddle.net/37Uge/2)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T09:25:23.840", "Id": "7879", "Score": "0", "body": "@Eldros that looks great! The only thing I would change is the naming inconsistency but that's just a cosmetic change (makes it easier to read variables with a similar naming style). `underscore_serparated` in some places and `camelCase` in others." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T01:10:37.390", "Id": "5187", "ParentId": "4861", "Score": "2" } }, { "body": "<p>I'd cache your loop variables as well...</p>\n\n<pre><code> for(var i=0; i&lt;divArray.length; i++){}\n</code></pre>\n\n<p>...would be written</p>\n\n<pre><code>var len = divArray.length;\n\nfor(var i = 0; i &lt; len ; i++){}\n</code></pre>\n\n<p>This is according to Addy Osmani's blog post \"<a href=\"http://addyosmani.com/blog/lessons-from-a-javascript-code-review/\" rel=\"nofollow\">Lessons From A JavaScript Code Review</a>\":</p>\n\n<blockquote>\n <p>Problem: An uncached array.length is being used in all for loops. This\n is particularly bad as you're using it when iterating through\n 'HTMLCollection's</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T02:15:09.600", "Id": "7804", "Score": "0", "body": "a shorter way of writing this would be: `for(var i = 0, len = divArray.length; i < len ; i++)`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T01:33:10.043", "Id": "5189", "ParentId": "4861", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T09:04:30.177", "Id": "4861", "Score": "3", "Tags": [ "javascript" ], "Title": "Foreach loop displaying instruction relative to a release number" }
4861
<p>This code is part of one of the methods. I'm pretty sure it is really bad programming. The third if statement is supposed to be called if all 4 variables were set. Is another method needed? How would you write this piece?</p> <pre><code>int width = img.Width; int height = img.Height; int thumbWidth = 0 , thumbHeight = 0; int preWidth = 0, preHeight = 0; //if Landscape if (width &gt; height &amp;&amp; width &gt;= 471) { thumbWidth = 120; thumbHeight = ((120 * height) / width); preWidth = 471; preHeight = ((471 * height) / width); } //if portrait else if (height &gt; width &amp;&amp; height &gt;= 353) { thumbHeight = 120; thumbWidth = ((120 * width) / height); preHeight = 353; preWidth = ((353 * width) / height); } //If values were set if (thumbWidth != 0 &amp;&amp; thumbHeight != 0 &amp;&amp; preWidth != 0 &amp;&amp; preHeight != 0) { } else { //do other stuff } </code></pre>
[]
[ { "body": "<p>How about this as a starter?</p>\n\n<pre><code> int width = img.Width;\n int height = img.Height;\n int thumbWidth = 0 , thumbHeight = 0;\n int preWidth = 0, preHeight = 0;\n\n bool valuesSet = false;\n\n //if Landscape\n if (width &gt; height &amp;&amp; width &gt;= 471)\n {\n thumbWidth = 120;\n thumbHeight = ((120 * height) / width);\n preWidth = 471;\n preHeight = ((471 * height) / width);\n valuesSet = true;\n }\n //if portrait \n else if (height &gt; width &amp;&amp; height &gt;= 353)\n {\n thumbHeight = 120;\n thumbWidth = ((120 * width) / height);\n preHeight = 353;\n preWidth = ((353 * width) / height);\n valuesSet = true;\n }\n\n //If values were set\n if (valuesSet)\n {\n }\n else \n { \n //do other stuff\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T14:03:32.983", "Id": "7260", "Score": "0", "body": "Thanks for the answer. I wouldn't really like to use flags for this purpose. Do you have any other suggestions ? Perhaps a new method that returns both values somehow. I just don't have enough experience yet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T14:38:56.497", "Id": "7263", "Score": "0", "body": "That's a fair comment - your question was originally posted on StackOverflow; had I known we were migrating to CodeReview I would have suggested something more radical. You've got some great other suggestions on the page now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T15:38:43.937", "Id": "7266", "Score": "0", "body": "I appreciate the answer anyway, Sam !" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T13:53:01.237", "Id": "4866", "ParentId": "4865", "Score": "0" } }, { "body": "<p>I think the logic flow reads better if you factor out the calculation of the thumb* and pre* variables:</p>\n\n<pre><code>private void Doit() {\n int width = img.Width;\n int height = img.Height;\n\n var dimensions=CalculateDimensions(width, height);\n\n //if values were set\n if(dimensions!=null) {\n\n } else {\n //do other stuff\n }\n}\n\nprivate static Dimension CalculateDimensions(int width, int height) {\n //if Landscape\n if(width &gt; height &amp;&amp; width &gt;= 471) {\n return new Dimension(120, ((120*height)/width), 471, ((471*height)/width));\n }\n if(height &gt; width &amp;&amp; height &gt;= 353) {\n return new Dimension(120, ((120*width)/height), 353, ((353*width)/height));\n }\n return null;\n}\n\npublic sealed class Dimension {\n ...\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T14:02:43.323", "Id": "4867", "ParentId": "4865", "Score": "1" } }, { "body": "<p>The problems I see here involve code duplication and magic values, and perhaps some incomplete logic. </p>\n\n<p>You use the numbers 120, 471, 353. I don't know what those mean. And they're duplicated. Make those variables with descriptive names. </p>\n\n<p>Now let's look at this: </p>\n\n<pre><code>//if Landscape\nif (width &gt; height &amp;&amp; width &gt;= 471)\n</code></pre>\n\n<p>This is more than than just <em>if landscape</em>. This is <em>if landscape and is too big.</em> But I'm not encouraging you to write a better comment! Instead, I encourage you to encapsulate that conditional into it's own method, with a more descriptive name, and then <em>remove</em> the comment. </p>\n\n<pre><code>private bool IsLandscapeAndTooBig(width, height)\n{\n return width &gt; height &amp;&amp; width &gt; maximumWidth; // notice the new variable?\n}\n</code></pre>\n\n<p>The same idea applies to your \"if portrait\" piece. </p>\n\n<p>Let's look inside those <em>ifs</em> now. Again, the problem is the magic values, but perhaps these inner blocks need to be methods, perhaps <code>ResizeLandscape</code> and <code>ResizePortrait</code> (but you probably want to think a bit longer on these names). And instead of operating on 4 local variables, perhaps they should instead return a single encapsuting data object. </p>\n\n<pre><code>class ImageDimension\n{\n public int ThumbWidth { get; set; }\n // continues \n}\n</code></pre>\n\n<p>one other thing I see is that you build thumbnail dimensions for too large of a landscape and too large of a portrait, but you don't seem to build them for images that are <em>not</em> too large. Does something just smaller than your threshold for \"large\" not need a thumbnail? This is where I think you might have some missing logic. On the other hand, you might not, I don't know entirely what you are trying to do. Just keep this in mind.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T14:44:43.130", "Id": "7264", "Score": "0", "body": "+1 Nice: Like the idea of moving test to descriptive methods so that comments can be removed." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T14:12:15.497", "Id": "4868", "ParentId": "4865", "Score": "8" } }, { "body": "<p>The code is not <em>terrible</em>, but I can make a few observations that we can use to improve the code:</p>\n\n<ul>\n<li>It will be useful to know elsewhere (presentation time, perhaps?) whether or not this is portait or landscape. Let's build that now so we can keep the information somewhere useful.</li>\n<li>The <strong>only</strong> ways any of those values will ever by 0 (not set) is if height or width is zero, or the image is too small. That's probably an invalid state to begin with, and it should the responsibility of the code that calls this to deal with it. So let's check for that up front.</li>\n<li>I'm concerned about your use of \"magic numbers\": 471, 353, and 120. I'd love to see those factored out to variables.</li>\n</ul>\n\n<p>With that in mind, here's an idea:</p>\n\n<pre><code>//there are better places to define this, but I'll leave them here now for convenience in this example\nint minLandscapeWidth = 471, minPortiatHeight = 353, thumbLongSide = 120;\n\nint width = img.Width;\nint height = img.Height;\n\n//you may not need these checks, depending what your img object is and how you use it\nif (width &lt;= 0) throw new InvalidOperationException(\"img.Width should be greater than zero\");\nif (height&lt;= 0) throw new InvalidOperationException(\"img.Height should be greater than zero\");\n\nbool landscape = (width &gt; height);\n\nif ( (landscape &amp;&amp; width &lt; minLandscapeWidth) || (!landscape &amp;&amp; height &lt; minPortraitHeight) )\n throw new InvalidOperationException(\"the image is too small\");\n\nint thumbWidth, thumbHeight, preWidth, preHeight;\n\nif (landscape)\n{\n thumbWidth = thumbLongSide;\n thumbHeight = ((thumbLongSide * height) / width);\n preWidth = minLandscapeWidth;\n preHeight = ((minLandscapeWidth * height) / width);\n}\nelse \n{\n thumbHeight = thumbLongSide;\n thumbWidth = ((thumbLongSide * width) / height);\n preHeight = minPortraitHeight ;\n preWidth = ((minPortraitHeight * width) / height);\n}\n\n//values are now set\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T14:38:15.767", "Id": "7262", "Score": "1", "body": "It's interesting that you come away from the original code thinking there are problems with images being too small, and I come away thinking that it intends to deal with images that are too big. I wonder if seeing the actual class/method name would help provide the correct context. @Chuchelo, this is an example of where I think you see the importance of descriptive names, because absent that, people are left to interpret what code might actually mean." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T14:17:56.160", "Id": "4869", "ParentId": "4865", "Score": "8" } } ]
{ "AcceptedAnswerId": "4869", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T13:50:34.270", "Id": "4865", "Score": "6", "Tags": [ "c#", "image" ], "Title": "Checking for minimum image dimensions" }
4865
<p>So I have this SDK I'm working with, which lives in unmanaged land, and when it wants to tell me something in particular it sends me a particular Windows API message and passes a pointer to a Date in the LParam of that message. I figured out that the date is OA-compatible (a double representing a fractional number of days since the epoch), and so after some playing around I came up with this:</p> <ul> <li>Dereference the pointer by marshalling the raw bits at the address into an Int64.</li> <li>Perform a bitwise conversion of the Int64 into a Double.</li> <li>Treat that double as an OA Date and pass it to the static methods on DateTime to get the answer.</li> </ul> <p>It totally works, but conceptually it sounds really kludgy; pointer, to long, to double (bitwise to boot), to DateTime. Other than inlining these three lines with only the final result being stored, is there any more direct way in .NET to turn an IntPtr to an OLE Date into a DateTime?</p> <pre><code>private void GetDateFromWinMsg(Message message) { ... var dateAsULong = Marshal.ReadInt64(message.LParam); var dateAsDouble = BitConverter.Int64BitsToDouble(dateAsULong); var dateTime = DateTime.FromOADate(dateAsDouble); ... } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T17:47:06.607", "Id": "7271", "Score": "3", "body": "Doesn't look kludgy to me ...although that doesn't mean there isn't a shorter process. Think of each function as a tool - you need 3 tools to perform the conversion." } ]
[ { "body": "<p>I agree with @IAbstract that the inline code looks fine. I would wrap it and name it differently since nothing in the current code reveals that it is a pointer to an OLE/OA Date.</p>\n\n<pre><code>public DateTime DateTimeFromOLEDatePointer(Int64 oaDate)\n {\n var dateAsULong = Marshal.ReadInt64(oaDate); \n var dateAsDouble = BitConverter.Int64BitsToDouble(dateAsULong); \n var dateTime = DateTime.FromOADate(dateAsDouble); \n } \n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>private void GetDateFromWinMsg(Message message)\n {\n return DateTimeFromOLEDatePointer(message.LParam);\n }\n</code></pre>\n\n<p>Could also make it an extension method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-16T17:17:49.230", "Id": "7869", "ParentId": "4871", "Score": "2" } } ]
{ "AcceptedAnswerId": "7869", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T17:02:24.143", "Id": "4871", "Score": "5", "Tags": [ "c#", "datetime" ], "Title": ".NET - Get a DateTime from a pointer to an OLE Date" }
4871
<p>As part of my implementation of cross-validation, I find myself needing to split a list into chunks of roughly equal size.</p> <pre><code>import random def chunk(xs, n): ys = list(xs) random.shuffle(ys) ylen = len(ys) size = int(ylen / n) chunks = [ys[0+size*i : size*(i+1)] for i in xrange(n)] leftover = ylen - size*n edge = size*n for i in xrange(leftover): chunks[i%n].append(ys[edge+i]) return chunks </code></pre> <p>This works as intended</p> <pre><code>&gt;&gt;&gt; chunk(range(10), 3) [[4, 1, 2, 7], [5, 3, 6], [9, 8, 0]] </code></pre> <p>But it seems rather long and boring. Is there a library function that could perform this operation? Are there pythonic improvements that can be made to my code?</p>
[]
[ { "body": "<blockquote>\n <p>Is there a library function that could perform this operation? </p>\n</blockquote>\n\n<p>No.</p>\n\n<blockquote>\n <p>Are there pythonic improvements that can be made to my code?</p>\n</blockquote>\n\n<p>A few.</p>\n\n<p>Sorry it seems boring, but there's not much better you can do.</p>\n\n<p>The biggest change might be to make this into a generator function, which may be a tiny bit neater. </p>\n\n<pre><code>def chunk(xs, n):\n ys = list(xs)\n random.shuffle(ys)\n size = len(ys) // n\n leftovers= ys[size*n:]\n for c in xrange(n):\n if leftovers:\n extra= [ leftovers.pop() ] \n else:\n extra= []\n yield ys[c*size:(c+1)*size] + extra\n</code></pre>\n\n<p>The use case changes, slightly, depending on what you're doing</p>\n\n<pre><code>chunk_list= list( chunk(range(10),3) )\n</code></pre>\n\n<p>The <code>if</code> statement can be removed, also, since it's really two generators. But that's being really fussy about performance.</p>\n\n<pre><code>def chunk(xs, n):\n ys = list(xs)\n random.shuffle(ys)\n size = len(ys) // n\n leftovers= ys[size*n:]\n for c, xtra in enumerate(leftovers):\n yield ys[c*size:(c+1)*size] + [ xtra ]\n for c in xrange(c+1,n):\n yield ys[c*size:(c+1)*size]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T20:51:19.490", "Id": "4873", "ParentId": "4872", "Score": "2" } }, { "body": "<p>Make it a generator. You could then simplify the logic.</p>\n\n<pre><code>def chunk(xs, n):\n ys = list(xs)\n random.shuffle(ys)\n chunk_length = len(ys) // n\n needs_extra = len(ys) % n\n start = 0\n for i in xrange(n):\n if i &lt; needs_extra:\n end = start + chunk_length + 1\n else:\n end = start + chunk_length\n yield ys[start:end]\n start = end\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T21:13:46.607", "Id": "4874", "ParentId": "4872", "Score": "0" } }, { "body": "<pre><code>import random\n\ndef chunk(xs, n):\n ys = list(xs)\n</code></pre>\n\n<p>Copies of lists are usually taken using <code>xs[:]</code></p>\n\n<pre><code> random.shuffle(ys)\n ylen = len(ys)\n</code></pre>\n\n<p>I don't think storing the length in a variable actually helps your code much</p>\n\n<pre><code> size = int(ylen / n)\n</code></pre>\n\n<p>Use <code>size = ylen // n</code> // is the integer division operator</p>\n\n<pre><code> chunks = [ys[0+size*i : size*(i+1)] for i in xrange(n)]\n</code></pre>\n\n<p>Why the <code>0+</code>? </p>\n\n<pre><code> leftover = ylen - size*n\n</code></pre>\n\n<p>Actually, you can find size and leftover using <code>size, leftover = divmod(ylen, n)</code></p>\n\n<pre><code> edge = size*n\n for i in xrange(leftover):\n chunks[i%n].append(ys[edge+i])\n</code></pre>\n\n<p>You can't have <code>len(leftovers) &gt;= n</code>. So you can do:</p>\n\n<pre><code> for chunk, value in zip(chunks, leftover):\n chunk.append(value)\n\n\n return chunks\n</code></pre>\n\n<p>Some more improvement could be had if you used numpy. If this is part of a number crunching code you should look into it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T22:27:21.407", "Id": "4880", "ParentId": "4872", "Score": "5" } } ]
{ "AcceptedAnswerId": "4880", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-16T19:46:13.750", "Id": "4872", "Score": "6", "Tags": [ "python" ], "Title": "Pythonic split list into n random chunks of roughly equal size" }
4872
<p>Just need to know if I'm doing something wrong in this code. my app seem work fast now with this code. I just want to if i really understant that</p> <pre><code> - (void)receive { NSString *post2 = [NSString stringWithFormat:@"expediteur=%@&amp;destinataire=%@", [[expediteurLbl text] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], [[destinataireLbl text] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; NSData *dataToSend2 = [NSData dataWithBytes:[post2 UTF8String] length:[post2 length] ]; request2 = [[[NSMutableURLRequest alloc] init] autorelease]; [request2 setURL:[NSURL URLWithString:@"http:/****************.php"]]; [request2 setHTTPMethod:@"POST"]; [request2 setHTTPBody:dataToSend2]; [request2 setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"]; [NSThread detachNewThreadSelector:@selector(displayView) toTarget:self withObject:nil]; } -(void)displayView { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; NSURLResponse *response2; NSError *error2; NSData *data2 = [NSURLConnection sendSynchronousRequest:request2 returningResponse:&amp;response2 error:&amp;error2]; reponseServeur2= [[NSMutableString alloc] initWithData:data2 encoding: NSASCIIStringEncoding]; responseString2 = [[NSString alloc] initWithData:data2 encoding:NSUTF8StringEncoding]; [[reponseServeur2 stringByReplacingOccurrencesOfString:@"\n" withString:@""] mutableCopy]; self.messageArray = [responseString2 JSONValue]; [messTableView reloadData]; [pool release]; } </code></pre> <p>and</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; [self performSelectorInBackground:@selector(receive) withObject:nil]; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T00:16:30.233", "Id": "7286", "Score": "0", "body": "i don't have errors but in console somes warnings \"NSAutoreleaseNoPool(): Object 0x4e45ab0 of class NSCFString autoreleased with no pool in place - just leaking\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T00:23:16.557", "Id": "7287", "Score": "0", "body": "You're not autoreleasing any objects inside the autorelease pool, so why have you used it inside `displayView`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T00:27:33.957", "Id": "7288", "Score": "0", "body": "i can not release NSArray?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T00:30:14.997", "Id": "7289", "Score": "0", "body": "What array? The only array there *might* be is `self.messageArray`. Looks like you've synthesized that property, so you'll only need to release it in your `dealloc` method if you're using `retain` or `copy` on the property." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T00:34:00.880", "Id": "7290", "Score": "0", "body": "ok i understand. but I 'trying to do a thread not to slow down the application" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T00:47:30.173", "Id": "7291", "Score": "0", "body": "Yeah, but you're calling UI methods (`reloadData`) in a thread that is not the main thread - and that is a bad thing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T00:49:34.393", "Id": "7292", "Score": "0", "body": "@Alex There are many autoreleased objects in both `receive` and `displayView`, including the NSData returned by `sendSynchronousRequest`, the object returned by `JSONValue`, and several others." } ]
[ { "body": "<p>I gather that <code>request2</code> is an instance variable? It's risky at best to set it with an autoreleased value and then expect it to be valid later in your <code>displayView</code> method. </p>\n\n<p>But it probably works because you execute <code>receive</code> in a background task, and background tasks have no default autorelease pool. If it weren't for that <code>request2</code> would likely go \"poof\" before it got to <code>displayView</code>.</p>\n\n<p>So all of the autoreleased data items in <code>receive</code> -- post2, dataToSend2, request2, several temporary strings, and at least one temporary URL -- are leaking.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T00:34:22.977", "Id": "4883", "ParentId": "4882", "Score": "2" } }, { "body": "<blockquote>\n <p>Just need to know if I'm doing something wrong in this code.</p>\n</blockquote>\n\n<p>The short answer is YES.</p>\n\n<ol>\n<li>request2 is allocated and autoreleased in a different thread than its referenced and may be dealloc'd before you get to use it in displayView. This would be a 'race condition' and you probably won't see it happen consistently, but it'll crash the app when it does happen.</li>\n<li><code>reponseServeur2</code> and <code>responseString2</code> are never released (or autoreleased) at all. These are memory leaks</li>\n<li>The line <code>[[reponseServeur2 stringByReplacingOccurrencesOfString:@\"\\n\" withString:@\"\"] mutableCopy];</code> does nothing. You'd want to assign the result of that expression to some variable.</li>\n<li><p>You appear to repeat the sequence:</p>\n\n<pre><code>self.messageArray = [responseString2 JSONValue];\n[messTableView reloadData];\n</code></pre>\n\n<p>which is probably just a typo.</p></li>\n<li>Everything in <code>receive</code> is happening without an Autorelease pool, so <code>post2</code>, <code>dataToSend2</code>, and <code>request2</code> will leak. The warning you report is for <code>post2</code>, probably. Minimally, you need to wrap the contents of <code>receive</code> in an NSAutoreleasePool just like <code>displayView</code>.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T00:56:13.223", "Id": "7293", "Score": "0", "body": "ok thk for answer but i m sorry i m dropped :( . i try to something to use receveive in background for not slowing the app" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-29T22:00:07.727", "Id": "9928", "Score": "0", "body": "6. You shouldn't be updating the view from your thread; the UIKit is generally main-thread-only unless explicitly documented otherwise." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T00:40:23.490", "Id": "4884", "ParentId": "4882", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T00:10:53.543", "Id": "4882", "Score": "1", "Tags": [ "objective-c", "json", "memory-management" ], "Title": "NSAutoreleasePool with Json Data" }
4882
<p>The idea is to lock resources in C# or Java using Qt:</p> <pre><code>lock(obj){/*process with locked obj*/}` </code></pre> <p>Now I see the problem with deleting <code>obj</code> under <code>lock()</code>.</p> <p><strong>resourcelocker.h</strong></p> <pre><code>#ifndef RESOURCELOCKER_H #define RESOURCELOCKER_H #include &lt;QObject&gt; #include &lt;QHash&gt; #include &lt;QSemaphore&gt; class ResourceLocker : public QObject { Q_OBJECT public: friend class ResourceWatcher; explicit ResourceLocker(QObject *parent = 0); ~ResourceLocker(); bool lock(); private: static QHash&lt;QObject*,QSemaphore*&gt; resources; QSemaphore * sem; QObject * expectedParent; bool doubleLock; signals: public slots: }; #define _LOCK(object) for (ResourceLocker locker((object)); locker.lock(); ) #endif // RESOURCELOCKER_H </code></pre> <p><strong>resourcelocker.cpp</strong></p> <pre><code>#include "resourcelocker.h" #include &lt;QMutex&gt; #include &lt;QMutexLocker&gt; #include &lt;QSemaphore&gt; #include &lt;QDebug&gt; QHash&lt;QObject* ,QSemaphore*&gt; ResourceLocker::resources; class ResourceWatcher: public QObject { public: explicit ResourceWatcher(QObject * parent): QObject(parent) { //qDebug()&lt;&lt;"creating watcher"; } ~ResourceWatcher() { QSemaphore * sem = ResourceLocker::resources.value(parent(),NULL); if (sem-&gt;available()&gt;0) { //unlocked ResourceLocker::resources.remove(parent()); delete sem; } else { //locked ResourceLocker::resources.remove(parent()); } //qDebug()&lt;&lt;"removing sem"; } }; ResourceLocker::ResourceLocker(QObject *parent) :QObject(),expectedParent(parent),doubleLock(false) { } bool ResourceLocker::lock() { static QMutex internalMutex; { QMutexLocker locker(&amp;internalMutex); if (doubleLock) return false; doubleLock = true; //qDebug()&lt;&lt;&amp;expectedParent; sem = resources.value(expectedParent,NULL); if (sem == NULL) { //qDebug()&lt;&lt;"Crearting sem"; sem = new QSemaphore(1); resources.insert(expectedParent,sem); new ResourceWatcher(expectedParent); } } //qDebug()&lt;&lt;"acquiring"; sem-&gt;acquire(); return true; } ResourceLocker::~ResourceLocker() { QMutex internalMutex; QMutexLocker locker(&amp;internalMutex); //qDebug()&lt;&lt;"releasing"; sem-&gt;release(); if (!resources.values().contains(sem)) delete sem; } </code></pre> <p><strong>Usage:</strong></p> <pre><code>_LOCK(smth) { //prcoess with smth locked } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T14:18:17.720", "Id": "7298", "Score": "0", "body": "C++ is not Java or C#. Stop trying to apply concepts from other languages (in the other languages concept), it will just make learning to do things correctly harder. Learn how they are done in C++." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T14:25:04.610", "Id": "7299", "Score": "0", "body": "PS> _LOCK() is a reserved identifier." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T16:05:25.083", "Id": "7301", "Score": "0", "body": "Ok, I posted it here in hope that someone can show me real issues, connected with this code. Could you be more specific? Also, what alternative do you know to this in c++. I mean the way to synchronize access to some object with only knowing pointer to an object" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T16:09:52.117", "Id": "7302", "Score": "0", "body": "The real issue here is not in the code but in the attempt to apply concepts that don't fit. As far as I am concerned there is no point in further analysis. Others may be able/willing to help you." } ]
[ { "body": "<p>There reason languages like Java has that feature is because they don't have RAII like C++ does.</p>\n\n<p>I don't quite see how that is better than simply:</p>\n\n<pre><code>// Note: Braces for scope. \"mutex\" could optionally be declared static, or as a class member.\n{ \n QMutexLocker lock(&amp;mutex);\n\n /* code */\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-18T09:28:31.220", "Id": "7310", "Score": "0", "body": "A use case for my locker is when you have a resource (like file) and you access it in many places. If you just use mutex, you destroy encapsulation (you really need a pair of objects: real object and mutex to operate with real object) and get missconcept (lock of mutex instead of resource realy)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-18T10:11:47.283", "Id": "7312", "Score": "0", "body": "If you access it in many places I would call it bad design, you are already breaking encapsulation. But lets say that's the case anyways, wouldn't it be easier and faster to simply create a LockableObject wrapper around the \"resource\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-18T11:14:40.117", "Id": "7313", "Score": "0", "body": "I agree, that creating a wrapper is a solution of the problem and that it would be faster, still my code is more universal solution (written once, can be used later without writing additional code)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T21:55:41.087", "Id": "4894", "ParentId": "4886", "Score": "2" } } ]
{ "AcceptedAnswerId": "4894", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T10:20:26.223", "Id": "4886", "Score": "3", "Tags": [ "c++", "multithreading", "locking", "synchronization", "qt" ], "Title": "Resource locker in Qt" }
4886
<p>I'm writing a SQLite wrapper for C++. I have this class representing a database:</p> <pre><code> class Database { sqlite3 *db; public: Database(const std::string&amp; file_path, bool readonly = false) throw(SQLiteException); ~Database(); std::vector&lt;std::map&lt;std::string, Value&gt; &gt; Query(const std::string&amp; query) throw(SQLiteException); std::vector&lt;std::map&lt;std::string, Value&gt; &gt; Query(const std::string&amp; query, const std::vector&lt;Value&gt;&amp; bindings) throw(SQLiteException); }; </code></pre> <p>Where <code>Value</code> is a container for an <code>int</code>, <code>double</code>, <code>std::string</code> or <code>std::vector&lt;char&gt;</code> (because the returned type isn't yet known at compile-time).</p> <p>I'm concerned about the return value types of <code>Database::Query</code>. How could I simplify this?</p>
[]
[ { "body": "<p>Types have to be known at compile time. Unfortunately to be flexable you need to look up arbitory types at runtime for a DB. So either you need to use some form of template-meta programming or you can use a variant type. I would go for something like <a href=\"http://www.boost.org/doc/libs/1_47_0/doc/html/any.html\" rel=\"nofollow\">boost Any</a> object or <a href=\"http://www.boost.org/doc/libs/1_47_0/doc/html/variant.html\" rel=\"nofollow\">boost variant</a> this will allow you to return arbitrary types.</p>\n\n<p>I don't think you want to return the result from the DB after creating the Query. You want to return a query object that will allow you to bind things and execute the query at a latter stage. This is because in most DB systems creating the query is relatively expensive.</p>\n\n<p>And when you do execute the query you want to use the concept of the cursor (iterator) to move over the result set rather than generating the full result in one go (as this could potentially be huge).</p>\n\n<pre><code>int main();\n{\n Database db(\"Bla\", \"Passowrd\", true);\n Query getName = db.query(\"SELECT Name,Address,Phone \"\n \"FROM Users Where Age=%d and Sex=%s\");\n\n // Allow user to bind values to the query and execute.\n // As building the query can be expensive. So you want to re-use it.\n Result age25 = getName.execute(bind() % 25 % \"M\"));\n\n // Re-use the Query object for the next query (Note bind should allow multiple param)\n Result age31 = getName.execute(bind() % 31 % \"F\"));\n\n // Rather than returning all the results from the query in one go\n // Have the result object provide an `input iterator` allowing you to retrieve the\n // the rows as required. That way you do not need to copy out huge objects all in\n // one go. You can scan over the input until you get the bit you want (potentially)\n // only copying selected parts out of the result.\n\n if (!age25) // convert object to boolean to test for OK\n { // Like a std::stream object. This way if the query has\n // an error you can quickly an easily test for it.\n\n std::cout &lt;&lt; age25.error() &lt;&lt; \"\\n\";\n }\n else\n {\n for(RowIter row = RowIter(age25); row != RowIter(); ++row)\n { // ^^^^^^^^^ like std::istream_iteator\n // an empty object is end()\n\n std::cout &lt;&lt; db_cast&lt;std::string&gt;(row-&gt;get(\"Name\")) &lt;&lt; \" \"\n &lt;&lt; db_cast&lt;std::string&gt;(row-&gt;get(\"Address\")) &lt;&lt; \" \"\n &lt;&lt; db_cast&lt;int&gt;(row-&gt;get(\"Phone\")) &lt;&lt; \"\\n\";\n // ^^^^^^^^^^^^\n // Convert the object into the correct type\n // using a cast like syntax.\n\n }\n }\n}\n</code></pre>\n\n<p>Also do not limit it to sqlite.<br>\nMake it so it is easily expandable to other DB types.</p>\n\n<p>I would go with a prefix Notation on the DB name:</p>\n\n<pre><code>DataBase db1(\"sqlite://FileName1\", \"OptionalPassword\", flags);\nDataBase db2(\"mysql://db@host.bob.com\", \"Password\", flags);\nDatabase db3(\"oracle://plop.foo.bar\");\n</code></pre>\n\n<p>Internally you can then use the PIMPL design pattern to abstract the different types of DB. For now you just implement the sqlite version make the others generate an exception.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T14:56:05.243", "Id": "4889", "ParentId": "4887", "Score": "3" } } ]
{ "AcceptedAnswerId": "4889", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T11:45:30.337", "Id": "4887", "Score": "3", "Tags": [ "c++", "object-oriented", "sqlite" ], "Title": "Database class design" }
4887
<p>In the main class, loops generate numbers (0~100), and when its generated number is > 20, its value is passed to the thread where it simulates some work with this number. Meanwhile, while this number is being processed, other generated numbers > 20 must be skipped.</p> <p>Is this code OK? I am not sure if I'm doing something bad or not. In fact it seems to be working fine, but I don't know if it can be written by that way or even "better.".</p> <pre><code>class Program { delegate void SetNumberDelegate(int number); delegate bool IsBusyDelegate(); static void Main(string[] args) { Random rnd = new Random(); ProcessingClass processClass = new ProcessingClass(); SetNumberDelegate setNum = new SetNumberDelegate(processClass.setNumber); IsBusyDelegate isBusy = new IsBusyDelegate(processClass.isBusy); Thread processThread = new Thread(new ThreadStart(processClass.processNumbers)); processThread.Start(); int num; int count = 0; while (count++ &lt; 100) { num = rnd.Next(0, 100); Console.WriteLine("Generated number {0}", num); if (num &gt; 20) { if (!isBusy()) { setNum(num); } else { Console.WriteLine("Thread BUSY! Skipping number:{0}", num); } } Thread.Sleep(1); } processThread.Abort(); processThread.Join(); Console.ReadKey(); } } class ProcessingClass { private volatile bool busy; private volatile int number; public ProcessingClass() { busy = false; number = -1; } public bool isBusy() { return busy; } public void setNumber(int num) { number = num; } public void processNumbers() { while (true) { if (number &gt; -1 &amp;&amp; !busy) { busy = true; Console.WriteLine("Processing number:{0}", number); // simulate some work with number e.g. computing and storing to db Thread.Sleep(500); Console.WriteLine("Done"); number = -1; busy = false; } } } } </code></pre>
[]
[ { "body": "<p>There is no synchronisation here and so all access to the thread's state is subject to data races. It is comprehensively not threadsafe.</p>\n\n<p>From what I can tell all you need is to implement a producer/consumer pattern. Do this with a blocking queue. Please don't use busy loops. They burn CPU cycles and are horribly non-performant.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T18:34:56.463", "Id": "7307", "Score": "2", "body": "any short code sample, please?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T18:26:39.133", "Id": "4891", "ParentId": "4890", "Score": "3" } }, { "body": "<p>This is NOT thread-safe at all... for this sort of thing (Producer/Consumer) use BlockingCollection - see MSDN reference including code sample at <a href=\"http://msdn.microsoft.com/en-us/library/dd997371.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/dd997371.aspx</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T21:40:27.917", "Id": "4892", "ParentId": "4890", "Score": "1" } }, { "body": "<p>I think this should do what you expected to do.\nEnqueue all Numbers greater than 20 if no number is in the queue of the thread.<br/>\nPlease leave a comment if you wanted to do something else, i would be glad giving you the right examples.</p>\n\n<pre><code>class Program\n{\n delegate void SetNumberDelegate (int number);\n\n delegate bool IsBusyDelegate ();\n\n static void Main (string[] args) {\n Random rnd = new Random ();\n ProcessingClass processClass = new ProcessingClass ();\n\n ManualResetEvent resetEvent = new ManualResetEvent (false);\n ThreadPool.QueueUserWorkItem (processClass.ProcessNumbers, resetEvent);\n\n int num;\n int count = 0;\n while (count++ &lt; 100) {\n num = rnd.Next (0, 100);\n Console.WriteLine (\"Generated number {0}\", num);\n\n if (num &gt; 20) {\n if (!processClass.IsBusy) {\n processClass.Enqueue (num);\n } else {\n Console.WriteLine (\"Thread BUSY! Skipping number:{0}\", num);\n }\n }\n System.Threading.Thread.Sleep (1);\n }\n resetEvent.WaitOne ();\n Console.ReadKey ();\n }\n}\n\nclass ProcessingClass\n{\n readonly Queue numberQueue = Queue.Synchronized (new Queue ());\n bool aborting = false;\n object abortingLock = new object ();\n\n public bool Aborting {\n get {\n lock (abortingLock) {\n return aborting;\n }\n }\n set {\n lock (abortingLock) {\n aborting = value;\n }\n }\n }\n\n public bool IsBusy {\n get {\n return numberQueue.Count &gt; 0;\n }\n }\n\n public void Abort () {\n Aborting = true;\n }\n\n public void Enqueue (int num) {\n lock (numberQueue) {\n numberQueue.Enqueue (num);\n Monitor.PulseAll (numberQueue);\n }\n\n }\n\n public int Dequeue () {\n lock (numberQueue) {\n if (numberQueue.Count == 0)\n Monitor.Wait (numberQueue); \n return (int)numberQueue.Dequeue ();\n }\n\n }\n\n public void ProcessNumbers (object threadContext) {\n //please create an own class for this!\n ManualResetEvent resetEvent = (ManualResetEvent)threadContext;\n //\n StartProcessingNumbers ();\n resetEvent.Set ();\n\n }\n\n private void StartProcessingNumbers () {\n while (!aborting) {\n int num = Dequeue ();\n Console.WriteLine (\"Processing number:{0}\", num);\n // simulate some work with number e.g. computing and storing to db\n System.Threading.Thread.Sleep (200); \n Console.WriteLine (\"Done\"); \n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T18:56:58.477", "Id": "5084", "ParentId": "4890", "Score": "2" } }, { "body": "<p>Why not use <code>BackgroundWorker</code>?</p>\n\n<pre><code>static void Main(string[] args)\n{\n Random rnd = new Random();\n int count = 0, num;\n\n BackgroundWorker bw = new BackgroundWorker();\n bw.WorkerReportsProgress = true;\n bw.WorkerSupportsCancellation = true;\n bw.DoWork += new DoWorkEventHandler(bw_DoWork);\n\n while(count++ &lt; 100)\n {\n num = rnd.Next(0, 100)\n Console.WriteLine(\"Generated number {0}\", num);\n if(num &gt; 20)\n {\n if(!bw.IsBusy)\n bw.RunWorkerAsync(); //calls bw_DoWork function\n else\n Console.WriteLine(\"Thread BUSY! Skipping number:{0}\", num);\n } \n }\n void bw_DoWork(object sender, DoWorkEventArgs e)\n {\n //do something with number in background\n }\n}\n</code></pre>\n\n<p>If you wish to abort, call <code>bw.CancelWorkerAsync()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-08T05:35:16.910", "Id": "46613", "ParentId": "4890", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-17T18:09:53.907", "Id": "4890", "Score": "4", "Tags": [ "c#", "multithreading", "delegates", "thread-safety" ], "Title": "Thread-safety and delegates with generated numbers" }
4890
<p>I'm 100% sure improvements can be made. Any help is greatly appreciated. I should add that I am new to OOP and am not sure if I'm using this the right way.</p> <pre><code>&lt;?php defined('_VALID') or die('Restricted Access!'); class email { public function addtemplate($html, $public) { global $conn; $sql = "INSERT INTO emailtemplate SET id = '', parentid = '" . $_SESSION['uid'] . "', html = '" . mysql_escape_string($html) . "', public = '" . $public . "', added = '" . time() . "'"; $conn-&gt;execute($sql); if ($conn-&gt;affected_rows() == 1) { return true; } else { return false; } } public function addtext($subject, $text) { global $conn; $sql = "INSERT INTO emailtext SET id = '', parentid = '" . $_SESSION['uid'] . "', subject = '" . mysql_escape_string($subject) . "', text = '" . mysql_escape_string($text) . "', added = '" . time() . "'"; $conn-&gt;execute($sql); if ($conn-&gt;affected_rows() == 1) { return $conn-&gt;insert_id(); } else { return false; } } public function addqueue($to, $text, $template) { global $conn; $sql = "INSERT INTO emailqueue SET eid = '', parentid = '" . $_SESSION['uid'] . "', eto = '" . $to . "', etext = '" . $text . "', etemplate = '" . $template . "', added = '" . time() . "', status = 'pending'"; $conn-&gt;execute($sql); if ($conn-&gt;affected_rows() == 1) { return true; } else { return false; } } public function delete($eid) { global $conn; $sql = "DELETE FROM emailqueue WHERE eid = '" . $eid . "' AND parentid = '" . $_SESSION['uid'] . "' AND status = 'pending'"; $conn-&gt;execute($sql); if ($conn-&gt;affected_rows() == 1) { return true; } else { return false; } } public function generate($eid) { global $conn; $sql = "SELECT q.*, x.*, t.*, c.id, c.fname, c.email, p.UID, p.company, p.hash FROM emailqueue AS q, emailtext AS x, emailtemplate AS t, clients AS c, signup AS p WHERE q.eid = '" . $eid . "' AND q.etemplate = t.id AND q.etext = x.id AND c.id = q.eto AND p.UID = q.parentid"; $rs = $conn-&gt;execute($sql); $email = $rs-&gt;getrows(); $email = $email[0]; $find = array( '{name}', '{email}', '{company}', '{hash}' ); $replace = array( $email['fname'], $email['email'], $email['company'], $email['hash'] ); $body = str_replace('{bodytext}', $email['text'], stripslashes($email['html'])); $final = str_replace($find, $replace, $body); $array['body'] = stripslashes($final); $array['subject'] = $email['subject']; $array['to'] = $email['email']; return $array; } public function from($eid) { global $conn; $sql = "SELECT q.*, s.UID, s.email, s.company FROM emailqueue AS q, signup AS s WHERE q.eid = '" . $eid . "' AND q.parentid = s.UID"; $rs = $conn-&gt;execute($sql); $email = $rs-&gt;getrows(); $email = $email[0]; $array['company'] = $email['company']; $array['email'] = $email['email']; return $array; } public function send($eid) { $msg = $this-&gt;generate($eid); $from = $this-&gt;from($eid); $headers = "From: " . $from['company'] . " &lt;noreply@emailsmsmarketing.com&gt;\r\n"; $headers .= "Reply-To: " . $from['email'] . "\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; \r\n"; if (mail($msg['to'], $msg['subject'], $msg['body'], $headers)) { return true; } else { return false; } } } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-19T16:13:53.360", "Id": "7331", "Score": "0", "body": "defined('_VALID') or die('Restricted Access!'); // Restricting access is best done in an OOP way as well. Additionally, it would be better to have this closer to the code that is concerned with whether or not someone has access." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-19T16:17:46.210", "Id": "7332", "Score": "0", "body": "General Rule: Globals are bad. Rather than a global $conn, use Dependency Injection. If most methods require it, pass it in via the constructor (or factory method) otherwise pass it in to the specific method(s) that require it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T09:23:22.173", "Id": "7357", "Score": "0", "body": "I have replaced the global with a constructor. I don`t understand what you mean by your first comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T18:09:27.353", "Id": "7615", "Score": "0", "body": "It may simply be that I don't understand your business case for having the defined('_VALID') check. Whatever the reason, it seems misplaced. Class files are best left with nothing more than the class itself. Only your app will be loading the classes defined, so you should manage access requirements elsewhere." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T10:40:55.197", "Id": "7677", "Score": "0", "body": "Any script that tries to include this file without having _VALID defined will fail to do so. I see your point though." } ]
[ { "body": "<p>Not a PHP expert, but things like</p>\n\n<pre><code>if ($conn-&gt;affected_rows() == 1) {\n return true;\n} else {\n return false;\n}\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>return $conn-&gt;affected_rows() == 1;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-19T11:57:17.010", "Id": "7326", "Score": "0", "body": "Would this return false in the event $conn->affected_rows() is not 1?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-19T12:17:22.557", "Id": "7327", "Score": "2", "body": "Yes. But also if its not `true`. Better to check `$conn->affected_rows() === 1`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-19T08:52:34.457", "Id": "4903", "ParentId": "4895", "Score": "1" } }, { "body": "<p>See <a href=\"http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php\" rel=\"nofollow\">this page on SQL injection</a> and why you shouldn't do it. You run a security risk that allows a user with a little maliciousness and knowledge of SQL to purposefully bypass certain checks in order to cause your server to possibly crash. I see you escape certain values but not all. You had better either be sure that the values which arrive are already escaped or you should add it in.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T09:06:46.033", "Id": "7356", "Score": "0", "body": "The values that are not escaped are generated by my script so I saw no use in escaping them." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-19T13:13:04.467", "Id": "4905", "ParentId": "4895", "Score": "0" } } ]
{ "AcceptedAnswerId": "4903", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-18T04:44:40.450", "Id": "4895", "Score": "1", "Tags": [ "php", "object-oriented", "mysql" ], "Title": "Class for sending emails" }
4895
<p>I have Model Object Car.</p> <pre><code>public class Car { private String colour; private String make; private String yearOfMake; } </code></pre> <p>Then a managed bean</p> <pre><code>public Class CarSearchManagedBean { private Car car; @EJB private CarFacade carFacade; public String search() { this.car =carFacade.find(car); ..... } } </code></pre> <p>Then I have a JSF facelet with input fields connected to car object by backing bean and a search button linked to search method .There is no Ajax and use can provide values for any property and since there is no auto cleaning can possibly provide values more than one property but search only uses one. </p> <p>Then before I show <code>CarFacade</code> I will show CarDao becasue I think makes more sense here.</p> <pre><code>public class CarDaoImpl implements CarDao { public Car findByColour(Car car){ //Calls a webservice method } public Car findByMake(Car car){ //Calls a webservice method } public Car findByYearOfMake(Car car){ //Calls a webservice method } } </code></pre> <p>Now if the CarFacade I have this ugly if statment that I do not know how to avoid.</p> <pre><code>public class CarFacade { @EJB CarDao carDao; public Car find(final Car car) { Car aCar ; //How can improve the design to avoid this If statment if (car.getColour()!=null) { aCar = carDao.findByColour(car) } else if (car.getMake()!=null) { aCar = carDao.findByMake(car); } else { aCar =carDao.findByYearOfMake(car); } return aCar; } } </code></pre>
[]
[ { "body": "<p>You'll want to look up the <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow\">Strategy Pattern</a>. </p>\n\n<p>In your specific case, you're probably going to want to do something along these lines (note - I've never worked with ManagedBeans, so I don't know what spanners that throws).</p>\n\n<p>Leave your <code>Car</code> class as normal. Or, well, you may want to provide specific types for assignments, if possible (So make <code>Colour</code> an actual class, even if it only contains an actual <code>String</code> - just so people can't assign a <code>Make</code> value to it...).</p>\n\n<p>Your <code>CarDAO</code> should be multiple instances. Something like:</p>\n\n<pre><code>public class CarColorFinderDAOImpl implements CarDAO {\n\n public Car find(String colorToFind) {\n // search by color here\n }\n}\n</code></pre>\n\n<p>Then your <code>CarFacade</code> actually transforms to something like this:</p>\n\n<pre><code>public class CarFacade {\n\n private Map&lt;String, CarDAO&gt; finderDAO = new HashMap&lt;String, CarDAO&gt;();\n\n public Car find(Sring searchValue, String searchColumn) {\n\n return finderDAO.get(searchColumn).find(searchValue);\n }\n\n public void registerFinder(String searchColumn, CarDAO finder) {\n finderDAO.put(searchColumn, finder);\n }\n}\n</code></pre>\n\n<p>Which you then call (mostly) as normal from your managed bean.<br>\nPlease not that there are further abstractions available (such as encapsulating <code>searchValue</code> and <code>searchColumn</code> in some sort of <code>FinderContract</code> object). But this is a quick basic one to get you started.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-19T20:35:07.553", "Id": "7341", "Score": "0", "body": "Great thanks never thought I will get this answer.I am already using Strong Types for Colour Make etc and have similar abstractions to FinderContract which I did not show to cut down to bare minimum . Thanks again it does look nice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T10:32:12.540", "Id": "7358", "Score": "0", "body": "@x-zero How does this avoid the if-statements? Wouldn't you still have to check if your car has a colour, make etc to determine what \"searchColumn\" to use when you call `CarFacade.find`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T15:49:43.277", "Id": "7374", "Score": "0", "body": "@dogbane Possibly - it depends on how the decision is being made higher up. This is only the `Model` part of the program; generally, the same pattern can (and potentially should) be applied to the `View` portion as well. When returning to the webserver, the parameters passed would be similar to `radioButtonGroup.selected.name` and `searchTextBox.value` - no if statements needed (note - been too long since I've done web programming)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-19T18:49:09.650", "Id": "4912", "ParentId": "4896", "Score": "4" } } ]
{ "AcceptedAnswerId": "4912", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-18T08:27:01.987", "Id": "4896", "Score": "4", "Tags": [ "java" ], "Title": "What improvements can I make to avoid these If statments?" }
4896
<p>I have two accordions on the same page </p> <p>First, I have a page, Freemarker, that includes two other Freemarkers that have the accordion.</p> <pre><code>[#include "page1.ftl"] [#include "page2.ftl"] </code></pre> <p>On page1:</p> <pre><code>&lt;h3 class="trigger"&gt;&lt;div id="toggle-image"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Page1&lt;/div&gt;&lt;/h3&gt; &lt;div class="toggle-container"&gt; </code></pre> <p>On page2:</p> <pre><code>&lt;h3 class="trigger2"&gt;&lt;div id="toggle-image2"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Page2&lt;/div&gt;&lt;/h3&gt; &lt;div class="toggle-container2"&gt; </code></pre> <p>In the Javascript file:</p> <pre><code>$(document).ready(function(){ $('#toggle-image').attr("class", "toggle-image-expand"); //Hide (Collapse) the toggle containers on load $(".toggle-container").hide(); $("h3.trigger").click(function(){ $(this).toggleClass("active").next().slideToggle("slow"); if($('#toggle-image').attr("class") == "toggle-image-collapse") { $('#toggle-image').attr("class", "toggle-image-expand"); } else { $('#toggle-image').attr("class", "toggle-image-collapse"); } return false; }); }); $(document).ready(function(){ $('#toggle-image2').attr("class", "toggle-image-expand"); //Hide (Collapse) the toggle containers on load $(".toggle-container2").hide(); $("h3.trigger2").click(function(){ $(this).toggleClass("active").next().slideToggle("slow"); if($('#toggle-image2').attr("class") == "toggle-image-collapse") { $('#toggle-image2').attr("class", "toggle-image-expand"); } else { $('#toggle-image2').attr("class", "toggle-image-collapse"); } return false; }); </code></pre> <p>It works fine, but the redundant code I used in JS is typical and the difference is on the variable it uses. How could I make it dynamic?</p>
[]
[ { "body": "<ol>\n<li>Don't rely on IDs when your cases are general. Rely on classes. </li>\n<li>Use the DOM hierarchy to reference elements</li>\n</ol>\n\n<p>page1 (added a container div, \"toggle-image\" class name):</p>\n\n<pre><code>&lt;div&gt;\n &lt;h3 class=\"trigger\"&gt;\n &lt;div id=\"toggle-image\" class=\"toggle-image\"&gt;\n &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Page1\n &lt;/div&gt;\n &lt;/h3&gt;\n &lt;div class=\"toggle-container\"&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>page2 (same changes):</p>\n\n<pre><code>&lt;div&gt;\n &lt;h3 class=\"trigger\"&gt;\n &lt;div id=\"toggle-image2\" class=\"toggle-image\"&gt;\n &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Page2\n &lt;/div&gt;\n &lt;/h3&gt;\n &lt;div class=\"toggle-container\"&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>JavaScript (generalized with class selectors, sibling selectors, improved class logic):</p>\n\n<pre><code> $(document).ready(function(){\n $('.toggle-image').attr(\"class\", \"toggle-image-expand\");\n //Hide (Collapse) the toggle containers on load\n $(\".toggle-container\").hide();\n\n $(\"h3.trigger\").click(function(){\n $(this).toggleClass(\"active\").next().slideToggle(\"slow\");\n\n $(this).children('.toggle-image')\n .toggleClass('toggle-image-collapse') \n .toggleClass('toggle-image-expand');\n\n return false;\n });\n });\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-18T17:54:20.020", "Id": "7315", "Score": "0", "body": "Actually the purpose of \"toggle-image\" to display \"+\" or \"-\" to indicate to be Expanded or collapsed respectively.This approach doesn't display the sign at all . It works fine for Accordion but I need the sign to be displayed as well ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-18T18:03:18.247", "Id": "7316", "Score": "0", "body": "Small Update this approach displays sign but it doesn't change whenever I click on the accordion ..It always\"+\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-18T18:06:18.670", "Id": "7317", "Score": "0", "body": "There is no reason that this approach can't facilitate your image display. In your posted code, is the image displayed for .trigger2 different from the image displayed for .trigger1? If this is the case just add a second class to the divs in my code and then update your css to add the background image for elements that match the two classes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-18T18:08:55.793", "Id": "7318", "Score": "0", "body": "Actually, you should display the +/- images based on wether your `div.toggle-image` also has one of these classes: `toggle-image-collapse` or `toggle-image-expand`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-18T18:09:33.453", "Id": "7319", "Score": "0", "body": "and change `$('.toggle-image').attr(\"class\", \"toggle-image-expand\");` to `$('.toggle-image').addClass(\"toggle-image-expand\");`" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-18T17:47:33.113", "Id": "4898", "ParentId": "4897", "Score": "1" } } ]
{ "AcceptedAnswerId": "4898", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-18T17:26:06.660", "Id": "4897", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Multiple Accordion on one page" }
4897
<p>My goal was to be able to render my view models using a standard <code>Object.cshtml</code> editor and display template. In order to do so I needed to be able to always call <code>Html.Editor(propertyName)</code> or <code>Html.Display(propertyName)</code> in order to render the HTML element.</p> <p>There were plenty of resources for creating custom attributes and custom editor templates. However I ran into a wall when creating the <code>DropDownListAttribute</code> and template since I needed to obtain the values for the select list as well as set the selected item based on the current instance of the view model.</p> <p><a href="http://weblogs.asp.net/seanmcalinden/archive/2010/06/11/custom-asp-net-mvc-2-modelmetadataprovider-for-using-custom-view-model-attributes.aspx" rel="nofollow noreferrer">Here is the reference</a> I used to create the custom <code>ModelMetadataProvider</code> and custom attributes.</p> <p><a href="https://stackoverflow.com/questions/5241012/obtain-containing-object-instance-from-modelmetadataprovider-in-asp-net-mvc">Here is the problem</a> I ran into with getting the current instance of the view model.</p> <p>It turns out using reflection here to access the view model is not safe. Depending on how you iterate over the property metadata the view model can sometimes be null.</p> <p>Here is my implementation using the resource referenced above. This is a simple version that only uses a <code>List&lt;string&gt;</code> for the <code>DropDownList</code>. Using this example it would be trivial to use dictionaries and set the text/value properties:</p> <p><strong>View Model:</strong></p> <pre><code>public class PhoneNumberViewModel { // ... normal properties and attributes [DropDownList("ContactTypes")] // &lt;-- This is the important one! public string ContactType { get; set; } public static IEnumerable&lt;string&gt; ContactTypes { get { return new List&lt;string&gt;() { "Home", "Work", "Mobile" } } } } </code></pre> <p><strong>DropDownListAttribute Implementation</strong></p> <pre><code>public class DropDownListAttribute : MetadataAttribute { private string _items; public DropDownListAttribute(string items) { _items = items; } public override void Process(System.Web.Mvc.ModelMetadata modelMetaData) { modelMetaData.AdditionalValues.Add("Items", _items); modelMetaData.TemplateHint = TemplateHints.DropDownList; // Just a const string } } </code></pre> <p><strong>Custom HTML Helper used to render elements that need access to the view model instance</strong></p> <pre><code>@Html.ContextualEditor(propertyName) </code></pre> <p><strong>ContextualEditor HTML Helper Implementation</strong></p> <pre><code>public static MvcHtmlString ContextualEditor(this HtmlHelper html, string expression) { var model = html.ViewData.Model; var propertyMetadata = html.ViewData.ModelMetadata.Properties.Where(x =&gt; x.PropertyName == expression).Single(); switch (propertyMetadata.TemplateHint) { case TemplateHints.DropDownList: var items = (IEnumerable&lt;string&gt;)model.GetType().GetProperty((string)propertyMetadata.AdditionalValues["Items"]).GetValue(model, null); var selectedValue = (string)model.GetType().GetProperty(expression).GetValue(model, null); var selectList = new TagBuilder("select"); selectList.MergeAttribute("id", expression); selectList.MergeAttribute("name", expression); var options = new StringBuilder(); foreach (var item in items) { var option = new TagBuilder("option"); option.InnerHtml = item; if (item == selectedValue) option.MergeAttribute("selected", "selected"); options.Append(option.ToString()); } selectList.InnerHtml = options.ToString(); return MvcHtmlString.Create(selectList.ToString()); default: return System.Web.Mvc.Html.EditorExtensions.Editor(html, expression); } } </code></pre> <p>Please let me know what you think of the implementation. I'd be interested to know if anyone has found a more elegant way of achieving this result.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-27T00:54:35.320", "Id": "18031", "Score": "0", "body": "What exactly are you trying to do? Are you trying to display a drop-down list?" } ]
[ { "body": "<p>Why not just do this?</p>\n\n<pre><code>public class PhoneNumberViewModel\n{\n // ... normal properties and attributes\n [DropDownList(\"ContactTypes\")] // &lt;-- This is the important one!\n public string ContactType { get; set; }\n\n public static IEnumerable&lt;SelectListItem&gt; ContactTypes\n {\n get { return new[] { \"Home\", \"Work\", \"Mobile\" }.ToSelectList(); }\n }\n}\n\npublic static class ExtensionsForSelectListItem\n{\n public static IEnumerable&lt;SelectListItem&gt; ToSelectList(this IEnumerable&lt;string&gt; items)\n {\n return items.Select(x =&gt; new SelectListItem { Value = x });\n }\n\n public static MvcHtmlString ContextualEditor(this HtmlHelper html, string expression)\n {\n\n var model = html.ViewData.Model;\n\n var propertyMetadata = ModelMetadata.FromStringExpression(expression, html.ViewData);\n\n\n switch (propertyMetadata.TemplateHint)\n {\n case TemplateHints.DropDownList:\n var items = (IEnumerable&lt;SelectListItem&gt;)model.GetType().GetProperty((string)propertyMetadata.AdditionalValues[\"Items\"]).GetValue(model, null);\n return html.DropDownList(expression, items);\n default:\n return System.Web.Mvc.Html.EditorExtensions.Editor(html, expression);\n }\n }\n\n\n}\n</code></pre>\n\n<p>I didn't test the code to get the items. But I'm assuming that you had that part working.</p>\n\n<p>I also authored my own HTML Helper Library if you want check out some other examples.</p>\n\n<p><a href=\"https://bitbucket.org/grcodemonkey/buildmvc\" rel=\"nofollow\">https://bitbucket.org/grcodemonkey/buildmvc</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-08T13:24:22.973", "Id": "15435", "ParentId": "4899", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-18T18:06:24.673", "Id": "4899", "Score": "11", "Tags": [ "c#", "asp.net-mvc-3" ], "Title": "Implementing a generic DropDownList attribute and templating solution" }
4899
<p>This is my first experience of creating a useful tool in Python. I'd appreciate any critics on this. <br> I can also post the config file if needed.</p> <pre><code># !/usr/bin/env python # -*- coding: utf-8 -*- """ A Python script that checks for Portage tree and overlays updates and notifies of the list of packages available for upgrade. This tool was inspired by Porticron (https://github.com/hollow/porticron) by Benedikt Böhm. """ import os import subprocess import smtplib import socket import ConfigParser import xmpp import re import tempfile import time COLORS = {'\x1b[32m': '&lt;/span&gt;&lt;span style="color:darkgreen;font-weight:normal"&gt;', '\x1b[36;01m': '&lt;/span&gt;&lt;span style="color:turquoise;font-weight:bold"&gt;', '\x1b[34;01m': '&lt;/span&gt;&lt;span style="color:blue;font-weight:bold"&gt;', '\x1b[39;49;00m': '&lt;/span&gt;&lt;span style="color:black;font-weight:normal"&gt;', '\x1b[33;01m': '&lt;/span&gt;&lt;span style="color:orange;font-weight:bold"&gt;', '\x1b[32;01m': '&lt;/span&gt;&lt;span style="color:limegreen;font-weight:bold"&gt;', '\x1b[31;01m': '&lt;/span&gt;&lt;span style="color:red;font-weight:bold"&gt;', '\x0d': '&lt;br&gt;' } class Timestamp(tempfile._RandomNameSequence): def next(self): return time.strftime('%Y%m%d-%H%M%S') tempfile._RandomNameSequence = Timestamp class GUN(): """Main class """ def __init__(self): """Reads configuration file, performs basic setup """ config = ConfigParser.RawConfigParser() try: config.read('/etc/gun.conf') except IOError: print 'Cannot open configuration file' # General settings self.sync_overlays = config.getboolean('GENERAL', 'sync_overlays') # Synchronization settings self.sync_tree_command = config.get('SYNC', 'tree_command') if self.sync_overlays: self.sync_overlays_command = config.get('SYNC', 'overlays_command') emerge_command = config.get('UPDATE', 'command') # Notification settings self.email_notify = config.getboolean('NOTIFY', 'email') self.jabber_notify = config.getboolean('NOTIFY', 'jabber') # Email settings self.mail_host = config.get('EMAIL', 'host') self.mail_user = config.get('EMAIL', 'user') self.mail_password = config.get('EMAIL', 'password') self.mail_port = config.get('EMAIL', 'port') self.mail_sender = config.get('EMAIL', 'mailfrom') self.mail_recipient = config.get('EMAIL', 'mailto') # Jabber settings self.jabber_sender = config.get('JABBER', 'jabber_from') self.jabber_password = config.get('JABBER', 'password') self.jabber_recipient = config.get('JABBER', 'jabber_to') # Output file timestamp = time.strftime('%Y%m%d-%H%M%S') self.output_file = tempfile.NamedTemporaryFile(suffix = '', prefix = 'gun-', dir = '/var/tmp', delete = False) self.update_command = 'script -q -c \'%s\' -f %s' % (emerge_command, self.output_file.name) def sync(self): """SYNC Portage tree and overlays """ output = subprocess.Popen([self.sync_tree_command], shell=True, stdout=subprocess.PIPE) output.communicate() if self.sync_overlays: output = subprocess.Popen([self.sync_overlays_command], shell=True, stdout=subprocess.PIPE) output.communicate() def pretend_update(self): """Runs emerge to get the list of packages ready for upgrade. Writes the list to file. """ output = subprocess.Popen([self.update_command], shell=True) output.communicate() self.output_file.seek(0) def _ansi2html(self, colors): """Parses the output file, produced by the script Linux tool and translates ANSI terminal color codes into HTML tags """ # Remove 'header' and 'footer' from the file text = re.sub("(?s).*?(\[\x1b\[32mebuild)", "\\1", self.output_file.read(), 1).split('Total', 1)[0] pattern = '|'.join(map(re.escape, colors.keys())) message = re.sub(pattern, lambda m:colors[m.group()], text) self.output_file.seek(0) return message def _send_email(self): headers = ("From: %s\r\nTo: %s\r\nSubject: [%s] %s Packages to update\r\nContent-Type: text/html; charset=utf-8\r\n" % (self.mail_sender, self.mail_recipient, os.uname()[1], time.strftime('%Y-%m-%d'))) message = headers + self._ansi2html(colors = COLORS) server = smtplib.SMTP() try: server.connect(self.mail_host, self.mail_port) except socket.error: print 'Cannot connect to SMTP server' try: server.login(self.mail_user, self.mail_password) except smtplib.SMTPAuthenticationError: print 'Cannot authenticate on SMTP server' server.sendmail(self.mail_sender, self.mail_recipient, message) server.quit() def _send_jabber(self): for key in COLORS.iterkeys(): COLORS[key] = '' message = self._ansi2html(colors = COLORS) jid = xmpp.protocol.JID(self.jabber_sender) cl = xmpp.Client(jid.getDomain(), debug=[]) if not cl.connect(): raise IOError('Cannot connect to Jabber server') else: if not cl.auth(jid.getNode(), self.jabber_password, resource=jid.getResource()): raise IOError('Cannot authenticate on Jabber server') else: cl.send(xmpp.protocol.Message(self.jabber_recipient, message)) cl.disconnect() def notify(self): if self.email_notify: self._send_email() if self.jabber_notify: self._send_jabber() def main(): s = GUN() s.sync() s.pretend_update() s.notify() # EOF </code></pre>
[]
[ { "body": "<pre><code>class Timestamp(tempfile._RandomNameSequence):\n def next(self):\n return time.strftime('%Y%m%d-%H%M%S')\n\ntempfile._RandomNameSequence = Timestamp\n</code></pre>\n\n<p>Names beginning with underscores are considered internal to that module. Monkey patching like this is generally a hack which should be avoided. Since you are producing the string based on the current time (and only up to milliseconds), this class you are putting in probably doesn't act the way the tempfile code expects it to.</p>\n\n<pre><code>class GUN():\n</code></pre>\n\n<p>Use <code>class Gun:</code> or <code>class Gun(object):</code> If this python 2.x the later is better.</p>\n\n<pre><code> def __init__(self):\n \"\"\"Reads configuration file, performs basic setup\n \"\"\"\n config = ConfigParser.RawConfigParser()\n try:\n config.read('/etc/gun.conf')\n except IOError:\n print 'Cannot open configuration file'\n</code></pre>\n\n<p>Stylistically, I'd pass the config object to the constructor. That way I've got more flexibility if I want to reuse the object.</p>\n\n<pre><code> # Output file\n timestamp = time.strftime('%Y%m%d-%H%M%S')\n self.output_file = tempfile.NamedTemporaryFile(suffix = '',\n prefix = 'gun-',\n dir = '/var/tmp',\n delete = False)\n</code></pre>\n\n<p>What exactly is the point of using tempfile here? Given that you've replaced the random sequence with your own, why don't you just create the file? Why do want to control the name of the file anyways?</p>\n\n<pre><code> self.update_command = 'script -q -c \\'%s\\' -f %s' % (emerge_command,\n self.output_file.name)\n</code></pre>\n\n<p>Another option to look at is using subprocess and reading the standard_output into memory.</p>\n\n<pre><code> def sync(self):\n \"\"\"SYNC Portage tree and overlays\n \"\"\"\n output = subprocess.Popen([self.sync_tree_command],\n shell=True,\n stdout=subprocess.PIPE)\n output.communicate()\n</code></pre>\n\n<p>This piece of code modulo the command executed happens over and over and over again in your code. Write a helper function.</p>\n\n<pre><code> def _ansi2html(self, colors):\n \"\"\"Parses the output file, produced by the script Linux tool and\n translates ANSI terminal color codes into HTML tags\n \"\"\"\n # Remove 'header' and 'footer' from the file\n text = re.sub(\"(?s).*?(\\[\\x1b\\[32mebuild)\",\n \"\\\\1\",\n self.output_file.read(),\n 1).split('Total', 1)[0]\n pattern = '|'.join(map(re.escape, colors.keys()))\n message = re.sub(pattern,\n lambda m:colors[m.group()],\n text)\n self.output_file.seek(0)\n\n return message\n</code></pre>\n\n<p>Stylistically, I'd move this to be a free standing function, and pass in the output_file.</p>\n\n<pre><code> def _send_email(self):\n headers = (\"From: %s\\r\\nTo: %s\\r\\nSubject: [%s] %s Packages to update\\r\\nContent-Type: text/html; charset=utf-8\\r\\n\"\n % (self.mail_sender,\n self.mail_recipient,\n os.uname()[1],\n time.strftime('%Y-%m-%d')))\n message = headers + self._ansi2html(colors = COLORS)\n server = smtplib.SMTP()\n try:\n server.connect(self.mail_host,\n self.mail_port)\n except socket.error:\n print 'Cannot connect to SMTP server'\n try:\n server.login(self.mail_user,\n self.mail_password)\n except smtplib.SMTPAuthenticationError:\n print 'Cannot authenticate on SMTP server'\n server.sendmail(self.mail_sender,\n self.mail_recipient,\n message)\n server.quit()\n</code></pre>\n\n<p>Stylistically, sending e-mail is distinct from what this class is doing. I'd probably look into moving this into its own class. So I'd have an e-mail sending class which this would call with the data. </p>\n\n<pre><code> def notify(self):\n if self.email_notify:\n self._send_email()\n if self.jabber_notify:\n self._send_jabber()\n</code></pre>\n\n<p>What I'd do here is implement email sending and jabber sending as two objects which both implement the same interface. Then notify would loop over a list of notifiables which would be those two objects. Then you'd reduce coupling because GUN wouldn't know about e-mail/jabber or vice versa.</p>\n\n<pre><code>def main():\n s = GUN()\n s.sync()\n s.pretend_update()\n s.notify()\n</code></pre>\n\n<p>Typically something like</p>\n\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n\n<p>Is included so that python will execute the main function when the script is run.</p>\n\n<pre><code># EOF\n</code></pre>\n\n<p>That's a pretty much useless comment.</p>\n\n<p><strong>EDIT</strong> </p>\n\n<p>Notify structure:</p>\n\n<pre><code>class JabberNotifier(object):\n def __init__(self, config)\n # get jabber config settings\n\n def send(self, message):\n ...\n\nclass EmailNotifier(object):\n def __init__(self, config)\n # get email config settings\n\n def send(self, message):\n ...\n\nclass GUN(object):\n def __init__(self, config):\n self.notifiers = []\n if config.should_do_emails():\n self.notifiers.append( EmailNotifier(config) )\n if config.should_do_jabber():\n self.notifiers.append( JabberNotifier(config) )\n\n def notify(self):\n for notifier in self.notifiers:\n notifier.send(message)\n</code></pre>\n\n<p>The real purist in me would also be inclined to move config stuff completely out of the constructors. Basically, I'd pass all of the parameters that you are pulling out the config file into the constructors. </p>\n\n<p>Also, you can do the same thing that script is doing inside python using the pty module. If you use that you should be able to avoid using script or hitting temporary files.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-19T14:22:58.317", "Id": "7328", "Score": "0", "body": "1. Regarding the tempfile module patching and using - this was just an attempt to learn how to patch modules in runtime. I'll consider creating a simple file instead of using the tempfile module. 2. Regarding reading the standard_output into memory. The reason why I am using the script linux tool is that I need the output with terminal colors, which I then translate into HTML. Reading to stdout strips all the formatting (colors in particular). And I could not find any Pythonic approach to this. As for the rest of remarks - thanks, I'll change the script accordingly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-19T14:31:52.693", "Id": "7329", "Score": "0", "body": "And the main function is called from the executable file, which is created with setup.py: entry_points = {\n 'console_scripts': [\n 'gun = gun.sync:main'\n ]" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-19T18:05:45.050", "Id": "7338", "Score": "0", "body": "@Ch00k, I'm somewhat surprised by the colors. Its not unusual for a program to not send colors out when its not actually on a tty. But then I'd expect not to write it to your file either." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-19T19:04:06.483", "Id": "7339", "Score": "0", "body": "I do need the colors, that's why I've chosen to use script. It can produce the same output for a non-tty program, as if it was run in a tty." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-19T19:35:47.133", "Id": "7340", "Score": "0", "body": "I somewhat reworked my script according to your suggestions. However, I still cannot understand the notify method. What exactly do you mean? Maybe you could provide an example for me to better understand?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-19T23:30:31.493", "Id": "7344", "Score": "0", "body": "@Ch00k, edited. I've added what I'm thinking for notify and noted a way to avoid using script/temporary file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T08:24:52.367", "Id": "7355", "Score": "0", "body": "In case of your implementation of the notify method: how do I go about replacing the COLORS values with '' for formatting a message for Jabber? Or should I create a separate dict for this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T12:17:29.877", "Id": "7359", "Score": "0", "body": "@Ch00k, I'd create another class Message, with methods as_html and as_text. I'd pass that message object to both the Notifiers and they'd fetch the version of the text they need." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T12:23:55.777", "Id": "7360", "Score": "0", "body": "I ended up doing it like this: if isinstance(notifier, JabberNotifier):\n for key in ESCAPE_MAP.iterkeys():\n ESCAPE_MAP[key] = ''" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T12:33:51.160", "Id": "7361", "Score": "0", "body": "@Ch00k, Stylistically it is preffered if the Jabber class makes that decision rather then using isinstance. Using polymorphism is preferred to type checks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T12:51:37.027", "Id": "7362", "Score": "0", "body": "With a separate Message class, did you mean doing it like this? http://pastebin.com/gbhkxrhr" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T13:39:37.480", "Id": "7367", "Score": "0", "body": "@Ch00k, yes. Although I'd probably ansi2html into that class because its tightly related to what that class is doing. Also, your code is modifying the global copy of the colors dictionary. you should probably modify a copy of it. (I'd probably just pass in a bool use_colors instead)" } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-19T13:38:30.427", "Id": "4906", "ParentId": "4904", "Score": "1" } } ]
{ "AcceptedAnswerId": "4906", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-19T12:39:29.063", "Id": "4904", "Score": "2", "Tags": [ "python" ], "Title": "Gentoo linux updates notifier" }
4904
<p>I have implemented generic doubly-linked list class, which supports <code>IEnumerable&lt;T&gt;</code>,<code>IEnumerator&lt;T&gt;</code> interfaces.</p> <p><code>DoublyLinkedList&lt;T&gt;</code> is fully compatible with standart BCL classes.</p> <p>Targets:</p> <ul> <li>class can be used as a standard replacement for <code>Stack&lt;T&gt;</code>, <code>Queue&lt;T&gt;</code> and <code>List&lt;T&gt;</code>.</li> <li>class itself is <em>immutable</em>, so you can-not change the containing value of the element.</li> <li>class methods raises exceptions which conforms for common considerations.</li> <li>class method's <code>lock</code> statement was used for locking current <em>active</em> element. </li> <li>class <em>Push</em>, <em>Pop</em>, <em>Peek</em> operations is breaking the current state of the enumerated object.</li> </ul> <p>How can we compare the performance for that class compared to the BCL classes and other implementation?</p> <p>Will you provide the C# code to compare to the BCL classes like <code>Stack&lt;T&gt;</code>, <code>Querty&lt;T&gt;</code>, <code>List&lt;T&gt;</code>?</p> <p>Unit tests (code coverage - 100%):</p> <pre><code>[TestClass] public class DoublyLinkedListUnitTest { [TestMethod] public void TestValueMethod() { DoublyLinkedList&lt;int&gt; dll = new DoublyLinkedList&lt;int&gt;(); int i1 = 1; int i2 = 2; int i3 = 3; Assert.AreEqual(((IDoublyLinkedList&lt;int&gt;)dll).Index, -1); try { dll.Peek(); } catch (Exception ex) { Assert.AreEqual(typeof(InvalidOperationException), ex.GetType()); } using (IEnumerator&lt;int&gt; dllEnumerator = dll.GetEnumerator()) { Assert.AreEqual(dll.MoveLast(), false); Assert.AreEqual(dll.MovePrevious(), false); Assert.AreEqual(dllEnumerator.MoveNext(), false); Assert.AreEqual(dllEnumerator.Current, default(int)); Assert.AreEqual(dll.Count, 0); Assert.AreEqual(dll.CurrentIndex, -1); try { dll.Pop(); } catch (Exception ex) { Assert.AreEqual(typeof(InvalidOperationException), ex.GetType()); } dll.Add(i1); dll.MovePrevious(); try { dll.Remove(); } catch (Exception ex) { Assert.AreEqual(typeof(InvalidOperationException), ex.GetType()); } dll.MoveLast(); Assert.AreEqual(dllEnumerator.MoveNext(), true); Assert.AreEqual(dllEnumerator.Current, i1); Assert.AreEqual(dll.Count, 1); Assert.AreEqual(dll.CurrentIndex, 0); dll.Add(i2); Assert.AreEqual(dllEnumerator.MoveNext(), true); Assert.AreEqual(dllEnumerator.Current, i2); Assert.AreEqual(dll.Count, 2); Assert.AreEqual(dll.CurrentIndex, 1); dll.MoveFirst(); try { dll.Remove(); } catch (Exception ex) { Assert.AreEqual(typeof(InvalidOperationException), ex.GetType()); } try { dll.Add(i1); } catch (Exception ex) { Assert.AreEqual(typeof(InvalidOperationException), ex.GetType()); } dll.MoveLast(); dll.Add(i3); Assert.AreEqual(dllEnumerator.MoveNext(), true); Assert.AreEqual(dllEnumerator.Current, i3); Assert.AreEqual(dll.Count, 3); Assert.AreEqual(dll.CurrentIndex, 2); } IEnumerator o = ((IEnumerable)dll).GetEnumerator(); o.MoveNext(); Assert.AreEqual(o.Current, i1); List&lt;int&gt; list = new List&lt;int&gt;(); dll.CopyTo(list); Assert.AreEqual(dll.ToList().Except(list).Count(), 0); Assert.AreEqual(list.Except(dll).Count(), 0); Assert.AreEqual(list.Count, 3); Assert.AreEqual(list[0], i1); Assert.AreEqual(list[1], i2); Assert.AreEqual(list[2], i3); using (IEnumerator&lt;int&gt; dllEnumerator = dll.GetEnumerator()) { if (dll.Count &gt; 0) { dll.Remove(); } Assert.AreEqual(dllEnumerator.MoveNext(), true); Assert.AreEqual(dllEnumerator.Current, i1); if (dll.Count &gt; 0) { dll.Remove(); } Assert.AreEqual(dllEnumerator.MoveNext(), false); if (dll.Count &gt; 0) { dll.Remove(); } } try { dll.Remove(); } catch (Exception ex) { Assert.AreEqual(typeof(InvalidOperationException), ex.GetType()); } dll.AddRange(list); try { dll.AddRange(null); } catch (Exception ex) { Assert.AreEqual(typeof(ArgumentNullException), ex.GetType()); } try { dll.MoveFirst(); dll.AddRange(list); } catch (Exception ex) { Assert.AreEqual(typeof(InvalidOperationException), ex.GetType()); } Assert.AreEqual(dll.Contains(i1), true); Assert.AreEqual(dll.Contains(i2), true); Assert.AreEqual(dll.Contains(i3), true); Assert.AreEqual(dll.Contains(default(int)), false); using (IEnumerator&lt;int&gt; dllEnumerator = dll.GetEnumerator()) { Assert.AreEqual(dllEnumerator.MoveNext(), true); Assert.AreEqual(dllEnumerator.Current, i1); Assert.AreEqual(dllEnumerator.MoveNext(), true); Assert.AreEqual(dllEnumerator.Current, i2); Assert.AreEqual(dllEnumerator.MoveNext(), true); Assert.AreEqual(dllEnumerator.Current, i3); } Stack&lt;int&gt; stack = new Stack&lt;int&gt;(); stack.Push(i3); stack.Push(i2); stack.Push(i1); foreach (object value in dll) { Assert.AreEqual(stack.Pop(), value); } try { int value = default(int); while ((value = dll.Pop()) != default(int)) { stack.Push(value); } } catch (Exception ex) { Assert.AreEqual(typeof(InvalidOperationException), ex.GetType()); } dll.Push(i1); dll.Push(i2); dll.Push(i3); dll.Clear(); Assert.AreEqual(dll.MoveFirst(), false); stack.Clear(); stack.Push(i3); stack.Push(i2); stack.Push(i1); foreach (int value in stack) { dll.Push(value); Assert.AreEqual(dll.Peek(), value); } IDoublyLinkedList&lt;int&gt; dllInterface = dll; dllInterface.Reset(); Assert.AreEqual(dllInterface.MovePrevious(), false); Assert.AreEqual(dllInterface.Current, default(int)); Assert.AreEqual(dllInterface.CurrentIndex, -1); Assert.AreEqual(dllInterface.MoveNext(), true); Assert.AreEqual(dllInterface.Current, i1); Assert.AreEqual(dllInterface.CurrentIndex, 0); Assert.AreEqual(dllInterface.MoveNext(), true); Assert.AreEqual(dllInterface.Current, i2); Assert.AreEqual(dllInterface.CurrentIndex, 1); Assert.AreEqual(dllInterface.MoveNext(), true); Assert.AreEqual(dllInterface.Current, i3); Assert.AreEqual(dllInterface.CurrentIndex, 2); Assert.AreEqual(dllInterface.MoveFirst(), true); Assert.AreEqual(dllInterface.Current, i1); Assert.AreEqual(dllInterface.CurrentIndex, 0); Assert.AreEqual(dllInterface.MoveLast(), true); Assert.AreEqual(dllInterface.Current, i3); Assert.AreEqual(dllInterface.CurrentIndex, 2); Assert.AreEqual(dllInterface.MovePrevious(), true); Assert.AreEqual(dllInterface.Current, i2); Assert.AreEqual(dllInterface.CurrentIndex, 1); Assert.AreEqual(dllInterface.MovePrevious(), true); Assert.AreEqual(dllInterface.Current, i1); Assert.AreEqual(dllInterface.CurrentIndex, 0); Assert.AreEqual(dllInterface.MovePrevious(), true); Assert.AreEqual(dllInterface.Current, default(int)); Assert.AreEqual(dllInterface.CurrentIndex, -1); } [TestMethod] public void TestReferenceMethod() { DoublyLinkedList&lt;object&gt; dll = new DoublyLinkedList&lt;object&gt;(); object o1 = new object(); object o2 = new object(); object o3 = new object(); Assert.AreEqual(((IDoublyLinkedList&lt;object&gt;)dll).Index, -1); try { dll.Peek(); } catch (Exception ex) { Assert.AreEqual(typeof(InvalidOperationException), ex.GetType()); } using (IEnumerator&lt;object&gt; dllEnumerator = dll.GetEnumerator()) { Assert.AreEqual(dll.MoveLast(), false); Assert.AreEqual(dll.MovePrevious(), false); Assert.AreEqual(dllEnumerator.MoveNext(), false); Assert.AreEqual(dllEnumerator.Current, default(object)); Assert.AreEqual(dll.Count, 0); Assert.AreEqual(dll.CurrentIndex, -1); try { dll.Pop(); } catch (Exception ex) { Assert.AreEqual(typeof(InvalidOperationException), ex.GetType()); } dll.Add(o1); dll.MovePrevious(); try { dll.Remove(); } catch (Exception ex) { Assert.AreEqual(typeof(InvalidOperationException), ex.GetType()); } dll.MoveLast(); Assert.AreEqual(dllEnumerator.MoveNext(), true); Assert.AreEqual(dllEnumerator.Current, o1); Assert.AreEqual(dll.Count, 1); Assert.AreEqual(dll.CurrentIndex, 0); dll.Add(o2); Assert.AreEqual(dllEnumerator.MoveNext(), true); Assert.AreEqual(dllEnumerator.Current, o2); Assert.AreEqual(dll.Count, 2); Assert.AreEqual(dll.CurrentIndex, 1); dll.MoveFirst(); try { dll.Add(o1); } catch (Exception ex) { Assert.AreEqual(typeof(InvalidOperationException), ex.GetType()); } dll.MoveLast(); dll.Add(o3); Assert.AreEqual(dllEnumerator.MoveNext(), true); Assert.AreEqual(dllEnumerator.Current, o3); Assert.AreEqual(dll.Count, 3); Assert.AreEqual(dll.CurrentIndex, 2); } IEnumerator o = ((IEnumerable)dll).GetEnumerator(); o.MoveNext(); Assert.AreEqual(o.Current, o1); List&lt;object&gt; list = new List&lt;object&gt;(); dll.CopyTo(list); Assert.AreEqual(dll.ToList().Except(list).Count(), 0); Assert.AreEqual(list.Except(dll).Count(), 0); Assert.AreEqual(list.Count, 3); Assert.AreEqual(list[0], o1); Assert.AreEqual(list[1], o2); Assert.AreEqual(list[2], o3); using (IEnumerator&lt;object&gt; dllEnumerator = dll.GetEnumerator()) { if (dll.Count &gt; 0) { dll.Remove(); } Assert.AreEqual(dllEnumerator.MoveNext(), true); Assert.AreEqual(dllEnumerator.Current, o1); if (dll.Count &gt; 0) { dll.Remove(); } Assert.AreEqual(dllEnumerator.MoveNext(), false); if (dll.Count &gt; 0) { dll.Remove(); } } try { dll.Remove(); } catch (Exception ex) { Assert.AreEqual(typeof(InvalidOperationException), ex.GetType()); } dll.AddRange(list); try { dll.AddRange(null); } catch (Exception ex) { Assert.AreEqual(typeof(ArgumentNullException), ex.GetType()); } try { dll.MoveFirst(); dll.AddRange(list); } catch (Exception ex) { Assert.AreEqual(typeof(InvalidOperationException), ex.GetType()); } Assert.AreEqual(dll.Contains(o1), true); Assert.AreEqual(dll.Contains(o2), true); Assert.AreEqual(dll.Contains(o3), true); Assert.AreEqual(dll.Contains(default(object)), false); using (IEnumerator&lt;object&gt; dllEnumerator = dll.GetEnumerator()) { Assert.AreEqual(dllEnumerator.MoveNext(), true); Assert.AreEqual(dllEnumerator.Current, o1); Assert.AreEqual(dllEnumerator.MoveNext(), true); Assert.AreEqual(dllEnumerator.Current, o2); Assert.AreEqual(dllEnumerator.MoveNext(), true); Assert.AreEqual(dllEnumerator.Current, o3); } Stack&lt;object&gt; stack = new Stack&lt;object&gt;(); stack.Push(o3); stack.Push(o2); stack.Push(o1); foreach (object value in dll) { Assert.AreEqual(stack.Pop(), value); } try { object value = default(object); while ((value = dll.Pop()) != default(object)) { stack.Push(value); } } catch (Exception ex) { Assert.AreEqual(typeof(InvalidOperationException), ex.GetType()); } dll.Push(o1); dll.Push(o2); dll.Push(o3); dll.Clear(); Assert.AreEqual(dll.MoveFirst(), false); stack.Clear(); stack.Push(o3); stack.Push(o2); stack.Push(o1); foreach (object value in stack) { dll.Push(value); Assert.AreEqual(dll.Peek(), value); } IDoublyLinkedList&lt;object&gt; dllInterface = dll; dllInterface.Reset(); Assert.AreEqual(dllInterface.MovePrevious(), false); Assert.AreEqual(dllInterface.Current, default(object)); Assert.AreEqual(dllInterface.CurrentIndex, -1); Assert.AreEqual(dllInterface.MoveNext(), true); Assert.AreEqual(dllInterface.Current, o1); Assert.AreEqual(dllInterface.CurrentIndex, 0); Assert.AreEqual(dllInterface.MoveNext(), true); Assert.AreEqual(dllInterface.Current, o2); Assert.AreEqual(dllInterface.CurrentIndex, 1); Assert.AreEqual(dllInterface.MoveNext(), true); Assert.AreEqual(dllInterface.Current, o3); Assert.AreEqual(dllInterface.CurrentIndex, 2); Assert.AreEqual(dllInterface.MoveFirst(), true); Assert.AreEqual(dllInterface.Current, o1); Assert.AreEqual(dllInterface.CurrentIndex, 0); Assert.AreEqual(dllInterface.MoveLast(), true); Assert.AreEqual(dllInterface.Current, o3); Assert.AreEqual(dllInterface.CurrentIndex, 2); Assert.AreEqual(dllInterface.MovePrevious(), true); Assert.AreEqual(dllInterface.Current, o2); Assert.AreEqual(dllInterface.CurrentIndex, 1); Assert.AreEqual(dllInterface.MovePrevious(), true); Assert.AreEqual(dllInterface.Current, o1); Assert.AreEqual(dllInterface.CurrentIndex, 0); Assert.AreEqual(dllInterface.MovePrevious(), true); Assert.AreEqual(dllInterface.Current, default(object)); Assert.AreEqual(dllInterface.CurrentIndex, -1); } } </code></pre> <p>Source code:</p> <pre><code>public interface IDoublyLinkedList&lt;T&gt; : IEnumerator&lt;T&gt;, IEnumerable&lt;T&gt;, IEnumerator, IEnumerable, IDisposable { void Add(T value); void AddRange(IEnumerable&lt;T&gt; values); bool Contains(T item); void Remove(); bool MoveFirst(); bool MovePrevious(); bool MoveLast(); void CopyTo(List&lt;T&gt; list); List&lt;T&gt; ToList(); void Clear(); T Pop(); T Peek(); void Push(T value); int Count { get; } int Index { get; } int CurrentIndex { get; } } public class DoublyLinkedList&lt;T&gt; : IDoublyLinkedList&lt;T&gt; { private DoublyLinkedList&lt;T&gt; _current; private DoublyLinkedList&lt;T&gt; _previous; private DoublyLinkedList&lt;T&gt; _first; private DoublyLinkedList&lt;T&gt; _last; private readonly T _value; private readonly int _count; public DoublyLinkedList() { _current = this; } private DoublyLinkedList(DoublyLinkedList&lt;T&gt; copy) { _current = copy; _previous = copy._previous; _first = copy._first; _last = copy._last; _count = copy._count; } public int Count { get { lock (_current) { if (_last != null) { return _last._count; } return 0; } } } public int Index { get { lock (_current) { return _count - 1; } } } public int CurrentIndex { get { lock (_current) { return _current._count - 1; } } } private DoublyLinkedList(DoublyLinkedList&lt;T&gt; previous, T value) { _current = this; _previous = previous; _value = value; _count = previous._count + 1; } public void Clear() { _current = this; _previous = null; _first = null; _last = null; } public bool Contains(T item) { lock (_current) { foreach (T value in this) { if (object.Equals(value, item)) return true; } return false; } } public void CopyTo(List&lt;T&gt; list) { lock (_current) { list.AddRange(this); } } public List&lt;T&gt; ToList() { lock (_current) { return new List&lt;T&gt;(this); } } public void AddRange(IEnumerable&lt;T&gt; values) { lock (_current) { if (values != null) { if (_current._first == null) { foreach (T value in values) { _current._first = new DoublyLinkedList&lt;T&gt;(_current, value); _current = _current._first; } _last = _current; return; } throw new InvalidOperationException(); } throw new ArgumentNullException(); } } public void Add(T value) { lock (_current) { if (_current._first == null) { _current._first = new DoublyLinkedList&lt;T&gt;(_current, value); _last = _current = _current._first; return; } throw new InvalidOperationException(); } } public void Remove() { lock (_current) { if (_current._first == null) { if (_current._previous != null) { _last = _current = _current._previous; _current._first = null; return; } throw new InvalidOperationException(); } throw new InvalidOperationException(); } } public T Pop() { lock (_current) { if (_last != null) { _current = _last; } if (_current._previous != null) { T value = _current._value; _last = _current = _current._previous; _current._first = null; return value; } throw new InvalidOperationException(); } } public T Peek() { lock (_current) { if (_last != null) { _current = _last; } if (_current._previous != null) { T value = _current._value; return value; } throw new InvalidOperationException(); } } public void Push(T value) { lock (_current) { if (_last != null) { _current = _last; } _current._first = new DoublyLinkedList&lt;T&gt;(_current, value); _last = _current = _current._first; } } public bool MoveFirst() { lock (_current) { if (_first != null) { _current = _first; return true; } return false; } } public bool MoveLast() { lock (_current) { if (_last != null) { _current = _last; return true; } return false; } } public bool MovePrevious() { lock (_current) { if (_current._previous != null) { _current = _current._previous; return true; } return false; } } T IEnumerator&lt;T&gt;.Current { get { lock (_current) { return _current._value; } } } public IEnumerator&lt;T&gt; GetEnumerator() { lock (_current) { return new DoublyLinkedList&lt;T&gt;(this); } } bool IEnumerator.MoveNext() { lock (_current) { if (_current._first != null) { _current = _current._first; return true; } return false; } } object IEnumerator.Current { get { lock (_current) { return _current._value; } } } void IEnumerator.Reset() { lock (_current) { _current = this; } } IEnumerator IEnumerable.GetEnumerator() { lock (_current) { return new DoublyLinkedList&lt;T&gt;(this); } } void IDisposable.Dispose() { } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-14T20:11:13.083", "Id": "9299", "Score": "0", "body": "As an observation, your unit tests don't seem to be testing... a unit of work. It's testing the entire swath of functionality of the class, once for value types and once for reference types. I would recommend breaking them up into smaller, more granular tests which hit upon each area of functionality. A quick rule-of-thumb would be one operation, one assert per test. I'm going to post an answer with a short example of this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-15T15:37:03.450", "Id": "9343", "Score": "0", "body": "_\"Will you provide the C# code to compare to the BCL classes like Stack<T>, Querty<T>, List<T>?\"_ ... That's [not what Code Review is for](http://codereview.stackexchange.com/faq)." } ]
[ { "body": "<p>More granular unit tests as per my comment above.</p>\n\n<pre><code> [TestClass]\n public sealed class DoublyLinkedListUnitTest\n {\n private IDoublyLinkedList&lt;int&gt; valueDll;\n\n [TestInitialize]\n public void TestEmptyValueDllInitialize()\n {\n this.valueDll = new DoublyLinkedList&lt;int&gt;();\n }\n\n [TestMethod]\n public void TestEmptyValueDllIndex()\n {\n Assert.AreEqual(-1, this.valueDll.Index);\n }\n\n [TestMethod]\n [ExpectedException(typeof(InvalidOperationException))]\n public void TestEmptyValueDllPeek()\n {\n var intValue = this.valueDll.Peek();\n }\n\n [TestMethod]\n public void TestEmptyValueDllMoveLast()\n {\n Assert.AreEqual(false, this.valueDll.MoveLast());\n }\n\n [TestMethod]\n public void TestEmptyValueDllMovePrevious()\n {\n Assert.AreEqual(false, this.valueDll.MovePrevious());\n }\n\n [TestMethod]\n public void TestEmptyValueDllEnumeratorMoveNext()\n {\n using (var dllEnumerator = this.valueDll.GetEnumerator())\n {\n Assert.AreEqual(false, dllEnumerator.MoveNext());\n }\n }\n\n [TestMethod]\n public void TestEmptyValueDllEnumeratorCurrent()\n {\n using (var dllEnumerator = this.valueDll.GetEnumerator())\n {\n Assert.AreEqual(default(int), dllEnumerator.Current);\n }\n }\n\n [TestMethod]\n public void TestEmptyValueDllCount()\n {\n Assert.AreEqual(0, this.valueDll.Count);\n }\n\n [TestMethod]\n public void TestEmptyValueDllCurrentIndex()\n {\n Assert.AreEqual(-1, this.valueDll.CurrentIndex);\n }\n\n [TestMethod]\n [ExpectedException(typeof(InvalidOperationException))]\n public void TestEmptyValueDllPop()\n {\n var intValue = this.valueDll.Pop();\n }\n\n [TestMethod]\n public void TestEmptyValueDllAdd()\n {\n const int I1 = 1;\n\n this.valueDll.Add(I1);\n this.TestEmptyValueDllIndex();\n Assert.AreEqual(1, this.valueDll.Count);\n Assert.AreEqual(0, this.valueDll.CurrentIndex);\n\n var i1 = this.valueDll.Peek(); // Technically not a \"unit\" test since we are relying on Peek() to work too.\n\n Assert.AreEqual(I1, i1);\n }\n\n //// Add more unit tests here.\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-14T20:21:02.313", "Id": "6039", "ParentId": "4911", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-19T18:45:49.590", "Id": "4911", "Score": "6", "Tags": [ "c#", ".net", "performance" ], "Title": "Comparing DoublyLinkedList<T> implementation performance with other BCL (.NET) classes" }
4911
<p>I have a function that accepts a big amount of data as a parameter (sometimes 1 megabyte) I was thinking which would be the fastest way to pass that data, dunno if I got this right, but here is what I think (functionality doesn't matter, all are the same in my app, since data is never used again after this function).</p> <pre><code>// slow since the data must be copied to another location // in memory and passed to myfunction function myfunction(data: string): boolean; // faster since a pointer to the original data is passed to // the function and data is never copied function myfunction(var data: string): boolean; // no idea ??!!! function myfunction(const data: string): boolean; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T18:28:53.677", "Id": "13379", "Score": "1", "body": "See also: [Is the use of const dogmatic or rational?](http://stackoverflow.com/questions/5844904/is-the-use-of-const-dogmatic-or-rational)" } ]
[ { "body": "<p>This appears similar to <a href=\"https://stackoverflow.com/questions/1951192/delphi-performance-of-passing-const-strings-versus-passing-var-strings\">StackOverflow question 1951192</a>. If you have a real performance need, then try the suggestion there of using FastMM4. You are right that pass-by-reference should blow away pass-by-value for speed on large strings (or large any-kind-of-data).</p>\n\n<p>It could also be worth benchmarking (var data:string) vs. (const data:string) in case the compiler optimizes once better than the other. If they're the same, use const if your function doesn't need to alter the contents of string.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T21:36:38.553", "Id": "5025", "ParentId": "4917", "Score": "0" } }, { "body": "<p>If code in <code>myfunction</code> don't modify string, then, surprisingly, all three variants are pretty equal. Strings in Delphi use \"copy-on-write semantics\" (see <a href=\"http://docwiki.embarcadero.com/RADStudio/en/String_Types#AnsiString\" rel=\"nofollow\">last paragraph of AnsiString in help</a>), so they aren't copied until you change them.</p>\n\n<p>From the other hand, \"var\" and \"const\" will have same speed. Quote from help: <a href=\"http://docwiki.embarcadero.com/RADStudio/en/Parameters_%28Delphi%29#Constant_Parameters\" rel=\"nofollow\">Constant parameters are similar to value parameters, except that you can't assign a value to a constant parameter within the body of a procedure or function, nor can you pass one as a var parameter to another routine.</a></p>\n\n<p>So, taking into account string handling specifics, first variant, without any modifier, will behave pretty equal to others - string will be passed as pointer, and will be copied <em>only</em> when your code will actually write to it.</p>\n\n<p>Anyway, to be 100% sure, I suggest you write some profiling test. It is quite easy with use of <a href=\"http://docwiki.embarcadero.com/VCL/en/Diagnostics.TStopwatch\" rel=\"nofollow\">Diagnostics.TStopwatch</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T19:26:25.060", "Id": "5291", "ParentId": "4917", "Score": "1" } }, { "body": "<p><strong>Executive summary</strong></p>\n\n<p>Passing by <code>const</code> is the fastest for Delphi string types.</p>\n\n<p><strong>Details</strong></p>\n\n<blockquote>\n<pre><code>function myfunction(data: string): boolean;\n</code></pre>\n \n <p>Slow since the data must be copied to another location in memory and passed to <code>myfunction</code></p>\n</blockquote>\n\n<p>That's not what happens. In fact the caller does nothing more than pass the string variable, stored as a pointer, to the function. What happens in <code>myfunction</code> is that the reference count to the string is incremented on entry and decremented on exit. This requires an implicit try/finally to be written into the code to ensure that the decrement happens in case of exceptions. The reference counting code and the try/finally consume time.</p>\n\n<p>Note that the string contents are not copied at all because Delphi strings are optimised to use copy-on-write. You only pay the price of copying them if you modify the string.</p>\n\n<blockquote>\n<pre><code>function myfunction(var data: string): boolean;\n</code></pre>\n \n <p>Faster since a pointer to the original data is passed to the function and data is never copied</p>\n</blockquote>\n\n<p>This is pretty much equivalent to the previous by value code above. The parameter (i.e. the pointer to the string) is passed by reference rather than value, but otherwise there are no differences.</p>\n\n<blockquote>\n<pre><code>function myfunction(const data: string): boolean;\n</code></pre>\n</blockquote>\n\n<p>And now we come to the winner. Since the function is not allowed to modify the contents of the string, the compiler can omit the reference counting code and the try/finally. So this is the fastest of all.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-17T22:59:31.753", "Id": "6132", "ParentId": "4917", "Score": "12" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T06:29:09.683", "Id": "4917", "Score": "9", "Tags": [ "delphi" ], "Title": "Fastest Parameter Passing in delphi 7?" }
4917
<p>I've developed a log reader which can filter it's output following a few criteria: errorlevel, product, category, id. It is functioning, but when the log file is really big, it becomes very slow, to the point of going beyond the time limit.</p> <p>log_reader.php</p> <pre><code>&lt;?php session_start(); unset($_SESSION['errorlevel']); unset($_SESSION['category']); unset($_SESSION['product']); unset($_SESSION['id']); $lines = file("error.log"); $categories = array(); $products = array(); $ids = array(); foreach($lines as $line){ $segments = explode("][",substr($line,1,strrpos($line,']')-1)); if((!in_array($segments[2],$categories))&amp;&amp;(!empty($segments[2]))){ $categories[] = $segments[2]; } if((!in_array($segments[3],$products))&amp;&amp;(!empty($segments[3]))){ $products[] = $segments[3]; } if((!in_array($segments[4],$ids))&amp;&amp;(!empty($segments[4]))){ $ids[] = $segments[4]; } } sort($categories); sort($products); sort($ids); ?&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Log Reader&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="style.css" /&gt; &lt;script type="text/javascript"&gt; function showHide(selection){ var name = selection.name; var opt = selection.options[selection.selectedIndex].value; if (window.XMLHttpRequest){ //code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); }else{ // code for IE6, IE5 xmlhttp=new ActiveXObject('Microsoft.XMLHTTP'); } xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 &amp;&amp; xmlhttp.status==200){ document.getElementById('logterminal').innerHTML=xmlhttp.responseText; } } xmlhttp.open('GET', 'filteredlog.php?'+name+'='+opt, true); xmlhttp.send(); return false; } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div style="background-color:#fffacd;"&gt; &lt;form&gt; &lt;select name="errorlevel" onchange="return showHide(this);"&gt; &lt;option value="DEBUG"&gt;DEBUG&lt;/option&gt; &lt;option value="INFO" selected="selected"&gt;INFO&lt;/option&gt; &lt;option value="WARN"&gt;WARN&lt;/option&gt; &lt;option value="ERROR"&gt;ERROR&lt;/option&gt; &lt;/select&gt; &lt;select name="category" onchange="return showHide(this);"&gt; &lt;option value="All"&gt;All Categories&lt;/option&gt; &lt;?php foreach($categories as $category){ echo "&lt;option value='".$category."'&gt;".$category."&lt;/option&gt;"; } ?&gt; &lt;/select&gt; &lt;select name="product" onchange="return showHide(this);"&gt; &lt;option value="All"&gt;All Products&lt;/option&gt; &lt;?php foreach($products as $product){ echo "&lt;option value='".$product."'&gt;".$product."&lt;/option&gt;"; } ?&gt; &lt;/select&gt; &lt;select name="id" onchange="return showHide(this);"&gt; &lt;option value="All"&gt;All IDs&lt;/option&gt; &lt;?php foreach($ids as $id){ echo "&lt;option value='".$id."'&gt;".$id."&lt;/option&gt;"; } ?&gt; &lt;/select&gt; &lt;/form&gt; &lt;/div&gt; &lt;div id="logterminal"&gt; &lt;?php include("filteredlog.php"); ?&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>filteredlog.php</p> <pre><code>&lt;?php if(count(debug_backtrace())==0){; session_start(); } $errorlevel = $_GET['errorlevel']; $errorlevels = array("DEBUG", "INFO", "WARN", "ERROR"); if(empty($errorlevel)){ if(isset($_SESSION['errorlevel'])){ $errorlevel = $_SESSION['errorlevel']; }else{ $errorlevel = "INFO"; } }else{ $_SESSION['errorlevel']=$errorlevel; } $category = $_GET['category']; if(empty($category)){ if(isset($_SESSION['category'])){ $category = $_SESSION['category']; }else{ $category = "All"; } }else{ $_SESSION['category']=$category; } $product = $_GET['product']; if(empty($product)){ if(isset($_SESSION['product'])){ $product = $_SESSION['product']; }else{ $product = "All"; } }else{ $_SESSION['product']=$product; } $id = $_GET['id']; if(empty($id)){ if(isset($_SESSION['id'])){ $id = $_SESSION['id']; }else{ $id = "All"; } }else{ $_SESSION['id']=$id; } $lines = file("error.log"); $categories = array(); $products = array(); $ids = array(); foreach($lines as $line){ $segments = explode("][",substr($line,1,strrpos($line,']')-1)); if((!in_array($segments[2],$categories))&amp;&amp;(!empty($segments[2]))){ $categories[] = $segments[2]; } if((!in_array($segments[3],$products))&amp;&amp;(!empty($segments[3]))){ $products[] = $segments[3]; } if((!in_array($segments[4],$ids))&amp;&amp;(!empty($segments[4]))){ $ids[] = $segments[4]; } } echo $errorlevel . $category . $product . $id . "&lt;br /&gt;&lt;br /&gt;"; $currentlvl = ""; $filterlines = array(); foreach($lines as $line){ $segments = explode("][",substr($line,1,strrpos($line,']')-1)); $line_errlvl = $segments[0]; if(!in_array($line_errlvl,$errorlevels)){ $line_errlvl = $currentlvl; } switch($errorlevel){ case "DEBUG": if($line_errlvl=="DEBUG"){ $filterlines[] = $line; } case "INFO": if($line_errlvl=="INFO"){ $filterlines[] = $line; } case "WARN": if($line_errlvl=="WARN"){ $filterlines[] = $line; } case "ERROR": if($line_errlvl=="ERROR"){ $filterlines[] = $line; } default: $currentlvl = $line_errlvl; break; } } if($product != "All"){ $lines = $filterlines; $currentcat = ""; $filterlines = array(); foreach($lines as $line){ $segments = explode("][",substr($line,1,strrpos($line,']')-1)); $line_cat = $segments[2]; if(!in_array($line_cat,$categories)){ $line_cat = $currentcat; } if($line_cat==$category){ $filterlines[] = $line; } $currentcat = $line_cat; } } if($product != "All"){ $lines = $filterlines; $currentprod = ""; $filterlines = array(); foreach($lines as $line){ $segments = explode("][",substr($line,1,strrpos($line,']')-1)); $line_prod = $segments[3]; if(!in_array($line_prod,$releases)){ $line_prod = $currentprod; } if($line_prod==$product){ $filterlines[] = $line; } $currentprod = $line_prod; } } if($id != "All"){ $lines = $filterlines; $currentid = ""; $filterlines = array(); foreach($lines as $line){ $segments = explode("][",substr($line,1,strrpos($line,']')-1)); $line_id = $segments[4]; if(!in_array($line_id,$ids)){ $line_id = $currentid; } if($line_id==$id){ $filterlines[] = $line; } $currentid = $line_id; } } foreach($filterlines as $line){ echo $line . "&lt;br /&gt;"; } ?&gt; </code></pre>
[]
[ { "body": "<p>I wouldn't say this would affect your performance much, but usually <code>if((!in_array($segments[4],$ids))&amp;&amp;(!empty($segments[4])))</code>\nIs written as <code>if(!empty($segments[4])&amp;&amp;!in_array($segments[4],$ids))</code> so as to short out if the item is empty. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T03:10:39.980", "Id": "4938", "ParentId": "4918", "Score": "2" } }, { "body": "<p>Well, if you have product, ID, and category set to \"ALL\" (or equivalent), then your script calls:</p>\n\n<pre><code>$segments = explode(\"][\",substr($line,1,strrpos($line,']')-1));\n</code></pre>\n\n<p>ON EVERY LINE OF THE FILE, <strong><em>FIVE TIMES</em></strong>.</p>\n\n<p>Consider, instead:</p>\n\n<pre><code>$segs = array();\nforeach($lines as $line){\n $segments = explode(\"][\",substr($line,1,strrpos($line,']')-1));\n $segs[] = $segments;\n // then continue modifying/filtering the processed data instead of the strings\n</code></pre>\n\n<p>This block creates a series of variables which are not used anywhere else. I recommend chopping it:</p>\n\n<pre><code>$categories = array();\n$products = array();\n$ids = array();\nforeach($lines as $line){\n $segments = explode(\"][\",substr($line,1,strrpos($line,']')-1));\n if((!in_array($segments[2],$categories))&amp;&amp;(!empty($segments[2]))){\n $categories[] = $segments[2];\n }\n if((!in_array($segments[3],$products))&amp;&amp;(!empty($segments[3]))){\n $products[] = $segments[3];\n }\n if((!in_array($segments[4],$ids))&amp;&amp;(!empty($segments[4]))){\n $ids[] = $segments[4];\n }\n}\n</code></pre>\n\n<p>As a general rule, test to see if the array index exists before using it too, but once you've gotten rid of that block, you won't have to worry about that as that type of array look-up only happens there.</p>\n\n<p>On a more subtle point:</p>\n\n<pre><code>// this was foreach($lines as $line){, but I am assuming the fix suggested earlier.\nforeach($segs as $segments){\n $line_errlvl = $segments[0];\n if(!in_array($line_errlvl,$errorlevels)){\n $line_errlvl = $currentlvl;\n }\n switch($errorlevel){\n case \"DEBUG\":\n if($line_errlvl==\"DEBUG\"){\n $filterlines[] = $line;\n }//...\n</code></pre>\n\n<p>So, <code>in_array</code> performs a basic search of the array and returns true or false. If, however, we change this to <code>array_search</code> we could use the <code>&lt;</code> operator. Consider:</p>\n\n<pre><code>$numericLevel = array_search($errorlevel, $errorlevels);\n$currentlvl = 0;\n$filterlines = array();\nforeach($segs as $idx =&gt; $segments){\n // in_array basically does the same thing (on the machine level), \n // only it is less useful here.\n $line_errlvl = array_search($segments[0], $errorlevels);\n if(FALSE === $line_errlvl) $line_errlvl = $currentlvl;\n if($line_errlvl &gt;= $numericLevel) $filterlines[] = $lines[$idx];\n $currentlvl = $line_errlvl;\n}\n</code></pre>\n\n<p>That will both future-proof your code (you can add in a log level \"Skunk\" later, and it will still work), and it also makes it more efficient -- if you were set to \"DEBUG\" and ran the original:</p>\n\n<pre><code>switch($errorlevel){\n case \"DEBUG\":\n</code></pre>\n\n<p>You would end up comparing a DEBUG line to INFO, WARN, and ERROR. This makes exactly one comparison.</p>\n\n<p><hr />\nPersonally, I also feel that this is not somewhere you want to be using sessions. This should just be a series of reads, it does not really make sense to store it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T07:39:48.213", "Id": "7491", "Score": "0", "body": "I see only one problem: if you replace `foreach($lines as $line)` by `foreach($segs as $segments){`, how do you get the line in the expression `if($line_errlvl >= $numericLevel) $filterlines[] = $line;`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T12:38:17.117", "Id": "7495", "Score": "0", "body": "@Eldros Modified to reference numeric index of original array" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T14:01:52.460", "Id": "7498", "Score": "0", "body": "Ok, that's already one problem down. Now, choping the session code means that only the changed variable would be sent to filteredlog.php and all other variable would take their default value in the best of the case. What would you advice in this case?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T17:33:41.653", "Id": "7505", "Score": "0", "body": "@Eldros make everything work through GET and send all values -- since there are only four possible GET variables it will not add real overhead to either the server-side code or the client side code and it means that you don't need to store extra info on the SESSION (or even call `session_start`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T08:24:46.810", "Id": "7514", "Score": "0", "body": "So, I went through your changes, and it react quite quickly when the only filter specified is the errorlevel, but as soon as I choose a category, a product and/or and id, the performance drop abruptly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T14:35:48.723", "Id": "7520", "Score": "0", "body": "You are still looping over the same values multiple times. Place all of your logic the loop and run it once. You can see an example [here](http://pastebin.com/rpzfyRvY)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T08:30:09.753", "Id": "7558", "Score": "0", "body": "Ok, now it grows exponentially slow the more lines it should display. To be fair I added some code to it, as a line without any segments is part of a group which began with the last line with segments. See [here](http://pastebin.com/GBC5p2SP)." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T04:06:24.393", "Id": "4940", "ParentId": "4918", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T07:05:42.733", "Id": "4918", "Score": "2", "Tags": [ "php", "javascript", "performance" ], "Title": "Filtered log reader" }
4918
<p>I have a performance issue causing test->code->test cycle to be really slow. The slowness is hard to avoid, since I am doing some heavy image processing, and I am trying to accelerate things a bit by not running functions when it is not needed. For ex: compute some numbers from big images -> serialize results in text files -> resume computations from text files.</p> <p>Currently, I commit the text files containing the results to share them with the team, and let other people run the tests quickly. But I have to make sure that whenever one dependency is updated (src images, preprocessing functions, etc), those value are recomputed. I looked for a tool which would allow me to describe dependencies and production rules to automate the process and avoid committing data in the codebase. I thought about makefile, but I read a lot of negative advice against it. I found stuff like Scons and other build <a href="http://en.wikipedia.org/wiki/List_of_build_automation_software" rel="nofollow">automation tools</a>, but those are for building software, and they do not seem adapted for my task.</p> <p>I decided to write a small lib to tackle this issue (my environment is mainly Python and some C). The goal was to have objects knowing the production rule for their own output, and aware of the other objects they depend upon. An object knows if its output is up-to-date by comparing the current MD5 checksum of the file against the last one (stored somewhere in a small temp file).</p> <p>Am I reinventing a wheel here? Is there a tool out there I should use instead of a custom lib? If not, is this a good pattern for taking care of this problem?</p> <pre><code>import os import path from md5 import md5 as stdMd5 # path.root is the root of our repo hashDir = os.path.join(path.root, '_hashes') def md5(toHash): return stdMd5(toHash).hexdigest() class BaseRule(object): '''base object, managing work like checking if results are up to date, and calling production rules if they are not''' outPath = None def __init__(self, func): self.func = func @property def hashPath(self): return os.path.join(hashDir, md5(self.outPath)) def getOutHash(self): with open(self.outPath) as f: fileHash = md5(f.read()) return fileHash def isUpToDate(self): if not os.path.exists(self.outPath): return False if not os.path.exists(self.hashPath): return False with open(self.outPath) as f: fileHash = self.getOutHash() with open(self.hashPath) as f: storedHash = f.read().strip() return storedHash == fileHash def storeHash(self): if not os.path.exists(hashDir): os.makedirs(hashDir) with open(self.hashPath, 'w') as f: f.write(self.getOutHash()) def get(self): inputPathes = dict([(key, inp.get()) for key, inp in self.inputs.items()]) if not self.isUpToDate(): self.func(outPath=self.outPath, **inputPathes) self.storeHash() return self.outPath class StableSrc(BaseRule): 'source file that never change' inputs = {} def __init__(self, path): self.outPath = path def isUpToDate(self): return True def rule(_inputs, _outPath): 'decorator used to declare dependencies' class Rule(BaseRule): inputs = _inputs outPath = _outPath return Rule def copyTest(): 'test function' import shutil @rule({'inp' : StableSrc('test.txt')}, 'test2.txt') def newTest(inp, outPath): print 'copy' shutil.copy(inp, outPath) @rule({'inp' : newTest}, 'test3.txt') def newNewTest(inp, outPath): print 'copy2' shutil.copy(inp, outPath) return newNewTest.get() if __name__ == '__main__': copyTest() # will copy test.txt to test2.txt and test3.txt. If ran a second time, won't copy anything </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T15:42:15.330", "Id": "7373", "Score": "0", "body": "\"Am I reinventing a wheel here?\" Yes. \"Is there a tool out there I should use instead of a custom lib?\" Yes. SCons. \"those are for building softwares\". False. They're for processing dependencies. The default configuration builds software, since that's the 80% use case. You're the other 20%. You have to write customized rules." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T17:08:47.940", "Id": "7375", "Score": "0", "body": "Thank you. I will have a closer look to Scons. Does it integrate well in a python codebase, or should I maintain a strict separation between scons and python scripts?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T17:10:32.923", "Id": "7376", "Score": "0", "body": "What? \"a strict separation between scons and python scripts\"? What can this mean? Also. You should ask for details on Scons on Stackoverflow. Not here. That's not a code review question at all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-26T10:21:49.657", "Id": "7478", "Score": "0", "body": "Re: SCons: or nmake, GNU make, Ant, NAnt etc. everything that does dependency checking" } ]
[ { "body": "<pre><code># path.root is the root of our repo\nhashDir = os.path.join(path.root, '_hashes')\n</code></pre>\n\n<p>Python style guide recommends that global constants are ALL_CAPS</p>\n\n<pre><code>class BaseRule(object):\n '''base object, managing work like checking if results are up to date, and\n calling production rules if they are not'''\n\n outPath = None\n</code></pre>\n\n<p>Python style guide recommends that class level constants are ALL_CAPS</p>\n\n<pre><code> def isUpToDate(self):\n if not os.path.exists(self.outPath):\n return False\n if not os.path.exists(self.hashPath):\n return False\n with open(self.outPath) as f:\n fileHash = self.getOutHas()\n</code></pre>\n\n<p>You don't use the file you open here, instead you open the file inside getOutHash</p>\n\n<pre><code> with open(self.hashPath) as f:\n storedHash = f.read().strip()\n return storedHash == fileHash\n\n\n def get(self):\n inputPathes = dict([(key, inp.get()) for key, inp in self.inputs.items()])\n</code></pre>\n\n<p>No need for the square brackets. They make it so that it produces a list. But since you are creating a dictionary there is no need to make a list first.</p>\n\n<pre><code> if not self.isUpToDate():\n self.func(outPath=self.outPath, **inputPathes)\n self.storeHash()\n return self.outPath\n\nclass StableSrc(BaseRule):\n 'source file that never change'\n\n inputs = {}\n</code></pre>\n\n<p>I know you'll never modify this, but inputs is an object level attribute above, and its clearest if you keep it that way.</p>\n\n<pre><code> def __init__(self, path):\n self.outPath = path\n\n def isUpToDate(self):\n return True\n\n\n\ndef copyTest():\n 'test function'\n\n import shutil\n\n @rule({'inp' : StableSrc('test.txt')}, 'test2.txt')\n def newTest(inp, outPath):\n print 'copy'\n shutil.copy(inp, outPath)\n</code></pre>\n\n<p>Usually you've got a small number of possible actions with different inputs/outputs for each use. Your decorator method assumes that each action will be different. </p>\n\n<ol>\n<li>You aren't tracking dependencies amongst the rules. So you can't have some like .swig produces .cpp produces .o which is linked to produce .exe</li>\n<li>Creating a class for every rule is odd. It would make more sense to create an object for each rule.</li>\n<li>The only thing you've got over makefiles is your use of a hash rather then a timestamp</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T12:53:05.197", "Id": "7363", "Score": "0", "body": "thank you for your comments. Note that rules may be used several times on the same function without the decorator syntax, so I can define a small set of functions, and apply `rule` on them. The class creation seems more natural to me, because a decorator must be callable. Here `newTest` is an object, not a class. Do you think I should go for makefiles?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T14:05:40.307", "Id": "7370", "Score": "0", "body": "@Simon, functions and objects can also be callable. Creating various copies of a class at runtime isn't really expected behavior. Classes are expected to more or less be created once at import time and then used. Unless I'm misreading the code (possible) newTest is a class. The decorator replaces the function you define with a class. Makefiles: reusing existing solutions is usually the best choice. Makefiles are very simple but when they work, they work very well. I'd check to see whether the serve your purposes and if so, use them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T17:13:52.943", "Id": "7377", "Score": "0", "body": "if we express the decorator differently, we get `newTest=rule(args)(newTest)`. `rule(args)` is a class. `rule(args)(func)` is an object. I can make `rule(args)` a callable object which return a Rule instance when called with a function, but I think it is too complex compared to the class approach. Still, I don't think that this lib is a good idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T17:35:41.573", "Id": "7378", "Score": "0", "body": "@Simon, you are correct, I forgot how decorators worked. I'd probably define the class outside and use functools.partial rather then define a new class for every rule. But that a style preference I can't argue its clearly better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-21T07:54:39.247", "Id": "7381", "Score": "0", "body": "I see what you mean. Accepting this answer, since my original question is answered." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T12:32:23.470", "Id": "4921", "ParentId": "4920", "Score": "2" } } ]
{ "AcceptedAnswerId": "4921", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T12:00:36.990", "Id": "4920", "Score": "5", "Tags": [ "python", "performance", "unit-testing" ], "Title": "Faster tests with dependency analysis" }
4920
<p>I'm looking to improve this class - any suggestions? It checks for empty, name, email, and password. The regex for email is very simple. A very lengthy article from the Linux Journal for improving upon this is <a href="http://www.linuxjournal.com/article/9585" rel="nofollow noreferrer">here</a>. The character set for password I borrowed from the NASA signup page. For name I allow letters, periods, and dashes. Testing for empty was developed with in this <a href="https://stackoverflow.com/questions/7464515/testing-an-array-for-an-empty-string-and-returning-an-int-0-or-1-best-practic">SO Post</a></p> <pre><code>class check { static function empty_user($a) { return (int)!in_array('',$a,TRUE); } static function name($a) { return preg_match('/^[a-zA-Z-\.]{1,40}$/',$a); } static function email($a) { return preg_match('/^[a-zA-Z0-9._s-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{1,4}$/',$a); } static function pass($a) { return preg_match('/^[a-zA-Z0-9!@#$%^&amp;*]{6,20}$/',$a); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T02:54:39.927", "Id": "7364", "Score": "1", "body": "You really shouldn't use a regex to validate email addresses. Also, why is this in a class? A namespace would make more sense." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-03T21:11:33.563", "Id": "11650", "Score": "2", "body": "Please don't edit the question to make the existing answers meaningless. If you have new versions of the code post a new question. Reference this one (in it's original form) and explain that it's a new issue.\n http://meta.stackexchange.com/questions/94446/editing-a-question-and-asking-a-completely-different-question\n http://meta.stackexchange.com/questions/64459/rolling-back-a-completely-changed-question" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-03T21:39:28.843", "Id": "11659", "Score": "0", "body": "As @palacsint said: Please stop editing your questions to something unrelated. If you keep doing this, you'll be suspended." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T02:55:06.110", "Id": "62851", "Score": "0", "body": "For email validation/sanitization look at the built in (PHP 5.2+) filter functions. http://www.php.net/manual/en/filter.examples.sanitization.php" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T02:56:12.167", "Id": "62852", "Score": "0", "body": "is it possible to see the regex they use for the filters?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T02:59:46.013", "Id": "62853", "Score": "0", "body": "@Chris Aaker Good question. This link answers that http://stackoverflow.com/questions/5682106/how-are-phps-built-in-functions-implemented-internally/5682120#5682120" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T22:11:25.140", "Id": "64794", "Score": "0", "body": "To add to the previous, you may want to consider some more cases for the name. Apostrophes are a good idea to cater for Irish names, as well as allowing a single whitespace (for people with a von or a de in their names, such as yours truly). A better regex: /^[a-zA-Z-\\'\\.(\\s?)]{1,40}$/" } ]
[ { "body": "<p>First of all, as mentioned by @user7212, use php <code>filter_var()</code> for email validation. Please see below for example:</p>\n\n<pre><code>/**\n * Validate email\n *\n * @param string $email\n *\n * @return bool\n */\npublic static function email($email)\n{\n return filter_var($email, FILTER_VALIDATE_EMAIL);\n}\n</code></pre>\n\n<p>Second, why not naming your function params? If the email validation function would be called <code>$email</code>, if would be much easier to understand then <code>$a</code>.</p>\n\n<p><code>in_array()</code> function, according to it's <a href=\"http://us1.php.net/manual/ru/function.in-array.php\" rel=\"nofollow\">documentation</a>, returns <code>bool</code>. Why converting it to <code>int</code>? The result of the check should be <code>bool</code>.</p>\n\n<p>In the <code>pass()</code> function, are you checking a string or a hash? Which brings us to the following item - write comments for your code! <a href=\"http://en.wikipedia.org/wiki/PHPDoc\" rel=\"nofollow\">PHPDoc</a> is a good example on how to do that.</p>\n\n<p>And the last, but not the least - the name of the class. <code>Check</code> is not the most appropriate name. I would consider <code>Validation</code> or <code>Valid</code>.</p>\n\n<p>Hope this helps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-06T07:53:51.177", "Id": "331921", "Score": "0", "body": "Please tick the answer if it helped ;)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-17T19:46:59.400", "Id": "39507", "ParentId": "4922", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T02:51:39.813", "Id": "4922", "Score": "4", "Tags": [ "php" ], "Title": "class design improvement - user validation" }
4922
<p>I'm writing a little Downloader that will look through directories online and download the content. The first prototype of my program is a success, now I just want to refine it and learn some more C#. The task is this:</p> <p>Take this string: </p> <p><code>http://example.free.pl/plus%20violent/Dark%20The%20Suns/All%20Ends%20In%20Silence/</code></p> <p>and create the substring between the last two <code>/</code></p> <p>Result: <code>All%20Ends%20In%20Silence</code></p> <p>I find my current code brutish and probably not a clean, C# way of solving the problem:</p> <pre><code> string GetDirectoryName(string directory) { int lastIndex = directory.LastIndexOf("/"); int count = directory.Count&lt;char&gt;(elem =&gt; elem == '/') - 1; int startIndex = 0; while (count &gt; 0) { startIndex = directory.IndexOf("/", startIndex) + 1; --count; } return directory.Substring(startIndex, lastIndex - startIndex).Replace("%20", " "); } </code></pre> <p>Please advise me how I could make this code cleaner, clearer and following the C# methodology of programming.</p>
[]
[ { "body": "<p>The .NET framework will do this for you pretty cleanly with the right classes.</p>\n\n<p>For example:</p>\n\n<pre><code>string url = \"http://example.free.pl/plus%20violent/Dark%20The%20Suns/All%20Ends%20In%20Silence/\";\n\nDirectoryInfo di = new DirectoryInfo( new Uri(url).LocalPath );\n</code></pre>\n\n<p>The <code>di.Name</code> property contains \"All Ends In Silence\".</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T15:27:38.723", "Id": "7372", "Score": "0", "body": "That's pretty useful. I'll have to look at the library on MSDN, thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T15:00:51.233", "Id": "4926", "ParentId": "4924", "Score": "10" } }, { "body": "<p>You could replace your loop with a call to <a href=\"http://msdn.microsoft.com/en-us/library/1tw91fa3.aspx\" rel=\"nofollow\"><code>LastIndexOf</code></a>:</p>\n\n<pre><code>const char separator = '/';\nint lastSlash = directory.LastIndexOf(separator);\nint slashBeforeLast = directory.LastIndexOf(separator, lastSlash - 1);\nreturn directory.Substring(slashBeforeLast + 1, lastSlash - slashBeforeLast - 1);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-21T15:45:41.520", "Id": "7389", "Score": "0", "body": "I am already getting the last '/' with `LastIndexOf`. How would a second call to LastIndexOf get me the other '/' I need?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-21T21:00:34.703", "Id": "7392", "Score": "0", "body": "@SoulBeaver: By adding an index. I've specifically linked to the overload that takes an index. I'm updating my answer with an example." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T10:49:08.943", "Id": "7401", "Score": "0", "body": "Aaaah now I understand what you mean, thanks!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-21T13:09:51.023", "Id": "4933", "ParentId": "4924", "Score": "2" } } ]
{ "AcceptedAnswerId": "4926", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T13:19:01.507", "Id": "4924", "Score": "4", "Tags": [ "c#" ], "Title": "Find a specific Substring" }
4924
<p>This is my first ever attempt at Ajax form validation, and everything works as expected, the final true example will hold a lot more input fields than in my testing scripts which are below.</p> <p>The file is expected to get a lot bigger as in my testing I have only used 3 input fields, how can I improve on this:</p> <p><strong>HTML file</strong></p> <pre><code>&lt;form action="#" method="post"&gt; &lt;fieldset&gt; &lt;legend&gt;Login Details&lt;/legend&gt; &lt;label&gt;Your Email:&lt;/label&gt;&lt;input id="email" name="email" type="text" onblur="return ajax ('email');" /&gt; &lt;label&gt;Password:&lt;/label&gt;&lt;input id="password" name="password" type="text" onblur="return ajax ('password');" /&gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;legend&gt;Account Details&lt;/legend&gt; &lt;label&gt;Your Username:&lt;/label&gt;&lt;input id="username" name="username" type="text" onblur="return ajax ('username');" /&gt; &lt;/fieldset&gt; &lt;input class="submit" type="submit" value="Create Account" /&gt; &lt;/form&gt; </code></pre> <p>As you can see in the event of an onblur on the input fields I call the function ajax. I also send with the function a parameter which is exact to the id. Here is my function:</p> <p><strong>JavaScript</strong></p> <pre><code>function ajax (id) { var value = $('#' + id).val(); $('#' + id).after('&lt;div class="loading"&gt;&lt;/div&gt;'); if (id === 'email') { $.post('http://www.example.com/ajax.php', {email: value}, function (response) { $('#email_error, #email_success').hide(); setTimeout(function(){ $('.loading').hide(); finish_ajax (id, response); }, 1000); }); } if (id === 'password') { $.post('http://www.example.com/ajax.php', {password: value}, function (response) { $('#password_error, #password_success').hide(); setTimeout(function(){ $('.loading').hide(); finish_ajax (id, response); }, 1000); }); } if (id === 'username') { $.post('http://www.example.com/ajax.php', {username: value}, function (response) { $('#username_error, #username_success').hide(); setTimeout(function(){ $('.loading').hide(); finish_ajax (id, response); }, 1000); }); } return false; } function finish_ajax (id, response) { $('#' + id).after(response).fadeIn(2000); } </code></pre> <p>Here is what I have tried to do:</p> <ol> <li><p>With the id that I send with the function I assign the value of the input field to a variable named value.</p></li> <li><p>Using the same id I then assign a loading div which contains a gif image in my css.</p></li> <li><p>Depending on the id send the correct request with the correct name so I can determine in my php file the correct validation is done on each of the input fields. Here is my php file.</p></li> </ol> <p><strong>PHP file</strong></p> <pre><code>if (isset($_REQUEST['email'])) { $q = $dbc -&gt; prepare("SELECT email FROM accounts WHERE email = ?"); $q -&gt; execute(array($_REQUEST['email'])); if (!filter_var($_REQUEST['email'], FILTER_VALIDATE_EMAIL)) { echo '&lt;div id="email_error" class="error"&gt;This is not a valid email!&lt;/div&gt;'; } elseif ($q -&gt; rowCount() &gt; 0) { echo '&lt;div id="email_error" class="error"&gt;Email already owns an account!&lt;/div&gt;'; } else { echo '&lt;div id="email_success" class="success"&gt;Success!&lt;/div&gt;'; } } elseif (isset($_REQUEST['password'])) { if (strlen($_REQUEST['password']) &lt; 6) { echo '&lt;div id="password_error" class="error"&gt;Your password is not long enough.&lt;/div&gt;'; } else { echo '&lt;div id="password_success" class="success"&gt;Password Success!&lt;/div&gt;'; } } elseif (isset($_REQUEST['username'])) { $q = $dbc -&gt; prepare("SELECT username FROM accounts WHERE username = ?"); $q -&gt; execute(array($_REQUEST['username'])); if (strlen($_REQUEST['username']) &lt; 3) { echo '&lt;div id="username_error" class="error"&gt;Has to be at least 3 characters&lt;/div&gt;'; } elseif ($q -&gt; rowCount() &gt; 0) { echo '&lt;div id="username_error" class="error"&gt;Username already taken&lt;/div&gt;'; } else { echo '&lt;div id="username_success" class="success"&gt;Username available&lt;/div&gt;'; } } else { header('Location: http://www.projectv1.com'); exit(); } </code></pre> <p>Here I check the name of the request and perform the correct validation.</p> <p>I have tried to do this as best I can and there may be many errors in it performance-wise which I am unaware of.</p>
[]
[ { "body": "<p>Here's a few things I can observe at first glance:</p>\n\n<p><br/></p>\n\n<h2>HTML</h2>\n\n<ol>\n<li><p><code>form</code> elements don't accept <code>input</code> fields as direct child’s, so you should place your submit button inside a wrapper element.</p></li>\n<li><p>I don't know about your visual aspect, but you should use CSS to format your elements and keep HTML to a minimum.</p></li>\n<li><p>Your password field should have the type password as to allow the browser to obfuscate the characters being typed.</p></li>\n<li><p>If you're using jQuery, you're better of going with the <a href=\"http://api.jquery.com/blur/\" rel=\"nofollow\">.blur()</a> event instead of giving <code>onblur</code> attribute to all elements subjected to validation.</p></li>\n</ol>\n\n<p><strong>Your HTML form would become something like:</strong></p>\n\n<pre><code>&lt;form id=\"myForm\" action=\"#\" method=\"post\"&gt;\n &lt;fieldset&gt;\n &lt;legend&gt;Login Details&lt;/legend&gt;\n &lt;label&gt;Your Email:&lt;/label&gt;\n &lt;input id=\"email\" name=\"email\" type=\"text\" /&gt;\n &lt;label&gt;Password:&lt;/label&gt;\n &lt;input id=\"password\" name=\"password\" type=\"password\" /&gt;\n &lt;/fieldset&gt;\n &lt;fieldset&gt;\n &lt;legend&gt;Account Details&lt;/legend&gt;\n &lt;label&gt;Your Username:&lt;/label&gt;\n &lt;input id=\"username\" name=\"username\" type=\"text\" /&gt;\n &lt;/fieldset&gt;\n &lt;p&gt;\n &lt;input class=\"submit\" type=\"submit\" value=\"Create Account\" /&gt;\n &lt;/p&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p><br/></p>\n\n<h2>JQUERY</h2>\n\n<p>Your jQuery currently uses the same code over and over, the best option is always to make scripts as generic as possible, to minimize the amount of code that as to be downloaded and interpreted by the browser. Also, in future maintenance, you'll find it easy to deal with a small generic code then a large element specific one.</p>\n\n<ol>\n<li><p>As mentioned above, with the jQuery <code>.blur()</code> function, you can bind the event to all inputs inside the target form and start creating a more generic validation solution.</p></li>\n<li><p>Instead of having an <code>if</code> statement to ascertain the element subject to validation, send to the PHP file the field collected and its value.</p></li>\n<li><p>No need for specific error elements for each input subjected to validation, use classes and target then thru the <code>input</code> <code>id</code> attribute, that in conjunction with a generic class for messages gives your the target element for the user messages.</p></li>\n<li><p>If you are appending the element <code>.loading</code> to the form, you should also remove it when not needed. If the user keeps triggering the <code>blur</code> in the same <code>input</code> field, the element <code>.loading</code> keeps being added and you end up with tons of them.</p></li>\n</ol>\n\n<p><strong>Your jQuery code to validate the above form would become something like:</strong></p>\n\n<pre><code>$('#myForm input').blur(function() {\n\n var id = $(this).attr(\"id\");\n $('#' + id).after('&lt;div class=\"loading\"&gt;&lt;/div&gt;');\n\n $.post('http://www.example.com/ajax.php', {field:id, value:value}, function (response) {\n $('.'+id+'.msg').hide();\n setTimeout(function() {\n $('.loading').remove();\n finish_ajax (id, response);\n }, 1000);\n });\n\n});\n\nfunction finish_ajax (id, response) {\n $('#' + id).after(response).fadeIn(2000);\n} \n</code></pre>\n\n<p><br/></p>\n\n<h2>PHP</h2>\n\n<p>Your PHP code falls under the same issues as the jQuery code, that is, repeating several chunks of code that latter on will prove difficult to maintain.</p>\n\n<ol>\n<li><p>If you're using a <code>POST</code> method, check for it and the specific variables necessary to execute the script, otherwise, bailout.</p></li>\n<li><p>Perform some cleanup to the values before using them.</p></li>\n<li><p>Since you're querying the same table, having the field passed along with the value, proves useful to have a single database line to maintain instead of several across the script.<br>\nYou can choose to mascaraed the field name if your really want to obfuscate what's being done.</p></li>\n<li><p>When using many <code>If elseif else</code> statements, the best option is to migrate to a <code>switch case</code> statement. Easy to maintain, read and \"upgrade\".</p></li>\n<li><p>If the HTML that this script is outputting is the same, changing only the text and a class, best is to make use of variables to store the desirable values and have one single like with the script output.<br>\nWill prove useful when dealing with problems, having to \"upgrade\" the script, etc.</p></li>\n</ol>\n\n<p><strong>Your PHP code would become something like:</strong></p>\n\n<pre><code>if (isset($_POST[\"field\"]) &amp;&amp; isset($_POST[\"value\"])) {\n\n $field = cleanStr($_POST[\"field\"]);\n $value = cleanStr($_POST[\"value\"]);\n\n $q = $dbc -&gt; prepare(\"SELECT \".$field.\" FROM accounts WHERE \".field.\" = ?\");\n $q -&gt; execute(array($value));\n\n $msgType = \"error\";\n\n switch($field) {\n\n case \"email\": {\n if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {\n $message = \"This is not a valid email!\";\n } elseif ($q -&gt; rowCount() &gt; 0) {\n $message = \"Email already owns an account!\";\n } else {\n $message = \"Email success!\";\n $msgType = \"success\";\n }\n }\n break;\n\n case \"password\": {\n if (strlen($_REQUEST['password']) &lt; 6) {\n $message = \"Your password is not long enough.\";\n } else {\n $message = \"Password success!\";\n $msgType = \"success\";\n }\n }\n break;\n\n case \"username\": {\n if (strlen($_REQUEST['username']) &lt; 3) {\n $message = \"Has to be at least 3 characters\";\n } elseif ($q -&gt; rowCount() &gt; 0) {\n $message = \"Username already taken\";\n } else {\n $message = \"Username available!\";\n $msgType = \"success\";\n }\n break;\n }\n\n default:\n echo \"The field could not be identified!\";\n break;\n }\n\n echo '&lt;div class=\"'.$field.' msg '.$msgType.'\"&gt;'.$message.'&lt;/div&gt;';\n\n} else {\n header('Location: http://www.projectv1.com');\n exit();\n}\n\n\nfunction cleanStr($str) {\n return filter_var(trim($str),FILTER_SANITIZE_STRING);\n}\n</code></pre>\n\n<hr>\n\n<p>The above notes should give you an overall improvement on your form validation, leading to a valid code and a better solution for future maintenance.</p>\n\n<p>I haven't tested any of it, but it should be working.</p>\n\n<hr>\n\n<h2>Validating Code:</h2>\n\n<p>This links should prove useful as to validate your code and warn you about common mistakes:</p>\n\n<ul>\n<li>HTML: Validating HTML using the <a href=\"http://validator.w3.org/\" rel=\"nofollow\">W3C Markup Validation Service</a></li>\n<li>jQUERY: Validating jQuery using the <a href=\"http://www.jslint.com/\" rel=\"nofollow\">JSLint</a></li>\n<li>PHP code analysis using the <a href=\"http://phpcodechecker.com/\" rel=\"nofollow\">PHP code Checker</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-02T22:59:02.757", "Id": "16130", "ParentId": "4925", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T13:21:11.007", "Id": "4925", "Score": "5", "Tags": [ "php", "jquery", "ajax", "form", "validation" ], "Title": "Ajax form validation" }
4925
<p>I wrote a short ruby script to generate various screenshots, and event though I am not completely new to ruby I rarely use it. </p> <p>Full script (41 LOC): <a href="https://gist.github.com/1229115">https://gist.github.com/1229115</a></p> <p>The string substitutions irritate me. They don't look quite right - much too ugly for a beautiful and concise language like ruby. Am I overdoing it? What alternatives are there?</p> <p>Here is the lines I am concerned about (for context, please take a look at the gist):</p> <pre><code># assemble file name fname = "#{directory}/#{prefix}-#{timestamp}-#{commit}-#{size[:width]}x#{size[:height]}.png" # create command line stuff call = "#{macruby_exe} #{snapper} \ --width #{size[:width]} --height #{size[:height]} #{url} #{fname}" # now call it system call # just to show the progress (and the file sizes) puts "#{fname} (#{File.size?(fname) / 1024}kB)" </code></pre> <hr> <p>Just to illustrate the script, the output usually looks like:</p> <pre><code>screenies/screenshot-1316535022-0b5c7967887481deb17bcd9039cd3fe0ac4540d4-640x960.png (95kB) screenies/screenshot-1316535022-0b5c7967887481deb17bcd9039cd3fe0ac4540d4-800x480.png (62kB) screenies/screenshot-1316535022-0b5c7967887481deb17bcd9039cd3fe0ac4540d4-800x600.png (78kB) ^ ^ ^ ^ ^ | | | | ________|______ | | | | | | directory prefix timestamp commit size[:width] x size[:height] </code></pre>
[]
[ { "body": "<p>There are other ways you could write this but I'm not sure if you'd find any of them cleaner. One option is plain old <a href=\"http://ruby-doc.org/core/classes/Kernel.html#M001432\"><code>sprintf</code></a>. For example:</p>\n\n<pre><code># assemble file name\nfname = sprintf(\"%s/%s-%i-%s-%ix%i.png\", directory, prefix, timestamp,\n commit, size[:width], size[:height])\n</code></pre>\n\n<p>You could shorten it a little by giving <code>size</code> its own <code>to_s</code> method:</p>\n\n<pre><code>class &lt;&lt; size; def to_s; \"#{self[:width]}x#{self[:height]}\" end end\n\nfname = sprintf(\"%s/%s-%i-%s-%s.png\", directory, prefix, timestamp,\n commit, size)\n</code></pre>\n\n<p>...and perhaps create other convenience methods along the same lines. But still, very small gains.</p>\n\n<p>Another option would be to make your own super-small template engine, something like this:</p>\n\n<pre><code>def tiny_subst template, bndg\n param_exp = /:(\\w+)[^\\w:]+/i\n tmpl_params = template.scan(param_exp).flatten\n\n proc {\n out_str = template.clone\n\n tmpl_params.reduce(out_str) do |str, p|\n str.gsub \":#{p}\", eval(p, bndg).to_s unless p.empty?\n end\n }\nend\n\ntmpl = ':directory/:prefix-:timestamp-:commit-:size.png'\nsubber = tiny_subst(tmpl, binding)\n\ndirectory = 'screenies'\nprefix = 'screenshot'\ntimestamp = Time.now.to_i\ncommit = '0b5c7967887481deb17bcd9039cd3fe0ac4540d4'\nsize = '640x960'\n\nsubber.yield # =&gt; screenies/screenshot-1316535022-0b5c7967887481deb17bcd9039cd3fe0ac4540d4-640x960.png\n\ncommit = 'foobarbazquux'\nsize = '9000x9000'\n\nsubber.yield # =&gt; screenies/screenshot-1316535022-foobarbazquux-9000x9000.png\n</code></pre>\n\n<p>So, that's kinda nice, but is it really worth it? Not for me, but I guess if you really hate \"<code>#{this}</code>\" it might be.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T10:22:28.093", "Id": "7400", "Score": "0", "body": "Thank you - an inspiring answer. I don't really hate `#{this}` but the mini-template seems nicer, I'll try it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T15:15:57.687", "Id": "7405", "Score": "0", "body": "Well it's not really intended for use but if you find it useful I actually put it up on GitHub last night: https://github.com/jrunning/StupidLittleTemplate There are probably security implications to eval-ing variables in the local scope, so please don't use it in a production app, or at the very least sanitize user data until it sparkles before passing it in." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T12:28:32.157", "Id": "7416", "Score": "0", "body": "Great, I'll take a look." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T08:09:25.980", "Id": "4942", "ParentId": "4927", "Score": "5" } }, { "body": "<p>Per your request (and drawing from your gist), more concise and readable is:</p>\n\n<pre><code>screensizes = [\n# width height\n [ 640, 960 ], # iPhone 4\n [ 800, 480 ], # wvga\n [ 800, 600 ], # old school\n [ 1024, 600 ], # netbook, WSVGA\n [ 1024, 786 ], # old school, iPad\n [ 1200, 800 ], # macbook\n [ 1366, 786 ], # netbook\n [ 1440, 900 ], # macbook pro\n [ 1600, 768 ], # strange\n [ 1680, 1050 ], # hires macbok\n]\n\nscreensizes.each do |w,h|\n# Assemble file name:\n f = \"#{directory}/#{prefix}-#{timestamp}-#{commit}-#{w}x#{h}.png\"\n\n# Create command line stuff:\n s = \"#{macruby_exe} #{snapper} --width #{w} --height #{h} #{url} #{f}\"\n\n# Now call it:\n system s\n\n# Show progress and file sizes:\n puts \"#{f} (#{File.size?(f) / 1024}kB)\"\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-21T23:56:46.357", "Id": "8179", "ParentId": "4927", "Score": "2" } } ]
{ "AcceptedAnswerId": "4942", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T16:12:43.690", "Id": "4927", "Score": "8", "Tags": [ "ruby", "strings" ], "Title": "String substitutions in ruby and coding style" }
4927
<p>I am fairly satisfied with my solution here but I would definitely appreciate any constructive criticism of my style and design. The basic idea is to use the strategy pattern to simplify assembling a custom procedural generator. I'm using modules rather than classes for improved simplicity of 'mixing' everything together. </p> <p>Here's the root of the 'strategy' class tree, <code>AbstractStrategy</code>:</p> <pre><code> # # the contract here is that the child strategy should implement an apply # function which takes a target problem instance and hash options. # module AbstractStrategy def apply!(problem, opts={}) log.debug "--- AbstractStrategy.apply! problem=#{problem}, opts=#{opts}" apply(problem, opts) end end </code></pre> <p>One level down, we have another 'parent' pattern which implements a particular strategy 'action' or 'style'. In this case it's an <code>AbstractGenerationStrategy</code> which implements <code>apply</code> according to the contract above.</p> <pre><code> # # the contract here is that the child strategy needs to implement "generate_[component]!({})" # module AbstractGenerationStrategy extend AbstractStrategy include AbstractStrategy def extend!(base) log.debug("--- extending #{base}") self.extend(base) end # # =&gt; use like -- generate :rooms, ConstructNestedRoomsStrategy, ...opts... # def generate(component, strategy, opts={}) log.debug "--- AbstractGenerationStrategy.generate[component=#{component}, strategy=#{strategy}]" extend!(strategy) apply!(component,opts) end def apply(component_to_generate, opts) log.debug "--- AbstractGenerationStrategy.apply component=#{component_to_generate}, opts=#{opts})" self.send("generate_#{component_to_generate}!", opts) end end </code></pre> <p>To see this in action, one strategy module which implements the above contract is <code>AbstractRoomGenerationStrategy</code>:</p> <pre><code> # # contract -- expects children to implement generate_room(opts) # module AbstractRoomGenerationStrategy extend AbstractGenerationStrategy include AbstractGenerationStrategy include LoggingHelpers DEFAULT_ROOM_COUNT = 3 def generate_rooms!(opts={}) room_count = opts[:count] || DEFAULT_ROOM_COUNT log.debug "generating #{opts[:count]} rooms" room_count.times { generate_room!(opts) } end end </code></pre> <p>Finally, a 'concrete' example of an <code>AbstractRoomGenerationStrategy</code> is <code>ConstructSingleHugeRoomStrategy</code>. Note at this point we are expecting to be 'mixed' into (technically, <code>extend</code>ed <em>from</em>) certain kinds of classes, and so we are expecting certain member variables (like <code>@width</code> and <code>@height</code>) to exist:</p> <pre><code> module ConstructSingleHugeRoomStrategy extend RoomGenerationStrategy include RoomGenerationStrategy def generate_room!(opts={}) @rooms ||= [] log.debug 'generating room' if @rooms.empty? place_first_room(opts) else # do nothing end end # # place a huge room in the center of the space # def place_first_room(opts) log.debug "placing first huge room" default_opts = { :width =&gt; @width/2, :height =&gt; @height/2, :position =&gt; [@width/4, @height/4] } opts ||= default_opts room = Room.new(opts) log.debug "new room created: #{room}" @rooms &lt;&lt; room end end </code></pre> <p>In the context of an appropriate class the operation can be invoked like</p> <pre><code>generate :rooms, ConstructSingleHugeRoomStrategy, opts </code></pre> <p>Here's a snippet from a test scenario exercising the above strategy:</p> <pre><code>log.info '--- building new space with defaults (no opts)' @@space = Space.new log.debug 'calling space.generate_rooms! with ConstructSingleHugeRoomStrategy' @@space.generate :rooms, ConstructSingleHugeRoomStrategy log.debug 'asserting room count == 1' @@space.rooms.count.should == 1 </code></pre> <p>At the moment I can't provide a direct link to more as the repository is in a private bitbucket, though I am happy to try to provide more context if necessary.</p> <p>I'd like feedback on class design and pattern usage (and of course coding style and correctness if you see real problems here.) Note the main goal of using the 'strategies' here was really just to enable me to mix and match algorithms in reusable and relatively straightforward way.</p>
[]
[ { "body": "<p>Stop trying to write Ruby like Java. You've got a whole mess of modules to do something fairly simple.</p>\n\n<p>Most (not all) of the Gang of Four patterns are workarounds for lack of flexibility in languages like C++ and Java, and are less necessary in a language like Ruby that has classes that are first-class objects and always extensible.</p>\n\n<p>I'd like to know a bit more about your use case, but it seems to me that you can probably remove a layer or two of indirection.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T22:12:38.533", "Id": "8372", "Score": "1", "body": "This is a very fair comment and really reasonable, thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T21:26:40.573", "Id": "5510", "ParentId": "4930", "Score": "3" } } ]
{ "AcceptedAnswerId": "5510", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T20:17:36.770", "Id": "4930", "Score": "6", "Tags": [ "ruby", "design-patterns" ], "Title": "Is this an appropriate class design for the strategy pattern in Ruby?" }
4930
<p>I have 2 Dictionaries. I am trying to optimize this code to run as fast as possible.</p> <p>This is for solving Shanks Baby Step Giant Step Algorithm<br> Algorithm:<br></p> <pre><code>Given b = a^x (mod p) First choose n, such that n^2 &gt;= p-1 Then create 2 lists: 1. a^j (mod p) for 0 &lt;= j &lt; n 2. b*(a(inverse)^n)^k for 0 &lt;= k &lt; n Finally look for a match between the 2 lists. public static BigInteger modInverse(BigInteger a, BigInteger n) { BigInteger i = n, v = 0, d = 1; while (a &gt; 0) { BigInteger t = i / a, x = a; a = i % x; i = x; x = d; d = v - t * x; v = x; } v %= n; if (v &lt; 0) v = (v + n) % n; return v; } static int Main() { BigInteger r = 92327518017225, rg, temp, two=2, tm, n = ((BigInteger)Math.Sqrt(247457076132467-1))+1, mod = 247457076132467; Dictionary&lt;int, BigInteger&gt; b = new Dictionary&lt;int, BigInteger&gt;(); Dictionary&lt;int, BigInteger&gt; g = new Dictionary&lt;int, BigInteger&gt;(); temp = modInverse(two, mod); temp = BigInteger.ModPow(temp, n, mod); for (int j = 0; (BigInteger)j &lt; n; j++) { rg = r * BigInteger.ModPow(temp, j, mod); g.Add(j, rg); } for (int i = 0; (BigInteger)i &lt; n ; i++) { tm = BigInteger.ModPow(2, i, mod); foreach (KeyValuePair&lt;int, BigInteger&gt; d in g) { if (d.Value.Equals(tm)) { Console.WriteLine("j={0} B*t^j(mod m) = {1}",d.Key,d.Value); Console.WriteLine("a^"+i+" = "+tm); } } b.Add(i,tm); } Console.ReadKey(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-21T10:45:57.477", "Id": "7384", "Score": "0", "body": "I am not all that familiar with this particular algorithm however what is the reason for the BigIntegers? What precision do you need?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-21T10:49:18.787", "Id": "7385", "Score": "0", "body": "More specifically I understand why you may need BigInteger for r, rg, temp, tm however n,i,j I don't believe should be cast to BigInteger so the question is what is the range of n?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-21T22:43:04.847", "Id": "7397", "Score": "1", "body": "Why are you using a Dictionary at all? You are simply storing keys contiguous from 0-n, i.e., you are using a Dictionary as an array." } ]
[ { "body": "<p>One way you can improve the speed of the search is:</p>\n\n<ul>\n<li>For one of the two dictionaries, construct an array of the values. Sort this array. </li>\n<li>To do the search: </li>\n<li>> Go through sequentially through the values of the other dictionary. </li>\n<li>> For each value, perform an Array.BinarySearch() for the value, in the sorted array to see if there is a match.</li>\n</ul>\n\n<p>Due to the binary search, this method will reduce down to O(N log N) instead of your current brute force method which is O(N²)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T00:45:14.050", "Id": "4937", "ParentId": "4932", "Score": "1" } }, { "body": "<p>There are some really obvious optimisations.</p>\n\n<ol>\n<li>Delete all the code relating to <code>b</code>. A dictionary you only insert into is a waste of time, memory, and programmer ability to understand what's going on.</li>\n<li>Use <code>g</code> as a dictionary. The way to do that is to change it from a <code>Dictionary&lt;int, BigInteger&gt;</code> into a <code>Dictionary&lt;BigInteger, int&gt;</code>. Then your <code>foreach</code> can be replaced with a simple <code>TryGetValue</code>.</li>\n<li><p>Ditch the cast of <code>j</code> to BigInteger:</p>\n\n<pre><code>int n_int = ((int)Math.Sqrt(247457076132467-1))+1;\n... \nn = (BigInteger)n_int\n</code></pre>\n\n<p>And compare <code>j</code> to <code>n_int</code>. If it doesn't fit in an int, <code>j</code> shouldn't be an int either.</p></li>\n<li><p>Exploit basic arithmetic properties in loops. E.g. rather than</p>\n\n<pre><code>tm = BigInteger.ModPow(2, i, mod);\n</code></pre>\n\n<p>you should have</p>\n\n<pre><code>tm = 1,\n...\nfor (int i = 0; i &lt; n_int; i++)\n{\n ...\n tm = (tm * 2) % mod;\n}\n</code></pre></li>\n</ol>\n\n<p>PS In fact, if you'd looked at the <a href=\"http://en.wikipedia.org/wiki/Baby-step_giant-step\" rel=\"nofollow\">Wikipedia page</a> on the algorithm you'd have found pseudocode which handles all this already.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T09:17:41.230", "Id": "4944", "ParentId": "4932", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-21T08:16:00.057", "Id": "4932", "Score": "4", "Tags": [ "c#" ], "Title": "Optimizing a c# program that creates 2 dictionaries and searches both for a matching value" }
4932
<p>So after answering a question about <a href="https://codereview.stackexchange.com/questions/4691">nested linked checkboxes</a> I mentioned it at work and surprisingly it turned out to be similar to something we needed.</p> <p>The requirements were:</p> <ol> <li>a "Select all" checkbox </li> <li>a nested "Select all" checkbox (only selects a small portion) </li> <li>Cannot rely upon the hierarchy of the markup. The given fiddle is an example only. <strong>EDIT:-</strong> from Discussions with <a href="https://codereview.stackexchange.com/users/7280">John</a> I now see there was this requirement and so I've added it. </li> </ol> <p>So realising it was different to the <a href="https://codereview.stackexchange.com/questions/4691">aforementioned</a> question I set about writing my own. I aimed for readability and minimal markup.</p> <pre><code>(function($) { $('input[type=checkbox][data-children]').unbind("change childchange childchangebubble").each(function() { var parent = $(this); var linkedChildren = $(parent.data("children")); //trigger a "childChange" event on the parent when any child is triggered. linkedChildren.bind("change childchangebubble", function() { parent.trigger("childchange"); }); parent.bind({ "change": function(event) { // Bind change event to check all children linkedChildren.prop("checked", parent.prop("checked")).trigger("change"); }, "childchange": function() { // have to bind custom event seperately, there seems to be a jQuery bug. // When a child is changed recalculate if parent should be checked var noChildrenUnchecked = !linkedChildren.is(":not(:checked)"); parent.prop("checked", noChildrenUnchecked).trigger("childchangebubble"); } }); }); })(jQuery); </code></pre> <p>the <code>data-children</code> attributes that are rendered to the page look like: <code>data-children="#child2sub1, #child2sub2"</code> on the parent and nothing extra needed on the children.</p> <p>I'd love any feedback on readability/maintainability, performance etc.</p> <p>current <a href="http://jsfiddle.net/tjMCQ/" rel="nofollow noreferrer">jsFiddle</a>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-26T04:52:24.100", "Id": "7475", "Score": "0", "body": "Adding a bounty on this. If you have even a small improvement for me please post it!" } ]
[ { "body": "<p>I have a suggestion. Basically I'm not sure why you are adding so much to the HTML to handle the the parent and child checkboxes. Isn't the hierarchy of the HTML enough to go on? From the HTML you can already determine the parent and child relationships. In additon why trigger more events. Just handle the event as it bubbles up though the DOM. </p>\n\n<p>Below is an example of some code that I believe to be far more reusable and much easier to implement. In addition, I have modified this to work with future checkboxes added to the DOM. It may be necessary to load some of the children via AJAX and/or appending to the DOM therefore your method would require you to bind your function on each append to the DOM, where as mine would handle it though delegation of events.</p>\n\n<pre><code>$.fn.nestedCheckboxes = function (stopPropogation) {\n this.addClass('nestedCheckboxes');\n this.click(nestedCheckboxHandler);\n this.delegate(':has( &gt; input:checkbox)', 'click', nestedCheckboxHandler);\n function nestedCheckboxHandler (evt) {\n if ($(evt.target).is(\"input:checkbox\")) {\n var parentContainer = $(this);\n var checkbox = parentContainer\n .find(' &gt; input:checkbox:eq(0)');\n var parentCheckbox = parentContainer\n .parent()\n .closest(':has( &gt; input:checkbox)')\n .children('input:checkbox');\n\n if (evt.target == checkbox[0]) {\n $('input:checkbox', parentContainer)\n .prop(\"checked\", checkbox.prop(\"checked\"));\n }\n var parentCheckboxValue = !parentCheckbox\n .parent()\n .find(\"input:checkbox\")\n .not(parentCheckbox[0])\n .is(\"input:checkbox:not(:checked)\");\n\n parentCheckbox.prop(\"checked\",parentCheckboxValue);\n } else if (stopPropogation) {\n evt.stopPropagation();\n }\n };\n};\n\n$(function () {\n $('div').nestedCheckboxes(); //this is how you would use the function\n\n $('#addChildren').click(function () {\n $(this).after('&lt;ul&gt;&lt;li&gt;&lt;input type=\"checkbox\" /&gt;&lt;label&gt;Child 2 SubChild 1&lt;/label&gt;&lt;/li&gt;&lt;li&gt;&lt;input type=\"checkbox\" /&gt;&lt;label&gt;Child 2 SubChild2&lt;/label&gt;&lt;/li&gt;&lt;/ul&gt;');\n return false;\n }); \n\n});\n</code></pre>\n\n<p>In addition I have added an option for the nestedCheckboxes to stopPropogation if an element other than a checkbox is clicked. By default this if set to false.</p>\n\n<p>Finally have a look at the fiddle I created and play around. You will see that the HTML Markup is far more simplistic.</p>\n\n<p><a href=\"http://jsfiddle.net/jfhartsock/WwtJr/\" rel=\"nofollow\">http://jsfiddle.net/jfhartsock/WwtJr/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T00:22:19.550", "Id": "7541", "Score": "0", "body": "\" Isn't the hierarchy of the HTML enough to go on?\" Simply: No. The checkboxes are spread across the html as it had to be added to an old form. Some of the checkboxes are in sequential rows of a table and some are not. So the order of the html cannot be relied upon. (and imho I don't think it should.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T00:32:44.403", "Id": "7542", "Score": "0", "body": "One small quibble I would add is the \"add two children button doesn't update/refresh the checkboxes after they add so their parent checkbox might be check when they get added and they won't. In that situation either the parent needs to be unchecked or the children need to be checked. In my code i just added a `.trigger(\"childChange\")` at the end." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T00:35:52.213", "Id": "7543", "Score": "0", "body": "But your binding event would never bind you would have to handle that manually as it does not handle future events. You should consider handling events using `delegate()` instead. But in any case it was just a thought as the html in your example showed you following the hierarchy in html. It my be wise to put \"Some of the checkboxes are in sequential rows of a table and some are not.\" as a specific requirement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T00:41:33.503", "Id": "7544", "Score": "0", "body": "in the spec I should have put the restriction that the layout f the markup cannot be relied on I just assumed it couldn't unless other specified. the `.trigger(\"childChange\")` works because the function is run it will unbind the previously bound events. It could be modified to only bind on the ones it needs but I didn't see it as a need. Can you?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T00:50:55.887", "Id": "7545", "Score": "0", "body": "No I guess not. Just offering a different point of view." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T15:25:05.930", "Id": "5038", "ParentId": "4939", "Score": "1" } }, { "body": "<p>Some small changes:</p>\n\n<ol>\n<li>Change <code>input[type=checkbox]</code> to <code>:checkbox</code>. Won’t do much except\nmake things look cleaner.</li>\n<li>It looks like you are using the data-children value as jQuery\nselectors and using all the id’s. if you want to shorten this you\ncould add a specific css class on them and put that value as the\ndata-children. Your code would still work and the markup would\nprobably be shorter.</li>\n<li>Also you should be careful as your code unbinds “change” which could\nunbind events from other jQuery code and this would probably break\nit.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T02:17:08.970", "Id": "5049", "ParentId": "4939", "Score": "1" } } ]
{ "AcceptedAnswerId": "5049", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T03:40:10.467", "Id": "4939", "Score": "5", "Tags": [ "javascript", "jquery", "html" ], "Title": "Nested \"Select All\" checkboxes" }
4939
<p>I have function which writes data of a specified type to a buffer. Here is the part of this which writes <code>Uint8</code>, <code>Uint16</code>, <code>Uint32</code> and <code>Uint64</code>, in big and little endian. As you can see that the same code is repeated several times, so I want to make this code more elegant.</p> <pre><code>... case BW_DATA_TYPE_UINT8: { Uint8_T val = *(static_cast(Uint8_T*, src)); Uint8ToLittleEndianAr( IN val, OUT_FROM &amp;bw-&gt;buffer[bw-&gt;curPos], OUT_TO &amp;bw-&gt;buffer[bw-&gt;curPos] ); bw-&gt;curPos += length; break; } case BW_DATA_TYPE_UINT16_LE: { Uint16_T val = *(static_cast(Uint16_T*, src)); Uint16ToLittleEndianAr( IN val, OUT_FROM &amp;bw-&gt;buffer[bw-&gt;curPos], OUT_TO &amp;bw-&gt;buffer[bw-&gt;curPos] + 1 ); bw-&gt;curPos += length; break; } case BW_DATA_TYPE_UINT32_LE: { Uint32_T val = *(static_cast(Uint32_T*, src)); Uint32ToLittleEndianAr( IN val, OUT_FROM &amp;bw-&gt;buffer[bw-&gt;curPos], OUT_TO &amp;bw-&gt;buffer[bw-&gt;curPos] + 3 ); bw-&gt;curPos += length; break; } case BW_DATA_TYPE_UINT64_LE: { Uint64_T val = *(static_cast(Uint64_T*, src)); Uint64ToLittleEndianAr( IN val, OUT_FROM &amp;bw-&gt;buffer[bw-&gt;curPos], OUT_TO &amp;bw-&gt;buffer[bw-&gt;curPos] + 7 ); bw-&gt;curPos += length; break; } case BW_DATA_TYPE_UINT16_BE: { Uint16_T val = *(static_cast(Uint16_T*, src)); Uint16ToBigEndianAr( IN val, OUT_FROM &amp;bw-&gt;buffer[bw-&gt;curPos], OUT_TO &amp;bw-&gt;buffer[bw-&gt;curPos] + 1 ); bw-&gt;curPos += length; break; } case BW_DATA_TYPE_UINT32_BE: { Uint32_T val = *(static_cast(Uint32_T*, src)); Uint32ToBigEndianAr( IN val, OUT_FROM &amp;bw-&gt;buffer[bw-&gt;curPos], OUT_TO &amp;bw-&gt;buffer[bw-&gt;curPos] + 3 ); bw-&gt;curPos += length; break; } case BW_DATA_TYPE_UINT64_BE: { Uint64_T val = *(static_cast(Uint64_T*, src)); Uint64ToBigEndianAr( IN val, OUT_FROM &amp;bw-&gt;buffer[bw-&gt;curPos], OUT_TO &amp;bw-&gt;buffer[bw-&gt;curPos] + 7 ); bw-&gt;curPos += length; break; } ... </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T14:18:52.173", "Id": "7404", "Score": "2", "body": "This is C++ code not C. RTTI casts are only available in C++." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T22:06:22.800", "Id": "7412", "Score": "0", "body": "@Lundin: `static_cast`s aren't available in C -- but they don't use RTTI. RTTI would only get involved if you used `dynamic_cast`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T14:23:29.423", "Id": "7419", "Score": "0", "body": "@Lundin: It is not C++ static_cast<>, it is macros which I defined by my own, to use instead of old style type conversations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T11:16:59.017", "Id": "7516", "Score": "0", "body": "@akmal Ah I see. This would be the main reason why it is a bad idea to redefine C++ reserved keywords in C code: it confuses programmers who work with both languages :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T13:14:43.593", "Id": "7752", "Score": "0", "body": "@Lundin, why you think that it is a bad idea, it is better than old style conversation, and similar to new style(c++ style) conversation, so programmer who mainly works in C++ can easily understand that it is type conversation. Can you please give me the better way of doing this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T11:03:59.923", "Id": "7816", "Score": "1", "body": "@akmal If you implement something from C++ you better make sure that it works _exactly_ in the same way. In this case you _can't_ achieve it, since there is no way to enforce C to get as strong typing as C++. A conventional \"old style\" cast would therefore have been better, because then you aren't tricking anyone, including yourself, that you have suddenly achieved strong typing in C. Try to motivate your own statement: why exactly would this C macro be better than \"old style\"? You can't. Also, it confuses the reader, as we can I see I thought this was C++ myself." } ]
[ { "body": "<pre><code>#define CONVERT(T, F, v) T val = *(static_cast(T*, src)); \\\n F( IN val, OUT_FROM &amp;bw-&gt;buffer[bw-&gt;curPos], OUT_TO &amp;bw-&gt;buffer[bw-&gt;curPos] + v ); \\\n bw-&gt;curPos += length;\n\n [...]\n\n case BW_DATA_TYPE_UINT8:\n {\n CONVERT(Uint8_T, Uint8ToLittleEndianAr, 0)\n break;\n }\n\n case BW_DATA_TYPE_UINT16_LE:\n {\n CONVERT(Uint16_T, Uint16ToLittleEndianAr, 1)\n break;\n }\n\n case BW_DATA_TYPE_UINT32_LE:\n {\n CONVERT(Uint32_T, Uint32ToLittleEndianAr, 3)\n break;\n }\n\n case BW_DATA_TYPE_UINT64_LE:\n {\n CONVERT(Uint64_T, Uint64ToLittleEndianAr, 7)\n break;\n }\n\n case BW_DATA_TYPE_UINT16_BE:\n {\n CONVERT(Uint16_T, Uint16ToBigEndianAr, 1)\n break;\n }\n</code></pre>\n\n<p>(untested!)<br>\nYou can go beyond that and even generate the whole case, but this version is a compromise to keep readability.<br>\n[EDIT] I missed the bottom of your code, but I suppose you can complete yourself... :-)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T14:16:18.993", "Id": "7403", "Score": "8", "body": "Function-like macros are usually a very bad idea. I think this made the code _less_ readable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T21:10:56.963", "Id": "7409", "Score": "0", "body": "@Lundin, I'm not sure its less readable, but an inline function would be better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T00:28:05.487", "Id": "7413", "Score": "0", "body": "@Winston Ewert: I would go with less readable. Not strictly because it is in the source but because you can't read it from the debugger it is totally opaque from that point of view. Not to mention all the other problems associated with using function macros." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T08:26:32.250", "Id": "4943", "ParentId": "4941", "Score": "4" } }, { "body": "<p>First of all, I don't think there is anything wrong with the original code. It is clear what it does and the compiler is competent enough to optimize things that are repeated in every case statement.</p>\n\n<p>But if you really must distill this switch into something that only contains the differences between the case statements you can do like this:</p>\n\n<pre><code>// typedef a function pointer, change \"type\" with the appropriate types for the function.\ntypedef void(*ToLittleEndianType)(type in, type out_from, type out_to);\n\nUint8_T val;\nUint8_T offset;\nToLittleEndianType ToLittleEndianAr;\n\n\ncase BW_DATA_TYPE_UINT8:\n{\n val = *(static_cast(Uint8_T*, src));\n offset = 0;\n ToLittleEndianAr = Uint8ToLittleEndianAr;\n break;\n}\n\ncase BW_DATA_TYPE_UINT16_LE:\n{\n val = *(static_cast(Uint16_T*, src));\n offset = 1;\n ToLittleEndianAr = Uint16ToLittleEndianAr;\n break;\n}\n\ncase BW_DATA_TYPE_UINT32_LE:\n{\n val = *(static_cast(Uint32_T*, src));\n offset = 3;\n ToLittleEndianAr = Uint32ToLittleEndianAr;\n break;\n}\n\ncase BW_DATA_TYPE_UINT64_LE:\n{\n val = *(static_cast(Uint64_T*, src));\n offset = 7;\n ToLittleEndianAr = Uint64ToLittleEndianAr;\n break;\n}\n\n\ncase BW_DATA_TYPE_UINT16_BE:\n{\n val = *(static_cast(Uint16_T*, src));\n offset = 1;\n ToLittleEndianAr = Uint16ToBigEndianAr;\n break;\n}\n\ncase BW_DATA_TYPE_UINT32_BE:\n{\n val = *(static_cast(Uint32_T*, src));\n offset = 3;\n ToLittleEndianAr = Uint32ToBigEndianAr;\n break;\n}\n\ncase BW_DATA_TYPE_UINT64_BE:\n{\n val = *(static_cast(Uint64_T*, src));\n offset = 7;\n ToLittleEndianAr = Uint64ToBigEndianAr;\n break;\n}\n\nToLittleEndianAr(IN val, OUT_FROM &amp;bw-&gt;buffer[bw-&gt;curPos], OUT_TO &amp;bw-&gt;buffer[bw-&gt;curPos] + offset);\nbw-&gt;curPos += length;\n</code></pre>\n\n<p>NOTE: This code is type safe, unlike macros.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T10:46:13.570", "Id": "7415", "Score": "0", "body": "Will this even work? type in will be different for each function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T14:21:14.697", "Id": "7418", "Score": "0", "body": "I have no idea what the code is supposed to do, so that's difficult to say. Function pointers can only be used if the functions have the very same parameters. Which in turn means that the functions may or may not need void pointers. It is a C solution, in C++ you could perhaps consider using templates or \"functors\" instead." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T14:30:28.620", "Id": "4946", "ParentId": "4941", "Score": "2" } } ]
{ "AcceptedAnswerId": "4943", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T04:29:57.953", "Id": "4941", "Score": "7", "Tags": [ "c", "integer" ], "Title": "Writing data of a certain integer type to a buffer" }
4941
<p>The whole idea behind this ,is the user enters : 1. hg commit -m "NO-TIK" and is able to submit the changeset 2. hg commit -m "NO-REVIEW" also does the same as # 1 3. hg commit -m "JIRA-123 blah blah" is also submitted as long as there is a valid issue "JIRA-123" otherwise the commit is reverted with the message "%s does not exist"%ticket 4. hg commit -m "plain english without ANY of the above, reverts the changes , so the above 3 rules MUST be observed.</p> <pre><code> #!/usr/bin/env python import re, os, sys, jira, subprocess from optparse import OptionParser import warnings from collections import namedtuple def verify_commit_text(tags): for line in tags: if re.match(r'[^\NO-TIK]',line): sys.exit(1) elif re.match(r'[^\NO-REVIEW]', line): sys.exit(1) elif re.match(r'[a-zA-Z]+-\d+', line): # Validate the JIRA ID m = re.search("([a-zA-Z]+-\d+)",line) m_args = m.group(1) m_args = [m_args] if CheckForJiraIssueRecord(m_args): sys.exit(1) else: print >> sys.stderr, ("%s does not exist"%m_args) else: sys.exit(0) def CheckForJiraIssueRecord(my_args): # turn off stdout #sys.stdout = open(os.devnull) #sys.stderr = open(os.devnull) com = jira.Commands() logger = jira.setupLogging() jira_env = {'home':os.environ['HOME']} command_name = "cat" server = "http://jira.server.com:8080/rpc/soap/jirasoapservice-v2?wsdl" options = namedtuple('Options', 'user password')('user','password') jira.soap = jira.Client(server) jira.start_login(options, jira_env, command_name, com, logger) issue = com.run(command_name, logger, jira_env, my_args) if issue: return True if __name__ == '__main__': commit_text_verified = verify_commit_text(os.popen('hg tip --template "{desc}"')) if commit_text_verified: sys.exit(0) else: print >> sys.stderr, ('[obey the rules!]') sys.exit(1) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T18:36:07.833", "Id": "7406", "Score": "0", "body": "i know using sys.exit(1) is reverse of what should be used, but that is the only way , this works" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T19:30:39.887", "Id": "7407", "Score": "0", "body": "Does this code work? Or you asking for help fixing something?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T20:48:24.457", "Id": "7408", "Score": "0", "body": "this code works, but i had to reverse the logic to make it work, like \n if re.match(r'[^\\NO-TIK]',line):\n sys.exit(1)\nbut in Python sys.exit(0) is success, etc\nand the function CheckForJiraIssueRecord \nreturning True if issue, not sure of this is correct way, just wanted some one who has python experience to comment on my code, even though i know it sucks, but at least i would learn, how else would i know? right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T03:13:58.163", "Id": "7414", "Score": "1", "body": "This code does not, in any sense, work. `verify_commit_text` simply stops running with weird OS status codes all over the place. This is not a good code review question. This is a better StackOverflow question." } ]
[ { "body": "<p>You seem confused about <code>sys.exit</code> is doing. It exits your program. You function verify_commit_text never exits. Your code after calling verify_commit_text is never executed. The program always hits a sys.exit in verify_commit_text and terminates. The first thing you need to do is eliminate all the sys.exit() except in the <code>__main__</code> section. You should really only have sys.exit in there.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T21:22:49.327", "Id": "7410", "Score": "0", "body": "Thanks, i really appreciate it, one more question:\nWhat is the best way to call CheckForJiraIssueRecord(my_args):\nfrom within verify_commit_text(tags):\nsince that is the code that makes a soap call and seturns a WSDL, and then verifies if \"my_args\" which seem to be a list is indeed a valid ticket number or not: These are the sample tags that get returned:\nKey: JIRA-65\nSummary: Summary of the issue (the most recent versions) are installed on the server\nReporter: reporter\nAssignee: user\nDescription: None\nEnvironment: None\nProject: ABC\nVotes: 0\nType: Task\nStatus: Open" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T21:47:31.490", "Id": "7411", "Score": "0", "body": "@kamal, the best way to call that function is to call that function... I'm not sure what exactly your concern there is. If you remove all the sys.exit() and posted the new version of your code as an edit on your question, I'll review it again for anything that can be improved. Sys.exit is just such a big thing that it needs to be fixed before I can point out any small things." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T21:05:11.387", "Id": "4948", "ParentId": "4947", "Score": "2" } } ]
{ "AcceptedAnswerId": "4948", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T18:27:05.563", "Id": "4947", "Score": "0", "Tags": [ "python" ], "Title": "The logic for re.match() , sys.exit(1) does not make sense, plus why can't i use return True if the re.match regex matches" }
4947
<p>I am actually pretty excited about this approach, but for sanity's sake I wanted to hear some thoughts on others on my strategy here. My basic goal is to parse a YAML file and recursively create module constants using <code>eval</code>. The core business logic is here:</p> <pre><code># # configure application based on an easily-managed .yml file -- use 'eval' # to generate constants based on the structure of the hash we get from the yaml. # most of the business logic for recursively parsing a hash and creating module # constants basically just involves tracking module names properly. # def parse_and_recursively_create_constants!(hash, module_context = []) hash.each do |key, value| if value.is_a? Hash module_name = convert_string_to_camel_case(key) context = module_context.dup &lt;&lt; module_name parse_and_recursively_create_constants! hash[key], context else value_is_a_module = false if value.is_a? String if value.include? "::" value_is_a_module = true else value = "\"#{value}\"" end end if value_is_a_module # explicitly build out this module (since it doesn't exist) so that we can talk about it expression = value.split('::').map { |module_name| "module #{module_name}; "}.join(' ') value.split('::').count.times { expression &lt;&lt; "end; "} eval(expression, $__global_scope) end # define the given constant depth = module_context.count expr = module_context.map { |module_name| "module #{module_name}; " }.join(" ") expr &lt;&lt; "#{key.upcase} = #{value}; " depth.times { expr &lt;&lt; "end; "} expr = "module #{@project_name}; #{expr}; end" eval(expr, $__global_scope) end end </code></pre> <p>Note I am having to bind the default scope to a global <code>$__global_scope</code> which occurs just before the class definition containing this method. I was wondering if there were some cleaner way of handling that, but either way the behavior certainly is what I want it to be. Here's an example configuration file:</p> <pre><code>key: value numeric_data: 3.221 sample_module: some_key: another value key_should_be_module: I::Am::A::Module </code></pre> <p>And the associated test case:</p> <pre><code>configure! "Sample", "spec/resources/sample.yml" Sample::KEY.should == 'value' Sample::NUMERIC_DATA.should == 3.221 Sample::SampleModule::SOME_KEY.should == 'another value' Sample::KEY_SHOULD_BE_MODULE.should be_a_kind_of(Module) Sample::KEY_SHOULD_BE_MODULE.should == I::Am::A::Module </code></pre> <p><strong><a href="https://rubygems.org/gems/rconfigurator" rel="nofollow">I have released this as a gem</a></strong>, and if you'd like more context the full source is on Github <a href="https://github.com/jweissman1986/RConfigurator" rel="nofollow">here</a>. </p>
[]
[ { "body": "<p>You use eval, but <a href=\"https://stackoverflow.com/questions/2571401/why-exactly-is-eval-evil\">eval is evil</a>.</p>\n\n<p>I tried a solution without eval. For this I used:</p>\n\n<ul>\n<li><code>Module.const_set</code> to define constants</li>\n<li><code>Module.const_defined</code> to check if a constant is defined</li>\n<li><code>Module.const_get</code> to navigate inside modules</li>\n<li><code>Module.new</code> to define new modules.</li>\n</ul>\n\n<p>My solution (including a little test):</p>\n\n<pre><code>def def_constants!(hash, context)\n\n #context should be a module. If not, then get (or build) it.\n if context.is_a? String \n lcontext = Object\n context.split('::').each{ |module_name| \n lcontext.const_set(module_name, Module.new) unless lcontext.const_defined?(module_name)\n lcontext = lcontext.const_get(module_name)\n }\n context = lcontext\n end\n\n raise ArgumentError unless context.is_a?(Module)\n\n hash.each do |key, value|\n case value\n when Hash\n module_name = key.upcase #fixme -- convert_string_to_camel_case(key)\n def_constants!( hash[key], [context.name, module_name].join('::'))\n when /::/ # explicitly build out this module (since it doesn't exist) so that we can talk about it\n context.const_set(key.upcase, Module.new)\n lmod = context.const_get(key.upcase)\n value.split('::').each{ |module_name| \n lmod = lmod.const_set(module_name, Module.new )\n }\n else\n # define the given constant\n context.const_set(key.upcase, value)\n end\n end #hash\nend\n\nmodule AA #define a start\nend\n\nrequire 'yaml'\ndef_constants!(YAML.load(DATA), AA)\np AA.constants\np AA::KEY\np AA::SAMPLE_MODULE::SOME_KEY\np AA::KEY_SHOULD_BE_MODULE\np AA::KEY_SHOULD_BE_MODULE::I\np AA::KEY_SHOULD_BE_MODULE::I.constants\np AA::KEY_SHOULD_BE_MODULE::I::Am\np AA::KEY_SHOULD_BE_MODULE::I::Am::A\np AA::KEY_SHOULD_BE_MODULE::I::Am::A::Module\n\n\n__END__\nkey: value\nnumeric_data: 3.221\nsample_module:\n some_key: another value\nkey_should_be_module: I::Am::A::Module\n</code></pre>\n\n<p>I haven't tested it for each usecase. I expect problems, when you try to define modules, where you have already constants with the same name.</p>\n\n<p>Some changes, to use it in your code:</p>\n\n<ul>\n<li>I skipped convert_string_to_camel_case(key) and replaced it with <code>upcase</code></li>\n<li>Your <code>@project_name</code> is my initial <code>context</code>.</li>\n<li>(and sure: I renamed the method ;-) )</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-14T22:36:24.230", "Id": "6045", "ParentId": "4949", "Score": "2" } } ]
{ "AcceptedAnswerId": "6045", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T23:21:14.707", "Id": "4949", "Score": "0", "Tags": [ "ruby" ], "Title": "What if any design issues are there in this method of loading configuration data from YAML in Ruby?" }
4949
<p>This code is from a flex app and is the PHP to determine if a user has read a section of text and answered a question correctly.</p> <p>I write to a table that is similar to a bookmark, and then update the users points. This code works, but since I am making two calls to the database I am worried that it is too "expensive". I tried a few things like using a subquery (maybe I just don't know the syntax). I am using this for now, but I just want to do as well as I can.</p> <pre><code>public function createReadSectionAndPnts($userId, $item){ $stmt = mysqli_prepare($this-&gt;connection, "INSERT INTO readSection ( user_id, chapter_id, section_letter, section_id, sub_section ) VALUES (?, ?, ?, ?, ?)"); $this-&gt;throwExceptionOnError(); mysqli_bind_param($stmt, 'iisss', $userId, $item-&gt;chapter_id, $item-&gt;section_letter, $item-&gt;section_id, $item-&gt;sub_section); $this-&gt;throwExceptionOnError(); mysqli_stmt_execute($stmt); $this-&gt;throwExceptionOnError(); $autoid = mysqli_stmt_insert_id($stmt); mysqli_stmt_free_result($stmt); $stmt2 = mysqli_prepare($this-&gt;connection, "UPDATE users SET total_points = (5 + total_points) WHERE id =?"); $this-&gt;throwExceptionOnError(); mysqli_bind_param($stmt2, 'i', $userId); $this-&gt;throwExceptionOnError(); mysqli_stmt_execute($stmt2); $this-&gt;throwExceptionOnError(); mysqli_stmt_free_result($stmt2); mysqli_close($this-&gt;connection); return $autoid; } </code></pre>
[]
[ { "body": "<p>Sorry. You need to use two statement since you are updating two different tables.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-26T23:12:31.627", "Id": "7486", "Score": "0", "body": "Thanks for the reply. I really appreciate your time. I have to say I am disappointed that there is not a better way to do this. I guess I will just stick with what I have. Thanks again." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-24T10:46:50.603", "Id": "4995", "ParentId": "4950", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T00:27:12.887", "Id": "4950", "Score": "2", "Tags": [ "php", "mysqli" ], "Title": "Evaluating text section answer accuracy" }
4950
<p>In SQL Server, there is two tables: Houses, and their images.</p> <p>I need a list with 20 houses with the first of their images (only one). I tried:</p> <pre><code>SELECT top 20 h.id, h.name, im.id, im.name FROM image im INNER JOIN house h ON im.house_id = h.id WHERE 1=1 AND im.id=(SELECT TOP (1) im2.id FROM image im2 WHERE im.id=im2.id ORDER BY image_code) </code></pre> <p>but that runs very slowly. There is any way to improve this query?</p> <p>EDIT:</p> <p>With the query:</p> <pre><code>SELECT h.id, h.name, im.id, im.name -- What you want to select FROM _house h, _image im -- Tables in join WHERE h.id = im.id_house -- The join (equivalent to inner join) GROUP BY h.id -- This compresses all entries with the -- same h.id into a single row HAVING im.id = min(im.id) -- This is how we select across a group -- (thus compressing the image table per house) </code></pre> <p>I'm getting a error message:</p> <p><em>_image.id' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause.</em></p> <p>Then, I change to:</p> <pre><code>SELECT h.id, h.name, im.id, im.name -- What you want to select FROM _house h, _image im -- Tables in join WHERE h.id = im.house_id -- The join (equivalent to inner join) GROUP BY h.id,im.id, h.name, im.name -- This compresses all entries with the -- same h.id into a single row HAVING im.id = min(im.id) </code></pre> <p>And then I get this result:</p> <p><img src="https://i.stack.imgur.com/8BzRA.png" alt="enter image description here"></p> <p>How can I take out the repeated values?</p> <p>EDIT2: </p> <p>If somebody want to test the queries, this is the script to create the tables and the data that I'm using now (the real data is about 1Million rows):</p> <pre><code>CREATE TABLE _house( [id] [int] NOT NULL, [name] [varchar](50) NULL ) CREATE TABLE _image( [id] [int] NULL, [name] [varchar](50) NULL, [house_id] [int] NULL ) insert into _house (id, name) values (1,'house1'); insert into _house (id, name) values (2,'house2'); insert into _image (id, name, house_id) values (31,'img1',1); insert into _image (id, name, house_id) values (32,'img2',2); insert into _image (id, name, house_id) values (33,'img3',2); insert into _image (id, name, house_id) values (34,'img4',2); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-25T14:29:04.990", "Id": "9765", "Score": "0", "body": "In SQL Server 2005 or newer version you could use [ranking functions](http://msdn.microsoft.com/en-us/library/ms189798.aspx \"Ranking Functions (Transact-SQL)\") to fetch top N rows per match." } ]
[ { "body": "<p>You should be using the clause <code>group by</code></p>\n\n<pre><code>SELECT h.id, h.name, im.id, im.name -- What you want to select\nFROM house h,image im -- Tables in join\nWHERE h.id = im.house_id -- The join (equivalent to inner join)\n\nGROUP BY h.id -- This compresses all entries with the\n -- same h.id into a single row \nHAVING min(im.id) -- This is how we select across a group\n -- (thus compressing the image table per house)\n\nLIMIT 20; -- Selecting the first n values is very\n -- DB specific on mysql use the limit clause\n -- But I see in your DB it is `top 20`\n</code></pre>\n\n<p>Note:</p>\n\n<p>Accosding to this page: <a href=\"http://developer.mimer.com/validator/parser200x/index.tml#parser\" rel=\"noreferrer\">http://developer.mimer.com/validator/parser200x/index.tml#parser</a></p>\n\n<p>The having clause is more standard when specified like this (though I can't test this).</p>\n\n<pre><code>HAVING im.id = min(im.id)\n</code></pre>\n\n<h3>Edit (Based on question Edit).</h3>\n\n<p>Your problem is this line:</p>\n\n<pre><code>GROUP BY h.id, im.id, h.name, im.name \n</code></pre>\n\n<p>This means for every line that is unique across all four values will be compressed together (ie if all four values are the same the lines are compressed together). You need to maintain the original <code>GROUP BY</code> clause (and fix another part of the query).</p>\n\n<pre><code>GROUP BY h.id\n</code></pre>\n\n<p>I can't test this as I only have MySQL available and you seem to be using an MS product (and my original query worked on MySQL). But based on the error message:</p>\n\n<blockquote>\n <p>*_image.id' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause.*</p>\n</blockquote>\n\n<p>We don't want to add anything to the <code>GROUP BY</code> clause. Thus following the error message indicates we need to use aggregate functions (in the select probably).</p>\n\n<p>Try changing the select:</p>\n\n<pre><code>SELECT h.id, h.name, min(im.id), im.name \n ^^^^^^^^^^\n</code></pre>\n\n<p>I am sure if you play around with this you should be able to get it working. Sorry I can not be more exact but that would require using the same product as you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-25T00:25:03.040", "Id": "7465", "Score": "0", "body": "Your use of the having and limit clauses are not valid in SQL Server 2008 (and so presumably also not valid in earlier versions). You might need to join onto a sub-select that does the grouping instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-25T05:02:37.693", "Id": "7466", "Score": "0", "body": "I can accept that the LIMIT is not valid SQL (its an extension). The `HAVING` clause is standard SQL though different implementations I have seen have different aggregation functions (though I have not see one that did not support min()). A quick check here http://developer.mimer.com/validator/parser200x/index.tml#parser indicates a minor error." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-25T06:11:16.813", "Id": "7467", "Score": "0", "body": "My issue was not with the existance of the having clause, but with it having a non-boolean expression. I did try `im.id = min(im.id)` before commenting but, in SQL Server, the having clause expects all referenced fields to appear in an aggregating function or in the group by clause. Pitty, something like this would be very useful :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-26T12:50:24.860", "Id": "7481", "Score": "0", "body": "It doesn't work, the problem is that with the new query, I get repeat values:" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-26T18:21:58.843", "Id": "7485", "Score": "0", "body": "@user674887: You are going to have to be more specific. Are you getting more than 1 row for each h.id? If so then I would look at your table data to make sure that it is unique (ie do you have a key with spaces in it)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T07:40:12.047", "Id": "7492", "Score": "0", "body": "@Tux-D You're right. I've added more information at the question to become more clear. Thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T10:54:26.273", "Id": "7678", "Score": "0", "body": "@Tux-D It doesn't work, but I upvoted because I've learned for the explanations. Thanks" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-24T10:42:28.407", "Id": "4994", "ParentId": "4952", "Score": "7" } }, { "body": "<p>I don't know if there is a faster way, but I would use sub-queries. For example:</p>\n\n<pre><code>select top 20 h.id, h.name, im.mid, i.name\nfrom _house h\njoin\n(\nselect min(id) as mid,house_id from _image\ngroup by house_id\n) im on im.house_id=h.id\njoin _image i on i.id=im.mid\n</code></pre>\n\n<p>Depending on the context it might be faster to generate a temporary table with just one image per house.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T15:16:36.747", "Id": "5017", "ParentId": "4952", "Score": "6" } }, { "body": "<p><code>GROUP BY x</code> collapses all the rows with the same value of <code>x</code> into one row. Your query <code>FROM _house h, _image im ... GROUP BY h.id</code> is not right because it does not say what to do with <code>_image</code>.</p>\n\n<p><code>FROM _house h, _image im ... GROUP BY h.id, im.id, h.name, im.name</code> is not what you want because that keeps every possible combination of h.id, im.id, h.name, and im.name; but you do not want all possible <code>im</code> rows, only the rows where <code>im.id</code> is the minimum value.</p>\n\n<p>You want to collapse all rows of <code>_image</code> with the same <code>house_id</code>, or <code>GROUP BY house_id</code>. Then for each of these rows you want the minimum <code>id</code>:</p>\n\n<pre><code>SELECT house_id, Min(id) FROM _image GROUP BY house_id\n</code></pre>\n\n<p>That gives you the minimum <code>_image.id</code> for each <code>house_id</code>. Now if you want to find the <code>_house.name</code> that has this minimum id, you have to join the <code>house_id</code> against <code>_house.id</code>. You could put the previous query into a temporary table and join against that, but I believe SQL Server allows joining against a subselect:</p>\n\n<pre><code>SELECT h.id, h.name, mi.minImageId\nFROM _house h\n JOIN (SELECT house_id, Min(id) AS minImageId\n FROM _image GROUP BY house_id) mi ON mi.house_id = h.id\n</code></pre>\n\n<p>I gave <code>Min(id)</code> a name because we are going to need it later. You want to find <code>name</code> of the <code>_image</code> row with the minimum <code>id</code> for each row in your <code>GROUP BY</code> subselect. You do not want to put that in your <code>GROUP BY</code> subselect because that will, again, include every possible <code>name</code>. You only want the <code>name</code> of the <code>_image</code> row with the minimum Id, which we now know and have named <code>minImageId</code>. Joining the subselect against that should give you what you want:</p>\n\n<pre><code>SELECT h.id, h.name, mi.minImageId, i.name\nFROM _house h\n JOIN (SELECT house_id, Min(id) AS minImageId\n FROM _image GROUP BY house_id) mi ON mi.house_id = h.id\n JOIN _image i ON i.id = mi.minImageId\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T10:56:00.793", "Id": "7679", "Score": "0", "body": "The last query doesn't work, but I upvoted because the explanations were very interesting. Thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T17:56:57.057", "Id": "7691", "Score": "0", "body": "@user674887, it would help if you told me what \"doesn't work\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T06:27:49.933", "Id": "7735", "Score": "0", "body": "You're right. The problem is the colon of the second line: \"FROM _house h,\" that causes \"Incorrect syntax near the keyword 'join'.\". When I leaved, I get the same perfomance as the accepted answer. Thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-25T14:22:06.850", "Id": "9764", "Score": "0", "body": "There's a redundant comma in your last code snippet, the one after `_house h`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-18T00:33:18.890", "Id": "12533", "Score": "0", "body": "Thanks guys. Now that I've fixed it, I see it is exactly the same as what @Mike had already posted..." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T00:03:25.583", "Id": "5073", "ParentId": "4952", "Score": "2" } } ]
{ "AcceptedAnswerId": "5017", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T12:10:54.440", "Id": "4952", "Score": "3", "Tags": [ "performance", "sql", "sql-server", "join" ], "Title": "Inner join with first result" }
4952
<p>I'm playing around with PHP, trying to write a small ORM. Having worked with Magento quite a bit lately, I've fallen in love with the automagic getters/setters that Magento, I think, inherited from Zend. </p> <p>For those, who've never seen it in action, this is what I'm talking about:</p> <blockquote> <pre><code>$my_object-&gt;setSomeProperty('foo'); </code></pre> </blockquote> <p>just works, as does:</p> <blockquote> <pre><code>$my_object-&gt;getSomeProperty(); </code></pre> </blockquote> <p>which obviously yields "foo".</p> <p>Since I'm trying to implement an ORM, my goal is to provide the user with the ability to use generic functions on one hand, where:</p> <blockquote> <pre><code>$orm_object-&gt;setSomeProperty('foo'): </code></pre> </blockquote> <p>would map to:</p> <blockquote> <pre><code>$orm_object-&gt;set('some_property', 'foo') // set() would obviously be a generic part of the ORM </code></pre> </blockquote> <p>by convention.</p> <p>On the other hand, if the user wanted to handle some situations differently, he could do so by defining a more specifically named function.</p> <blockquote> <pre><code>class foo extends ORM { function setSome($arg_1, $arg_2) { … } } </code></pre> </blockquote> <p>The above example call</p> <blockquote> <pre><code>$orm_object-&gt;setSomeProperty('foo') </code></pre> </blockquote> <p>would now be mapped to</p> <blockquote> <pre><code>$orm_object-&gt;setSome('property', 'foo') </code></pre> </blockquote> <p>instead of the default <code>set()</code>.</p> <p>Do you have any feedback on my implementation?</p> <pre><code>function __call($name, $arguments) { if(preg_match('/([a-z]+)/', $name, $matches)) { $action = $matches[0]; if(preg_match_all('/([A-Z]+)([^A-Z]+)/', $name, $matches)) { $matches = $matches[0]; array_unshift(&amp;$matches, $action); for ($i = count($matches); $i &gt; 0; $i--) { $potential_func_name = implode('', array_slice($matches, 0, $i)); if (method_exists($this, $potential_func_name)) { $arguments_rest = array_slice($matches, $i); break; // found matching function! } } // handle number of arguments now! $reflector = new ReflectionClass($this); $num_expected_params = count($reflector-&gt;getMethod($potential_func_name)-&gt;getParameters()); $num_expected_params = $num_expected_params - count($arguments); $params = array(); for ($i = $num_expected_params; $i &gt; 1; $i--) { $params[] = strtolower(array_shift($arguments_rest)); } $last_var = ''; $i = 0; foreach($arguments_rest as $part) { $last_var .= strtolower($part); $i++; if ($i != count($arguments_rest)) $last_var .= '_'; } $params[] = $last_var; if (count($arguments) == 1) { $arguments = array_shift(&amp;$arguments); } $params[] = $arguments; return(call_user_func_array(array($this, $potential_func_name), $params)); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T10:39:54.750", "Id": "28462", "Score": "0", "body": "There are probably a lot of reasons I'm unaware of as a frontend guy to use this code, but I'm wondering why you would use this instead of existing PHP magic overloading? See http://php.net/language.oop5.overloading.php" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T14:39:56.843", "Id": "4953", "Score": "2", "Tags": [ "php", "algorithm", "reflection" ], "Title": "ORM with magic getters/setters" }
4953
<p>I'm using some slow-ish emit() methods in Python (2.7) logging (email, http POST, etc.) and having them done synchronously in the calling thread is delaying web requests. I put together this function to take an existing handler and make it asynchronous, but I'm new to python and want to make sure my assumptions about object scope are correct. Here's the code:</p> <pre><code>def patchAsyncEmit(handler): base_emit = handler.emit queue = Queue.Queue() def loop(): while True: record = queue.get(True) # blocks try : base_emit(record) except: # not much you can do when your logger is broken print sys.exc_info() thread = threading.Thread(target=loop) thread.daemon = True thread.start() def asyncEmit(record): queue.put(record) handler.emit = asyncEmit return handler </code></pre> <p>That let's me create an asynchronous LogHandler using code like:</p> <pre><code>handler = patchAsyncEmit(logging.handlers.HttpHandler(...)) </code></pre> <p>I've confirmed the messages are sent, and not in the calling thread, but I want to make sure I'm getting only one queue and only one thread per Handler, and that I'm not at risk of those somehow going out of scope.</p> <p>Am I off base or did I get that okay?</p>
[]
[ { "body": "<p>It would seem to me that writing a class would be better:</p>\n\n<pre><code>class AsyncHandler(threading.Thread):\n def __init__(self, handler):\n self._handler = handler\n self._queue = Queue.Queue()\n\n self.daemon = True\n self.start()\n\n def run(self):\n while True:\n record = self._queue.get(True)\n self._handler.emit(record)\n\n def emit(self, record):\n self._queue.put(record)\n</code></pre>\n\n<p>Patching objects can be useful, but its usually clearer to create another object like this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T16:09:12.830", "Id": "7422", "Score": "0", "body": "A decorator like that (the pattern not the @pythonthing) is the route I wanted to go, but the LogHandler creation, at least when using the dictionary schema http://docs.python.org/library/logging.config.html#configuration-dictionary-schema ), doesn't allow for passing a handler into a handler's constructor -- only literals. So I couldn't think of a way to make that work using dict config (which I recognize I didn't mention in the question), but if there is a way I'd welcome it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T16:36:39.773", "Id": "7423", "Score": "0", "body": "@Ry4an, ah. Actually, I believe you can pass objects using the cfg:// syntax." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T16:49:45.510", "Id": "7424", "Score": "0", "body": "oh, wow, I hadn't previously seen that at all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T04:53:47.487", "Id": "7488", "Score": "0", "body": "A LogHandler has a few other important methods (configuration, etc.) would all of those have to be written into the AsyncHander to delegate correctly to the `_handler`? Is there an easy way to pull in all of `_handler`'s method except the one we want to override?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T12:47:58.423", "Id": "7496", "Score": "0", "body": "@Ry4an, in that case I'd probably want to subclass the handler of interest." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T16:05:15.467", "Id": "7502", "Score": "0", "body": "But if I want an asynchronous wrapper for the python standard HTTPLogHandler, SocketHandler, and SMTPHandler do I need to put the async code in a subclass of each of them? I did end up subclassing them but then had the __init__ method of each subclass call my original `patchAsychEmit` with `self` as an argument. I see python provides BufferingHandler and MemoryHandler which are decorators w/ a target of the sort you did, so that's probably the right way even if it does mean wrapping some extra methods. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T16:18:02.437", "Id": "7503", "Score": "0", "body": "@Ry4an, with a little multiple inheritance you should be able to avoid putting the async code in multiple classes or doing the patching. Whether thats better then the extra method wrapping is hard to say. You could also overload __getattr__, but that quickly gets messy so I can't recommend it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T17:54:27.117", "Id": "7506", "Score": "0", "body": "Yeah, I tried pulling all the attributes of the \"target\" into the client automatically and that quickly went past the depth of my meager python knowledge. I'll stick with the patch for now, but it makes sense that a class is the way to go and multiple inheritance is the way to do it. In Scala I'd be using a trait, which is multiple inheritance without the horror. Thanks a ton." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T15:57:03.223", "Id": "4958", "ParentId": "4954", "Score": "2" } } ]
{ "AcceptedAnswerId": "4958", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T15:11:58.413", "Id": "4954", "Score": "2", "Tags": [ "python", "multithreading", "thread-safety", "asynchronous", "python-2.x" ], "Title": "Is this a safe/correct way to make a python LogHandler asynchronous?" }
4954
<p>The purpose of this function is to report processing progress to the terminal. It loops through an array of maps that contain two properties: <code>:sequence</code> and <code>:function</code>. Within each <code>sequence-function-map,</code> it will loop through the sequence, and run the function on each item in the sequence.</p> <p>This is my first Clojure program that will be used in a production environment. This particular function does the job, but I suspect that it's not very lispy.</p> <pre><code>(defn run-with-reporting [sequence-function-maps stop-time] (def beginning-time (java.util.Date.)) (let [seq-counts (map #(count (:sequence %)) sequence-function-maps)] (def total-sequence-counts (reduce + seq-counts))) (println (str "total counts = " total-sequence-counts)) (def prog-rpt-ref (ref {:todo total-sequence-counts, :done 0, :total-time-taken 0})) (doseq [sequence-function-map sequence-function-maps] (let [sequence (:sequence sequence-function-map), function (:function sequence-function-map)] (loop [loop-seq sequence] (if (and stop-time (clj-time/after? (clj-time/now) stop-time)) (println "stopped at " (clj-time/now) ". Requested stop at " stop-time) (if loop-seq (do (def item (first loop-seq)) (def start-time (java.util.Date.)) (function item) (def end-time (java.util.Date.)) (def time-delta (- (.getTime end-time) (.getTime start-time))) (let [derefd-rpt (deref prog-rpt-ref)] (dosync (alter prog-rpt-ref assoc :done (inc (:done derefd-rpt)), :total-time-taken (+ (:total-time-taken derefd-rpt) time-delta)))) (let [derefd-rpt (deref prog-rpt-ref)] (let [average-time (/ (:total-time-taken derefd-rpt) (:done derefd-rpt))] (println "Avg time / each = " (hrs-min-sec average-time) ", Estimated total time left = " (hrs-min-sec (* average-time (- (:todo derefd-rpt) (:done derefd-rpt))))))) (recur (next loop-seq)))))))) (let [derefd-rpt (deref prog-rpt-ref)] (println "Total time taken = " (hrs-min-sec (- (.getTime (java.util.Date.)) (.getTime beginning-time))) ", Done = " (:done derefd-rpt) "/" (:todo derefd-rpt)))) </code></pre> <p>Here's a testing function</p> <pre><code>(defn test-run-w-reporting [stop-clj-time] (def testing-func (fn [item] (. java.lang.Thread sleep (rand 1000)))) (let [sequence-function-maps [{:sequence (range 30), :function testing-func}, {:sequence (range 15), :function testing-func}]] (run-with-reporting sequence-function-maps stop-clj-time))) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-16T11:52:21.870", "Id": "12448", "Score": "1", "body": "I would probably break this up into more managable chunks." } ]
[ { "body": "<p>I will point out stuff that I'd do differently, though I am by no means a clojure expert, I do have some experience in it. Numbered items will reappear inside the code as comments.</p>\n\n<ol>\n<li>no DEF inside defn body\n<ul>\n<li>def will define the var for your entire namespace as such, you will pollude your namespace with temporaries</li>\n<li>use LET instead</li>\n</ul></li>\n<li>no DO necessary inside the body of IF\n<ul>\n<li>furthermore, I find it more idiomatic to use WHEN in the case that no else branch exists</li>\n</ul></li>\n<li>using @ instead of DEREF could reduce verbosity</li>\n<li>by using UPDATE-IN instead of INC, you can simply pass a transformation function\n<ul>\n<li>note the vector notation however: UPDATE-IN takes a vector of keywords</li>\n</ul></li>\n<li>You can pass a partial function, i.e. a function which is\npartially applied as the transformation function to update the total-time-taken</li>\n<li>No need to nest LETs, you can write all definitions into a single let</li>\n</ol>\n\n<p>Code:</p>\n\n<pre><code>(defn run-with-reporting [sequence-function-maps stop-time]\n (let [beginning-time (java.util.Date.) ;; 1.\n seq-counts (map #(count (:sequence %)) sequence-function-maps)\n total-sequence-counts (reduce + seq-counts)\n prog-rpt-ref (ref {:todo total-sequence-counts, :done 0, :total-time-taken 0})]\n (println (str \"total counts = \" total-sequence-counts))\n (doseq [sequence-function-map sequence-function-maps]\n (let [sequence (:sequence sequence-function-map),\n function (:function sequence-function-map)]\n (loop [loop-seq sequence]\n (if (and stop-time (clj-time/after? (clj-time/now) stop-time))\n (println \"stopped at \" (clj-time/now) \". Requested stop at \" stop-time)\n (when loop-seq ;; 2.\n (let [item (first loop-seq)\n start-time (java.util.Date.)]\n (function item)\n (let [end-time (java.util.Date.)\n time-delta (- (.getTime end-time) (.getTime start-time))\n derefd-rpt @prog-rpt-ref] ;; 3.\n (dosync (alter prog-rpt-ref update-in ;; 4.\n [:done] inc,\n [:total-time-taken] (partial + time-delta))) ;; 5.\n (let [derefd-rpt @prog-rpt-ref ;; 3. &amp; 6.\n average-time (/ (:total-time-taken derefd-rpt) (:done derefd-rpt))]\n (println \"Avg time / each = \" (hrs-min-sec average-time)\n \", Estimated total time left = \"\n (hrs-min-sec (* average-time (- (:todo derefd-rpt) (:done derefd-rpt)))))))\n (recur (next loop-seq))))))))\n (let [derefd-rpt (deref prog-rpt-ref)]\n (println \"Total time taken = \" (hrs-min-sec (- (.getTime (java.util.Date.)) (.getTime beginning-time))) \", Done = \" (:done derefd-rpt) \"/\" (:todo derefd-rpt))))\n )\n</code></pre>\n\n<ol>\n<li><p>I would try to reduce verbosity and increase readability (in the\nliterate sense) by utilising descriptive helper functions -\ncurrent-time instead of (.getTime (java.util.Date.))</p></li>\n<li><p>Personally I like to keep the amount of variables as low as\npossible. Variables are great for producing side-effects,\ndescribing complex results or for when you need a result several\ntimes. In the case of the ref, writing @ instead of using a\ntemporary seems more natural to me.</p>\n\n<p>As such:</p>\n\n<ul>\n<li>I would try to reduce the amount of side-effects and</li>\n<li>use descriptive functions to calculate complex results and place them where they belong\nwithout temporary variables</li>\n</ul></li>\n<li>You can use destructring for maps\n<ul>\n<li>(let [{:keys [key1 key2]} mymap] ...) will let-bind key1 and key2 by extracting :key1 &amp; :key2 from mymap</li>\n</ul></li>\n</ol>\n\n<p>Code:</p>\n\n<pre><code>(defn current-time\n \"Return the current time. Same as (.getTime (java.util.Date.)).\"\n []\n (.getTime (java.util.Date.)))\n\n(defn run-with-reporting [sequence-function-maps stop-time]\n (let [beginning-time (current-time) ;; 1.\n seq-counts (map #(count (:sequence %)) sequence-function-maps)\n total-sequence-counts (reduce + seq-counts)\n prog-rpt-ref (ref {:todo total-sequence-counts, :done 0, :total-time-taken 0})]\n (println (str \"total counts = \" total-sequence-counts))\n (doseq [sequence-function-map sequence-function-maps]\n (let [{:keys [sequence function]} sequence-function-map] ;; 9.\n (loop [loop-seq sequence]\n (if (and stop-time (clj-time/after? (clj-time/now) stop-time))\n (println \"stopped at \" (clj-time/now) \". Requested stop at \" stop-time)\n (when loop-seq ;; 2.\n (let [item (first loop-seq)\n start-time (current-time)] ;; 7.\n (function item)\n (dosync (alter prog-rpt-ref update-in ;; 4.\n [:done] inc,\n [:total-time-taken] (partial + (- (current-time) start-time)))) ;; 5., 7. &amp; 8.\n (let [average-time (/ (:total-time-taken @prog-rpt-ref) (:done @prog-rpt-ref))] ;; 8.\n (println \"Avg time / each = \" (hrs-min-sec average-time)\n \", Estimated total time left = \"\n (hrs-min-sec (* average-time (- (:todo @prog-rpt-ref) (:done @prog-rpt-ref)))))) ;; 8.\n (recur (next loop-seq))))))))\n (println \"Total time taken = \" (hrs-min-sec (- (current-time) beginning-time))\n \", Done = \" (:done @prog-rpt-ref)\n \"/\" (:todo @prog-rpt-ref))))\n</code></pre>\n\n<p>Now, lets take a look at the function itself. In general, when\nwriting in clojure you should try to keep your functions generic\nand simple. By keeping them simple and focusing on only a single\ntask, they are usually easier to compose and reuse.\nI would thus recommend splitting up your function.</p>\n\n<p>In your case what you want to do is really:</p>\n\n<ol>\n<li>map a function over a sequence: clojure already provides a function for that, namely MAP.</li>\n<li>stop the mapping operation if a specified time has been reached.</li>\n<li>print out the average time per call</li>\n<li>print out total time taken</li>\n</ol>\n\n<p>The first point is trivial.</p>\n\n<p>For the second point, we can exploit the fact that clojure has lazy\nsequences. This allows us to use the built-in TAKE-WHILE function\nwith a predicate which checks the time and stops when it has passed\nyour stop-time:</p>\n\n<pre><code>(defn take-until\n \"Returns a lazy seq of items from coll util the STOP-TIME has been reached.\"\n [stop-time coll]\n (take-while\n (fn [item]\n (if (not (&gt; (current-time) stop-time))\n true\n (do (println \"stopped at \" (current-time) \". Requested stop at \" stop-time)\n false)))\n coll))\n</code></pre>\n\n<p>The third point can be achieved by simply mapping over a collection\nand printing out the necessary information. This again is really\njust what you did, but refactored into a function that works on any\nsequence:</p>\n\n<pre><code>(defn measure-coll-retrieval\n \"Returns a lazy seq of items from coll. Will print to stdout the\n average time between element extractions.\"\n ;; you can use destructuring inside the argument list as well, here\n ;; we're additionaly specifying some defaults for when the caller\n ;; does not provide a value\n [coll &amp; {:keys [start-count total-count] :or {start-count 0 total-count nil}}]\n (let [beginning-time (current-time)]\n (map-indexed\n (fn [index item]\n (let [index (+ start-count index 1)\n average-time (/ (- (current-time) beginning-time) index)]\n (print \"Avg time / each = \" (hrs-min-sec average-time))\n (if total-count\n (println \", Estimated total time left = \"\n (hrs-min-sec (* average-time (- total-count index))))\n (println))\n item))\n coll)))\n</code></pre>\n\n<p>Before writing the reporting function, a little helper so we can\nget around seq-chunking in clojure:</p>\n\n<pre><code>(defn unchunk\n \"takes a chunked sequence and turns it into an unchunked sequence\"\n [s]\n (lazy-seq\n (when-let [[x] (seq s)]\n (cons x (unchunk (rest s))))))\n</code></pre>\n\n<p>Now we can write the actual reporting function:</p>\n\n<pre><code>(defn run-with-reporting [sequence-function-maps stop-time]\n (let [beginning-time (current-time) ;; 1.\n seq-counts (map (comp count :sequence) sequence-function-maps)\n total-sequence-counts (reduce + seq-counts)\n intermed-count (atom 0)]\n (println (str \"total counts = \" total-sequence-counts))\n ;; note how it is possible to immediately destructure the map\n (doseq [{:keys [sequence function]} sequence-function-maps]\n (swap! intermed-count\n +\n (count\n ;; this is where everything happens: apply function,\n ;; take-until stop-time reached &amp; measure average time\n (measure-coll-retrieval\n (take-until stop-time (map function (unchunk sequence)))\n :start-count @intermed-count\n :total-count total-sequence-counts))))\n (println \"Total time taken = \" (hrs-min-sec (- (current-time) beginning-time))\n \", Done = \" @intermed-count\n \"/\" total-sequence-counts)))\n\n(defn test-run-w-reporting [stop-clj-time]\n (def testing-func (fn [item] (. java.lang.Thread sleep (rand 1000))))\n (let [sequence-function-maps [{:sequence (range 30), :function testing-func},\n {:sequence (range 15), :function testing-func}]]\n (run-with-reporting sequence-function-maps stop-clj-time)))\n</code></pre>\n\n<p>I hope this has helped you some.</p>\n\n<p>Kind regards,\nThomas</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-18T19:50:57.553", "Id": "7936", "ParentId": "4956", "Score": "5" } } ]
{ "AcceptedAnswerId": "7936", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T15:42:10.223", "Id": "4956", "Score": "4", "Tags": [ "beginner", "clojure", "lisp" ], "Title": "A crude clojure progress reporting function" }
4956
<p>Since Python's ConfigParser does not throw an exception if the file does not exist, is it fine to do it this way:</p> <pre><code>try: config = ConfigParser.RawConfigParser() if config.read('/home/me/file.conf') != []: pass else: raise IOError('Cannot open configuration file') except IOError, error: sys.exit(error) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-04T09:27:49.427", "Id": "376987", "Score": "0", "body": "Won't that also throw if the file exists, but is empty?" } ]
[ { "body": "<ol>\n<li>you should try to put as little as possible inside the try block</li>\n<li>There isn't a whole lot of point to throwing an exception just to catch it on the next line.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T18:29:21.073", "Id": "4962", "ParentId": "4957", "Score": "2" } } ]
{ "AcceptedAnswerId": "4962", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T15:55:52.227", "Id": "4957", "Score": "-1", "Tags": [ "python" ], "Title": "ConfigParser inexisting file exception" }
4957
<p>Simple really my javascript function for checking my form.</p> <pre><code>var errors = {}; errors.email = true; errors.cemail = true; errors.password = true; errors.cpassword = true; errors.username = true; function joinAjax (id) { var val = $('#' + id).val(); if (id == 'email') { $('#emailMsg').hide(); var reg = /[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/; if (val == '') { $('#' + id).after('&lt;div id="emailMsg" class="error"&gt;Enter your email&lt;/div&gt;'); } else if (reg.test(val) == false) { $('#' + id).after('&lt;div id="emailMsg" class="error"&gt;Email invalid&lt;/div&gt;'); } else { errors.email = false; $('#' + id).after('&lt;div id="emailMsg" class="success"&gt;Email OK&lt;/div&gt;'); } joinAjax('cemail'); } if (id == 'cemail') { $('#cemailMsg').hide(); var email = $('#email').val(); if (errors.email == false) { if (val != email) { $('#' + id).after('&lt;div id="cemailMsg" class="error"&gt;Emails do not match&lt;/div&gt;'); } else { errors.cemail = false; $('#' + id).after('&lt;div id="cemailMsg" class="success"&gt;Success&lt;/div&gt;'); } } else { $('#cemail').val(''); } } if (id == 'password') { $('#passwordMsg').hide(); if (val == '') { $('#' + id).after('&lt;div id="passwordMsg" class="error"&gt;Enter a password&lt;/div&gt;'); } else if (val.length &lt; 6) { $('#' + id).after('&lt;div id="passwordMsg" class="error"&gt;Minimum length of 6&lt;/div&gt;'); } else { errors.password = false; $('#' + id).after('&lt;div id="passwordMsg" class="success"&gt;Password OK&lt;/div&gt;'); } joinAjax('cpassword'); } if (id == 'cpassword') { $('#cpasswordMsg').hide(); var password = $('#password').val(); if (errors.password == false) { if (val != password) { $('#' + id).after('&lt;div id="cpasswordMsg" class="error"&gt;Passwords do not match&lt;/div&gt;'); } else { errors.cpassword = false; $('#' + id).after('&lt;div id="cpasswordMsg" class="success"&gt;Success&lt;/div&gt;'); } } else { $('#cpassword').val(''); } } if (id == 'username') { $('#usernameMsg').hide(); if (val == '') { $('#' + id).after('&lt;div id="usernameMsg" class="error"&gt;Enter a username&lt;/div&gt;'); } else if (val.length &lt; 3) { $('#' + id).after('&lt;div id="usernameMsg" class="error"&gt;Minimum length is 3&lt;/div&gt;'); } else { errors.username = false; $('#' + id).after('&lt;div id="usernameMsg" class="success"&gt;Available&lt;/div&gt;'); } } $('#joinForm').submit(function(event){ if ((errors.email == true) || (errors.cemail == true) || (errors.password == true) || (errors.cpassword == true) || (errors.username == true)) { event.preventDefault(); } return true; }); } </code></pre> <p>Can this be improved? I was looking for a way to create a function for the submit event, but I can't figure it how as I don't know how many parameters I will need each time.</p>
[]
[ { "body": "<p>Some tips:</p>\n\n<ul>\n<li>you'd probably better have a look at some <a href=\"http://docs.jquery.com/Plugins/validation\" rel=\"nofollow\">jquery validation plugin</a> that would do what you are looking for <em>out of the box</em></li>\n<li>to solve your \"unknown parameters\", you could probably use the <a href=\"http://api.jquery.com/serialize/\" rel=\"nofollow\">jquery .serialize() function</a> and loop through the array</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-26T06:38:05.217", "Id": "5000", "ParentId": "4959", "Score": "3" } }, { "body": "<p>I see a few references to $('#' + id), it may be easier to maintain and also save some memory usage if you declare a variable and set it to that value.</p>\n\n<pre><code>var form_id = $('#' + id);\n</code></pre>\n\n<p>Then anywhere you reference $('#' + id), just put in form_id.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-26T13:25:19.730", "Id": "5003", "ParentId": "4959", "Score": "3" } }, { "body": "<p>A few things I'll recommend:</p>\n\n<p>Turn lines 1 - 7 into an object literal, it makes the intent a bit clearer.</p>\n\n<pre><code>var errors = {\n email : true,\n cemail : true,\n password : true,\n cpassword : true,\n username : true\n};\n</code></pre>\n\n<p>Use the non type-coersion comparison operators === and != instead of == when evaluating false and numeric values.</p>\n\n<p>So change line 33 to:</p>\n\n<pre><code>if (errors.email === false) {\n</code></pre>\n\n<p>Encapsulate your error checking into separate functions, one example would be something like:</p>\n\n<pre><code>if (id == 'cemail') {\n checkEmail();\n}\n\nfunction checkEmail(){\n\n $('#cemailMsg').hide();\n\n var email = $('#email').val();\n\n if (errors.email === false) {\n\n if (val != email) {\n\n $('#' + id).after('&lt;div id=\"cemailMsg\" class=\"error\"&gt;Emails do not match&lt;/div&gt;');\n }\n else {\n\n errors.cemail = false;\n $('#' + id).after('&lt;div id=\"cemailMsg\" class=\"success\"&gt;Success&lt;/div&gt;');\n }\n }\n else {\n\n $('#cemail').val('');\n }\n}\n</code></pre>\n\n<p>Then once you get to that level of encapsulation and granularity you can start to add out functions for adding your error messages so you aren't duplicating that code. Off the top of my head something like:</p>\n\n<pre><code>if (val != email) {\n\n addError(id,'&lt;div id=\"cemailMsg\" class=\"error\"&gt;Emails do not match&lt;/div&gt;');\n }\n\nfunction addError(divId,error){\n $('#' + divId).after(error);\n}\n</code></pre>\n\n<p>This way if you change how you handle errors you can do it in one place. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T11:50:37.157", "Id": "5079", "ParentId": "4959", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T16:03:25.777", "Id": "4959", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "My form error javascript code" }
4959
<p>I'm trying to isolate a webservice in its own class, and I plan to add separate classes to each webmethod there is in the webservice. What I have so far works, but I have this feeling tickling that I've missed something (except for the invisible variable declarations down here, I didn't want to clog the page).</p> <p>Webservice instantiation class and its fault handler:</p> <pre><code> public class CfdWS { [Bindable] private var model:ModelLocator = ModelLocator.getInstance(); public function loadWebService():WebService{ var webService : WebService = new WebService(); webService.wsdl = model.configXML.cfdwsWSDL; webService.addEventListener(FaultEvent.FAULT, onWebServiceFault); webService.loadWSDL(); return webService; } private function onWebServiceFault(event:FaultEvent):void{ var fault: Fault = event.fault; var message:String = "\ncodigo: " + fault.faultCode; message += "\nDetalle: " + fault.faultDetail; Alert.show("Error de webservice:" + message); } } } </code></pre> <p>The following is my webservice method call class. I have written only what I think is the essential code for the question.</p> <pre><code>public class GeneratePDF extends CfdWS{ public function generatePDF():void{ webService = loadWebService(); webService.addEventListener(LoadEvent.LOAD, doGeneratePDF); } private function doGeneratePDF(event:LoadEvent):void{ webService.generatePDF.addEventListener(ResultEvent.RESULT, generatePDFResultHandler); webService.generatePDF(pdfData); } private function generatePDFResultHandler (event:ResultEvent):void{ // After getting what I want, I remove the event listeners here. } } </code></pre> <p>I'm trying to re-write an application that is already in production while on testing phase (testing for the next version I mean).</p>
[]
[ { "body": "<p>I don't see why would you put every method of the service in a separate class. A \"method\" is a function of the class. I imagine you wanted to decouple your code, but doing it this way you will force a lot of overhead:</p>\n\n<ul>\n<li>the service is instantiated for every 'method' called, and then, hopefully, garbage collected (as you remove event listeners and there's no more references to the service left)</li>\n<li>because of above, the service is stateless; with time you may want to add some functionality like caching, but you'd need to change whole code structure for that</li>\n<li>CfdWS - not descriptive name; your way of decoupling code will force you to make three or even five times more classes then you normally would, so I would expect a hell on the file-naming level</li>\n<li>really, dividing to so many classes is not a good idea - you don't want to switch between files all the time; try to put related code in one Class, and if it grows big, create some helper classes</li>\n</ul>\n\n<p>I think you already understand the benefit of a good MVC implementation, try Robotlegs, it really makes a life easier:\n<a href=\"http://www.robotlegs.org/\">http://www.robotlegs.org/</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-15T07:35:11.547", "Id": "15642", "ParentId": "4960", "Score": "5" } } ]
{ "AcceptedAnswerId": "15642", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T16:38:31.527", "Id": "4960", "Score": "5", "Tags": [ "actionscript-3" ], "Title": "Actionscript web service and web method call classes" }
4960
<p>Can you suggest how I might make the following code more efficient:</p> <pre><code>from collections import Counter a = [1,1,3,3,1,3,2,1,4,1,6,6] c = Counter(a) length = len(set(c.values())) normalisedValueCount = {} previousCount = 0 i = 0 for key in sorted(c, reverse=True): count = c[key] if not previousCount == count: i = i+1 previousCount = count normalisedValueCount[key] = i/length print(normalisedValueCount) </code></pre> <p>It basically gives a dictionary similar to counter, but instead of counting the number of occurrences, it contains a weighting based on the number of occurrences.</p> <ul> <li>The number 1 is associated with 1.0 (<code>4/length</code>) because it occurs the most often.</li> <li>2 and 4 occur the least often and are associated with the value <code>1/length</code>.</li> <li>6 is the second least occurring value and is associated with <code>2/length</code>.</li> <li>3 is the third least occurring value and is associated with <code>3/length</code>. </li> </ul> <p>Some more examples: </p> <ul> <li>The list <code>a[1,2,3]</code> results in a <code>normalisedValueCount</code> of 1:1.0, 2:1.0, 3:1.0.</li> <li>The list <code>a[2,1,2]</code> results in a <code>normalisedValueCount</code> of 2:1.0, 1:0.5.</li> <li>The list <code>a[2,1,2,3]</code> results in a <code>normalisedValueCount</code> of 2:1.0, 1:0.5, 3:0.5.</li> <li>The list <code>a[2,2,2,2,2,2,2,2,2,2,1,2,3,3]</code> results in a <code>normalisedValueCount</code> of 2:1.0, 3:0.66666, 1:0.33333.</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-25T19:28:27.850", "Id": "7472", "Score": "0", "body": "Your most recent edit changed the contents of the last list but didn't update the `normaizedValueCount`s. Are those the results you would be expecting?" } ]
[ { "body": "<p>I have no idea what you code is doing, it doesn't look like any normalization I've seen. I'd offer a more specific suggestion on restructuring if I understood what you are doing.</p>\n\n<p>You:</p>\n\n<ol>\n<li>Put a in a counter</li>\n<li>Put that counter's values into a set</li>\n<li>sort the keys of the counter</li>\n</ol>\n\n<p>I'd look for another approach that doesn't involve so much moving around.</p>\n\n<pre><code>if not previousCount == count:\n</code></pre>\n\n<p>better as</p>\n\n<pre><code>if previousCount != count:\n</code></pre>\n\n<p><strong>EDIT</strong></p>\n\n<ol>\n<li>Counter.most_common returns what you are fetching using sorted(c, reverse=True)</li>\n<li>itertools.groupby allows you group together common elements nicely (such as the same count)</li>\n<li>enumerate can be used to count over the elements in a list rather then keeping track of the counter</li>\n</ol>\n\n<p>My code: </p>\n\n<pre><code>c = Counter(a)\nlength = len(set(c.values()))\ncounter_groups = itertools.groupby(c.most_common(), key = lambda x: x[1]))\nnormalisedValueCount = {}\nfor i, (group_key, items) in enumerate(counter_groups)\n for key, count in items:\n normalisedValueCount[key] = (i+1)/length\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T19:55:16.200", "Id": "7510", "Score": "0", "body": "Shouldn't it be?- counter_groups = itertools.groupby(reversed(combinationsCount.most_common()), key = lambda x: x[1])" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T21:41:07.760", "Id": "7512", "Score": "0", "body": "@Baz, I may be wrong, but I don't think so. `most_common` returns the elements from the most common to the least common. Of course your the best judge of whether that is what you wanted." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T18:50:30.747", "Id": "7528", "Score": "0", "body": "Yes, but if the items are sorted from most to least common then the __for loop__ section will start with the most common number when i = 0. This will result in the most common values being associated with the smaller __normalisedValueCounts__ ((i+1)/length), which is the opposite of what we want. Thanks again!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T19:59:21.350", "Id": "7532", "Score": "0", "body": "@Baz, okay, I guess I misread the original code. Your welcome." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T22:12:45.327", "Id": "4975", "ParentId": "4963", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T20:13:25.657", "Id": "4963", "Score": "3", "Tags": [ "python", "optimization", "python-3.x", "collections" ], "Title": "Collections.Counter in Python3" }
4963
<p>I have all large file of all the order sold in one week. This file gives one line for every order. We have over 5000 orders a day. It read the file line by line and then adds the sale to a database of sales. to I really need to boost performance.</p> <pre><code> static void sold4weeks1() { string sold, asin; string[] lines = System.IO.File.ReadAllLines(@"C:\out\qqqqq.txt"); inventoryBLL u = new inventoryBLL(); try { foreach (string line in lines) { char[] tabs = { '\t' }; string[] words = line.Split(tabs); asin = words[12]; sold = words[14]; if (words[0].Substring(0, 3) == "S01") continue; try { if (words[4] == "Shipped" || words[4] == "Unshipped") { u.setSoldin28(asin, Convert.ToInt16(sold)); Console.WriteLine("Update"); } } catch { } } } catch { } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T20:42:37.473", "Id": "7429", "Score": "1", "body": "@joe what is the purpose of this?> if (words[0].Substring(0, 3) == \"S01\") continue;" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T20:43:44.197", "Id": "7430", "Score": "0", "body": "@I__ I was just wondering the same thing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T20:43:49.127", "Id": "7431", "Score": "0", "body": "@I__ S01 is a prefix for destroyed or requestioned order." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T20:44:20.873", "Id": "7432", "Score": "7", "body": "Just a reminder...you should never use try...catch{} and do nothing. Eating exceptions is horrible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T20:51:11.553", "Id": "7433", "Score": "0", "body": "If you can use PLinq, you can parallelize this so that each line is processed on seperate threads. This should give you a nice hefty performance boost (assuming your database can handle it)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T21:06:36.487", "Id": "7434", "Score": "3", "body": "@Coding: That will just introduce unnecessary overheads to this and ultimately make it a lot slower than it has to be. What's being done in the code isn't enough to justify doing that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T14:22:48.197", "Id": "7722", "Score": "0", "body": "Did you try Regular Expressions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T09:56:02.357", "Id": "7723", "Score": "0", "body": "http://xkcd.com/208/ ? Why and where do you think regex is going to be faster? If a plain substring is enough, that will match quicker than a regex." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T08:18:44.510", "Id": "7740", "Score": "0", "body": "Just as an FYI - **NEVER** catch a generic exception and do *nothing*. Either avoid the error which you are expecting by performing some logic or catch the *specific* error you are interested in." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T08:21:52.600", "Id": "7741", "Score": "0", "body": "@HansKesting The Regex may be faster as it will not need to split the entire line into words. It will only need to check as far as it needs to. eg If the first character is not an `S` it can stop..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-29T02:55:14.217", "Id": "16636", "Score": "0", "body": "A text file of 5000 lines is so small that it doesn't matter if you use regular expressions or `String.StartsWith`. They are both fast enough. Clear and simple code matters in this case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T20:47:58.867", "Id": "58713", "Score": "0", "body": "Your code doesn't show the database part -- are you inserting in large chunks or are you adding one record at a time? You also are lacking a baseline: How long does it take now? How do you know this code is the bottle neck?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T20:48:09.793", "Id": "64482", "Score": "0", "body": "1. Remove logging statement.\n2. Remove unneeded try/catch blocks." } ]
[ { "body": "<p>Don't use <code>ReadAllLines</code>, read it line by line, it will boost performance by a lot</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-26T10:19:11.593", "Id": "7477", "Score": "1", "body": "@Dani: as given. However, we know that they have ~5000 lines in it (let's guess 2.4 MB) and.... _there is going to be database insertion/update in the tail of the process_. Mmm. My bet is that the speed loss is in the tail that's not being shown" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T20:41:47.100", "Id": "4966", "ParentId": "4965", "Score": "2" } }, { "body": "<p>Is <code>u.setSoldin28(asin, Convert.ToInt16(sold));</code> writing to the database?</p>\n\n<p>Save up all your changes and make them all under a single connection when the parse is finished. That should save quite a bit of time.</p>\n\n<p>You have alot of other issues with this code though. I strongly urge you to look into proper exception handling techniques.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T23:01:54.337", "Id": "7446", "Score": "4", "body": "This is really the only improvement to be made. This whole task is going to be IO bound, what the CPU does with it is hardly going to matter." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T20:43:23.323", "Id": "4967", "ParentId": "4965", "Score": "8" } }, { "body": "<p>From your above code performance should not be a big issue at all except for the exception handling.\nReading in the file should be relatively fast, especially since its once a day. The processing of that file however I have to assumem is the issue here. Download ANTS profile.\nAre you inserting data in a transaction, etc. There's more here than is visible.\nAs mentioned, try/catch will have a detrimental effect as well (we noticed the same thing in an internal app)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T20:50:02.600", "Id": "4970", "ParentId": "4965", "Score": "1" } }, { "body": "<p>move the char array to outside the loop.</p>\n\n<p>In my experience, using StreamReader is the fastest way to read from a file. </p>\n\n<p>Parallel.For/ForEach that per line loop.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T20:59:53.013", "Id": "4973", "ParentId": "4965", "Score": "2" } }, { "body": "<p>Instead of writing one line of sale to database at a time try the following for boosting performance - </p>\n\n<ul>\n<li>Bulk insert lines into a temp table (create a table with just an\nidentity column and a string column and each line will be inserted\ninto the string column with identity field auto-incremented).</li>\n<li>Write a stored procedure to read the temp table created above,\nparse the line and separate out fields. Insert separated out fields\ninto the main sales table where you want the data to go to.</li>\n<li>Since the SP will run under SQL server itself, rather than having a connection open from programming runtime to SQL it will execute faster. \n<ul>\n<li>You can schedule a job to run during off hours so that other database accesses are not hampered.</li>\n</ul></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T04:33:35.023", "Id": "5029", "ParentId": "4965", "Score": "0" } }, { "body": "<p>I tried to get a clue if there is a performance leak in the posted code or not so i wrote a litte check Consoleapp for your Problem. (Excluding the Update of the Database off course).<br/>\nIt would give me a great pleasure if you would run this \"analysis\" with your code and post us the results.</p>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Diagnostics;\n\nnamespace PerformanceCheck\n{\nclass MainClass\n{\n public static void Main (string[] args) {\n Console.WriteLine (\"Press enter to write file\");\n Console.ReadLine ();\n\n FileStream stream = null;\n TextWriter writer = null;\n try {\n FileInfo info = new FileInfo (\"/tmp/file.txt\");\n if(info.Exists)\n info.Delete();\n\n stream = info.OpenWrite ();\n\n writer = new StreamWriter (stream);\n for (int i = 0; i&lt; 500; i++) {\n writer.WriteLine (\"S01\\tsdf\\tsdf\\tsdf\\tShipped\\tsdf\\tsdf\\tsdf\\tsdf\\tsdf\\tsdf\\tsdf\\tsdf\\tsdf\\t\" + i);\n writer.WriteLine (\"S01\\tsdf\\tsdf\\tsdf\\tUnshipped\\tsdf\\tsdf\\tsdf\\tsdf\\tsdf\\tsdf\\tsdf\\tsdf\\tsdf\\t\" + i);\n writer.WriteLine (\"S02\\tsdf\\tsdf\\tsdf\\tShipped\\tsdf\\tsdf\\tsdf\\tsdf\\tsdf\\tsdf\\tsdf\\tsdf\\tsdf\\t\" + i);\n writer.WriteLine (\"S02\\tsdf\\tsdf\\tsdf\\tUnshipped\\tsdf\\tsdf\\tsdf\\tsdf\\tsdf\\tsdf\\tsdf\\tsdf\\tsdf\\t\" + i);\n }\n\n Console.WriteLine (\"Successfully written file!\"); \n } catch (Exception ex) {\n Console.WriteLine (\"Dude, Exception!\");\n Console.WriteLine (ex.Message);\n Console.WriteLine (\"Press enter to quit;\");\n Console.ReadLine ();\n return;\n } finally {\n if (writer != null)\n writer.Flush ();\n if (stream != null)\n stream.Close ();\n }\n Console.WriteLine (\"Press enter to insert Data into Database\");\n Console.ReadLine ();\n sold4weeks1 ();\n Console.WriteLine (\"Data updated, press enter to quit\");\n Console.ReadLine ();\n }\n\n static void sold4weeks1 () {\n\n Stopwatch watch = new Stopwatch ();\n\n string sold, asin;\n\n watch.Start ();\n string[] lines = System.IO.File.ReadAllLines (\"/tmp/file.txt\");\n\n Console.WriteLine (\"Reading lines took: \" + watch.ElapsedMilliseconds + \"ms\");\n watch.Reset ();\n\n watch.Start ();\n Stopwatch lineReadWatch = new Stopwatch ();\n try {\n foreach (string line in lines) {\n lineReadWatch.Start ();\n\n char[] tabs = { '\\t' };\n string[] words = line.Split (tabs);\n asin = words [12];\n sold = words [14];\n\n if (words [0].Substring (0, 3) == \"S01\")\n continue;\n try {\n if (words [4] == \"Shipped\" || words [4] == \"Unshipped\") {\n\n int i = Convert.ToInt16 (sold);\n Console.WriteLine (\"Update: \"+i);\n }\n } catch {\n } finally {\n lineReadWatch.Stop ();\n lineReadWatch.Reset ();\n Console.WriteLine (\"Handling of line took: \" + lineReadWatch.ElapsedMilliseconds + \"ms\");\n }\n }\n } catch {\n }\n Console.WriteLine (\"Whole routine took: \" + watch.ElapsedMilliseconds + \"ms\");\n watch.Stop ();\n }\n\n}\n}\n</code></pre>\n\n<p><em>Developed and successfully tested on Mono/OSX</em></p>\n\n<p>As far as i can see, yes there are some points where performance can be gained, but i would be intrested, if this is the real bottleneck. As the others before i believe the huge performance gains can be made in the database update code.<br/>\nBut I'm ready to be profen wrong and so I would be verry interested in your performance mesurements!</p>\n\n<p>Output Snippet:</p>\n\n<blockquote>\n <p>Handling of line took: 0ms<br/>\n Update: 499<br/>\n Handling of line took: 0ms<br/>\n Whole routine took: 38ms<br/>\n Data updated, press enter to quit</p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T20:43:25.697", "Id": "5072", "ParentId": "4965", "Score": "0" } }, { "body": "<p>First of all it is critical make performance profiles. I recommend setting up dottrace from <a href=\"http://www.jetbrains.com/profiler/\" rel=\"nofollow\">http://www.jetbrains.com/profiler/</a>. \nUsing this get the baseline numbers. These baseline numbers would be great to prove performance improvement. </p>\n\n<p>It is also critical to write scalable code. Instead of loading all 5000 lines in-memory try using powers of database as suggested by samiksc</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T07:28:47.307", "Id": "5131", "ParentId": "4965", "Score": "0" } }, { "body": "<p>Is it really necessary to boost performance? \nThis is a typical batch job that can run in nighttime for hours without any problem. Just make it rock solid (firstly remove the empty catch block, big mistake). No need for complicated logic or clever tricks.</p>\n\n<p>If it does take unacceptable time to process the data, the bottleneck must be in the inventoryBBL class (or the way you use it). Don't commit changes to database after every single modifications (batch processing). A .NET profiler and a database profiler are also good ideas. How much time do you code spend in .NET code and how much in SQL time compared to processing time?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T14:47:42.193", "Id": "5172", "ParentId": "4965", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T20:39:39.143", "Id": "4965", "Score": "3", "Tags": [ "c#", "performance" ], "Title": "How do I make this function faster?" }
4965
<pre><code>&lt;?php $userinput = $_GET['host']; $e = escapeshellcmd($userinput); $arr = (explode(".",$e)); $num = count($arr); $times = (int)$_GET['times']; $time = (range(1,51)); if (!isset($time[$times])){ $times = 5; } function isValidURL($url){ return preg_match('/(www\.)?(.)*[\.](.)*$/i', $url); } if($num == "2"){ if(isValidURL($e)){ echo"&lt;pre style=\"background:black; color:white;\"&gt;", passthru("ping -n $times $e"),"&lt;/pre&gt;";} else { echo "The URL or IP $e isn't valid &lt;br /&gt;"; } ?&gt; </code></pre> <p>This code is pinging the user requested host. Is this code insecure because I am using the <code>passthru()</code> function?</p> <p>I am using <code>explode</code> to know if it's <code>domain.com</code> or just text and a regular expression to validate its not <code>texttext.text</code>. Is there way for the user to access my terminal with this?</p>
[]
[ { "body": "<p>I would do <code>$times = min( (int)$_GET['times'], 999);</code> where 999 is the maximum number of times.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T22:50:06.153", "Id": "7436", "Score": "0", "body": "that's an idea , but not my point , my point is what breaches are there so i will make a script to avoid that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T23:02:58.190", "Id": "7447", "Score": "0", "body": "That's part of it. Someone might know how to kill `ping` by sending excessively huge numbers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T23:04:06.160", "Id": "7448", "Score": "1", "body": "Also, you should validate the URL before escaping it..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-24T02:55:58.670", "Id": "7457", "Score": "0", "body": "@Christian could you clarify why you'd do what you suggest in your answer? I'm not a PHP expert but just curious. (At any rate you should consider adding these clarifications into your answer.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-24T09:31:24.420", "Id": "7459", "Score": "0", "body": "@Joseph Weissman well what i said is to make the limiter of the times for ping with count() instead of array" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T22:43:30.600", "Id": "4976", "ParentId": "4974", "Score": "2" } }, { "body": "<p>Your regular expression for detecting valid urls is very weak and you can slip a lot past it.</p>\n\n<p>Though you have used escapeshellcmd() to protect yourself a bit from people trying to run alternative commands you have not protected yourself from people sending extra parameters to ping. </p>\n\n<p>Two alternative attacks spring to mind:</p>\n\n<ul>\n<li>You can overload your servers by making them send lots of useless packets in the ping requests.</li>\n<li>You can use your servers as the host for an attack on somebody else.</li>\n</ul>\n\n<p>An example of sending extra bytes with ping (I put your script in the file test.php on myhost (not real name).</p>\n\n<p><a href=\"http://myhost.com/test.php?host=plop.com%20-s%20500\" rel=\"nofollow\">http://myhost.com/test.php?host=plop.com%20-s%20500</a></p>\n\n<p>Generates:</p>\n\n<pre><code>ping -n 0 plop.com -s 500\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-24T10:49:39.737", "Id": "7460", "Score": "0", "body": "well this code isn't effective online anywhere yet , i wanna see all attack / breaches that i have in mind before ill upload it" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-24T10:22:39.760", "Id": "4993", "ParentId": "4974", "Score": "4" } }, { "body": "<p>Should <code>escapeshellarg</code> or <code>escapeshellcmd</code> be used for the host? I've read both of the man pages just now, and they offer conflicting advice. I'm about 99% sure that <code>escapeshellarg</code> should be used with the host though:</p>\n\n<pre><code>$host = shellescapearg(\"google.com\");\nexec(\"ping {$host}\");\n</code></pre>\n\n<p>As Christian Sciberras began saying in his comment:</p>\n\n<p>I would validate the url before escaping it instead of afterwards. I can't imagine that an escaped one would ever pass when a non-escaped one would not; however, when you escape it and then check it, you're not really validating what was inputted, but rather you're validating a processed version of it.</p>\n\n<p>Imagine this scenario: You have user profiles, and they allow users to enter a description of themselves. Now, these may have some HTML entities in them, such as <code>&amp;</code> or <code>&lt;</code>. Now, when you store this, you're going to store the original version. When you display it back to the browser, you will pass it through something like <code>htmlentities()</code>. My point is, when you let the user update their profile, you're going to validate the original version with <code>&amp;</code> instead of <code>&amp;amp;</code>.</p>\n\n<p>Christian's (and my) feelings on the host validation are along those same lines. When you validate user input, you want to validate the actual input, not the processed version.</p>\n\n<p>But also to add something:</p>\n\n<p>You should never assume that array keys exist in the <code>$_GET</code>/<code>$_POST</code>/<code>$_COOKIES</code>, so on arrays (any user-dependent array).</p>\n\n<p>For example:</p>\n\n<pre><code>$userinput = $_GET['host'];\n</code></pre>\n\n<p>If the user just goes to <code>mypage.php</code> without the host param, then PHP will throw a notice when your script tries to access a non-existent array key.</p>\n\n<p>Another case where users can trigger errors messages is something like:\n<code>mypage.php?host[]=blah</code></p>\n\n<p>That means that <code>$_GET['host']</code> is <code>array('blah')</code>. So, when you try to pass that into <code>escapeshellcmd</code> or <code>explode</code>, it will throw an error about expecting a string and getting an array.</p>\n\n<p>What I typically do is something like:</p>\n\n<pre><code>if(isset($_GET['blah']) &amp;&amp; is_string($_GET['blah'])) {\n $blah = $_GET['blah'];\n} else {\n $blah = null;\n}\n</code></pre>\n\n<p>Or, the shorter version I usually use:</p>\n\n<pre><code>$blah = (isset($_GET['blah']) &amp;&amp; is_string($_GET['blah'])) ? $_GET['blah'] : null;\n</code></pre>\n\n<p>Note though that <code>isset()</code> is not the same as <code>array_key_exists</code>, which sometimes makes more sense. Also, you can always use <code>is_string</code> because input arrays will always contain string values, even if the user's input is numeric. (The exception is, if the user inputs an array, it does become an array.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-25T22:33:16.817", "Id": "4999", "ParentId": "4974", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-23T21:38:26.817", "Id": "4974", "Score": "3", "Tags": [ "php", "security", "regex" ], "Title": "Pinging the user requested host - is this code insecure?" }
4974
<p>This is basically my first Ruby class, which is to remove all empty lines and blank times from a .txt file. A simple test case is also included.</p> <p>I tested the code and it works fine. But I did not have much idea about if the code style is good, or if there are some potential issues. Can someone please do a quick review and kindly provide some feedback?</p> <ol> <li><p>Is there any potential issue in the code? did I miss some boundary check?</p></li> <li><p>Is the code style good in general? e.g, name convention, indent, etc.</p></li> <li><p>what can I do if I want to make it more professional? e.g., better choice of functions, error-handling, object-oriented, test-driven, etc.</p></li> </ol> <p></p> <pre><code>require 'test/unit' class BlankLineRemover def initialize() puts "BlankLineRemover initialized." end def generate(input_filename, output_filename) reader = File.read(input_filename) f = File.new(output_filename, "w") f.puts remove(reader) f.close end def remove(stringToremove) regEx = /^[\s]*$\n/ stringToReturn = stringToremove.gsub(regEx, '') stringToReturn.strip! if stringToReturn.length &gt;= 1 return stringToReturn else return "" end end end class TestCleaner &lt; Test::Unit::TestCase def test_basic sInput1 = "line1\n\t\nline4\n\tline5\n" sExpectedOutput1 = "line1\nline4\n\tline5" sInput2="" sExpectedOutput2 = "" sInput3="\n\t\t\n" sExpectedOutput3 = "" testCleaner = BlankLineRemover.new assert_equal(sExpectedOutput1, testCleaner.remove(sInput1)) assert_equal(sExpectedOutput2, testCleaner.remove(sInput2)) assert_equal(sExpectedOutput3, testCleaner.remove(sInput3)) end end unless ARGV.length == 2 puts "Usage: ruby Blanker.rb input.txt output.txt\n" exit end simpleRemover = BlankLineRemover.new simpleRemover.generate(ARGV[0],ARGV[1]) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T04:16:53.640", "Id": "7437", "Score": "0", "body": "On the method `remove` you have an `if/else` that could be re-written as `stringToReturn.length >= 1 ? stringToReturn : \"\"`, but to check that a string has a size bigger than one you're better of with `!stringToReturn.empty?` but then again the only way to fall on that `else` is if `stringToReturn` is an empty string (which is the return value of the else) and therefore you don't need that `if/else` at all and simply let `stringToReturn.strip!` be the return value of that method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T15:55:53.860", "Id": "7439", "Score": "0", "body": "I think, it is not great idea to read full file at once, you may need to read it line by line and populate result file in a go. Also, you can remove \"()\" parameterless method declaration. Usually, only underscores are used in variable and method names in Ruby to separate words instead of camel case." } ]
[ { "body": "<p>I would also remove the following: \\r\\n</p>\n\n<p>Also, this part could be simplified a tad:</p>\n\n<pre><code>if stringToReturn.length &gt;= 1\n return stringToReturn\nelse\n return \"\"\nend\n</code></pre>\n\n<p>to:</p>\n\n<pre><code> stringToReturn.length &gt;= 1 ? stringToReturn : \"\"\n</code></pre>\n\n<p>Once you have the \\r\\n removed, don't forget to test for that. Lastly (just a style issue), I wouldn't use camelcase variables in Ruby as it's not commonly done (that I've seen), so stringToremove could become string_to_remove for instance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T04:29:06.533", "Id": "7440", "Score": "0", "body": "@ James - thx for yr feedback. but which \"following: \\r\\n\" did u mean? can you specify?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T04:36:27.197", "Id": "7441", "Score": "0", "body": "He means the newline `\\r\\n`, check this: http://en.wikipedia.org/wiki/Newline and see how it can vary depending on the OS" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T05:13:49.417", "Id": "7442", "Score": "0", "body": "got it. thx for the clarification. ( i guess you guys know each other:) ).\n\nbesides the string length check and newline, any feedbacks at other aspects like error-handling, object-oriented, testing case, file handling, etc?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T05:17:06.687", "Id": "7443", "Score": "0", "body": "@ Derp/James - I guess I have the completionist mind-set. so forgive me if i am getting overly detail-oriented here. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T13:02:33.380", "Id": "7444", "Score": "0", "body": "I added a little more to my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T14:18:01.347", "Id": "7445", "Score": "0", "body": "thx for the feedback, James. will change the variable naming style to \"string_to_remove\" (and others)." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T04:00:21.840", "Id": "4978", "ParentId": "4977", "Score": "2" } }, { "body": "<p>Here's how I might reformulate your core business logic (warning -- untested -- you should probably consider this pseudocode):</p>\n\n<pre><code>outfile = File.new(outfilename)\nFile.read(infilename) do |line|\n unless line =~ /^[\\s]*$\\n/ # unless all spaces\n outfile.puts(line)\n end\nend\n</code></pre>\n\n<p>I might write the class around this as the 'core' method -- note that one of the keys in a dynamic language is that it's important to keep the level of abstraction of your statements consistent throughout a code 'neighborhood'. In terms of 'Rubyisms' you could demonstrate knowledge of Ruby's mixin capabilities by writing a <code>AbstractFileTransformer</code> that you could <code>extend</code> from, while <code>includ</code>-ing a <em>module</em> <code>BlankLineRemovingCopyTransformation</code> -- it would basically just be refactoring the class you've written into two, and then creating a 'concrete instance' which mixed both together. (Alternatively you could do this with classes and <code>yield</code>.) If you wish I can attempt to provide a pseudocode example here, but at any rate, let's consider your tests for a moment. </p>\n\n<p>Given the apparent simplicity of the functionality, you may certainly be forgiven for writing a barebones test case. I might suggest splitting the test case into several sub-tests which together describe the system. Note there's lots of different kinds of tests you can write besides ones that just demonstrate 'how it works' -- you can also write tests about integrating different pieces of the system together (as opposed to testing each in isolation); you can write tests that involve intentionally giving the system bad input and guaranteeing that it fails, etc. You could have a test which tries to invoke your script as a command-line tool and the validates the behavior is as expected. It's worth trying to write a lot of different kinds of tests for an application.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-24T00:43:54.687", "Id": "4991", "ParentId": "4977", "Score": "0" } }, { "body": "<p>What follows is a <em>fairly harsh</em> critique, but I'm hoping that that's what you're looking for as you seem to want to improve you ruby and programming style. Ruby is a lovely language, but getting to know it takes some time - eventually you'll realise that just about everything you write used to take twice as many lines. So, a few <em>pointers</em>:</p>\n\n<h2>Variables</h2>\n\n<p>Generally in ruby normal variables are underscored. So instead of <code>aVariableName</code> you should probably use <code>a_variable_name</code>. Both will work, but the latter would fit the Ruby style better.</p>\n\n<p>Additionally you choice of variable names seems to go from overly verbose to the opposite. Some are great, but others leave my guessing.</p>\n\n<p>For example where you write:</p>\n\n<pre><code>reader = File.read(input_filename)\n</code></pre>\n\n<p>I would prefer to write:</p>\n\n<pre><code>in_file = File.read(in_filename)\n</code></pre>\n\n<h2>Functions</h2>\n\n<p>Like your variables, the naming of your functions could do with a touch-up. Your functions do not make use of the implicit return that Ruby offers, something that is often considered a better practice.</p>\n\n<p>For example where you write:</p>\n\n<pre><code> def remove(stringToremove)\n\n regEx = /^[\\s]*$\\n/\n\n stringToReturn = stringToremove.gsub(regEx, '')\n stringToReturn.strip!\n\n if stringToReturn.length &gt;= 1\n return stringToReturn\n else\n return \"\"\n end\n end\n</code></pre>\n\n<p>In this regard I might have written:</p>\n\n<pre><code> def remove(stringToremove)\n\n regEx = /^[\\s]*$\\n/\n\n stringToReturn = stringToremove.gsub(regEx, '').strip\n end\n</code></pre>\n\n<p>Also on your <code>initialize</code> function you include brackets in the definitions this is not required, and is discouraged. Additionally you don't need to include a initializer if there's nothing for it to do.</p>\n\n<h2>Rubyness</h2>\n\n<p>Some things you might want to consider further as you do more programming in ruby are:</p>\n\n<ul>\n<li><p>Chaining. For example you can do <code>a_string.gsub(\"some\", \"substitution\").strip.reverse</code> and other such things all in one line and still keep readability high. Obviously there's a point where it's too much, but that's your judgement.</p></li>\n<li><p>Your code formatting is a bit out. In a lot of places you seem to be using extra spaces. For example you class definition is <code>class BlankLineRemover</code> and should really be <code>class BlankLineRemover</code>. You might be using soft-tabs here, and if that's the case - please don't.</p></li>\n<li><p>You spacing is also very generous. Unless you're separating code into particular chunks then you can skip a few newlines.</p></li>\n<li><p>This is a real nit-pick, but generally using <code>.size</code> is considered better than <code>.length</code>.</p></li>\n</ul>\n\n<h1>Rewrite</h1>\n\n<p>Here's your main class rewritten the way I would have gone about it.</p>\n\n<pre><code>class BlankLineRemover\n def run(in_filename, out_filename)\n File.open(out_filename, \"w\") do |out_file|\n out_file.write clean(File.read(in_filename))\n end\n end\n\n def clean(input)\n input.gsub(/^[\\s]*$\\n/, \"\").strip\n end\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T03:56:57.943", "Id": "7597", "Score": "0", "body": "Also, you may want to consider using `File.expand_path()` unless the filenames are known to be full paths. That's caught me more than once." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T04:25:56.387", "Id": "7598", "Score": "0", "body": "Good point, that too." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-26T09:05:14.090", "Id": "5001", "ParentId": "4977", "Score": "6" } } ]
{ "AcceptedAnswerId": "4978", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-22T03:56:09.627", "Id": "4977", "Score": "2", "Tags": [ "beginner", "ruby", "unit-testing", "regex" ], "Title": "Regular Expression to remove blank lines" }
4977
<p>Doing practise questions for a Java exam which have no answers (useful) I have been asked to do the following:</p> <p>Write a class called <code>Person</code> with the following features:</p> <ul> <li>a <code>private int</code> called <code>age</code>;</li> <li>a <code>private String</code> called <code>name</code>;</li> <li>a constructor with a <code>String</code> argument, which initialises <code>name</code> to the received value and <code>age</code> to <code>0</code>;</li> <li>a public method <code>toString(boolean full)</code>. If <code>full</code> is <code>true</code>, then the method returns a string consisting of the person’s name followed by their age in brackets; if <code>full</code> is <code>false</code>, the method returns a string consisting of just the name. For example, a returned string could be <code>Sue (21)</code> or <code>Sue</code>;</li> <li>a public method <code>incrementAge()</code>, which increments age and returns the new age;</li> <li>a public method <code>canVote()</code> which returns <code>true</code> if <code>age</code> is <code>18</code> or more and <code>false</code> otherwise.</li> </ul> <p>My code is as follows can someone point out any errors?</p> <pre><code>public class Person { private int age; private String name; public Person(String st) { name = st; age = 0; } public String toString(boolean full) { if(full == true) { return name + "(" + age + ")"; } else { return name; } } public int incrementAge() { age++; return age; } public boolean canVote() { if(age &gt;= 18) { return true; } else { return false; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-30T14:27:22.420", "Id": "7449", "Score": "0", "body": "I don't see any errors :)" } ]
[ { "body": "<p>That's fine, but I would have written the last method as <code>return (age &gt;= 18);</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-30T14:26:12.013", "Id": "4980", "ParentId": "4979", "Score": "11" } }, { "body": "<p>instead of </p>\n\n<pre><code>if(full == true)\n</code></pre>\n\n<p>use</p>\n\n<pre><code>if (full)\n</code></pre>\n\n<p>and instead of </p>\n\n<pre><code>if(age &gt;= 18)\n{\n return true;\n}\nelse\n{\n return false;\n}\n</code></pre>\n\n<p>use:</p>\n\n<pre><code>return age &gt;= 18\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-30T14:31:38.520", "Id": "7450", "Score": "0", "body": "Thank you both for your answers, just wee small minor things i need to keep an eye on then." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-30T14:26:46.353", "Id": "4981", "ParentId": "4979", "Score": "14" } }, { "body": "<pre><code> return name + \"(\" + age + \")\";\n</code></pre>\n\n<p>to</p>\n\n<pre><code>return name + \" (\" + age + \")\";\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-30T14:28:29.370", "Id": "4982", "ParentId": "4979", "Score": "14" } }, { "body": "<p>Looks fine, only canVote is maybe a bit clumsy:</p>\n\n<pre><code> public boolean canVote()\n {\n return age &gt;= 18;\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-30T14:28:41.923", "Id": "4983", "ParentId": "4979", "Score": "2" } }, { "body": "<p>I don't think it's a good idea to write <code>toString</code> method with arguments - doing so you will not override the default <code>Object.toString</code> and will have no benefits from using it outside your code. For example, when outputting elements of a collection which contain <code>Person</code> won't display neither age nor name, but something like <code>Person@a3f33f</code> (default implementation).\nAt least provide <code>toString</code> with no arguments as well</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-30T14:34:20.720", "Id": "7452", "Score": "0", "body": "Denisk that actually moves onto my next question, Does the Person class overload or override any methods? Briefly explain your\nanswer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-30T14:35:08.500", "Id": "7453", "Score": "0", "body": "I was going with override until i seen your comment and would go with overload the Object.toString?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-30T14:38:55.920", "Id": "7454", "Score": "0", "body": "Currently you have `toString` method overloaded - thus, you actually have 2 `toString` methods - one inherited from `Object` (default no-arg method), and one with `boolean` argument. If you declared your `toString` with no arguments it would override `Object.toString`, and you would end up with 1 `toString` method (which, as I have mentioned, can be widely used by many things outside your own code)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-03T13:44:08.333", "Id": "15286", "Score": "0", "body": "I agree with denisk, and want to point out that flags like `full` in method arguments are a code smell: A method should do one and only one thing (Single Responsibility Principle), and a method with a flag does at least two things. Uncle Bob agrees as well (Clean Code: http://www.amazon.de/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882 )" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T12:04:32.977", "Id": "32980", "Score": "0", "body": "The `toString(boolean)` method is part of the assignment requirements. But normally, this is good advice." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-30T14:28:50.150", "Id": "4984", "ParentId": "4979", "Score": "9" } }, { "body": "<p>If the age is implemented as a primitive integer there is no need to initialize it to 0 because all primitive number instance variables are initialized to 0 by default. Anyway if you had used a wrapper instead (Integer) the initialization to 0 is required.</p>\n\n<p>Take a look at the \"<strong>Default Values</strong>\" section:</p>\n\n<p><a href=\"http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html\" rel=\"nofollow\">http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-30T14:29:50.220", "Id": "4985", "ParentId": "4979", "Score": "4" } }, { "body": "<p>I would see if you can make the code less verbose.</p>\n\n<pre><code>public boolean canVote() {\n return age &gt;= 18;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-30T14:30:18.643", "Id": "4986", "ParentId": "4979", "Score": "2" } }, { "body": "<p>This is also less verbose</p>\n\n<pre><code>public int incrementAge() {\n return ++age;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T12:07:13.643", "Id": "32981", "Score": "0", "body": "I worry that a student might be docked points for readability if they put that answer. Otherwise, I would write it like that too." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-30T14:32:23.840", "Id": "4987", "ParentId": "4979", "Score": "2" } }, { "body": "<p>Your code is almost fine. I would change two things: </p>\n\n<p>The following is a little shorter :)</p>\n\n<pre><code>public boolean canVote()\n{\n return age &gt;= 18;\n}\n</code></pre>\n\n<p>Your <code>toString(true)</code> would return <code>\"Sue(21)\"</code> rather than the <code>\"Sue (21)\"</code> (with space) which is asked for. My toString would look like this:</p>\n\n<pre><code>public String toString(boolean full)\n{\n String str = name;\n if(full) {\n str += \" (\" + age + \")\";\n }\n\n return str; \n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-30T14:34:07.753", "Id": "4988", "ParentId": "4979", "Score": "5" } }, { "body": "<p>In addition to the other comments, on your constructor, having an argument called \"st\" isn't particularly useful to the reader as it doesn't tell them what it's for. From a code style perspective might be better to have an argument called name, and explicitly set <code>this.name = name</code> in the body.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-30T14:44:06.903", "Id": "7455", "Score": "1", "body": "To add on, at this moment of learning it may seem not to matter, but when you're developing, these little things that make the usage more intuitive (especially when you're using auto-completion) will reduce your (and others') pain." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-30T14:39:40.057", "Id": "4989", "ParentId": "4979", "Score": "5" } }, { "body": "<p>How about adding a constant for 18, say MIN_AGE_TO_VOTE?</p>\n\n<p>And:</p>\n\n<pre><code>return name + (full ? \" (\" + age + \")\" : \"\");\n</code></pre>\n\n<p>Less readable, I agree :-)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T15:56:51.957", "Id": "21691", "Score": "1", "body": "+1 for only the constant. (I agree, the ternary operator is not too readable and harder to maintain.)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-30T15:46:06.663", "Id": "4990", "ParentId": "4979", "Score": "3" } }, { "body": "<p>My version of Person class would be,</p>\n\n<pre><code>public class Person\n{\nprivate int age;\nprivate String name;\n\npublic Person(String st)\n{\n this.name = st;\n this.age = 0;\n}\npublic String toString(boolean full)\n{\n return full?name + \"(\" + this.age + \")\":name;\n}\n\npublic int incrementAge()\n{\n return ++this.age;\n}\n\npublic boolean canVote()\n{\n return (this.age &gt;= 18); \n}\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T16:21:00.047", "Id": "21654", "Score": "1", "body": "No StringBuilder in the toString method?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-01-19T09:37:37.090", "Id": "353699", "Score": "1", "body": "This is not a valid answer, as it is just a new version without any explaination or recommendations. Furthermore it contains many of the same mistakes as the original code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-06T11:03:18.307", "Id": "13390", "ParentId": "4979", "Score": "0" } }, { "body": "<p>Use <a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#format%28java.lang.String,%20java.lang.Object...%29\" rel=\"nofollow\"><code>String.format</code></a> instead of string concatenation:<br>\n<del>return name + \"(\" + age + \")\";</del> becomes</p>\n\n<pre><code>return String.format(\"%s (%s)\", name, age);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T22:09:20.817", "Id": "21694", "Score": "0", "body": "It's a Java question ;)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T21:34:42.460", "Id": "13422", "ParentId": "4979", "Score": "2" } }, { "body": "<ol>\n<li><p>The name field could be <code>final</code>. Making a variable final relieves the programmer of excess mental juggling - he/she doesn't have to scan through the code to see if the variable has changed. (From <a href=\"https://softwareengineering.stackexchange.com/a/98796/36726\">@nerdytenor's answers.</a>)</p></li>\n<li><p>You should check the argument in the constructor. Does it make sense to create a <code>Person</code> object with a name which is <code>null</code> or an empty String? If not, check it and throw a <code>NullPointerException</code> or an <code>IllegalArgumentException</code>. (<em>Effective Java, Second Edition, Item 38: Check parameters for validity</em>)</p></li>\n<li><p>A note about the specification:</p>\n\n<blockquote>\n <p>Flag arguments are ugly. Passing a boolean into a function is a truly terrible practice. It\n immediately complicates the signature of the method, loudly proclaiming that this function\n does more than one thing. It does one thing if the flag is true and another if the flag is false!</p>\n</blockquote>\n\n<p>Source: <em>Clean Code by Robert C. Martin, Chapter 3: Functions.</em></p>\n\n<p>This should be two methods: <code>toString()</code> and <code>toFullString()</code>, for example, without any parameter.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-08T20:46:39.960", "Id": "13444", "ParentId": "4979", "Score": "2" } }, { "body": "<pre><code>public Person(String st)\n{\n name = st;\n age = 0;\n}\n</code></pre>\n\n<p><code>st</code> is not a good name for a variable or parameter, because it does not tell you what it contains. It implies that it means \"string\", but even that is not clear. Call it <code>name</code> instead. Use <code>this.name = name</code> to distinguish member and parameter names.</p>\n\n<hr>\n\n<p>Put the opening brackets on the first line of the block, not at the beginning of the next line, since it is common practise in Java (even though I find it prettier if it is on the next line, since I code C# more than Java). Other Java developers reading your code will be used to it.</p>\n\n<hr>\n\n<p>Others have already pointed it out: Write <code>if (full)</code> instead of <code>if (full == true)</code>. That is clearer and easier to read. You can use the ternary operator for a one liner:</p>\n\n<p><code>return full ? name + \"(\" + age + \")\" : name;</code>.</p>\n\n<hr>\n\n<p>Your <code>incrementAge()</code> looks fine.</p>\n\n<hr>\n\n<pre><code> public boolean canVote()\n {\n if(age &gt;= 18)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n</code></pre>\n\n<p>Your indentation is weird. Use 4 spaces (less common tabs with width of 4 spaces) for indentation. You have sometimes 3 spaces, sometimes 2.</p>\n\n<p>Since <code>age &gt;= 18</code> is a boolean expression, you can return the result just like this:</p>\n\n<p><code>return age &gt;= 18;</code></p>\n\n<p>Use spaces after <code>if</code> and <code>for</code> (also <code>while</code> and similar) keywords. That makes the code clearer and more readable:</p>\n\n<pre><code>if (someCondition) {\n doThis();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-01-19T09:51:53.797", "Id": "185463", "ParentId": "4979", "Score": "1" } } ]
{ "AcceptedAnswerId": "4981", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-30T14:23:38.863", "Id": "4979", "Score": "11", "Tags": [ "java" ], "Title": "Java practise exam question" }
4979